Skip to main content

quickjs/
interp.rs

1//! The bytecode interpreter.
2//!
3//! The machine is the same shape as the reference's: a value stack per frame, a
4//! program counter into `js_compile`'s resolved bytecode, and a frame chain. Two
5//! properties of that design are worth stating up front because they are visible
6//! everywhere below.
7//!
8//! **Frames are explicit, not recursive.** A JavaScript call pushes a frame onto
9//! [`Interp::frames`] and the loop continues; it never recurses in Rust. Deep
10//! JavaScript recursion therefore costs heap, not C stack, and the depth limit is
11//! ours to enforce rather than the host's to crash.
12//!
13//! **Exceptions live on the value stack.** `catch` pushes a [`Value::CatchOffset`]
14//! marker and an exception is found by walking the frame's stack downwards looking
15//! for the innermost one. There is no side table, which is why a `try` inside a
16//! loop costs nothing until it throws.
17
18use std::collections::{BTreeMap, BTreeSet};
19
20use js_compile::bytecode::{Atom, ClosureType, Constant, Function as CompiledFunction};
21use js_compile::opcode::Opcode;
22use js_gc::{Gc, Heap, WeakGc};
23
24use crate::object::{
25    Callable, ClassDef, ClassId, ClosureEnv, CompiledCode, EvalScope, JsObject, LocalVars,
26    NativeFn, ObjectKind, Opaque, Property, PropertyKey, array_index, has_own, lookup_key,
27    lookup_key_above, same_proto,
28};
29use crate::value::{Cell, Value, number_to_string};
30
31/// Why execution stopped.
32#[derive(Debug, Clone)]
33pub enum Signal {
34    /// A JavaScript exception carrying the thrown value.
35    Throw(Value),
36    /// The runtime ran out of memory.
37    OutOfMemory,
38}
39
40/// What an execution step produced.
41pub type JsResult<T> = std::result::Result<T, Signal>;
42
43/// The result of one instruction.
44enum Step {
45    /// Keep executing the current frame.
46    Continue,
47    /// The current frame returned this value.
48    Return(Value),
49    /// The frame parked at a suspension point, with the yielded value on its stack.
50    ///
51    /// Only a generator or an async function can produce this, and only its own frame —
52    /// a nested ordinary call cannot contain a `yield`. The frame is not popped: it is
53    /// detached and handed to the generator object, which is what lets it resume later
54    /// with its locals and operand stack intact.
55    Suspend(SuspendKind),
56}
57
58/// Why a frame parked, which decides how the resumption is delivered.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum SuspendKind {
61    /// `initial_yield`: the body has not started. The first `next()` resumes *after* it
62    /// without passing a value, because there is no `yield` expression to receive one.
63    Initial,
64    /// `yield expr`: the value is on the stack and the caller gets `{value, done:false}`.
65    Yield,
66    /// `yield* expr` in a *sync* generator: like `Yield`, but the value is already an
67    /// `{value, done}` object from the inner iterator and is handed straight back.
68    YieldStar,
69    /// `yield* expr` in an *async* generator: the compiled shape extracts `.value` first, so
70    /// what was yielded is the plain value and still has to be awaited and wrapped —
71    /// `AsyncGeneratorYield` does `Await(value)` before handing it out. Sharing `YieldStar`
72    /// made it pass a bare value through as if it were an iterator result, so
73    /// `async function* g(){ yield* [1] }` answered `{value: {value: 1, done: false}}`.
74    AsyncYieldStar,
75    /// `await expr`: the value is a promise the async machinery has to settle first.
76    Await,
77}
78
79/// Everything one JavaScript realm owns.
80///
81/// A realm is the set of objects a script can reach without naming them: the global
82/// object, the prototype chain roots, and the global binding cells.
83pub struct Realm {
84    /// The global object.
85    pub global: Gc<JsObject>,
86    /// `Object.prototype`.
87    pub object_proto: Gc<JsObject>,
88    /// `Function.prototype`, which is itself callable.
89    pub function_proto: Gc<JsObject>,
90    /// `Array.prototype`.
91    pub array_proto: Gc<JsObject>,
92    /// The **intrinsic** `%Object.prototype.toString%`.
93    ///
94    /// Not a lookup on `Object.prototype`: `Array.prototype.toString` names the intrinsic
95    /// directly, so `delete Object.prototype.toString` does not change its fallback
96    /// (`Array/prototype/toString/non-callable-join-string-tag` deletes it and then calls
97    /// `Array.prototype.toString` on a dozen receivers).
98    pub object_proto_to_string: Option<Gc<JsObject>>,
99    /// The `%Array%` constructor, so `ArraySpeciesCreate` can recognise "the default".
100    pub array_constructor: Option<Gc<JsObject>>,
101    /// The `%Promise%` constructor, for the same reason in `NewPromiseCapability`.
102    pub promise_constructor: Option<Gc<JsObject>>,
103    /// Reference cells for globals declared by the script.
104    ///
105    /// A declared global is read with `get_var` (by name) but written with
106    /// `put_var_ref` (through the cell), so the cell is what makes a function
107    /// declaration and its uses agree on one binding.
108    pub globals: BTreeMap<String, Gc<Cell>>,
109    /// Names of the globals that came from a *declaration*, which are
110    /// non-configurable properties of the global object.
111    pub declared: Vec<String>,
112    /// Names among the lexical globals that are `const`.
113    ///
114    /// `const`-ness cannot be read back off the bytecode in every case: a closure that
115    /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
116    /// path does not carry, so a store through it would look like a plain `let`. The
117    /// realm records it once, at declaration, and answers for every reader.
118    pub lexical_consts: BTreeSet<String>,
119    /// The error constructors by class name, so a runtime error can throw a real
120    /// `TypeError` instance rather than a look-alike object.
121    pub errors: BTreeMap<&'static str, Gc<JsObject>>,
122    /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
123    pub string_proto: Option<Gc<JsObject>>,
124    /// `Number.prototype`.
125    pub number_proto: Option<Gc<JsObject>>,
126    /// `Boolean.prototype`.
127    pub boolean_proto: Option<Gc<JsObject>>,
128    /// `BigInt.prototype`.
129    pub bigint_proto: Option<Gc<JsObject>>,
130    /// `Error.prototype`, the prototype of every error instance.
131    pub error_proto: Gc<JsObject>,
132    /// `Date.prototype`, so the constructor can build an instance in the
133    /// function-call form (`Date()` returns a string) without going through `new`.
134    pub date_proto: Gc<JsObject>,
135    /// `%ThrowTypeError%`, the single frozen thrower behind every restricted property.
136    ///
137    /// §10.2.4 makes it *one* object per realm, and the identity is observable: test262's
138    /// whole `ThrowTypeError/` directory finds it through
139    /// `Object.getOwnPropertyDescriptor(function(){"use strict"; return arguments;}(),
140    /// "callee").get` and then asserts on its `length`, `name`, prototype and frozenness.
141    /// Creating a fresh one per property would make
142    /// `getOwnPropertyDescriptor(Function.prototype, "caller").get ===
143    /// getOwnPropertyDescriptor(Function.prototype, "arguments").get` false.
144    pub throw_type_error: Option<Gc<JsObject>>,
145    /// `%GeneratorPrototype%`, the prototype of every generator object.
146    pub generator_proto: Gc<JsObject>,
147    /// `Promise.prototype`, the prototype of every promise.
148    pub promise_proto: Option<Gc<JsObject>>,
149    /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
150    pub async_generator_proto: Option<Gc<JsObject>>,
151    /// `%AsyncIteratorPrototype%`, the prototype of `%AsyncGeneratorPrototype%`.
152    ///
153    /// It carries exactly two methods — `@@asyncIterator` and `@@asyncDispose` — and is the
154    /// object test262 reaches through
155    /// `Object.getPrototypeOf(Object.getPrototypeOf(generator.prototype))`.
156    pub async_iterator_proto: Option<Gc<JsObject>>,
157    /// `Symbol.prototype`.
158    pub symbol_proto: Option<Gc<JsObject>>,
159    /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
160    /// `_date_value`.
161    ///
162    /// These are *symbol* keys on purpose. A `"_value"` property is visible to
163    /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
164    /// language does not have and `new Error()` listed `_class` beside `message` and
165    /// `stack` — and a caller that copies every own property (which
166    /// `Object.create(null, props)` effectively does) tried to write an internal name and
167    /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
168    /// and `JSON.stringify`, while remaining an ordinary traced property.
169    ///
170    /// `RefCell` because interning is memoisation rather than observable state: filling the
171    /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
172    /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
173    /// built while reporting a failure must not require an exclusive borrow.
174    pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
175
176    /// The `Symbol.for` registry: `key -> symbol`.
177    ///
178    /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
179    /// symbol every time within one script while a fresh realm starts empty.
180    pub symbol_registry: BTreeMap<String, Value>,
181    /// `RegExp.prototype`, filled in by the `RegExp` builtin.
182    pub regexp_proto: Option<Gc<JsObject>>,
183    /// The `RegExp` constructor.
184    pub regexp_ctor: Option<Gc<JsObject>>,
185    /// `SuppressedError.prototype`, which `using` builds its aggregates from.
186    ///
187    /// The prototype rather than the constructor on purpose: a script that replaces
188    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
189    /// error wrapping, which the `using` test suite checks explicitly.
190    pub suppressed_error_proto: Option<Gc<JsObject>>,
191    /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
192    pub disposable_stack_proto: Option<Gc<JsObject>>,
193    /// `Map.prototype`.
194    pub map_proto: Option<Gc<JsObject>>,
195    /// `Set.prototype`.
196    pub set_proto: Option<Gc<JsObject>>,
197    /// Every live `FinalizationRegistry`, held weakly.
198    ///
199    /// The cleanup callback has to run from a *safe point* — a place where script is not
200    /// already executing and no engine borrow is held — and the collector cannot enumerate
201    /// heap objects by type. Registering each registry here gives the drain a list to walk.
202    ///
203    /// The handles are weak on purpose: a registry the script dropped must be collectable,
204    /// and it must not be resurrected merely because the drain knew about it. Entries whose
205    /// target has expired are swept out as the drain walks, so the vector does not grow
206    /// without bound in a program that creates many short-lived registries.
207    pub finalization_registries: Vec<WeakGc<JsObject>>,
208    /// `ArrayBuffer.prototype`.
209    pub array_buffer_proto: Option<Gc<JsObject>>,
210    /// `%TypedArray%.prototype`, the prototype every view type inherits from.
211    pub typed_array_proto: Option<Gc<JsObject>>,
212    /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
213    ///
214    /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
215    /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
216    /// `"Object"` and `r instanceof Int32Array` is false.
217    pub typed_array_protos: Vec<Gc<JsObject>>,
218    /// `DataView.prototype`.
219    pub data_view_proto: Option<Gc<JsObject>>,
220    /// The `AsyncDisposableStack` prototype.
221    pub async_disposable_stack_proto: Option<Gc<JsObject>>,
222    /// `CreateAsyncFromSyncIterator`, as a script function.
223    ///
224    /// `GetIterator(obj, async)` has to wrap the synchronous iterator it falls back to, and
225    /// the wrapper's state machine is written in JavaScript (see
226    /// [`crate::builtins::async_from_sync`]). Holding the factory here is what lets the Rust
227    /// side call it without a global name a script could shadow.
228    pub async_from_sync: Option<Value>,
229    /// `Iterator.prototype`.
230    pub iterator_proto: Option<Gc<JsObject>>,
231    /// The `Iterator` constructor itself.
232    ///
233    /// `Iterator.prototype.constructor` is an accessor whose getter has to answer this
234    /// object, and the getter is a bare `fn` pointer that cannot capture it — so the only
235    /// place it can live is the realm.
236    pub iterator_ctor: Option<Gc<JsObject>>,
237    /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
238    ///
239    /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
240    /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
241    /// `[object Iterator Helper]`).
242    pub iterator_helper_proto: Option<Gc<JsObject>>,
243    /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
244    /// that was not already an `Iterator`.
245    ///
246    /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
247    /// untouched and does *not* override `@@toStringTag`, so
248    /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
249    pub iterator_wrap_proto: Option<Gc<JsObject>>,
250    /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
251    pub generator_function_proto: Option<Gc<JsObject>>,
252    /// `%AsyncFunction.prototype%`.
253    pub async_function_proto: Option<Gc<JsObject>>,
254    /// `%AsyncGeneratorFunction.prototype%`.
255    pub async_generator_function_proto: Option<Gc<JsObject>>,
256    /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
257    ///
258    /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
259    /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
260    /// prototype per iterator made every array iterator's prototype distinct.
261    pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
262    /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
263    ///
264    /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
265    /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
266    /// both faster and impossible to break from a script.
267    well_known_symbols: WellKnownSymbols,
268    /// The classes the host registered, and the prototype each one hands its instances.
269    pub host_classes: HostClasses,
270    /// `[[TemplateMap]]` — §13.2.8.1 `GetTemplateObject`'s registry, keyed by call site.
271    ///
272    /// The spec keys it by *parse node*, which the runtime does not have; a compiled code
273    /// object plus the index of the `push_const` that names the template is the same
274    /// thing, because that pair is exactly one source location. It also gives the answer
275    /// the tests demand for `eval`: each `eval` call compiles a fresh code object, so two
276    /// calls of `eval("tag`${a}`")` see different objects while two iterations of a loop
277    /// *inside* one eval see the same one (`cache-eval-inner-function`).
278    template_map: std::collections::HashMap<u32, js_gc::WeakGc<JsObject>>,
279}
280
281/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
282///
283/// One per realm, because a class id is only meaningful within the runtime that handed it
284/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
285/// a host class cannot collide.
286pub struct HostClasses {
287    /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
288    /// `JS_GetOpaque(val, 0)` has to match nothing.
289    next_id: u32,
290    /// What each registered class does.
291    defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
292    /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
293    ///
294    /// A strong reference, so the prototype a host installed outlives every script
295    /// reference to it — which is what `JS_SetClassProto` promises.
296    protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
297}
298
299impl HostClasses {
300    fn new() -> HostClasses {
301        HostClasses {
302            next_id: 1,
303            defs: std::collections::BTreeMap::new(),
304            protos: std::collections::BTreeMap::new(),
305        }
306    }
307
308    /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
309    pub fn register(&mut self, def: ClassDef) -> ClassId {
310        let id = ClassId::from_raw(self.next_id);
311        self.next_id += 1;
312        self.defs.insert(id, std::rc::Rc::new(def));
313        id
314    }
315
316    /// Register `def` under an id the caller already has (`JS_NewClass`).
317    ///
318    /// The C API splits "get an id" from "register a class" because a module may be
319    /// initialised lazily; registering twice under one id replaces the definition, and an
320    /// object created under the old one keeps the old behaviour, since it carries its own
321    /// reference.
322    pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
323        if !id.is_valid() {
324            return false;
325        }
326        // Keep the counter past any id handed out explicitly, so a later `register` cannot
327        // reuse one.
328        self.next_id = self.next_id.max(id.get() + 1);
329        self.defs.insert(id, std::rc::Rc::new(def));
330        true
331    }
332
333    /// What `id` was registered with.
334    pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
335        self.defs.get(&id).cloned()
336    }
337
338    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
339    pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
340        self.protos.insert(id, proto);
341    }
342
343    /// The prototype installed for `id`, if the host installed one.
344    pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
345        self.protos.get(&id).cloned()
346    }
347
348    /// How many classes the host registered.
349    pub fn len(&self) -> usize {
350        self.defs.len()
351    }
352
353    /// Whether no class has been registered.
354    pub fn is_empty(&self) -> bool {
355        self.defs.is_empty()
356    }
357}
358
359impl Default for HostClasses {
360    fn default() -> HostClasses {
361        HostClasses::new()
362    }
363}
364
365/// One binding of the frame that called `eval`, so the eval'd code can read and
366/// write it by name.
367struct EvalBinding {
368    /// The name it was declared with.
369    name: String,
370    /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
371    /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
372    /// a function that declares `a` must find that `a`.
373    frame: usize,
374    /// Which table of that frame it lives in.
375    slot: EvalSlot,
376    /// The slot index within that table.
377    index: usize,
378}
379
380/// Which table of a frame an [`EvalBinding`] indexes.
381#[derive(Clone, Copy)]
382enum EvalSlot {
383    Arg,
384    Local,
385}
386
387/// One activation record.
388struct Frame {
389    /// The bytecode being run.
390    code: Gc<CompiledCode>,
391    /// The cells this closure captured.
392    env: Gc<ClosureEnv>,
393    /// The `this` binding.
394    this: Value,
395    /// Argument slots, sized to the declared parameter count.
396    args: Vec<Value>,
397    /// How many values the caller actually passed, which is what `arguments.length`
398    /// reports and what `...rest` slices from.
399    passed_count: usize,
400    /// The passed values, **only when they do not fit in [`Self::args`]**.
401    ///
402    /// `args` is sized to the declared parameters, so a call that passes no more than
403    /// that already holds every passed value in its first `passed_count` slots — copying
404    /// them here as well was two writes and a buffer per call, on the hottest path in
405    /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
406    /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
407    /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
408    /// its own copy.
409    ///
410    /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
411    /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
412    /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
413    /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
414    /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
415    /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
416    #[allow(clippy::box_collection)]
417    passed_overflow: Option<Box<Vec<Value>>>,
418    /// Local slots.
419    locals: Vec<Value>,
420    /// Reference cells for this frame's own captured bindings.
421    cells: Vec<Gc<Cell>>,
422    /// The operand stack.
423    stack: Vec<Value>,
424    /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
425    local_vars: Option<Gc<LocalVars>>,
426
427    /// Index of the next instruction, not a byte offset.
428    ///
429    /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
430    /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
431    /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
432    /// `Frame`, and `frames.push` copies the whole struct on every call.
433    pc: usize,
434    /// Byte offset of the instruction being executed, which is what a stack trace
435    /// reports. `pc` has already moved past it by the time an instruction runs.
436    ///
437    /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
438    at: usize,
439    /// The callee, so a native builtin can tell which constructor it is.
440    callee: Value,
441    /// `new.target`: the constructor under `new`, `undefined` for a plain call.
442    new_target: Value,
443    /// What this frame costs against [`Interp::stack_limit`], in bytes.
444    ///
445    /// Cached rather than recomputed because it is charged on every call and a call is the
446    /// hottest thing in the interpreter.
447    cost: usize,
448    /// [`Interp::stack_used`] before this frame was pushed.
449    ///
450    /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
451    /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
452    /// leave the counter wrong. There are eight places that drop frames; one subtraction
453    /// forgotten in any of them would leak budget until the depth limit moved.
454    stack_base: usize,
455    /// Whether this frame's body ended in a `tail_call`.
456    ///
457    /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
458    /// with its own frame just like `call` does and only skips storing the result
459    /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
460    /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
461    /// pushed as usual, and this marker makes its return value the *caller's* return
462    /// value without running the instructions after the call.
463    tail: bool,
464}
465
466impl Frame {
467    /// Read a local slot, taking the frame as `self`.
468    ///
469    /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
470    /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
471    /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
472    /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
473    /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
474    #[inline]
475    fn read_loc(&self, slot: usize) -> Value {
476        let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
477        if cell == -1 {
478            return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
479        }
480        match self.cells.get(cell as usize) {
481            Some(cell) => cell.get(),
482            None => Value::Undefined,
483        }
484    }
485
486    /// [`Self::read_loc`] for an argument slot.
487    #[inline]
488    fn read_arg(&self, slot: usize) -> Value {
489        let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
490        if cell == -1 {
491            return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
492        }
493        match self.cells.get(cell as usize) {
494            Some(cell) => cell.get(),
495            None => Value::Undefined,
496        }
497    }
498
499    /// The values the caller actually passed, which is what `arguments` exposes.
500    ///
501    /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
502    fn passed(&self) -> &[Value] {
503        match &self.passed_overflow {
504            Some(values) => values,
505            None => &self.args[..self.passed_count],
506        }
507    }
508
509    /// The decoded instructions of the function this frame runs.
510    ///
511    /// A method rather than `frame.code.insns` at the call site so that the borrow is
512    /// obviously of the frame — the dispatch loop holds one across a `get`.
513    fn insns(&self) -> &[crate::insn::Insn] {
514        &self.code.insns
515    }
516}
517
518impl js_gc::Trace for Frame {
519    fn trace(&self, tracer: &mut js_gc::Tracer) {
520        self.code.trace(tracer);
521        self.env.trace(tracer);
522        self.this.trace(tracer);
523        for value in &self.args {
524            value.trace(tracer);
525        }
526        for value in self.passed() {
527            value.trace(tracer);
528        }
529        for value in &self.locals {
530            value.trace(tracer);
531        }
532        for cell in &self.cells {
533            cell.trace(tracer);
534        }
535        if let Some(local_vars) = &self.local_vars {
536            tracer.visit(local_vars);
537        }
538        for value in &self.stack {
539            value.trace(tracer);
540        }
541        self.callee.trace(tracer);
542        self.new_target.trace(tracer);
543    }
544}
545
546/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
547/// emitted `if_false` treats as "keep going".
548/// How many finished frames' value buffers are kept for reuse.
549const RECYCLE_SLOTS: usize = 8;
550
551/// The largest buffer worth keeping. See [`Interp::free_values`].
552const RECYCLE_MAX_CAPACITY: usize = 4096;
553
554const RESUME_NEXT: i32 = 0;
555/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
556/// generator fall into its `return_async`.
557const RESUME_RETURN: i32 = 1;
558/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
559/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
560/// must forward the exception into the inner iterator rather than finish.
561const RESUME_THROW: i32 = 2;
562
563/// One microtask.
564///
565/// The queue holds *data* rather than closures because its contents are GC values: a
566/// closure would be invisible to the collector, and a pending reaction is exactly the
567/// kind of thing that must keep its handlers and its promise alive.
568pub enum Job {
569    /// A `then` reaction about to run.
570    Reaction {
571        /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
572        handler: Option<Value>,
573        /// The value or reason to call it with.
574        argument: Value,
575        /// Whether the source promise rejected, which decides the pass-through kind.
576        rejected: bool,
577        /// The promise the answer settles.
578        promise: Gc<JsObject>,
579    },
580    /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
581    Thenable {
582        /// The `then` that was found on the value.
583        then: Value,
584        /// The thenable itself, which becomes `then`'s `this`.
585        value: Value,
586        /// The promise being resolved.
587        promise: Gc<JsObject>,
588    },
589    /// A pending `import(specifier)`.
590    Import {
591        /// The specifier, already converted to a string.
592        specifier: String,
593        /// The module that asked, which the specifier resolves against.
594        referrer: String,
595        /// The promise `import()` handed back.
596        promise: Gc<JsObject>,
597    },
598    /// An async generator resuming after the value it awaited settled.
599    GeneratorResume {
600        /// The async generator to continue.
601        generator: Gc<JsObject>,
602        /// The promise the pending method returned.
603        promise: Gc<JsObject>,
604        /// Whether this delivers the value or raises the reason.
605        kind: ResumeKind,
606        /// The settled value, or the rejection reason.
607        value: Value,
608    },
609    /// An async function resuming after the value it awaited settled.
610    Resume {
611        /// The body, parked in a coroutine.
612        coroutine: Gc<JsObject>,
613        /// The promise the async function handed its caller.
614        promise: Gc<JsObject>,
615        /// Whether this resumption delivers a value or raises one.
616        kind: ResumeKind,
617        /// The settled value, or the rejection reason.
618        value: Value,
619    },
620}
621
622/// One macro-task: work the event loop owes the script but has not run yet.
623///
624/// The microtask queue ([`Job`]) is different: those run before the host regains control.
625/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
626/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
627/// logic: the engine decides *what* is due, the host decides *how to wait*.
628///
629/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
630/// reference counting even though nothing else references it — the same rule the `HostFn`
631/// documentation states from the other side (a host closure must not hold a `Gc`, so the
632/// `Gc` lives here instead).
633pub enum Task {
634    /// A `setTimeout` that is due at `due_at`.
635    ///
636    /// There is no `setInterval` variant because the reference has no `os.setInterval` at
637    /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
638    /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
639    /// would give this engine a timer the reference cannot produce, with nothing to
640    /// compare it against.
641    Timer {
642        /// The id `setTimeout` returned, for `clearTimeout`.
643        id: i32,
644        /// What to call when it fires.
645        callback: Value,
646        /// When it becomes runnable, as a monotonic instant.
647        due_at: std::time::Instant,
648    },
649}
650
651/// A descriptor the host has to poll, and which directions have a handler.
652///
653/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
654/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
655/// blocks on it, and the host reports back through [`Interp::fire_fd`].
656#[derive(Debug, Clone, Copy, PartialEq, Eq)]
657pub struct FdInterest {
658    /// The descriptor to watch.
659    pub fd: i32,
660    /// Whether `os.setReadHandler` registered a callback.
661    pub read: bool,
662    /// Whether `os.setWriteHandler` registered a callback.
663    pub write: bool,
664}
665
666/// The callbacks registered for one descriptor, per direction.
667#[derive(Default)]
668pub(crate) struct FdHandlers {
669    /// `os.setReadHandler`'s callback.
670    pub read: Option<Value>,
671    /// `os.setWriteHandler`'s callback.
672    pub write: Option<Value>,
673}
674
675/// The file name `eval` reports, which the reference does not inherit from the caller.
676///
677/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
678/// reference and the names show up in stack traces.
679/// The description of the private symbol a class brand is made from.
680///
681/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
682/// place no script can reach, since no expression can name a private symbol.
683const BRAND_DESCRIPTION: &str = "brand";
684
685/// One validated property lookup.
686///
687/// Covers both own-property hits and prototype hits. The second kind was deliberately left
688/// uncached at first ("a prototype hit depends on more than the object and the name"), and
689/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
690/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
691/// names on every iteration (measured: 100 ns per call over an empty loop).
692pub struct FieldCache {
693    /// The name, so two different properties of one object do not collide.
694    key: PropertyKey,
695    /// Where the value was found, relative to the chain below.
696    index: usize,
697    /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
698    level: u8,
699    /// The receiver and every prototype down to (and including) the level that answered,
700    /// each with the length of its property table at the time.
701    ///
702    /// That length is the whole guard, and it is sufficient for the ways the answer can
703    /// change without a lookup: adding or deleting any property moves it, and a
704    /// same-length rewrite is caught by `cached_data_property` re-checking the key and
705    /// refusing an accessor. Storing the *whole* chain — not just the object that answered
706    /// — is what catches a property appearing on an *intermediate* prototype and shadowing
707    /// the one that was cached.
708    ///
709    /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
710    /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
711    chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
712}
713
714/// How many links of a prototype chain a [`FieldCache`] remembers.
715///
716/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
717/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
718/// at three.
719const MAX_CACHED_CHAIN: usize = 3;
720
721/// A remembered global-variable lookup.
722///
723/// A `var` global is an ordinary property of the global object, so reading one walks the
724/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
725/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
726/// fixed by the bytecode, and the slot in the object's table only changes if the global
727/// object is mutated, which the index-and-name check below catches.
728pub struct GlobalCache {
729    /// The global object the lookup was resolved on, weakly.
730    object: js_gc::WeakGc<JsObject>,
731    /// Index of the data property in the global object's table.
732    index: usize,
733}
734
735/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
736const GLOBAL_CACHE_SLOTS: usize = 1024;
737
738/// How many property lookups are remembered.
739///
740/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
741/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
742/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
743/// lookup itself. Making it bigger stops helping: the working set of a real program's
744/// property sites is bounded by its code size.
745const FIELD_CACHE_SLOTS: usize = 4096;
746
747/// How much the heap may grow past the last `out of memory` before saying it again.
748///
749/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
750/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
751/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
752/// because it looks like it works. The reference gets this for free: it fails inside
753/// `js_malloc`, and its printing path happens not to allocate.
754///
755/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
756/// allocating is stopped within a rounding error of the limit) and far above what a
757/// handler needs.
758const OOM_HYSTERESIS: usize = 64 * 1024;
759
760/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
761pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
762
763/// How many instructions run between polls of [`Interp::interrupt`].
764///
765/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
766/// order of magnitude on both implementations — which is what lets a C driver compare its
767/// output byte for byte (see `scripts/m15-capi.sh --embed`).
768pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
769
770/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
771///
772/// Chosen so that the byte budget is what actually decides for every ordinary
773/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
774/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
775/// millions of frames.
776pub const MAX_FRAMES: usize = 200_000;
777
778const EVAL_FILE: &str = "<input>";
779
780/// The file name `std.evalScript` reports.
781const EVAL_SCRIPT_FILE: &str = "<evalScript>";
782
783/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
784///
785/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
786/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
787fn clamp_delay(delay_ms: f64) -> std::time::Duration {
788    // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
789    // on a float, which reads as a typo even when it is deliberate. Both NaN and a
790    // non-positive delay mean "due now".
791    if delay_ms.is_nan() || delay_ms <= 0.0 {
792        return std::time::Duration::ZERO;
793    }
794    std::time::Duration::from_secs_f64(delay_ms / 1000.0)
795}
796
797impl js_gc::Trace for Task {
798    fn trace(&self, tracer: &mut js_gc::Tracer) {
799        let Task::Timer { callback, .. } = self;
800        callback.trace(tracer);
801    }
802}
803
804/// What one turn of the event loop did, so the caller cannot spin by accident.
805///
806/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
807/// core until the timer is due. Naming the three cases makes the wait explicit.
808#[derive(Debug, Clone, Copy, PartialEq, Eq)]
809pub enum Turn {
810    /// Something ran. Call again immediately — there may be more ready work.
811    Ran,
812    /// Nothing is runnable, but descriptors are registered: the host must poll
813    /// [`Interp::pending_fds`] for at most this long, then report readiness with
814    /// [`Interp::fire_fd`].
815    ///
816    /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
817    /// the failure this project treats as worst — a handler that silently never fires —
818    /// so the two cannot be confused by accident.
819    Poll(std::time::Duration),
820    /// Nothing is runnable yet, but something is pending. Block at most this long, then
821    /// call again.
822    Wait(std::time::Duration),
823    /// Nothing is pending at all: the loop is done.
824    Done,
825}
826
827impl js_gc::Trace for Job {
828    fn trace(&self, tracer: &mut js_gc::Tracer) {
829        match self {
830            Job::Reaction {
831                handler,
832                argument,
833                promise,
834                ..
835            } => {
836                if let Some(handler) = handler {
837                    handler.trace(tracer);
838                }
839                argument.trace(tracer);
840                tracer.visit(promise);
841            }
842            Job::Thenable {
843                then,
844                value,
845                promise,
846            } => {
847                then.trace(tracer);
848                value.trace(tracer);
849                tracer.visit(promise);
850            }
851            Job::Resume {
852                coroutine,
853                promise,
854                value,
855                ..
856            } => {
857                tracer.visit(coroutine);
858                tracer.visit(promise);
859                value.trace(tracer);
860            }
861            Job::Import { promise, .. } => tracer.visit(promise),
862            Job::GeneratorResume {
863                generator,
864                promise,
865                value,
866                ..
867            } => {
868                tracer.visit(generator);
869                tracer.visit(promise);
870                value.trace(tracer);
871            }
872        }
873    }
874}
875
876/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
877#[derive(Debug, Clone, Copy, PartialEq, Eq)]
878pub enum ResumeKind {
879    /// The generator was just created and is being run to its first suspension.
880    Start,
881    /// `next(v)`.
882    Next,
883    /// `return(v)`.
884    Return,
885    /// `throw(e)`.
886    Throw,
887}
888
889/// A generator object's saved execution.
890///
891/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
892/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
893/// separately allocated buffers.
894pub struct GeneratorState {
895    /// The detached frame, or `None` once the generator has finished or while it runs.
896    frame: Option<Frame>,
897    /// How far it got.
898    phase: GeneratorPhase,
899    /// Whether the last suspension was an `await` rather than a `yield`.
900    ///
901    /// The two resume with *different stack shapes*: a `yield` is re-entered with the
902    /// value and a magic number, because the emitted code branches on which method
903    /// resumed it, while an `await` simply continues with its value. Getting this wrong
904    /// leaves an extra value on the operand stack that the next instruction then
905    /// consumes — a wrong answer rather than a crash.
906    parked_on_await: bool,
907    /// Whether the last suspension was a `yield*` rather than a plain `yield`.
908    ///
909    /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
910    /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
911    /// has to be forwarded into the inner iterator's `throw` method instead — which is the
912    /// `rethrow` branch the compiled delegation emits — because that is the whole point of
913    /// delegating. Tracking it as part of the phase, the way the reference splits
914    /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
915    /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
916    /// exception and never reached `xs.throw`.
917    parked_on_yield_star: bool,
918    /// Pending `next`/`return`/`throw` calls, oldest first.
919    ///
920    /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
921    /// called back to back must answer in that order, with the second call's value
922    /// arriving at the *second* `yield`. Running each call straight into the body — which
923    /// is what this engine did before — delivered the last queued value to whichever
924    /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
925    /// `a === b ===` the final argument.
926    ///
927    /// The front entry is the one being served; it stays there (with `async_busy` set)
928    /// until its promise settles, because an `await` inside the body is a suspension of
929    /// the *driver*, not the end of the request.
930    requests: std::collections::VecDeque<AsyncRequest>,
931    /// Whether the front request is in flight.
932    async_busy: bool,
933    /// Whether this came from an `async function*`.
934    ///
935    /// A sync generator and an async one share `ObjectKind::Generator`, so without this
936    /// flag `%AsyncGeneratorPrototype%.next` happily ran a sync generator's body:
937    /// `AsyncGeneratorValidate` has to tell them apart
938    /// (`AsyncGeneratorPrototype/next/this-val-not-async-generator.js`).
939    pub is_async: bool,
940}
941
942/// How one async-generator request ended.
943enum AsyncOutcome {
944    /// The method answered this `{value, done}`.
945    Value(Value),
946    /// The body threw.
947    Error(Value),
948}
949
950/// One queued `next`/`return`/`throw` on an async generator: the reference's
951/// `JSAsyncGeneratorRequest`.
952pub struct AsyncRequest {
953    /// Which method was called.
954    kind: ResumeKind,
955    /// Its argument.
956    value: Value,
957    /// The promise the method answered.
958    promise: Gc<JsObject>,
959}
960
961/// Which of §27.5.3.3's states a generator is in.
962#[derive(Debug, Clone, Copy, PartialEq, Eq)]
963enum GeneratorPhase {
964    /// Created, `initial_yield` reached, body not entered.
965    SuspendedStart,
966    /// Parked at a `yield`.
967    SuspendedYield,
968    /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
969    Executing,
970    /// Finished; the frame is gone.
971    Completed,
972}
973
974impl js_gc::Trace for GeneratorState {
975    fn trace(&self, tracer: &mut js_gc::Tracer) {
976        if let Some(frame) = &self.frame {
977            frame.trace(tracer);
978        }
979        for request in &self.requests {
980            request.value.trace(tracer);
981            tracer.visit(&request.promise);
982        }
983    }
984}
985
986/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
987/// them in.
988///
989/// Each is a field rather than a map entry because the runtime reads them on hot paths
990/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
991/// failure — reaching a default here means the builtin did not install, and every
992/// accessor panics rather than silently answering `undefined`.
993///
994/// [`builtins::symbol`]: crate::builtins::symbol
995#[derive(Default)]
996pub struct WellKnownSymbols {
997    /// The symbol values, positionally. Empty until `Symbol` installs.
998    symbols: Vec<Value>,
999}
1000
1001/// Which well-known symbol a caller wants.
1002///
1003/// A typed accessor beats passing a name around: a typo is a compile error rather than
1004/// an `undefined` key that quietly matches nothing.
1005#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1006pub enum WellKnown {
1007    /// `Symbol.toPrimitive`.
1008    ToPrimitive,
1009    /// `Symbol.iterator`.
1010    Iterator,
1011    /// `Symbol.match`.
1012    Match,
1013    /// `Symbol.matchAll`.
1014    MatchAll,
1015    /// `Symbol.replace`.
1016    Replace,
1017    /// `Symbol.search`.
1018    Search,
1019    /// `Symbol.split`.
1020    Split,
1021    /// `Symbol.toStringTag`.
1022    ToStringTag,
1023    /// `Symbol.isConcatSpreadable`.
1024    IsConcatSpreadable,
1025    /// `Symbol.hasInstance`.
1026    HasInstance,
1027    /// `Symbol.species`.
1028    Species,
1029    /// `Symbol.unscopables`.
1030    Unscopables,
1031    /// `Symbol.asyncIterator`.
1032    AsyncIterator,
1033    /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
1034    Disposable,
1035    /// `Symbol.asyncDispose` — the awaited form.
1036    AsyncDisposable,
1037}
1038
1039impl WellKnown {
1040    /// The index `Symbol`'s installer creates this symbol at.
1041    fn index(self) -> usize {
1042        match self {
1043            WellKnown::ToPrimitive => 0,
1044            WellKnown::Iterator => 1,
1045            WellKnown::Match => 2,
1046            WellKnown::MatchAll => 3,
1047            WellKnown::Replace => 4,
1048            WellKnown::Search => 5,
1049            WellKnown::Split => 6,
1050            WellKnown::ToStringTag => 7,
1051            WellKnown::IsConcatSpreadable => 8,
1052            WellKnown::HasInstance => 9,
1053            WellKnown::Species => 10,
1054            WellKnown::Unscopables => 11,
1055            WellKnown::AsyncIterator => 12,
1056            WellKnown::Disposable => 13,
1057            WellKnown::AsyncDisposable => 14,
1058        }
1059    }
1060}
1061
1062impl Realm {
1063    /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1064    pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1065        self.well_known_symbols.symbols = symbols;
1066    }
1067
1068    /// A well-known symbol.
1069    pub fn well_known(&self, which: WellKnown) -> Value {
1070        self.well_known_symbols
1071            .symbols
1072            .get(which.index())
1073            .cloned()
1074            .unwrap_or(Value::Undefined)
1075    }
1076
1077    /// The well-known symbol as a property key.
1078    pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1079        match self.well_known(which) {
1080            Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1081            // Unreachable once `Symbol` has installed; an empty string key matches
1082            // nothing, which degrades to "the object has no such method".
1083            _ => PropertyKey::from(String::new()),
1084        }
1085    }
1086}
1087
1088/// The interpreter: a realm plus a frame stack.
1089pub struct Interp<'a> {
1090    /// The heap everything is allocated on.
1091    pub heap: &'a Heap,
1092    /// The realm.
1093    pub realm: Realm,
1094    /// Active frames, outermost first.
1095    frames: Vec<Frame>,
1096    /// Value buffers from frames that have finished, reused by the next call.
1097    ///
1098    /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1099    /// the locals and the operand stack — and free all four on return. `call:recursion`
1100    /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1101    /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1102    ///
1103    /// Bounded in both directions: a few buffers per kind, and none larger than
1104    /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1105    /// and keeping its buffer would pin that memory for the rest of the run.
1106    free_values: Vec<Vec<Value>>,
1107    /// A strict-mode `eval`'s own variable scope, while its script runs.
1108    ///
1109    /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1110    /// become a global. Name lookups still fall through to the realm, which is why
1111    /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1112    eval_scope: Option<BTreeMap<String, Value>>,
1113    /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1114    /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1115    eval_depth: usize,
1116    /// The calling frame's own bindings, which the running `eval` can read and write.
1117    ///
1118    /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1119    /// come from the frame, and a write is applied back to the frame (or to the cell
1120    /// the frame captured) when the eval finishes. That is what makes
1121    /// `f("a = 3")` visible to the caller as `a === 3`.
1122    eval_bindings: Vec<EvalBinding>,
1123    /// The calling frame's `arguments`, while an `eval` runs.
1124    ///
1125    /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1126    /// own yet still has to see the caller's `arguments`.
1127    eval_arguments: Option<Value>,
1128    /// The `with` objects live at the moment the running `eval` started, innermost first.
1129    ///
1130    /// `None` outside an eval, which is what keeps a finished block's object from
1131    /// shadowing ordinary bytecode reads.
1132    eval_with: Option<Vec<Gc<JsObject>>>,
1133    /// The bindings the running direct `eval` makes visible, as name → cell.
1134    ///
1135    /// Set for the duration of an eval and then restored, but every closure created
1136    /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1137    /// `eval("f = () => i")` work after the eval has returned.
1138    active_eval_scope: Option<Gc<EvalScope>>,
1139    /// The frame that called the direct `eval` currently running, if any.
1140    ///
1141    /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1142    /// on the global object, which is what keeps
1143    /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1144    /// gives each call its own `x`.
1145    eval_caller: Option<Option<usize>>,
1146    /// The caller's `new.target`, while an `eval` runs.
1147    ///
1148    /// The eval'd code is a script with no constructor of its own, so it inherits the
1149    /// one the enclosing function was called with.
1150    eval_new_target: Option<Value>,
1151    /// `new.target` for the frame about to be pushed.
1152    ///
1153    /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1154    /// value reaches the frame without threading a parameter through every call site.
1155    ///
1156    /// A **native** has no frame, so `call_value` takes it the same way and moves it to
1157    /// [`Interp::active_new_target`] for the duration of the call. Without that, a plain
1158    /// `native()` made from inside a constructor body saw the enclosing `new.target` — the
1159    /// value was parked for the outer call and never consumed.
1160    pending_new_target: Option<Value>,
1161    /// `new.target` of the call currently running, for [`Interp::current_new_target`].
1162    ///
1163    /// `undefined` outside a `new` call.
1164    active_new_target: Value,
1165    /// Names of the native functions currently executing, outermost first.
1166    ///
1167    /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1168    /// trace still names it with `(native)` instead of a position, so the names are
1169    /// tracked separately and stitched into [`Interp::stack_trace`].
1170    ///
1171    /// The third field is how many bytecode frames were live when the native was entered,
1172    /// which is what places it *among* them rather than before all of them. Native
1173    /// functions used to be emitted up front on the grounds that they never re-enter
1174    /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1175    /// The natives currently running, innermost last: the function object and the
1176    /// depth it was entered at.
1177    ///
1178    /// The *name* is deliberately not stored. It used to be, read with
1179    /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1180    /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1181    /// benchmark. A stack trace is built rarely; it can read the name then.
1182    native_frames: Vec<(Gc<JsObject>, usize)>,
1183    /// The native function currently executing, for the ones that have to know *which*
1184    /// function they are — a typed-array constructor reads its element type off itself.
1185    ///
1186    /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1187    /// reports whatever the enclosing bytecode frame was called with.
1188    current_native: Option<Gc<JsObject>>,
1189    /// Text written by `print` and friends, in order.
1190    ///
1191    /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1192    /// once at the end, which is also when upstream's line buffering becomes
1193    /// visible for the cases compared here.
1194    pub output: String,
1195    /// Where `print` also writes, as it goes. `output` keeps the full log for
1196    /// [`crate::Context::output`]; this is the live copy, flushed per line.
1197    ///
1198    /// Both exist on purpose. A host that gives a script a sink sees output *when it
1199    /// happens* — which is what a timer callback's `console.log` has to do, and what the
1200    /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1201    /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1202    /// would show a script's output all at once when it finished.
1203    pub output_sink: Option<Box<dyn std::io::Write>>,
1204    /// Where recent property reads found their value.
1205    ///
1206    /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1207    /// table remembering *which object* and *which entry of its property table* answered a
1208    /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1209    /// can move; the property can become an accessor), which is what makes a stale entry a
1210    /// miss rather than a wrong answer.
1211    ///
1212    /// The object is held weakly: a cache that held it strongly would keep up to
1213    /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1214    /// program cannot see and cannot work around.
1215    pub field_cache: Vec<Option<FieldCache>>,
1216    /// Global lookups, by binding slot. See [`GlobalCache`].
1217    global_cache: Vec<Option<GlobalCache>>,
1218    /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1219    /// under its limit. See [`Interp::check_memory`].
1220    pub oom_reported_at: usize,
1221    /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1222    /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1223    ///
1224    /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1225    /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1226    /// host that wants to stop a runaway script must not have to wait for it to return.
1227    ///
1228    /// Two things this cannot do, both of them differences a host can observe:
1229    ///
1230    /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1231    ///   uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1232    ///   needs a signal that the `catch` machinery does not see, which is a change to
1233    ///   [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1234    ///   a host that stops the script itself.
1235    /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1236    ///   also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1237    ///   both, so the difference is when the counter hits zero, not whether it will.
1238    pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1239    /// Instructions until the next [`Interp::interrupt`] poll.
1240    pub interrupt_counter: u32,
1241    /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1242    ///
1243    /// A separate field from [`Interp::uncatchable`] because the two live for different
1244    /// spans. This one is the host's standing request; it survives the start of an
1245    /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1246    /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1247    /// for both was the first attempt and it did nothing at all: the outermost `execute`
1248    /// cleared it before the script it was set for had a chance to throw.
1249    pub uncatchable_next: bool,
1250    /// Whether the exception now unwinding may be caught by a `catch`.
1251    ///
1252    /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1253    /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1254    /// a host stopping a runaway loop is not fought by the loop.
1255    ///
1256    /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1257    /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1258    /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1259    /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1260    pub uncatchable: bool,
1261    /// The most stack a JavaScript call chain may use, in bytes of frame state.
1262    ///
1263    /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1264    /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1265    /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1266    /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1267    /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1268    /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1269    ///
1270    /// The numbers come out close for the same reason a C frame and a heap frame of this
1271    /// shape cost about the same (both are a few hundred bytes, dominated by the value
1272    /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1273    /// and this engine lands in the same neighbourhood — measured, not fudged, by
1274    /// `crates/quickjs-cli/tests/limits.rs`.
1275    pub stack_limit: usize,
1276    /// The most frames that may be live at once, whatever the byte budget says.
1277    ///
1278    /// A second bound for a reason the reference does not have: our frames cost less than
1279    /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1280    /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1281    /// `--stack-size 1G` from being a memory bomb.
1282    pub max_frames: usize,
1283    /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1284    ///
1285    /// Script execution does not return until this has drained, which is what makes
1286    /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1287    /// than never. Reactions append to it while it drains, so the loop is a `while` and
1288    /// not a `for`.
1289    pub(crate) jobs: std::collections::VecDeque<Job>,
1290    /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1291    ///
1292    /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1293    /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1294    pub(crate) tasks: Vec<Task>,
1295    /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1296    /// barrier'd evaluation started.
1297    ///
1298    /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1299    /// lets a REPL report an error from the line it just evaluated without also reporting
1300    /// its own readline loop.
1301    trace_barriers: Vec<usize>,
1302    /// `os.signal` handlers, keyed by signal number.
1303    ///
1304    /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1305    /// a handler cannot be freed while it is still registered.
1306    pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1307    /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1308    ///
1309    /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1310    /// that is only reachable from a host closure could be freed while still registered.
1311    pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1312    /// The next timer id.
1313    ///
1314    /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1315    /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1316    next_timer_id: i32,
1317    /// Errors thrown by timer callbacks, already rendered.
1318    ///
1319    /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1320    /// that throws has no promise behind it. Both are reported by the host at the end of
1321    /// the loop, but only one is fixed up by a later `.catch`.
1322    timer_errors: Vec<String>,
1323    /// The module registry, keyed by canonical name.
1324    pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1325    /// How the host turns a specifier into bytes.
1326    pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1327    /// The module the host was asked to run, for `import.meta.main`.
1328    pub main_module_name: Option<String>,
1329    /// The name to register the *entry* module under, when the host supplies one.
1330    ///
1331    /// The entry's bytes come from a path on disk; this is the name the module graph should
1332    /// know it by. They differ for a host that evaluates a file it did not write — a test
1333    /// runner that prepends a harness, a bundler, a REPL — and getting it wrong is visible:
1334    /// a module importing *itself* resolves the specifier against the real path, finds no
1335    /// record under that name, and loads a second copy with its own bindings.
1336    pub entry_module_name: Option<String>,
1337    /// Module bodies currently running, innermost last.
1338    ///
1339    /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1340    /// this is the only place that knows which module that is.
1341    pub module_stack: Vec<String>,
1342    /// Rejections that no handler has claimed, with the promise they belong to.
1343    ///
1344    /// A `then` registered later prunes its entry, which is why the promise is kept: the
1345    /// reason alone cannot say whether somebody eventually listened.
1346    unhandled: Vec<(Gc<JsObject>, Value)>,
1347}
1348
1349impl<'a> Interp<'a> {
1350    /// Build an interpreter over `heap`, with a fresh realm.
1351    pub fn new(heap: &'a Heap) -> Interp<'a> {
1352        let object_proto = JsObject::ordinary(heap, None);
1353        let function_proto = JsObject::function(
1354            heap,
1355            Some(object_proto.clone()),
1356            Callable::Native {
1357                func: |_, _, _| Ok(Value::Undefined),
1358                own_instance: false,
1359            },
1360        );
1361        let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1362        let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1363        let mut interp = Interp {
1364            heap,
1365            realm: Realm {
1366                global,
1367                object_proto,
1368                function_proto,
1369                array_proto,
1370                array_constructor: None,
1371                promise_constructor: None,
1372                object_proto_to_string: None,
1373                globals: BTreeMap::new(),
1374                declared: Vec::new(),
1375                lexical_consts: BTreeSet::new(),
1376                errors: BTreeMap::new(),
1377                string_proto: None,
1378                number_proto: None,
1379                boolean_proto: None,
1380                bigint_proto: None,
1381                error_proto: JsObject::ordinary(heap, None),
1382                date_proto: JsObject::ordinary(heap, None),
1383                throw_type_error: None,
1384                generator_proto: JsObject::ordinary(heap, None),
1385                promise_proto: None,
1386                async_generator_proto: None,
1387                async_iterator_proto: None,
1388                symbol_proto: None,
1389                symbol_registry: BTreeMap::new(),
1390                internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1391                regexp_proto: None,
1392                regexp_ctor: None,
1393                suppressed_error_proto: None,
1394                disposable_stack_proto: None,
1395                map_proto: None,
1396                set_proto: None,
1397                finalization_registries: Vec::new(),
1398                array_buffer_proto: None,
1399                typed_array_proto: None,
1400                typed_array_protos: Vec::new(),
1401                data_view_proto: None,
1402                async_disposable_stack_proto: None,
1403                async_from_sync: None,
1404                iterator_proto: None,
1405                iterator_ctor: None,
1406                iterator_helper_proto: None,
1407                iterator_wrap_proto: None,
1408                generator_function_proto: None,
1409                async_function_proto: None,
1410                async_generator_function_proto: None,
1411                iterator_protos: std::collections::BTreeMap::new(),
1412                well_known_symbols: WellKnownSymbols::default(),
1413                host_classes: HostClasses::new(),
1414                template_map: std::collections::HashMap::new(),
1415            },
1416            frames: Vec::new(),
1417            free_values: Vec::new(),
1418            global_cache: {
1419                let mut cache = Vec::new();
1420                cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1421                cache
1422            },
1423            eval_scope: None,
1424            eval_depth: 0,
1425            eval_bindings: Vec::new(),
1426            eval_arguments: None,
1427            eval_with: None,
1428            active_eval_scope: None,
1429            eval_caller: None,
1430            pending_new_target: None,
1431            active_new_target: Value::Undefined,
1432            eval_new_target: None,
1433            native_frames: Vec::new(),
1434            current_native: None,
1435            output: String::new(),
1436            output_sink: None,
1437            field_cache: {
1438                let mut cache = Vec::new();
1439                cache.resize_with(FIELD_CACHE_SLOTS, || None);
1440                cache
1441            },
1442            oom_reported_at: 0,
1443            interrupt: None,
1444            interrupt_counter: INTERRUPT_POLL_INTERVAL,
1445            uncatchable_next: false,
1446            uncatchable: false,
1447            // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1448            // absent.
1449            stack_limit: DEFAULT_STACK_SIZE,
1450            max_frames: MAX_FRAMES,
1451            jobs: std::collections::VecDeque::new(),
1452            tasks: Vec::new(),
1453            trace_barriers: Vec::new(),
1454            signal_handlers: std::collections::BTreeMap::new(),
1455            fd_handlers: std::collections::BTreeMap::new(),
1456            next_timer_id: 1,
1457            timer_errors: Vec::new(),
1458            modules: std::collections::BTreeMap::new(),
1459            module_loader: None,
1460            main_module_name: None,
1461            entry_module_name: None,
1462            module_stack: Vec::new(),
1463            unhandled: Vec::new(),
1464        };
1465        crate::builtins::install(&mut interp);
1466        interp
1467    }
1468
1469    // -- allocation helpers -------------------------------------------------
1470
1471    /// A new string value.
1472    /// A `BigInt` value from a computed big integer.
1473    pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1474        Value::BigInt(Gc::new(self.heap, value))
1475    }
1476
1477    /// A string value from bytes that are already WTF-8, which is how a string with an
1478    /// unpaired surrogate reaches a `Value`.
1479    pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1480        Value::string_wtf8(self.heap, text)
1481    }
1482
1483    /// A new string value, from text that is valid UTF-8.
1484    pub fn string(&self, text: impl Into<String>) -> Value {
1485        Value::string(self.heap, text)
1486    }
1487
1488    /// A new ordinary object with the given prototype.
1489    pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1490        JsObject::ordinary(self.heap, proto)
1491    }
1492
1493    // -- host classes -------------------------------------------------------
1494
1495    /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1496    pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1497        self.realm.host_classes.register(def)
1498    }
1499
1500    /// Register `def` under an id the host already holds (`JS_NewClass`).
1501    ///
1502    /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1503    /// `JS_NewClass`.
1504    pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1505        self.realm.host_classes.define(id, def)
1506    }
1507
1508    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1509    pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1510        self.realm.host_classes.set_proto(id, proto);
1511    }
1512
1513    /// The prototype installed for `id`, if any.
1514    pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1515        self.realm.host_classes.proto(id)
1516    }
1517
1518    /// A new instance of `id` (`JS_NewObjectProtoClass`).
1519    ///
1520    /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1521    /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1522    /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1523    /// host installed none.
1524    ///
1525    /// Answers `None` for an id that was never registered: the C API would return an
1526    /// exception, and silently making an ordinary object instead would move the failure to
1527    /// the first `JS_GetOpaque` that no longer matches.
1528    pub fn new_host_object(
1529        &mut self,
1530        proto: Option<Gc<JsObject>>,
1531        class_id: ClassId,
1532    ) -> Option<Gc<JsObject>> {
1533        let class = self.realm.host_classes.def(class_id)?;
1534        let proto = proto
1535            .or_else(|| self.realm.host_classes.proto(class_id))
1536            .or_else(|| Some(self.realm.object_proto.clone()));
1537        Some(JsObject::host_object(self.heap, proto, class_id, class))
1538    }
1539
1540    /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1541    ///
1542    /// `None` covers both answers the C API gives as a null pointer — the value is not an
1543    /// object, it is an object of another class, or the class never got a payload. A host
1544    /// that has to tell them apart uses [`JsObject::host_class_id`].
1545    pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1546        let object = value.as_object()?;
1547        if object.host_class_id()? != class_id {
1548            return None;
1549        }
1550        object.host_opaque()
1551    }
1552
1553    /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1554    pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1555        match value.as_object() {
1556            Some(object) => object.set_host_opaque(opaque),
1557            None => false,
1558        }
1559    }
1560
1561    /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1562    ///
1563    /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1564    /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1565    /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1566    /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1567    /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1568    /// said `[object Object]` instead of `[object Array Iterator]`.
1569    ///
1570    /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1571    /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1572    /// its own.
1573    pub fn new_iterator_prototype(
1574        &mut self,
1575        tag: &str,
1576        next: crate::object::NativeFn,
1577    ) -> Gc<JsObject> {
1578        if let Some(existing) = self.realm.iterator_protos.get(tag) {
1579            return existing.clone();
1580        }
1581        let parent = self.realm.iterator_proto.clone();
1582        let proto = self.new_object(parent);
1583        let next = self.new_native("next", 0, next);
1584        proto.define(
1585            "next",
1586            Property::with_attributes(Value::Object(next), true, false),
1587        );
1588        let key = self.realm.well_known_key(WellKnown::Iterator);
1589        let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1590        proto.define_key(
1591            &key,
1592            Property::with_attributes(Value::Object(identity), true, false),
1593        );
1594        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1595        let tag_value = self.string(tag);
1596        // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1597        // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1598        // checks it.
1599        proto.define_key(&tag_key, Property::configurable_only(tag_value));
1600        self.realm
1601            .iterator_protos
1602            .insert(tag.to_string(), proto.clone());
1603        proto
1604    }
1605
1606    /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1607    ///
1608    /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1609    /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1610    /// produced. That is why the two branches are not merged.
1611    pub fn object_own_property_keys(
1612        &mut self,
1613        object: &Gc<JsObject>,
1614    ) -> JsResult<Vec<PropertyKey>> {
1615        if let Some(keys) = self.proxy_own_keys(object)? {
1616            return Ok(keys);
1617        }
1618        // Integer-like keys ascending, then the string keys in insertion order, then the
1619        // symbols — the order every schema that walks an object expects.
1620        let entries = object.property_entries();
1621        let mut numeric: Vec<u32> = Vec::new();
1622        // An integer-indexed exotic object reports its indices as own keys even though they
1623        // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1624        // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1625        // order). The length is asked per call, so a resizable buffer's view reports the
1626        // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1627        if object.typed_array_parts().is_some() {
1628            for index in 0..object.typed_array_length().unwrap_or(0) {
1629                // `u32::try_from` cannot fail for a real length, but the length is a
1630                // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1631                // as an array index and one element beyond is not.
1632                match u32::try_from(index) {
1633                    Ok(index) => numeric.push(index),
1634                    Err(_) => break,
1635                }
1636            }
1637        }
1638        let mut strings: Vec<PropertyKey> = Vec::new();
1639        let mut symbols: Vec<PropertyKey> = Vec::new();
1640        for (key, _) in entries {
1641            match &key {
1642                // A class-private name is never reported by any enumeration: that is the
1643                // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1644                // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1645                // symbol skip, `Object.assign`) therefore cannot see it.
1646                PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1647                PropertyKey::Symbol(_) => symbols.push(key),
1648                PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1649                    Some(index) => {
1650                        if !numeric.contains(&index) {
1651                            numeric.push(index);
1652                        }
1653                    }
1654                    None => strings.push(key),
1655                },
1656            }
1657        }
1658        // An array's `length` is an own property from the moment the array exists, so it
1659        // sits **before** every string key added afterwards — `arr.a = 1; arr.length` lists
1660        // as `["length", "a"]`, not `["a", "length"]`
1661        // (`getOwnPropertyNames/order-after-define-property`). It is synthesised rather
1662        // than stored in the property table, which is why it has to be placed here.
1663        if object.is_array() && object.proxy_state().is_none() {
1664            // Unconditionally: `Object.defineProperty(arr, "length", …)` files `length` in
1665            // the property table, at whatever position the *define* happened, but the key
1666            // lists it as the array's oldest string property because that is what it is.
1667            if let Some(position) = strings
1668                .iter()
1669                .position(|key| key.as_str() == Some("length"))
1670            {
1671                strings.remove(position);
1672            }
1673            strings.insert(0, PropertyKey::from("length"));
1674        }
1675        numeric.sort_unstable();
1676        let mut keys: Vec<PropertyKey> = numeric
1677            .into_iter()
1678            .map(|index| PropertyKey::from(index.to_string()))
1679            .collect();
1680        keys.extend(strings);
1681        keys.extend(symbols);
1682        Ok(keys)
1683    }
1684
1685    /// The state behind a promise object, or `None` when `object` is not one.
1686    pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1687        object.with(|data| match &data.kind {
1688            ObjectKind::Promise(state) => Some(state.clone()),
1689            _ => None,
1690        })
1691    }
1692
1693    /// A new pending promise.
1694    pub fn new_promise(&mut self) -> Gc<JsObject> {
1695        // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1696        // the one place every promise is built, and a subclass that builds its instances
1697        // somewhere else would be invisible to `instanceof`.
1698        let default = self.realm.promise_proto.clone();
1699        // A throwing `new.target.prototype` getter cannot be reported from here — this is
1700        // the raw promise constructor and its result is not `JsResult` — so the rejection is
1701        // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1702        // `prototype` getter therefore still gets a working promise; the alternative is a
1703        // panic, and the throwing path is covered by `Promise`'s own argument validation.
1704        let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1705        Self::make_promise_object(self.heap, proto)
1706    }
1707
1708    /// A promise object with an explicit prototype, and nothing else.
1709    ///
1710    /// Separate from [`Interp::new_promise`] for the callers that have to *report* an abrupt
1711    /// `Get(newTarget, "prototype")` — `new Promise(executor)` is specified as
1712    /// `OrdinaryCreateFromConstructor`, so a throwing `prototype` getter on `new.target` is an
1713    /// exception rather than a reason to fall back (`Promise/get-prototype-abrupt`).
1714    pub fn make_promise_object(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1715        let promise = JsObject::ordinary(heap, proto);
1716        promise.with_mut(|data| {
1717            data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1718                crate::object::PromiseState::default(),
1719            )));
1720        });
1721        promise
1722    }
1723
1724    /// Fulfil `promise`, unless it has already settled.
1725    ///
1726    /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1727    /// after `reject`, changes nothing.
1728    pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1729        let Some(state) = self.promise_state(promise) else {
1730            return;
1731        };
1732        let reactions = {
1733            let mut state = state.borrow_mut();
1734            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1735                return;
1736            }
1737            state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1738            std::mem::take(&mut state.reactions)
1739        };
1740        self.queue_reactions(reactions, value, false);
1741    }
1742
1743    /// Reject `promise`, unless it has already settled.
1744    pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1745        let Some(state) = self.promise_state(promise) else {
1746            return;
1747        };
1748        let reactions = {
1749            let mut state = state.borrow_mut();
1750            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1751                return;
1752            }
1753            state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1754            std::mem::take(&mut state.reactions)
1755        };
1756        // Remember it only when nothing is listening *now*; a `then` registered later
1757        // prunes the entry in `perform_then`.
1758        if reactions.is_empty() {
1759            self.unhandled.push((promise.clone(), reason.clone()));
1760        }
1761        self.queue_reactions(reactions, reason, true);
1762    }
1763
1764    /// Queue one job per reaction.
1765    ///
1766    /// This is what makes `then` asynchronous even on an already-settled promise:
1767    /// `p.then(f); g()` calls `g` first.
1768    fn queue_reactions(
1769        &mut self,
1770        reactions: Vec<crate::object::PromiseReaction>,
1771        argument: Value,
1772        rejected: bool,
1773    ) {
1774        for reaction in reactions {
1775            let handler = if rejected {
1776                reaction.on_rejected.clone()
1777            } else {
1778                reaction.on_fulfilled.clone()
1779            };
1780            self.jobs.push_back(Job::Reaction {
1781                handler,
1782                argument: argument.clone(),
1783                rejected,
1784                promise: reaction.promise,
1785            });
1786        }
1787    }
1788
1789    /// `NewPromiseCapability` as the executor receives it: the promise plus its
1790    /// resolve/reject pair.
1791    ///
1792    /// The pair are callable objects rather than Rust closures, because the script gets
1793    /// them and may stash them for later.
1794    pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1795        let promise = self.new_promise();
1796        // Both handlers are built-ins with an empty name and length 1, in
1797        // `length`-then-`name` order — `reject-function-property-order` reads the order back
1798        // off `Object.getOwnPropertyNames`.
1799        let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1800        let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1801        (promise, Value::Object(resolve), Value::Object(reject))
1802    }
1803
1804    /// §27.2.1.5 `NewPromiseCapability(C)`.
1805    ///
1806    /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1807    /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1808    /// decide what capability it hands back. That is the whole mechanism behind subclassing
1809    /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1810    /// silently ignored argument.
1811    ///
1812    /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1813    /// the engine's own executor is exactly what `new_promise_capability` builds.
1814    pub fn new_promise_capability_for(
1815        &mut self,
1816        constructor: &Value,
1817    ) -> JsResult<(Value, Value, Value)> {
1818        let Some(object) = constructor.as_object().cloned() else {
1819            return Err(self.type_error("promise constructor is not a constructor"));
1820        };
1821        if !object.is_constructor() {
1822            return Err(self.type_error("promise constructor is not a constructor"));
1823        }
1824        if self
1825            .realm
1826            .promise_constructor
1827            .as_ref()
1828            .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1829        {
1830            let (promise, resolve, reject) = self.new_promise_capability();
1831            return Ok((Value::Object(promise), resolve, reject));
1832        }
1833        let state = self.new_object(Some(self.realm.object_proto.clone()));
1834        // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1835        // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1836        // which only a *custom* constructor can observe, and none of the combinator tests
1837        // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1838        let executor = self.builtin_function(
1839            "",
1840            2,
1841            Callable::CapabilityExecutor {
1842                state: state.clone(),
1843            },
1844        );
1845        let promise = self.construct(
1846            Value::Object(object.clone()),
1847            Value::Object(object),
1848            vec![Value::Object(executor)],
1849        )?;
1850        // The pair is read *after* the constructor returns, so a constructor that never
1851        // called its executor, or called it with non-callables, is the spec's step 11
1852        // `TypeError` — not something the engine can paper over.
1853        let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1854            return Err(self.type_error("promise executor never ran"));
1855        };
1856        let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1857            return Err(self.type_error("promise executor never ran"));
1858        };
1859        for handler in [&resolve, &reject] {
1860            if !matches!(handler, Value::Object(object) if object.is_callable()) {
1861                return Err(self.type_error("promise capability handler is not callable"));
1862            }
1863        }
1864        Ok((promise, resolve, reject))
1865    }
1866
1867    /// §27.2.3.1 `PromiseResolve(C, x)`.
1868    ///
1869    /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1870    /// an `x` that is already a promise of exactly this constructor is handed back
1871    /// unchanged, and anything else gets a fresh capability from `C`.
1872    pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1873        if let Value::Object(object) = &value
1874            && self.promise_state(object).is_some()
1875        {
1876            // `x.constructor === C` means "already the right kind", so no capability is
1877            // built — which is observable through a `resolve` that counts its calls.
1878            let x_constructor = self.get_property(object, "constructor")?;
1879            let same = match (
1880                x_constructor.as_ref().and_then(Value::as_object),
1881                constructor.as_object(),
1882            ) {
1883                (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1884                _ => false,
1885            };
1886            if same {
1887                return Ok(value);
1888            }
1889        }
1890        let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1891        // §27.2.4.6 step 5: `? Call(resolve, undefined, «x»)` — an exception from a
1892        // *user* resolve function propagates (`resolve/capability-invocation-error`), while
1893        // the intrinsic one swallows its own self-resolution error.
1894        self.call_value(resolve, Value::Undefined, vec![value])?;
1895        Ok(promise)
1896    }
1897
1898    /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1899    /// promise, as `{ value: completion }`.
1900    ///
1901    /// The three cases are the reference's, and they differ on purpose:
1902    ///
1903    /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1904    ///   exception before any promise exists;
1905    /// * a **runtime** error rejects the returned promise;
1906    /// * success resolves it with `{ value }`, where the value is the script's completion
1907    ///   value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1908    ///   {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1909    ///   `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1910    ///   `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1911    ///
1912    /// # What this does not do
1913    ///
1914    /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1915    /// is evaluated in an async context, so `await` outside a function is legal. That needs
1916    /// the parser and the suspension machinery to accept a suspended top-level script, and
1917    /// is not implemented — such source is a syntax error here. Everything else about the
1918    /// flag is reproduced.
1919    pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1920        // The barrier goes up before compiling: a *parse* failure is reported with a trace
1921        // too, and the reference truncates that one at the same place as a runtime failure.
1922        if barrier {
1923            let depth = self.frames.len();
1924            self.trace_barriers.push(depth);
1925        }
1926        // Compiled before the promise exists, so a parse failure propagates as a throw
1927        // instead of being folded into a rejection.
1928        let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1929            Ok(compiled) => compiled,
1930            Err(error) => {
1931                if barrier {
1932                    self.trace_barriers.pop();
1933                }
1934                return Err(error);
1935            }
1936        };
1937        // An async body answers its own promise, and that promise is what the reference
1938        // hands back — the same object, not a wrapper around it. Its resolution value is
1939        // the `{value}` object the compiled epilogue built.
1940        if compiled.kind.is_async() {
1941            let strict = compiled.strict;
1942            let promise = self.run_eval_script(compiled, strict)?;
1943            if barrier {
1944                self.trace_barriers.pop();
1945            }
1946            return Ok(promise);
1947        }
1948        let (promise, resolve, reject) = self.new_promise_capability();
1949        let strict = compiled.strict;
1950        match self.run_eval_script(compiled, strict) {
1951            Ok(value) => {
1952                // `{ value }` is a plain object, so resolving with it adopts nothing even
1953                // when the completion value is itself a promise.
1954                let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1955                self.set_property(&wrapped, "value", value)?;
1956                self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1957            }
1958            Err(Signal::Throw(error)) => {
1959                self.call_value(reject, Value::Undefined, vec![error])?;
1960            }
1961            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1962        }
1963        if barrier {
1964            self.trace_barriers.pop();
1965        }
1966        Ok(Value::Object(promise))
1967    }
1968
1969    /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1970    ///
1971    /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1972    /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1973    /// timer table, where the collector already scans it.
1974    pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1975        let (promise, resolve, _reject) = self.new_promise_capability();
1976        let resolve = self.new_host_function(
1977            "resolve",
1978            1,
1979            Box::new(
1980                move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1981                    let value = args.first().cloned().unwrap_or(Value::Undefined);
1982                    interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1983                },
1984            ),
1985        );
1986        // The timer keeps the resolver alive: it is a property of the timer entry, and the
1987        // timer table is part of what the collector walks.
1988        self.schedule_timer(Value::Object(resolve), delay_ms);
1989        Ok(Value::Object(promise))
1990    }
1991
1992    /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1993    /// new promise resolved with it.
1994    pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1995        if let Value::Object(object) = &value
1996            && self.promise_state(object).is_some()
1997        {
1998            return Ok(value);
1999        }
2000        let promise = self.new_promise();
2001        self.resolve_promise_with(&promise, value)?;
2002        Ok(Value::Object(promise))
2003    }
2004
2005    /// §27.2.4.7 `PromiseResolve(%Promise%, value)`.
2006    ///
2007    /// The difference from [`Interp::promise_resolve_value`] is step 1.a: when `value` is
2008    /// already a promise, its **`constructor` is read**, and only if that is the intrinsic
2009    /// `%Promise%` is `value` returned unchanged. A getter placed on `constructor` is
2010    /// therefore observable — which is exactly what
2011    /// `AsyncGeneratorPrototype/return/return-*-broken-promise*.js` use to check that the
2012    /// `AsyncGeneratorAwaitReturn` path goes through `PromiseResolve` rather than a private
2013    /// shortcut.
2014    pub fn promise_resolve_intrinsic(&mut self, value: Value) -> JsResult<Value> {
2015        if let Value::Object(object) = &value
2016            && self.promise_state(object).is_some()
2017        {
2018            let constructor = self.get_property(object, "constructor")?;
2019            let same = match (&constructor, &self.realm.promise_constructor) {
2020                (Some(Value::Object(found)), Some(intrinsic)) => found.ptr_eq(intrinsic),
2021                _ => false,
2022            };
2023            if same {
2024                return Ok(value);
2025            }
2026        }
2027        let promise = self.new_promise();
2028        self.resolve_promise_with(&promise, value)?;
2029        Ok(Value::Object(promise))
2030    }
2031
2032    /// Claim `[[AlreadyResolved]]` for `promise`: `true` for the first caller, `false` after.
2033    ///
2034    /// The pair of resolving functions a promise hands to its executor shares this record, so
2035    /// whichever runs first wins and the other is a silent no-op. Promise *status* is not a
2036    /// substitute: resolving with a thenable leaves the promise `Pending` for a whole job.
2037    pub fn claim_resolution(&mut self, promise: &Gc<JsObject>) -> bool {
2038        let Some(state) = self.promise_state(promise) else {
2039            return true;
2040        };
2041        let mut state = state.borrow_mut();
2042        if state.resolved {
2043            return false;
2044        }
2045        state.resolved = true;
2046        true
2047    }
2048
2049    /// Clear `[[AlreadyResolved]]`, for the job that hands out a fresh pair.
2050    fn forget_resolution(&mut self, promise: &Gc<JsObject>) {
2051        let Some(state) = self.promise_state(promise) else {
2052            return;
2053        };
2054        state.borrow_mut().resolved = false;
2055    }
2056
2057    /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
2058    pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
2059        // Resolving a promise with itself is a `TypeError`. The check exists because the
2060        // alternative is a chain of self-reactions that never settles.
2061        if let Value::Object(object) = &value
2062            && object.ptr_eq(promise)
2063        {
2064            // The spec rejects *and* throws, so both the promise and the caller see it.
2065            let thrown = self.type_error("cannot resolve a promise with itself");
2066            let Signal::Throw(error) = thrown.clone() else {
2067                unreachable!("type_error always throws")
2068            };
2069            self.reject_promise(promise, error);
2070            return Err(thrown);
2071        }
2072        // §27.2.1.3.1 `NewPromiseResolveThenableJob` step 3: `Get(resolution, "then")` is a
2073        // `Completion`, and an abrupt one **rejects** the promise rather than throwing to
2074        // whoever resolved it — a poisoned `then` getter is the case every
2075        // `*-poisoned-then` test is written against.
2076        let then = match &value {
2077            Value::Object(object) => match self.get_property(object, "then") {
2078                Ok(then) => then,
2079                Err(signal) => {
2080                    if let Signal::Throw(reason) = signal {
2081                        self.reject_promise(promise, reason);
2082                        return Ok(());
2083                    }
2084                    return Err(signal);
2085                }
2086            },
2087            _ => None,
2088        };
2089        let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
2090        if !callable_then {
2091            // Not a thenable: a non-callable `then` makes the value fulfil as it is.
2092            self.fulfill_promise(promise, value);
2093            return Ok(());
2094        }
2095        // Adopting a thenable is asynchronous — `then` is called from a job, never from
2096        // inside `resolve`, so a script cannot make a promise settle synchronously.
2097        self.jobs.push_back(Job::Thenable {
2098            then: then.expect("checked callable"),
2099            value,
2100            promise: promise.clone(),
2101        });
2102        Ok(())
2103    }
2104
2105    /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
2106    ///
2107    /// `C.resolve` is user code and may answer a plain thenable rather than one of this
2108    /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
2109    ///
2110    /// The property read is **not** short-circuitable even for a real promise: the spec says
2111    /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
2112    /// expects it to run. Skipping the read for promises not only lost the throw, it made
2113    /// the combinator's loop infinite — the test's iterator never sets `done`.
2114    pub fn invoke_then(
2115        &mut self,
2116        thenable: Value,
2117        on_fulfilled: Value,
2118        on_rejected: Value,
2119    ) -> JsResult<()> {
2120        let then = match &thenable {
2121            Value::Object(object) => self.get_property(object, "then")?,
2122            primitive => {
2123                let boxed = self.object_from(primitive)?;
2124                self.get_property(&boxed, "then")?
2125            }
2126        };
2127        let Some(then) = then else {
2128            return Err(self.type_error("thenable has no then method"));
2129        };
2130        if !matches!(&then, Value::Object(object) if object.is_callable()) {
2131            return Err(self.type_error("then is not a function"));
2132        }
2133        self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
2134        Ok(())
2135    }
2136
2137    /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
2138    ///
2139    /// `Promise.prototype.then` in one step: register a reaction and answer the derived
2140    /// promise.
2141    pub fn perform_then(
2142        &mut self,
2143        promise: &Gc<JsObject>,
2144        on_fulfilled: Option<Value>,
2145        on_rejected: Option<Value>,
2146    ) -> JsResult<Value> {
2147        let Some(state) = self.promise_state(promise) else {
2148            return Err(self.type_error("not a promise"));
2149        };
2150        // Whether a rejection handler is being attached decides whether a recorded
2151        // rejection stops being unhandled, so it is read before the values are moved.
2152        let has_rejection_handler = on_rejected.is_some();
2153        let derived = self.new_promise();
2154        let reaction = crate::object::PromiseReaction {
2155            on_fulfilled,
2156            on_rejected,
2157            promise: derived.clone(),
2158        };
2159        let settled = {
2160            let mut state = state.borrow_mut();
2161            // A rejection somebody reacts to is no longer unhandled.
2162            state.handled = true;
2163            match &state.status {
2164                crate::object::PromiseStatus::Pending => {
2165                    state.reactions.push(reaction.clone());
2166                    None
2167                }
2168                crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2169                crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2170            }
2171        };
2172        // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2173        // later, means somebody is listening after all.
2174        if has_rejection_handler {
2175            self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2176        }
2177        if let Some((argument, rejected)) = settled {
2178            let handler = if rejected {
2179                reaction.on_rejected
2180            } else {
2181                reaction.on_fulfilled
2182            };
2183            self.jobs.push_back(Job::Reaction {
2184                handler,
2185                argument,
2186                rejected,
2187                promise: reaction.promise,
2188            });
2189        }
2190        Ok(Value::Object(derived))
2191    }
2192
2193    /// The rejections nobody listened to, formatted the way the reference reports them.
2194    ///
2195    /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2196    /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2197    /// unhandled at the point the queue drains, because a `then` may still be attached
2198    /// before the host acts on it.
2199    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2200        let entries = std::mem::take(&mut self.unhandled);
2201        // Somebody may have attached a handler after the rejection was recorded, so the
2202        // promise is the authority rather than the list.
2203        let still_unhandled: Vec<Value> = entries
2204            .into_iter()
2205            .filter_map(|(promise, reason)| {
2206                let handled = self
2207                    .promise_state(&promise)
2208                    .map(|state| state.borrow().handled)
2209                    .unwrap_or(true);
2210                (!handled).then_some(reason)
2211            })
2212            .collect();
2213        still_unhandled
2214            .into_iter()
2215            .map(|reason| {
2216                let text = self.describe_exception(&reason);
2217                let stack = match &reason {
2218                    Value::Object(object) => self
2219                        .get_property(object, "stack")
2220                        .ok()
2221                        .flatten()
2222                        .map(|value| value.to_js_string())
2223                        // `stack` carries a trailing newline of its own, which would leave
2224                        // a blank line between two reported rejections.
2225                        .map(|text| text.trim_end().to_string())
2226                        .unwrap_or_default(),
2227                    _ => String::new(),
2228                };
2229                if stack.is_empty() {
2230                    format!("Possibly unhandled promise rejection: {text}")
2231                } else {
2232                    format!("Possibly unhandled promise rejection: {text}\n{stack}")
2233                }
2234            })
2235            .collect()
2236    }
2237
2238    /// Run the microtask queue to exhaustion.
2239    ///
2240    /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2241    /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2242    /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2243    ///
2244    /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2245    /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2246    /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2247    pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2248        crate::builtins::json::parse_text(self, text, true)
2249    }
2250
2251    /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2252    ///
2253    /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2254    /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2255    /// immediately, and `setTimeout(f, -1)` is ordinary code.
2256    ///
2257    /// The callback is called with **no arguments**. The reference stores only the function
2258    /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2259    /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2260    /// extra arguments arrive as `undefined`.
2261    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2262        let id = self.next_timer_id;
2263        // Wrap rather than grow: the id reaches the script as an `Int32`.
2264        self.next_timer_id = if self.next_timer_id == i32::MAX {
2265            1
2266        } else {
2267            self.next_timer_id + 1
2268        };
2269        let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2270        self.tasks.push(Task::Timer {
2271            id,
2272            callback,
2273            due_at,
2274        });
2275        id
2276    }
2277
2278    /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2279    /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2280    pub fn cancel_timer(&mut self, id: i32) -> bool {
2281        let before = self.tasks.len();
2282        self.tasks.retain(|task| match task {
2283            Task::Timer { id: task_id, .. } => *task_id != id,
2284        });
2285        self.tasks.len() != before
2286    }
2287
2288    /// How long until the earliest pending timer, or `None` when none is pending.
2289    pub fn next_timeout(&self) -> Option<std::time::Duration> {
2290        let now = std::time::Instant::now();
2291        self.tasks
2292            .iter()
2293            .map(|task| match task {
2294                Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2295            })
2296            .min()
2297    }
2298
2299    /// Run one turn of the event loop.
2300    ///
2301    /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2302    /// run at most one due timer, then drain again. The blocking belongs to the caller
2303    /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2304    /// is how it asks.
2305    ///
2306    /// One timer per turn rather than all of them: a timer callback may schedule another
2307    /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2308    /// starve the microtask queue.
2309    pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2310        self.drain_jobs()?;
2311        let now = std::time::Instant::now();
2312        // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2313        // followed by `setTimeout(g, 1)` must run `g` first.
2314        let due = self
2315            .tasks
2316            .iter()
2317            .enumerate()
2318            .filter(|(_, task)| match task {
2319                Task::Timer { due_at, .. } => *due_at <= now,
2320            })
2321            .min_by_key(|(_, task)| match task {
2322                Task::Timer { due_at, .. } => *due_at,
2323            })
2324            .map(|(index, _)| index);
2325        let Some(index) = due else {
2326            // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2327            // descriptor is registered but no timer is closer, so a script that never
2328            // touches the descriptor still gets control back. Without a cap a handler on a
2329            // descriptor that is never ready would block for as long as the host allows.
2330            let timeout = self
2331                .next_timeout()
2332                .unwrap_or(std::time::Duration::from_secs(10))
2333                .min(std::time::Duration::from_secs(10));
2334            if !self.fd_handlers.is_empty() {
2335                // Blocking on a timer while descriptors are registered would starve them,
2336                // and blocking on the descriptors while a timer is due would delay it; the
2337                // host polls with the earlier of the two deadlines, which this timeout is.
2338                return Ok(Turn::Poll(timeout));
2339            }
2340            return Ok(match self.next_timeout() {
2341                Some(wait) => Turn::Wait(wait),
2342                None => Turn::Done,
2343            });
2344        };
2345        let Task::Timer { callback, .. } = self.tasks.remove(index);
2346        let this = Value::Undefined;
2347        // A throwing timer callback must not stop the loop: the reference reports it and
2348        // keeps going, because the alternative is that one bad timer silently stops every
2349        // later one.
2350        // No arguments: see `schedule_timer` — the reference calls the callback bare.
2351        match self.call_value(callback, this, Vec::new()) {
2352            Ok(_) => {}
2353            Err(Signal::Throw(value)) => {
2354                let text = self.describe_exception(&value);
2355                self.timer_errors.push(text);
2356            }
2357            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2358        }
2359        self.drain_jobs()?;
2360        Ok(Turn::Ran)
2361    }
2362
2363    /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2364    ///
2365    /// `callback` of `None` unregisters that direction, and an entry with neither direction
2366    /// left is removed — the reference does the same, so a script can rely on
2367    /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2368    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2369        let entry = self.fd_handlers.entry(fd).or_default();
2370        if readable {
2371            entry.read = callback;
2372        } else {
2373            entry.write = callback;
2374        }
2375        if entry.read.is_none() && entry.write.is_none() {
2376            self.fd_handlers.remove(&fd);
2377        }
2378    }
2379
2380    /// Register or clear an `os.signal` handler.
2381    ///
2382    /// `None` removes it; the host separately restores the default disposition or sets
2383    /// ignore, because which of those happened is the script's choice (`null` versus
2384    /// `undefined`) and not something this table can express.
2385    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2386        match handler {
2387            Some(handler) => {
2388                self.signal_handlers.insert(signal, handler);
2389            }
2390            None => {
2391                self.signal_handlers.remove(&signal);
2392            }
2393        }
2394    }
2395
2396    /// Run the handler for `signal`, reporting whether one ran.
2397    ///
2398    /// A throwing handler is reported and the loop continues, like a timer's.
2399    pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2400        let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2401            return Ok(false);
2402        };
2403        match self.call_value(handler, Value::Undefined, Vec::new()) {
2404            Ok(_) => {}
2405            Err(Signal::Throw(value)) => {
2406                let text = self.describe_exception(&value);
2407                self.timer_errors.push(text);
2408            }
2409            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2410        }
2411        self.drain_jobs()?;
2412        Ok(true)
2413    }
2414
2415    /// The descriptors the host has to poll, and in which direction.
2416    ///
2417    /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2418    /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2419    /// `os_poll` asks for.
2420    pub fn pending_fds(&self) -> Vec<FdInterest> {
2421        self.fd_handlers
2422            .iter()
2423            .map(|(fd, entry)| FdInterest {
2424                fd: *fd,
2425                read: entry.read.is_some(),
2426                write: entry.write.is_some(),
2427            })
2428            .collect()
2429    }
2430
2431    /// Call the handler registered for `fd`, reporting whether one ran.
2432    ///
2433    /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2434    /// poll iteration and then restarts the loop, because the handler may have changed the
2435    /// registration list underneath it; doing the same here keeps a handler that
2436    /// unregisters itself from being called with stale state.
2437    ///
2438    /// A throwing handler is reported and the loop continues — a bad handler must not stop
2439    /// every later one, exactly as with timers.
2440    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2441        let Some(entry) = self.fd_handlers.get(&fd) else {
2442            return Ok(false);
2443        };
2444        let callback = if readable {
2445            entry.read.clone()
2446        } else if writable {
2447            entry.write.clone()
2448        } else {
2449            None
2450        };
2451        let Some(callback) = callback else {
2452            return Ok(false);
2453        };
2454        self.drain_jobs()?;
2455        match self.call_value(callback, Value::Undefined, Vec::new()) {
2456            Ok(_) => {}
2457            Err(Signal::Throw(value)) => {
2458                let text = self.describe_exception(&value);
2459                self.timer_errors.push(text);
2460            }
2461            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2462        }
2463        self.drain_jobs()?;
2464        Ok(true)
2465    }
2466
2467    /// Take the errors timer callbacks threw, leaving the list empty.
2468    pub fn take_timer_errors(&mut self) -> Vec<String> {
2469        std::mem::take(&mut self.timer_errors)
2470    }
2471
2472    /// Whether anything is still pending: a microtask or a timer.
2473    pub fn has_pending_work(&self) -> bool {
2474        !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2475    }
2476
2477    /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2478    pub fn has_pending_timers_or_jobs(&self) -> bool {
2479        !self.jobs.is_empty() || !self.tasks.is_empty()
2480    }
2481
2482    /// Run every queued microtask, including ones queued while draining.
2483    pub fn drain_jobs(&mut self) -> JsResult<()> {
2484        // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2485        // would spin forever, so the drain is bounded the way the call stack is.
2486        let mut budget = 1_000_000usize;
2487        while let Some(job) = self.jobs.pop_front() {
2488            if budget == 0 {
2489                return Err(Signal::Throw(
2490                    self.make_error("InternalError", "promise job queue did not drain"),
2491                ));
2492            }
2493            budget -= 1;
2494            self.run_job(job)?;
2495            // `FinalizationRegistry` at the job boundary: this is the safe point where the
2496            // engine may run script that the script itself did not ask for. Doing it here
2497            // rather than from a drop hook is what keeps the callback out of arbitrary
2498            // engine bookkeeping — see `builtins::weak`'s header.
2499            crate::builtins::weak::drain_finalizers(self)?;
2500        }
2501        // A script that queued no jobs may still have dropped targets, so the checkpoint
2502        // runs once more after the queue empties.
2503        crate::builtins::weak::drain_finalizers(self)?;
2504        Ok(())
2505    }
2506
2507    /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2508    ///
2509    /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2510    /// `None` and is swept out here. This is also where the realm learns that a registry
2511    /// died, which is why it is a mutation rather than a read.
2512    pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2513        let handles = std::mem::take(&mut self.realm.finalization_registries);
2514        let mut live = Vec::with_capacity(handles.len());
2515        for handle in handles {
2516            let Some(object) = handle.upgrade() else {
2517                continue;
2518            };
2519            let Some(state) = object.finalization_state() else {
2520                continue;
2521            };
2522            live.push((object.clone(), *state));
2523            self.realm.finalization_registries.push(object.downgrade());
2524        }
2525        live
2526    }
2527
2528    /// Run one microtask.
2529    fn run_job(&mut self, job: Job) -> JsResult<()> {
2530        match job {
2531            Job::Reaction {
2532                handler: None,
2533                argument,
2534                rejected,
2535                promise,
2536            } => {
2537                // No handler: the settlement passes straight through to the derived
2538                // promise, which is why `p.catch(f)` ignores fulfilments.
2539                if rejected {
2540                    self.reject_promise(&promise, argument);
2541                } else {
2542                    self.fulfill_promise(&promise, argument);
2543                }
2544                Ok(())
2545            }
2546            Job::Reaction {
2547                handler: Some(handler),
2548                argument,
2549                promise,
2550                ..
2551            } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2552                Ok(answer) => {
2553                    if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2554                        self.reject_promise(&promise, error);
2555                    }
2556                    Ok(())
2557                }
2558                Err(Signal::Throw(reason)) => {
2559                    self.reject_promise(&promise, reason);
2560                    Ok(())
2561                }
2562                Err(other) => Err(other),
2563            },
2564            Job::Thenable {
2565                then,
2566                value,
2567                promise,
2568            } => {
2569                // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2570                // the value it produces settles `promise`.
2571                // The thenable's `then` gets this promise's own pair, so whatever it
2572                // produces settles `promise`.
2573                // `length: 1`, `name: ""` — a resolve/reject function is a
2574                // `%Promise.prototype.then%`-style pair, not a bare native. Building them
2575                // with `JsObject::function` left `length` at 0, which a test reads straight
2576                // off the function (`finally/resolved-observable-then-calls-argument`
2577                // requires `resolve.length === 1` for the pair handed to a thenable).
2578                let resolve =
2579                    self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
2580                let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
2581                // §27.2.2.2 step 1: the job builds a **fresh** pair of resolving functions,
2582                // so the one-shot record starts over. Without the reset the pair above was
2583                // already spent by the `resolve` that queued this job, and a thenable that
2584                // calls `reject` left the promise pending forever
2585                // (`Promise/all/reject-immed`).
2586                self.forget_resolution(&promise);
2587                let reject = Value::Object(reject);
2588                match self.call_value(then, value, vec![Value::Object(resolve), reject.clone()]) {
2589                    Ok(_) => Ok(()),
2590                    // Step 3.a is `Call(resolvingFunctions.[[Reject]], …)` — **through** the
2591                    // reject function, whose one-shot record makes this a no-op once `then`
2592                    // has already resolved the promise
2593                    // (`exception-after-resolve-in-thenable-job`).
2594                    Err(Signal::Throw(reason)) => {
2595                        self.call_value(reject, Value::Undefined, vec![reason])?;
2596                        Ok(())
2597                    }
2598                    Err(other) => Err(other),
2599                }
2600            }
2601            Job::Resume {
2602                coroutine,
2603                promise,
2604                kind,
2605                value,
2606            } => self.drive_async(&coroutine, &promise, kind, value),
2607            Job::GeneratorResume {
2608                generator,
2609                promise,
2610                kind,
2611                value,
2612            } => self.step_async_generator(&generator, &promise, kind, value),
2613            Job::Import {
2614                specifier,
2615                referrer,
2616                promise,
2617            } => {
2618                self.run_dynamic_import(&specifier, &referrer, &promise);
2619                Ok(())
2620            }
2621        }
2622    }
2623
2624    /// One element of a `Promise` combinator settled.
2625    ///
2626    /// The shared state object holds the result array, the number still outstanding, and
2627    /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2628    /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2629    /// to settle, only whatever `Sub` said a capability is.
2630    ///
2631    /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2632    /// and `any` must ignore every later settlement, and `all` must not report a second
2633    /// rejection after the first.
2634    fn settle_combinator(
2635        &mut self,
2636        state: &Gc<JsObject>,
2637        index: usize,
2638        fulfilled: bool,
2639        value: Value,
2640    ) -> JsResult<()> {
2641        let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2642        // Each element settles at most once: a thenable may call `onFulfilled` twice
2643        // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2644        // call a no-op. Without it the second call decremented `remaining` again and settled
2645        // `all` with a short values array (`call-resolve-element-items`).
2646        let done = field("done");
2647        let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2648        let settled = field("settled").is_some_and(|value| value.to_boolean());
2649        if settled {
2650            return Ok(());
2651        }
2652        if let Some(Value::Object(done)) = &done {
2653            if done
2654                .array_get(index)
2655                .is_some_and(|value| value.to_boolean())
2656            {
2657                return Ok(());
2658            }
2659            done.array_set(self.heap, index, Value::Bool(true));
2660        }
2661        let resolve = field("resolve");
2662        let reject = field("reject");
2663        let keys = field("keys");
2664        let results = field("results").and_then(|value| value.as_object().cloned());
2665        // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2666        // promise: the handler is a plain function the constructor chose.
2667        let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2668            if let Some(handler) = handler {
2669                interp.call_value(handler, Value::Undefined, vec![value])?;
2670            }
2671            Ok(())
2672        };
2673        match kind {
2674            // `race`: the first settlement wins and stops the rest.
2675            3 => {
2676                state.define_data("settled", Value::Bool(true));
2677                let handler = if fulfilled { resolve } else { reject };
2678                settle_with(self, handler, value)?;
2679                return Ok(());
2680            }
2681            // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2682            // the first rejection wins outright.
2683            0 | 4 if !fulfilled => {
2684                state.define_data("settled", Value::Bool(true));
2685                settle_with(self, reject, value)?;
2686                return Ok(());
2687            }
2688            // `any`: the first fulfilment wins.
2689            2 if fulfilled => {
2690                state.define_data("settled", Value::Bool(true));
2691                settle_with(self, resolve, value)?;
2692                return Ok(());
2693            }
2694            _ => {}
2695        }
2696        let Some(results) = &results else {
2697            return Ok(());
2698        };
2699        match kind {
2700            4 => {
2701                results.array_set(self.heap, index, value);
2702            }
2703            0 => {
2704                results.array_set(self.heap, index, value);
2705            }
2706            // `allSettled` (and its keyed twin) never rejects; each slot records what
2707            // happened.
2708            1 | 5 => {
2709                let record = self.new_object(Some(self.realm.object_proto.clone()));
2710                if fulfilled {
2711                    record.define_data("status", self.string("fulfilled"));
2712                    record.define_data("value", value);
2713                } else {
2714                    record.define_data("status", self.string("rejected"));
2715                    record.define_data("reason", value);
2716                }
2717                results.array_set(self.heap, index, Value::Object(record));
2718            }
2719            // `any`: a rejection is parked in the errors array and the sweep continues.
2720            2 => {
2721                results.array_set(self.heap, index, value);
2722            }
2723            _ => {}
2724        }
2725        let remaining = field("remaining")
2726            .map(|value| value.to_int32())
2727            .unwrap_or(0);
2728        let left = remaining - 1;
2729        state.define_data("remaining", Value::Int(left));
2730        if left != 0 {
2731            return Ok(());
2732        }
2733        state.define_data("settled", Value::Bool(true));
2734        match kind {
2735            0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2736            // The keyed result: an ordinary object with a **null** prototype, holding the
2737            // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2738            4 | 5 => {
2739                let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2740                settle_with(self, resolve, keyed)?;
2741            }
2742            2 => {
2743                // The rejection is an `AggregateError` whose `errors` is the results array
2744                // itself — the slots are the reasons, in input order.
2745                let errors = results.array_elements().unwrap_or_default();
2746                let error = self.aggregate_error(errors, "all promises were rejected");
2747                settle_with(self, reject, error)?;
2748            }
2749            _ => {}
2750        }
2751        Ok(())
2752    }
2753
2754    /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2755    ///
2756    /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2757    /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2758    /// prototype is load-bearing in both directions: a key called `toString` must not
2759    /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2760    /// (`resolves-empty-object.js`).
2761    pub(crate) fn keyed_result_object(
2762        &mut self,
2763        keys: Option<&Value>,
2764        values: &Gc<JsObject>,
2765    ) -> JsResult<Value> {
2766        let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2767            return Ok(Value::Object(self.new_object(None)));
2768        };
2769        let result = self.new_object(None);
2770        let count = values.array_length().unwrap_or(0);
2771        for index in 0..count {
2772            let Some(key) = keys.array_get(index) else {
2773                continue;
2774            };
2775            let Some(value) = values.array_get(index) else {
2776                continue;
2777            };
2778            let property = Property::with_attributes(value, true, true);
2779            match &key {
2780                Value::Symbol(symbol) => {
2781                    result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2782                }
2783                other => {
2784                    let text = self.to_js_string(other)?;
2785                    result.define_key(&PropertyKey::from(text.as_str()), property);
2786                }
2787            }
2788        }
2789        Ok(Value::Object(result))
2790    }
2791
2792    /// Build an async function's result: a promise whose body runs as a coroutine.
2793    pub fn new_async_function(
2794        &mut self,
2795        function: Value,
2796        this: Value,
2797        args: Vec<Value>,
2798    ) -> JsResult<Value> {
2799        let promise = self.new_promise();
2800        let coroutine = self.new_coroutine(function, this, args)?;
2801        if let Err(Signal::Throw(reason)) =
2802            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2803        {
2804            self.reject_promise(&promise, reason);
2805        }
2806        Ok(Value::Object(promise))
2807    }
2808
2809    /// The coroutine an async body runs in.
2810    ///
2811    /// Generator-shaped and never exposed to the script: what makes `await` work is the
2812    /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2813    /// than growing a second state machine. The difference is only in the ending — a
2814    /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2815    /// Run `code` as an async function body, answering the promise it settles.
2816    ///
2817    /// Used for a module with top-level `await`: its body is an async function whose
2818    /// caller is the host, so there is no function object to pass through
2819    /// [`Interp::new_async_function`].
2820    pub fn run_async_body(
2821        &mut self,
2822        code: Gc<CompiledCode>,
2823        env: Gc<ClosureEnv>,
2824        this: Value,
2825    ) -> JsResult<Value> {
2826        let promise = self.new_promise();
2827        let coroutine = self.new_coroutine_from(code, env, this, Vec::new(), Value::Undefined)?;
2828        if let Err(Signal::Throw(reason)) =
2829            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2830        {
2831            self.reject_promise(&promise, reason);
2832        }
2833        Ok(Value::Object(promise))
2834    }
2835
2836    fn new_coroutine(
2837        &mut self,
2838        function: Value,
2839        this: Value,
2840        args: Vec<Value>,
2841    ) -> JsResult<Gc<JsObject>> {
2842        let Some(object) = function.as_object().cloned() else {
2843            return Err(self.type_error("not a function"));
2844        };
2845        let Some((code, env)) = bytecode_of(&object) else {
2846            return Err(self.type_error("not a function"));
2847        };
2848        self.new_coroutine_from(code, env, this, args, function)
2849    }
2850
2851    /// Build a coroutine over an already-resolved body.
2852    ///
2853    /// `callee` is the function object the body belongs to, or `undefined` when there is
2854    /// none — a module with top-level `await`. It has to be handed over rather than
2855    /// defaulted: the frame's callee is what `special_object 2` answers, and an async
2856    /// function's body uses that to initialise its own-name binding. Passing `undefined`
2857    /// made `var f = async function Binding(){ return typeof Binding }` answer
2858    /// `"undefined"`, so a named async function expression could not see its own name and
2859    /// `Binding = 1` inside it silently succeeded (`named-reassign-fn-name-in-body`).
2860    fn new_coroutine_from(
2861        &mut self,
2862        code: Gc<CompiledCode>,
2863        env: Gc<ClosureEnv>,
2864        this: Value,
2865        args: Vec<Value>,
2866        callee: Value,
2867    ) -> JsResult<Gc<JsObject>> {
2868        self.push_frame(code, env, this, args, callee)?;
2869        let frame = self.frames.pop().expect("push_frame just pushed it");
2870        let state = GeneratorState {
2871            frame: Some(frame),
2872            phase: GeneratorPhase::SuspendedStart,
2873            parked_on_await: false,
2874            parked_on_yield_star: false,
2875            requests: std::collections::VecDeque::new(),
2876            async_busy: false,
2877            // An `async function` body is driven by `drive_async`, never by the generator
2878            // protocol, and the object is not reachable from script.
2879            is_async: false,
2880        };
2881        let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2882        coroutine.with_mut(|data| {
2883            data.kind = ObjectKind::Generator(Box::new(state));
2884        });
2885        Ok(coroutine)
2886    }
2887
2888    /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2889    /// `await` and `value` is what it awaited.
2890    fn resume_coroutine(
2891        &mut self,
2892        coroutine: &Gc<JsObject>,
2893        kind: ResumeKind,
2894        value: Value,
2895    ) -> JsResult<(Value, bool)> {
2896        let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2897            ObjectKind::Generator(state) => {
2898                let is_async = state.is_async;
2899                Some(std::mem::replace(
2900                    state.as_mut(),
2901                    GeneratorState {
2902                        frame: None,
2903                        phase: GeneratorPhase::Executing,
2904                        parked_on_await: false,
2905                        parked_on_yield_star: false,
2906                        requests: std::collections::VecDeque::new(),
2907                        async_busy: false,
2908                        is_async,
2909                    },
2910                ))
2911            }
2912            _ => None,
2913        }) else {
2914            return Err(self.type_error("not a coroutine"));
2915        };
2916        let result = self.step_generator(&mut state, kind, value);
2917        coroutine.with_mut(|data| {
2918            data.kind = ObjectKind::Generator(Box::new(state));
2919        });
2920        let (value, done, _ready, _reason) = result?;
2921        Ok((value, done))
2922    }
2923
2924    /// Advance an async body and settle its promise with the outcome.
2925    fn drive_async(
2926        &mut self,
2927        coroutine: &Gc<JsObject>,
2928        promise: &Gc<JsObject>,
2929        kind: ResumeKind,
2930        value: Value,
2931    ) -> JsResult<()> {
2932        match self.resume_coroutine(coroutine, kind, value) {
2933            Ok((value, true)) => {
2934                // `Ok` with `done` means the body finished *normally*, even when it was
2935                // resumed by a `throw` — `try { await p } catch {}` completes by
2936                // returning. Only the `Err` arm below is a rejection.
2937                //
2938                // Resolving rather than fulfilling matters: `return promise` in an async
2939                // body adopts the inner promise, so `async function f(){ return
2940                // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2941                // promise.
2942                if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2943                    self.reject_promise(promise, reason);
2944                }
2945                Ok(())
2946            }
2947            Ok((value, false)) => {
2948                // Parked on `await`: follow what it awaited and resume with the outcome.
2949                let awaited = match self.promise_resolve_value(value) {
2950                    Ok(awaited) => awaited,
2951                    Err(Signal::Throw(error)) => {
2952                        self.reject_promise(promise, error);
2953                        return Ok(());
2954                    }
2955                    Err(other) => return Err(other),
2956                };
2957                self.hook_await(awaited, coroutine, promise)
2958            }
2959            Err(Signal::Throw(reason)) => {
2960                self.reject_promise(promise, reason);
2961                Ok(())
2962            }
2963            Err(other) => Err(other),
2964        }
2965    }
2966
2967    /// Arrange for `coroutine` to resume when `awaited` settles.
2968    fn hook_await(
2969        &mut self,
2970        awaited: Value,
2971        coroutine: &Gc<JsObject>,
2972        promise: &Gc<JsObject>,
2973    ) -> JsResult<()> {
2974        let resumed = JsObject::function(
2975            self.heap,
2976            Some(self.realm.function_proto.clone()),
2977            Callable::AwaitResume {
2978                coroutine: coroutine.clone(),
2979                promise: promise.clone(),
2980                kind: ResumeKind::Next,
2981            },
2982        );
2983        let raised = JsObject::function(
2984            self.heap,
2985            Some(self.realm.function_proto.clone()),
2986            Callable::AwaitResume {
2987                coroutine: coroutine.clone(),
2988                promise: promise.clone(),
2989                kind: ResumeKind::Throw,
2990            },
2991        );
2992        // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2993        // guarantees one; the fallback keeps a mis-shaped value from panicking.
2994        let Value::Object(awaited) = &awaited else {
2995            self.jobs.push_back(Job::Resume {
2996                coroutine: coroutine.clone(),
2997                promise: promise.clone(),
2998                kind: ResumeKind::Next,
2999                value: awaited,
3000            });
3001            return Ok(());
3002        };
3003        self.perform_then(
3004            awaited,
3005            Some(Value::Object(resumed)),
3006            Some(Value::Object(raised)),
3007        )?;
3008        Ok(())
3009    }
3010
3011    /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
3012    /// things an engine keeps outside it — array elements and an array's `length`.
3013    fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
3014        if let Some(property) = object.own_property_key(key) {
3015            return Some(property);
3016        }
3017        // A typed array's indices are bytes in its buffer, so a descriptor for one has to
3018        // be synthesized too — and every one of them is a plain writable, enumerable,
3019        // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
3020        // `undefined` before this, which made `key-is-numericindex` fail on its own
3021        // side effect check.
3022        //
3023        // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
3024        // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
3025        // likewise not elements however numeric they look.
3026        if object.typed_array_element_type().is_some()
3027            && let Some(numeric) = canonical_numeric_index(key)
3028            && numeric.is_finite()
3029            && numeric.fract() == 0.0
3030            && !(numeric == 0.0 && numeric.is_sign_negative())
3031            && numeric >= 0.0
3032            && (numeric as usize) < object.typed_array_length().unwrap_or(0)
3033        {
3034            let value = object.typed_array_element(numeric as usize)?;
3035            return Some(Property::data(value));
3036        }
3037        // An array's elements live in their own vector rather than the property table, so
3038        // a descriptor for one has to be synthesized — with the attributes an element has.
3039        if let Some(index) = key.as_str().and_then(array_index)
3040            && let Some(value) = object.array_get(index as usize)
3041            && !matches!(value, Value::Hole)
3042        {
3043            return Some(Property::data(value));
3044        }
3045        // `length` is an own property of an array that is not in its property table
3046        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
3047        // and non-enumerable.
3048        if key.as_str() == Some("length")
3049            && let Some(length) = object.array_length()
3050        {
3051            return Some(Property {
3052                value: Some(crate::object::length_value(length)),
3053                writable: object.length_writable(),
3054                enumerable: false,
3055                configurable: false,
3056                getter: None,
3057                setter: None,
3058                descriptor_fields: None,
3059            });
3060        }
3061        None
3062    }
3063
3064    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
3065    pub fn object_get_own_property(
3066        &mut self,
3067        object: &Gc<JsObject>,
3068        key: &PropertyKey,
3069    ) -> JsResult<Option<Property>> {
3070        if let Some(answer) = self.proxy_get_own_property(object, key)? {
3071            return Ok(answer);
3072        }
3073        if let Some(exotic) = object.exotic()
3074            && let Some(answer) = exotic.get_own_property(self, object, key)?
3075        {
3076            return Ok(answer);
3077        }
3078        // A module namespace's bindings are accessors internally and data properties to
3079        // script; see `namespace_own_property`.
3080        if object.module_namespace_marker() {
3081            return self.namespace_own_property(object, key);
3082        }
3083        // A mapped `arguments` index is a data property as far as script can see: the
3084        // accessor pair that aliases the parameter is plumbing, and exposing it would
3085        // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
3086        // report a `get` where the spec has a `[[Value]]`.
3087        if let Some(index) = key.as_str().and_then(crate::object::array_index)
3088            && let Some(cell) = object.mapped_argument_cell(index as usize)
3089        {
3090            // Non-configurable is *not* the default: an ordinary mapped index is
3091            // configurable, and only becomes non-configurable once something
3092            // redefines it. Preserve whatever the property table currently says.
3093            // The attributes come from whatever the property table holds, because they
3094            // can be changed independently of the mapping; only the *value* and the
3095            // data-property *kind* are the accessor's secret.
3096            let flags = Self::ordinary_own_property(object, key);
3097            if let Some(existing) = &flags
3098                && !existing.is_accessor()
3099            {
3100                // Already demapped: the table entry is the answer, not the cell.
3101                return Ok(flags);
3102            }
3103            return Ok(Some(Property {
3104                value: Some(cell.get()),
3105                writable: true,
3106                enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
3107                configurable: flags.as_ref().is_some_and(|p| p.configurable),
3108                ..Property::default()
3109            }));
3110        }
3111        Ok(Self::ordinary_own_property(object, key))
3112    }
3113
3114    /// Whether `object` is a module namespace exotic object (§10.4.6).
3115    ///
3116    /// Recognised by shape rather than by a flag: a namespace is the only object whose
3117    /// properties are all accessors over a `ModuleBinding` cell. That is the same
3118    /// identification `Set`/`Add` membership tests use on function objects, and it keeps the
3119    /// distinction in one place instead of adding a boolean every constructor has to
3120    /// remember to set.
3121    pub fn is_module_namespace(&self, object: &Gc<JsObject>) -> bool {
3122        object.module_namespace_marker()
3123    }
3124
3125    /// `[[GetOwnProperty]]` for a module namespace exotic object.
3126    ///
3127    /// The bindings are stored as getters — that is the only way a live binding can be read
3128    /// through the namespace — but §10.4.6.5 says the *observable* descriptor is a data
3129    /// descriptor:
3130    ///
3131    /// ```text
3132    /// { [[Value]]: current value, [[Writable]]: true,
3133    ///   [[Enumerable]]: true, [[Configurable]]: false }
3134    /// ```
3135    ///
3136    /// So `Object.getOwnPropertyDescriptor(ns, "x").writable` is `true`, and `.get` is
3137    /// `undefined`. Reporting the accessor instead — which is what the property table holds
3138    /// — made every one of test262's namespace descriptor assertions fail, in both the
3139    /// `await-ns-*` and `promise-then-ns-*` families.
3140    ///
3141    /// `[[Configurable]]: false` is why `Reflect.defineProperty(ns, "x", {value: 1})` answers
3142    /// `true` only when the new value is `SameValue` the current one (`await-ns-define-own-
3143    /// property`); the ordinary descriptor machinery derives that from these attributes.
3144    pub fn namespace_own_property(
3145        &mut self,
3146        object: &Gc<JsObject>,
3147        key: &PropertyKey,
3148    ) -> JsResult<Option<Property>> {
3149        let Some(stored) = Self::ordinary_own_property(object, key) else {
3150            return Ok(None);
3151        };
3152        let Some(Property {
3153            getter: Some(getter),
3154            ..
3155        }) = Some(&stored)
3156        else {
3157            return Ok(Some(stored));
3158        };
3159        // Reading the binding is what a namespace `[[Get]]` does, and it can run script
3160        // (`export let x` assigned by a getter elsewhere), so the value is materialised here
3161        // rather than stored.
3162        let value = self.call_value(getter.clone(), Value::Object(object.clone()), Vec::new())?;
3163        Ok(Some(Property {
3164            value: Some(value),
3165            writable: true,
3166            enumerable: true,
3167            configurable: false,
3168            ..Property::default()
3169        }))
3170    }
3171
3172    /// `[[DefineOwnProperty]]` for a module namespace exotic object (§10.4.6.6).
3173    ///
3174    /// Modelled as "does this descriptor describe the property that is already there?",
3175    /// because a namespace property's attributes are fixed and its value cannot be changed
3176    /// through the namespace. The three ways to succeed:
3177    ///
3178    /// * a descriptor that names no field at all (`Reflect.defineProperty(ns, k, {})`);
3179    /// * one whose `[[Value]]` is `SameValue` the current binding value;
3180    /// * one whose attribute fields all restate `{writable: true, enumerable: true,
3181    ///   configurable: false}`.
3182    ///
3183    /// `@@toStringTag` is a real own property of the namespace (a data property, writable
3184    /// false), so it goes through the same check against its stored value — which is what
3185    /// makes `{value: "Module", writable: false, enumerable: false, configurable: false}`
3186    /// answer `true` while `{value: "Other"}` answers `false`.
3187    fn namespace_define_own_property(
3188        &mut self,
3189        object: &Gc<JsObject>,
3190        key: &PropertyKey,
3191        property: &Property,
3192    ) -> JsResult<bool> {
3193        let Some(current) = self.namespace_own_property(object, key)? else {
3194            // A name the namespace does not export cannot be added to it.
3195            return Ok(false);
3196        };
3197        if let Some(value) = &property.value {
3198            let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3199            if !self.same_value(value, current_value)? {
3200                return Ok(false);
3201            }
3202        }
3203        Ok(true)
3204    }
3205
3206    /// `[[DefineOwnProperty]]` for a namespace, driven by the *descriptor object*.
3207    ///
3208    /// §10.4.6.6 is worded entirely in terms of which fields the descriptor **has**: "If
3209    /// Desc has [[Value]] and SameValue(Desc.[[Value]], current) is false, return false",
3210    /// then the same for [[Writable]], [[Enumerable]] and [[Configurable]], then true. A
3211    /// descriptor with no fields at all therefore succeeds, which is what
3212    /// `Reflect.defineProperty(ns, k, {})` checks.
3213    ///
3214    /// Taking the *merged* `Property` instead cannot work: the merge inherits from the
3215    /// stored property, and a namespace stores its bindings as accessors, so every
3216    /// definition looked like "accessor → data kind changed" or carried `writable: false`
3217    /// from the accessor's own entry. Presence is only available here, before the merge.
3218    pub fn namespace_define_from_descriptor(
3219        &mut self,
3220        object: &Gc<JsObject>,
3221        key: &PropertyKey,
3222        descriptor: &Gc<JsObject>,
3223    ) -> JsResult<bool> {
3224        let Some(current) = self.namespace_own_property(object, key)? else {
3225            return Ok(false);
3226        };
3227        // An accessor descriptor can never describe a namespace binding.
3228        if self.get_property(descriptor, "get")?.is_some()
3229            || self.get_property(descriptor, "set")?.is_some()
3230        {
3231            return Ok(false);
3232        }
3233        if let Some(value) = self.get_property(descriptor, "value")? {
3234            let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3235            if !self.same_value(&value, current_value)? {
3236                return Ok(false);
3237            }
3238        }
3239        // The three attribute fields, when named, must restate what the property already
3240        // has. Not a fixed shape: an exported binding reports
3241        // `{writable: true, enumerable: true, configurable: false}` while `@@toStringTag`
3242        // is a real own data property with `{false, false, false}`, and both are namespace
3243        // properties. Comparing against `current` is what makes one rule cover both.
3244        for (name, have) in [
3245            ("writable", current.writable),
3246            ("enumerable", current.enumerable),
3247            ("configurable", current.configurable),
3248        ] {
3249            if let Some(named) = self.get_property(descriptor, name)?
3250                && named.to_boolean() != have
3251            {
3252                return Ok(false);
3253            }
3254        }
3255        Ok(true)
3256    }
3257
3258    /// `SameValue` (§7.2.9), exposed because the namespace's `[[DefineOwnProperty]]` needs to
3259    /// compare a requested value against a live binding.
3260    pub fn same_value(&mut self, a: &Value, b: &Value) -> JsResult<bool> {
3261        Ok(a.same_value(b))
3262    }
3263
3264    ///
3265    /// Written for `Error.prototype.stack`'s setter and the exact mechanism
3266    /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
3267    /// abstract operation here rather than a private helper in `error.rs`.
3268    ///
3269    /// The name is the whole point: the setter must behave as if the prototype were not
3270    /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3271    /// the accessor for every error object in the realm. Everything below follows from that:
3272    ///
3273    /// 1. `thisValue` must be an object — otherwise `TypeError`.
3274    /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3275    ///    accessor's own home an error rather than a self-shadow.
3276    /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3277    ///    either has a string or has made a mistake.
3278    /// 4. An existing *own* property decides the path — an own setter is called, an own
3279    ///    non-writable data property is a `TypeError` — and only a missing own property
3280    ///    falls through to defining one.
3281    /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3282    ///    traps and a non-extensible receiver is a `TypeError`.
3283    ///
3284    /// The installed shape is writable + configurable, not enumerable.
3285    pub fn setter_that_ignores_prototype_properties(
3286        &mut self,
3287        this_value: Value,
3288        home: &Gc<JsObject>,
3289        property_key: &str,
3290        args: &[Value],
3291    ) -> JsResult<Value> {
3292        self.setter_that_ignores_prototype_properties_key(
3293            this_value,
3294            home,
3295            &PropertyKey::from(property_key),
3296            args,
3297        )
3298    }
3299
3300    /// [`Interp::setter_that_ignores_prototype_properties`] for a key that may be a symbol.
3301    ///
3302    /// `Iterator.prototype[@@toStringTag]`'s setter is the symbol-keyed caller.
3303    pub fn setter_that_ignores_prototype_properties_key(
3304        &mut self,
3305        this_value: Value,
3306        home: &Gc<JsObject>,
3307        key: &PropertyKey,
3308        args: &[Value],
3309    ) -> JsResult<Value> {
3310        let Some(receiver) = this_value.as_object().cloned() else {
3311            return Err(self.type_error("setter called on a non-object"));
3312        };
3313        if Gc::ptr_eq(&receiver, home) {
3314            return Err(self.type_error("cannot assign to the accessor's own home object"));
3315        }
3316        // No type check here: §7.3.40 takes an arbitrary `v`, and
3317        // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3318        // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3319        // before calling this.
3320        let value = args.first().cloned().unwrap_or(Value::Undefined);
3321        // Step 4: an own property on the receiver changes what happens, and there are three
3322        // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3323        // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3324        // `Set` with `throw = true`, and a test exists for each.
3325        if let Some(existing) = self.object_get_own_property(&receiver, key)? {
3326            if existing.is_accessor() && existing.setter.is_none() {
3327                // A getter-only own accessor cannot be written through.
3328                return Err(self.type_error("no setter for the own property"));
3329            }
3330            // Everything else — an own data property, or an own accessor *with* a setter —
3331            // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3332            // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3333            // an own user setter receives the value (`setter-own-accessor`), because
3334            // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3335            // setter directly is the difference between one code path and two that can
3336            // disagree.
3337            self.set_property_with_key(
3338                &receiver,
3339                key,
3340                value.clone(),
3341                crate::interp::DeleteFailure::Throw,
3342            )?;
3343            return Ok(Value::Undefined);
3344        }
3345        let property = Property {
3346            value: Some(value.clone()),
3347            writable: true,
3348            // Enumerable, despite the accessor it shadows not being. The reference installs
3349            // it that way and six cases check it (`setter-creates-own-property` and friends).
3350            enumerable: true,
3351            configurable: true,
3352            ..Property::default()
3353        };
3354        if !self.object_define_own_property(&receiver, key, property)? {
3355            return Err(self.type_error("the receiver refused the definition"));
3356        }
3357        Ok(Value::Undefined)
3358    }
3359
3360    /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3361    ///
3362    /// The indices of a typed array are not properties at all — they are bytes in the
3363    /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3364    /// fly. That makes their descriptor shape fixed: every valid index is writable,
3365    /// enumerable and configurable, so a definition can only ever change the *value*, and
3366    /// every other descriptor is refused rather than applied.
3367    ///
3368    /// The order of the checks is the spec's, and two of them are load-bearing:
3369    ///
3370    /// * the index is validated **before** the value is converted, because the conversion
3371    ///   itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3372    ///   detaches from a `valueOf` and still expects `true` with no store, which only
3373    ///   happens when the index was valid on the way in;
3374    /// * the store is attempted even when the index has gone out of bounds by the time the
3375    ///   conversion finishes, because the store is a silent no-op rather than a failure —
3376    ///   the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3377    ///   the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3378    ///
3379    /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3380    /// the existing element, which is harmless here: every valid index is already
3381    /// writable, enumerable and configurable, so a `false` in the merged property can only
3382    /// have come from the descriptor having named `false`.
3383    fn integer_indexed_define_own_property(
3384        &mut self,
3385        object: &Gc<JsObject>,
3386        numeric: f64,
3387        property: &Property,
3388    ) -> JsResult<bool> {
3389        // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3390        // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3391        if !typed_array_index_is_valid(object, numeric) {
3392            return Ok(false);
3393        }
3394        // Step 6: the indices are data properties, so an accessor descriptor is refused
3395        // rather than converted. `Object.defineProperty` turns the `false` into a
3396        // `TypeError`; `Reflect.defineProperty` reports it.
3397        if property.is_accessor() {
3398            return Ok(false);
3399        }
3400        // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3401        // definition that asks for anything else cannot be honoured.
3402        if !property.writable || !property.enumerable || !property.configurable {
3403            return Ok(false);
3404        }
3405        // Step 10: only a descriptor that names a value stores anything.
3406        let Some(value) = property.value.clone() else {
3407            return Ok(true);
3408        };
3409        let Some(element) = object.typed_array_element_type() else {
3410            return Ok(false);
3411        };
3412        let stored = self.element_value(element, value)?;
3413        if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3414            return Err(self.type_error(reason));
3415        }
3416        Ok(true)
3417    }
3418
3419    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3420    pub fn object_define_own_property(
3421        &mut self,
3422        object: &Gc<JsObject>,
3423        key: &PropertyKey,
3424        property: Property,
3425    ) -> JsResult<bool> {
3426        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3427            return Ok(accepted);
3428        }
3429        // §10.4.6.6 `[[DefineOwnProperty]]` for a module namespace.
3430        //
3431        // The only definitions that can succeed are ones describing the property the
3432        // namespace *already* has: `Reflect.defineProperty(ns, "x", {})` asks for no change
3433        // and answers `true`; so does `{value: <SameValue current>}` or the exact attribute
3434        // set `{writable: true, enumerable: true, configurable: false}`. A different value,
3435        // `writable: false`, `configurable: true`, or any name the namespace does not
3436        // export is `false`.
3437        //
3438        // The ordinary path gets the no-change case right by accident — it compares against
3439        // `[[GetOwnProperty]]` — but cannot describe a namespace binding, because the binding
3440        // is an accessor internally while the definition script writes is a data descriptor.
3441        // Answering here is what makes that attribute-only definition a no-op rather than a
3442        // refusal (`namespace/await-ns-define-own-property`).
3443        if object.module_namespace_marker() {
3444            return self.namespace_define_own_property(object, key, &property);
3445        }
3446        // A proxy always answers above — with `Some` from its trap, or with `None` when
3447        // the trap is absent, and then the definition belongs to the **target**
3448        // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3449        // when there is no trap). Falling through to the ordinary path here defined the
3450        // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3451        // property the target never saw.
3452        if object.proxy_state().is_some() {
3453            let Some((target, _handler)) = self.proxy_parts(object)? else {
3454                return Err(self.type_error("cannot use a proxy that has been revoked"));
3455            };
3456            return self.object_define_own_property(&target, key, property);
3457        }
3458        // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3459        // they accept exactly one descriptor shape. This has to happen before the
3460        // ordinary path, which would happily store a data property next to the buffer —
3461        // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3462        // and `TypedArray/prototype/set` are about this section.
3463        if object.typed_array_element_type().is_some()
3464            && let Some(index) = canonical_numeric_index(key)
3465        {
3466            return self.integer_indexed_define_own_property(object, index, &property);
3467        }
3468        // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3469        // non-extensible object. The check lives here rather than in the callers because
3470        // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3471        // `Array.prototype.filter` uses to store its result, and a species object made
3472        // non-extensible by its own constructor must make that a `TypeError`
3473        // (`target-array-non-extensible`).
3474        // Note the `is_none()`: an already-present property may still be **redefined** on a
3475        // non-extensible object, and only *adding* one is refused (as Distinct from
3476        // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3477        // properties — testing extensibility before looking for the property made every
3478        // `Object.freeze` of an ordinary object refuse its own second step).
3479        if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3480            return Ok(false);
3481        }
3482        // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3483        // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3484        // an omitted field is left alone). Merging here rather than at each call site is
3485        // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3486        // the value and `enumerable` in place.
3487        //
3488        // The merge is a no-op when the property is absent: there is nothing to keep.
3489        let was_partial = property.descriptor_fields.is_some();
3490        let property = match property.descriptor_fields {
3491            None => property,
3492            Some(fields) => {
3493                let base = self.object_get_own_property(object, key)?;
3494                let mut merged = base.clone().unwrap_or_default();
3495                // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3496                // descriptor names, and switching kind discards the other half —
3497                // `{set: f}` on a data property is an accessor with no getter, not a data
3498                // property whose `get` happens to be absent.
3499                let wants_accessor = fields.get || fields.set;
3500                let wants_data = fields.value || fields.writable;
3501                if wants_accessor {
3502                    merged.value = None;
3503                    merged.writable = false;
3504                    merged.getter = property.getter.clone();
3505                    merged.setter = property.setter.clone();
3506                } else if wants_data {
3507                    merged.getter = None;
3508                    merged.setter = None;
3509                    if fields.value {
3510                        merged.value = property.value.clone();
3511                    }
3512                    if fields.writable {
3513                        merged.writable = property.writable;
3514                    }
3515                }
3516                if fields.enumerable {
3517                    merged.enumerable = property.enumerable;
3518                }
3519                if fields.configurable {
3520                    merged.configurable = property.configurable;
3521                }
3522                merged.descriptor_fields = None;
3523                merged
3524            }
3525        };
3526        // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3527        // descriptor. `define_property_on` runs the same check before it calls here, so an
3528        // ordinary object is already covered; what is *not* is the forwarding a proxy does
3529        // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3530        // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3531        // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3532        // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3533        // own define would have refused.
3534        //
3535        // Only partial descriptors are validated here. A whole `Property` passed by an
3536        // internal caller (`Property::data(…)`) carries attributes that say nothing about
3537        // what the descriptor "named", and those callers rely on the write landing.
3538        if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3539            // Every branch below is gated on `!existing.configurable`: a *configurable*
3540            // property may be reshaped however the descriptor likes, which is why an
3541            // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3542            // must succeed. Testing only `writable` refused that and broke
3543            // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3544            let same_kind = existing.is_accessor() == property.is_accessor();
3545            if !same_kind {
3546                // Step 4: a non-configurable property may not change kind.
3547                if !existing.configurable {
3548                    return Ok(false);
3549                }
3550            } else if existing.is_accessor() {
3551                // Step 6: an accessor's halves are its value.
3552                if !existing.configurable
3553                    && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3554                        || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3555                {
3556                    return Ok(false);
3557                }
3558            } else if !existing.configurable && !existing.writable {
3559                // Step 7: a non-configurable *and* non-writable data property's value is
3560                // fixed, and it may not become writable again.
3561                if property.writable {
3562                    return Ok(false);
3563                }
3564                let current = existing.value.clone().unwrap_or(Value::Undefined);
3565                let requested = property.value.clone().unwrap_or(Value::Undefined);
3566                if !current.same_value(&requested) {
3567                    return Ok(false);
3568                }
3569            }
3570            // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3571            // is frozen with it.
3572            if !existing.configurable
3573                && (property.configurable || property.enumerable != existing.enumerable)
3574            {
3575                return Ok(false);
3576            }
3577        }
3578        // A host class that intercepts definitions owns the attributes of the properties it
3579        // defines: `_class`-style storage on the native side is the usual reason.
3580        if let Some(exotic) = object.exotic()
3581            && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3582        {
3583            return Ok(accepted);
3584        }
3585        // An array index is stored in the element vector, which can hold a plain value and
3586        // nothing else. An accessor — or a data property with non-default attributes —
3587        // therefore has to live in the property table, and the element slot is blanked so
3588        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3589        // {get})` stored the accessor where no read ever looked, and the array kept
3590        // answering its old value.
3591        // An array's `length` is not stored in the property table, so defining it has to
3592        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3593        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3594        // {value: 1})` reported success and changed nothing.
3595        if key.as_str() == Some("length") && object.is_array() {
3596            // `{writable: false}` on `length` does not change the length, but it does make
3597            // it read-only — after which neither a later `{writable: true}` nor a store
3598            // past the end may succeed.
3599            if property.value.is_none() {
3600                if !object.length_writable() && property.writable {
3601                    return Ok(false);
3602                }
3603                object.set_length_writable(property.writable);
3604                return Ok(true);
3605            }
3606            if !object.length_writable() {
3607                return Ok(false);
3608            }
3609        }
3610        if key.as_str() == Some("length")
3611            && object.is_array()
3612            && let Some(value) = property.value.clone()
3613        {
3614            let requested = value.to_number();
3615            let valid = requested.is_finite()
3616                && requested >= 0.0
3617                && requested.fract() == 0.0
3618                && requested <= u32::MAX as f64;
3619            if !valid {
3620                return Err(self.range_error("invalid array length"));
3621            }
3622            // Truncating deletes the elements above the new length, and a non-configurable
3623            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3624            // makes `a.length = 2` fail rather than quietly drop it.
3625            let current = object.array_length().unwrap_or(0);
3626            let requested = requested as usize;
3627            if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3628                // §10.4.2.4 `ArraySetLength` step 3.i.2: the refusal still applies
3629                // `[[Writable]]: false` when the descriptor asked for it — the length is
3630                // left at its old value but locked. Returning `false` alone left it
3631                // writable, which `verifyProperty` catches
3632                // (`defineProperties/15.2.3.7-6-a-164`).
3633                if property
3634                    .descriptor_fields
3635                    .is_some_and(|fields| fields.writable)
3636                    && !property.writable
3637                    && object.length_writable()
3638                {
3639                    object.set_length_writable(false);
3640                }
3641                return Ok(false);
3642            }
3643            object.array_set_length(self.heap, requested);
3644            return Ok(true);
3645        }
3646        let plain = property.writable
3647            && property.enumerable
3648            && property.configurable
3649            && !property.is_accessor();
3650        if let Some(index) = key.as_str().and_then(array_index)
3651            && object.is_array()
3652        {
3653            // Growing the array needs a writable `length`: after
3654            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3655            // be added.
3656            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3657                return Ok(false);
3658            }
3659            if plain && property.value.is_some() {
3660                // An ordinary element: the vector is where a read looks first, so it has
3661                // to be the vector that changes — unless the index is too far out to be
3662                // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3663                // one property, because past its own limit it stores the index as an
3664                // ordinary key. Falling through to `define_key` below is the same choice,
3665                // and the alternative was worse: the store used to be *dropped* and the
3666                // length left at 0, which is a silent wrong answer.
3667                let value = property.value.clone().unwrap_or(Value::Undefined);
3668                object.delete_key(key);
3669                if object.array_set(self.heap, index as usize, value) {
3670                    return Ok(true);
3671                }
3672                // Past the dense limit the element lives in the table like any property.
3673                object.note_element_descriptor();
3674                object.define_key(key, property);
3675                // A sparse store past the dense limit still extends `length`, which is what
3676                // `a[a.length] = v` relies on — but only extends: shortening would delete
3677                // the sparse properties above the index, including this one.
3678                if index as usize + 1 > object.array_length().unwrap_or(0) {
3679                    object.array_set_length(self.heap, index as usize + 1);
3680                }
3681                return Ok(true);
3682            }
3683            // A non-plain element — an accessor, or an attribute that is not the default —
3684            // lives in the table while the slot becomes a hole. Recording it keeps every
3685            // later `a[i] = v` off the dense path, where the write would have shadowed the
3686            // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3687            // replace the accessor with a plain data property.
3688            object.note_element_descriptor();
3689            object.define_key(key, property);
3690            // The slot stays, so `length` does not shrink; a hole is not an element, so
3691            // the table entry is now what a read finds.
3692            object.array_set(self.heap, index as usize, Value::Hole);
3693            // `ArraySetLength` step 2 of `OrdinaryDefineOwnProperty`'s index branch —
3694            // `length = index + 1` — applies whatever the descriptor's *attributes* are,
3695            // not just to a plain one: `Object.defineProperty(a, 4294967294, {value: 100})`
3696            // makes `a.length` 4294967295 (`defineProperty/15.2.3.6-4-183`).
3697            if index as usize + 1 > object.array_length().unwrap_or(0) {
3698                object.array_set_length(self.heap, index as usize + 1);
3699            }
3700            return Ok(true);
3701        }
3702        object.define_key(key, property);
3703        Ok(true)
3704    }
3705
3706    /// Build a proxy object over `target`, with its traps read from `handler`.
3707    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3708        JsObject::proxy(self.heap, target, handler)
3709    }
3710
3711    /// The `revoke` function for a proxy's slots.
3712    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3713        let revoke = JsObject::function(
3714            self.heap,
3715            Some(self.realm.function_proto.clone()),
3716            Callable::Revoker(slots),
3717        );
3718        // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3719        // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3720        // inherited from `Function.prototype` reads the same but fails the three cases that
3721        // check the own-property list (`revocation-function-{length,name,property-order}`).
3722        revoke.define("length", Property::name_or_length(Value::Int(0)));
3723        revoke.define("name", Property::name_or_length(self.string("")));
3724        revoke
3725    }
3726
3727    /// A new array.
3728    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3729        let array = JsObject::array(
3730            self.heap,
3731            Some(self.realm.array_proto.clone()),
3732            elements.len(),
3733        );
3734        for (index, element) in elements.into_iter().enumerate() {
3735            array.array_set(self.heap, index, element);
3736        }
3737        array
3738    }
3739
3740    /// A new native function object.
3741    ///
3742    /// The observable `name` and `length` are installed as properties here, which is
3743    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3744    /// so `f.name = "x"` behaves like the writable property it is.
3745    /// A native constructor that builds its own instance after validating its arguments.
3746    ///
3747    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3748    /// check runs before `new.target.prototype` is read.
3749    pub fn new_native_ctor(
3750        &self,
3751        name: impl Into<String>,
3752        length: u32,
3753        func: NativeFn,
3754    ) -> Gc<JsObject> {
3755        let function = JsObject::function(
3756            self.heap,
3757            Some(self.realm.function_proto.clone()),
3758            Callable::Native {
3759                func,
3760                own_instance: true,
3761            },
3762        );
3763        function.set_constructible(true);
3764        function.define(
3765            "length",
3766            Property::name_or_length(Value::Int(length as i32)),
3767        );
3768        function.define("name", Property::name_or_length(self.string(name)));
3769        function
3770    }
3771
3772    /// A native constructor that lets `new` build the instance first.
3773    ///
3774    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3775    /// validation that must precede reading `new.target.prototype`, so the object can be
3776    /// created before the implementation runs. Distinct from [`Interp::new_native`],
3777    /// which makes a *method* and therefore not a constructor at all.
3778    pub fn new_native_constructor(
3779        &self,
3780        name: impl Into<String>,
3781        length: u32,
3782        func: NativeFn,
3783    ) -> Gc<JsObject> {
3784        let function = self.new_native(name, length, func);
3785        function.set_constructible(true);
3786        function
3787    }
3788
3789    /// A new host function object: a native closure that carries its own state.
3790    ///
3791    /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3792    /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3793    /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3794    /// this safe: the closure must not capture a `Gc`.
3795    pub fn new_host_function(
3796        &self,
3797        name: impl Into<String>,
3798        length: u32,
3799        func: crate::object::HostFn,
3800    ) -> Gc<JsObject> {
3801        self.new_host_inner(name.into(), length, func, false)
3802    }
3803
3804    /// A host constructor: `new` hands it `this = undefined`, so it validates its
3805    /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3806    pub fn new_host_ctor(
3807        &self,
3808        name: impl Into<String>,
3809        length: u32,
3810        func: crate::object::HostFn,
3811    ) -> Gc<JsObject> {
3812        let function = self.new_host_inner(name.into(), length, func, true);
3813        function.set_constructible(true);
3814        // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3815        // installs its own methods on it, so it starts as a plain object.
3816        let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3817        function.define(
3818            "prototype",
3819            Property {
3820                value: Some(Value::Object(proto)),
3821                writable: true,
3822                enumerable: false,
3823                configurable: false,
3824                ..Property::default()
3825            },
3826        );
3827        function
3828    }
3829
3830    fn new_host_inner(
3831        &self,
3832        name: String,
3833        length: u32,
3834        func: crate::object::HostFn,
3835        own_instance: bool,
3836    ) -> Gc<JsObject> {
3837        let function = JsObject::function(
3838            self.heap,
3839            Some(self.realm.function_proto.clone()),
3840            Callable::Host {
3841                func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3842                own_instance,
3843            },
3844        );
3845        function.define(
3846            "length",
3847            Property::name_or_length(Value::Int(length as i32)),
3848        );
3849        function.define("name", Property::name_or_length(self.string(name)));
3850        function
3851    }
3852
3853    /// A callable object with the `length`/`name` a built-in function has, in that order.
3854    ///
3855    /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3856    /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3857    /// [`JsObject::function`] defines neither, which is why every capability helper built
3858    /// with it reported no own `length` and no own `name` at all.
3859    ///
3860    /// The attributes are the spec's for a built-in: not writable, not enumerable,
3861    /// configurable.
3862    pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3863        let function =
3864            JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3865        function.define(
3866            "length",
3867            Property::name_or_length(Value::Int(length as i32)),
3868        );
3869        function.define("name", Property::name_or_length(self.string(name)));
3870        function
3871    }
3872
3873    /// A new native function object.
3874    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3875        let function = JsObject::function(
3876            self.heap,
3877            Some(self.realm.function_proto.clone()),
3878            Callable::Native {
3879                func,
3880                own_instance: false,
3881            },
3882        );
3883        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3884        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3885        // `length,name` and this listed `name,length`. A bytecode function already gets it
3886        // the right way round; only native ones were built backwards.
3887        function.define(
3888            "length",
3889            Property::name_or_length(Value::Int(length as i32)),
3890        );
3891        function.define("name", Property::name_or_length(self.string(name)));
3892        function
3893    }
3894
3895    /// A new bound function.
3896    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3897        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3898        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3899        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3900        let constructible = target
3901            .as_object()
3902            .is_some_and(|target| target.is_constructor());
3903        let bound = JsObject::function(
3904            self.heap,
3905            Some(self.realm.function_proto.clone()),
3906            Callable::Bound { target, this, args },
3907        );
3908        bound.set_constructible(constructible);
3909        bound
3910    }
3911
3912    /// A new reference cell.
3913    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3914        Gc::new(self.heap, Cell::new(value))
3915    }
3916
3917    // -- running ------------------------------------------------------------
3918
3919    /// Evaluate `code` as a script body and return its completion value.
3920    /// Compile and run `source` for the engine's own use, returning its completion value.
3921    ///
3922    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3923    /// needs to be a real async function, and the engine already runs those as coroutines,
3924    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3925    ///
3926    /// Differences from [`Self::eval_in_global`], both deliberate:
3927    ///
3928    /// * It does **not** drain the microtask queue. Install runs while the realm is still
3929    ///   being built, and the source is an IIFE that only constructs a closure, so there
3930    ///   is nothing to drain — and draining here would run script-queued jobs in the
3931    ///   middle of `install`.
3932    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3933    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3934    ///   and it should not look like the user wrote something wrong.
3935    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3936        let program = match js_parse::parse_script(source) {
3937            Ok(program) => program,
3938            Err(error) => {
3939                let message = format!("builtin source does not parse: {error}");
3940                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3941            }
3942        };
3943        let mut code = match js_compile::compile_script_with_source(&program, source) {
3944            Ok(code) => code,
3945            Err(error) => {
3946                let message = format!("builtin source does not compile: {}", error.message);
3947                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3948            }
3949        };
3950        // The frame has to name something, and `<builtin>` is what a stack trace through
3951        // this code should say.
3952        code.set_filename("<builtin>");
3953        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3954        let closure_vars = compiled.code.closure_vars.clone();
3955        let env = self.global_env(&closure_vars);
3956        let this = Value::Object(self.realm.global.clone());
3957        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3958    }
3959
3960    /// Run an already-parsed script and drain the microtasks it queued.
3961    ///
3962    /// The drain is what lets an `async` function's body advance past its first `await`
3963    /// before the host sees the result: nothing else pumps the job queue.
3964    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3965        let this = Value::Object(self.realm.global.clone());
3966        self.run_script_with_this(code, this)
3967    }
3968
3969    /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3970    ///
3971    /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3972    /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3973    /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3974    /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3975    /// state the next script evaluation tripped over.
3976    pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3977        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3978        let closure_vars = compiled.code.closure_vars.clone();
3979        let env = self.global_env(&closure_vars);
3980        let callee = Value::Undefined;
3981        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3982        // The script is done, so the microtasks it queued run before the host sees the
3983        // result. Without this an `async` function's body would never advance past its
3984        // first `await`, because nothing else drains the queue.
3985        self.drain_jobs()?;
3986        Ok(result)
3987    }
3988
3989    /// Compile and run `source` in global scope, returning its completion value.
3990    ///
3991    /// This is what `eval` and `new Function` use. Running it as a script means it
3992    /// sees the global object and nothing else, which is right for `eval("1+1")` and
3993    /// for a `Function` body; a *direct* eval that reads a local variable would need
3994    /// the compiler to hand its variable environment over, which is not implemented.
3995    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3996        self.eval_in_global_named(source, EVAL_FILE, false)
3997    }
3998
3999    /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
4000    ///
4001    /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
4002    /// shows `<evalScript>` — and the name is visible in every stack trace that passes
4003    /// through the code, so they cannot share one constant.
4004    pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
4005        self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
4006    }
4007
4008    /// Evaluate `source` as a global script, reported under `file`.
4009    ///
4010    /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
4011    /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
4012    /// from inside a C callback, where the interpreter is the running one rather than a
4013    /// context's own.
4014    pub fn eval_in_global_named(
4015        &mut self,
4016        source: &str,
4017        file: &str,
4018        barrier: bool,
4019    ) -> JsResult<Value> {
4020        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
4021        // eval-created global binding — configurable, unlike a script's own `var`.
4022        self.eval_depth += 1;
4023        if barrier {
4024            let depth = self.frames.len();
4025            self.trace_barriers.push(depth);
4026        }
4027        let result = self.eval_in_global_inner(source, file);
4028        if barrier {
4029            self.trace_barriers.pop();
4030        }
4031        self.eval_depth -= 1;
4032        result
4033    }
4034
4035    fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
4036        let compiled = self.compile_global_script(source, file, false)?;
4037        let strict = compiled.strict;
4038        self.run_eval_script(compiled, strict)
4039    }
4040
4041    /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
4042    ///
4043    /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
4044    /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
4045    /// is script-scoped, `var` becomes a global, and the body is not confined the way a
4046    /// direct eval's is.
4047    pub fn eval_script_with_this(
4048        &mut self,
4049        source: &str,
4050        file: &str,
4051        this: Value,
4052    ) -> JsResult<Value> {
4053        let program = match js_parse::parse_script(source) {
4054            Ok(program) => program,
4055            Err(error) => {
4056                return Err(Signal::Throw(self.syntax_error_at(
4057                    file,
4058                    error.span.start.line,
4059                    error.span.start.column,
4060                    &error.message,
4061                )));
4062            }
4063        };
4064        let mut compiled = match js_compile::compile_script(&program) {
4065            Ok(compiled) => compiled,
4066            Err(error) => {
4067                return Err(Signal::Throw(self.syntax_error_at(
4068                    file,
4069                    error.span.start.line,
4070                    error.span.start.column,
4071                    &error.message,
4072                )));
4073            }
4074        };
4075        compiled.set_filename(file);
4076        self.run_script_with_this(compiled, this)
4077    }
4078
4079    /// Parse and compile `source` as a global script, without running it.
4080    ///
4081    /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
4082    /// before a promise exists to reject — while still evaluating in the same eval context
4083    /// (direct-eval strictness, `new.target`, `super`).
4084    fn compile_global_script(
4085        &mut self,
4086        source: &str,
4087        file: &str,
4088        async_body: bool,
4089    ) -> JsResult<CompiledFunction> {
4090        // Nothing of the caller's is inherited by an *indirect* eval: `(0, eval)('super.x')`
4091        // and `(0, eval)('arguments')` are both `SyntaxError`s because there is no caller
4092        // context at all. The site is what tells the two apart — an indirect call leaves no
4093        // site behind, since only a bare `eval(...)` is recorded.
4094        let site = self.eval_site_at_cursor();
4095        // Strictness follows the same rule, and it is *not* a detail: §19.2.1.1 step 4
4096        // makes the eval code strict when the caller is strict **and the call is direct**.
4097        // So `var s = eval; s("var eval;")` called from strict code is sloppy — legal —
4098        // while `eval("var eval;")` there is a `SyntaxError`
4099        // (`statements/variable/12.2.1-*-s`). Inheriting unconditionally rejected the
4100        // indirect form. A `"use strict"` prologue in the source still works either way:
4101        // the parser reads the directive itself, which is how a script becomes strict.
4102        let strict = site.is_some() && self.current_strict();
4103        // `eval` runs in the caller's function context, so `new.target` is legal here
4104        // even though the source is a bare script — and so is `super.x` when the caller
4105        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
4106        // caller's, which is what `special_object 4` already does.
4107        let private = site
4108            .map(|site| site.private_names.clone())
4109            .unwrap_or_default();
4110        let context = js_parse::EvalContext {
4111            in_method: site.is_some() && self.enclosing_home_object().is_some(),
4112            // `super()` belongs to a derived constructor, and an eval'd body is not a
4113            // constructor at all: the caller frame's `this` is already built.
4114            in_derived_constructor: false,
4115            // Private names are lexically scoped, so a direct `eval` inside a class body
4116            // can see them; see `Interp::eval_private_names`.
4117            private_names: private.iter().map(|entry| entry.name.clone()).collect(),
4118            arguments_allowed: site.is_none_or(|site| site.arguments_allowed),
4119            new_target_allowed: site.is_some(),
4120        };
4121        // A *global* eval is not a function body: `new.target` and `super` are out of
4122        // reach there. Its `{async: true}` form differs in the other direction — the body
4123        // may `await` — so the two flags are independent and the reference sets both from
4124        // the eval type rather than from the caller.
4125        let parsed = if async_body {
4126            js_parse::parse_suspensible_global_eval(source, strict)
4127        } else {
4128            js_parse::parse_eval_script_in(source, strict, context)
4129        };
4130        let program = match parsed {
4131            Ok(program) => program,
4132            Err(error) => {
4133                // The message is bare: the position lives in `fileName`,
4134                // `lineNumber`, `columnNumber` and the stack frame above, which is where
4135                // the reference puts it. An `invalid source: L:C: ` prefix made
4136                // `e.message` differ from the reference while the stack already agreed.
4137                return Err(Signal::Throw(self.syntax_error_at(
4138                    file,
4139                    error.span.start.line,
4140                    error.span.start.column,
4141                    &error.message,
4142                )));
4143            }
4144        };
4145        let mut compiled = match if async_body {
4146            js_compile::compile_eval_with_private(&program, &private, true)
4147        } else {
4148            js_compile::compile_eval_with_private(&program, &private, false)
4149        } {
4150            Ok(compiled) => compiled,
4151            // A construct the compiler does not handle yet is reported the same way a
4152            // parse error is: it happens before anything runs, so the trace is the
4153            // position in the source followed by the caller.
4154            Err(error) => {
4155                return Err(Signal::Throw(self.syntax_error_at(
4156                    file,
4157                    error.span.start.line,
4158                    error.span.start.column,
4159                    &error.message,
4160                )));
4161            }
4162        };
4163        compiled.set_filename(file);
4164        Ok(compiled)
4165    }
4166
4167    /// The private names the code at the current position can see, innermost first.
4168    ///
4169    /// Private names are lexically scoped (§15.10.2 `AllPrivateIdentifiersValid`), and a
4170    /// direct `eval` runs inside its caller's scope, so
4171    /// `class C { #m = 44; f() { return eval("this.#m") } }` is legal. The names belong to the
4172    /// *call site's* compilation unit, so they are recorded on the `EvalSite` and read back
4173    /// here rather than being derivable from the eval'd source.
4174    ///
4175    /// An indirect `eval` gets nothing: `(0, eval)("this.#m")` outside a class is a
4176    /// `SyntaxError`, and an indirect call leaves no site behind, which is exactly the test
4177    /// [`Interp::run_eval_script`] uses for "direct".
4178    fn eval_site_at_cursor(&self) -> Option<&js_compile::bytecode::EvalSite> {
4179        let frame = self.frames.last()?;
4180        let (line, column) = frame
4181            .code
4182            .code
4183            .position_at(frame.at as u32)
4184            .unwrap_or_default();
4185        // The nearest site at or before the current position: the recorded position of the
4186        // `call` instruction is the callee's, which sits a few columns inside the call
4187        // expression the compiler recorded, so an exact match would never be found.
4188        frame
4189            .code
4190            .code
4191            .eval_sites
4192            .iter()
4193            .filter(|site| (site.line, site.column) <= (line, column))
4194            .max_by_key(|site| (site.line, site.column))
4195    }
4196
4197    /// Run an `eval`'d script in the caller's scope.
4198    ///
4199    /// Three things have to come from the calling frame, because the eval'd code is a
4200    /// script and would otherwise see only the global object:
4201    ///
4202    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
4203    /// * `arguments`, exposed as a binding of the eval's own scope, so
4204    ///   `f("arguments.length", 1)` sees the caller's arguments;
4205    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
4206    ///   `eval("var v = 1")` into the global object.
4207    ///
4208    /// Locals of the calling function are *not* reachable: that needs the compiler to
4209    /// hand its variable environment over, which this milestone does not do.
4210    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
4211        // `this` and `arguments` come from the innermost frame only — those are not
4212        // lexical — while the name bindings come from the whole chain of frames, part
4213        // of it being ordinary scope resolution.
4214        // An arrow has no `this` of its own, so an `eval` inside one inherits the
4215        // enclosing function's receiver — the lexical `this` the arrow was compiled to
4216        // read from its closure.
4217        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
4218        // variable environment is the innermost frame of all: an arrow's own body is where
4219        // `var`s declared by an `eval` inside it belong.
4220        let caller_index = self
4221            .frames
4222            .iter()
4223            .rposition(|frame| !frame.code.code.is_arrow)
4224            .or_else(|| self.frames.len().checked_sub(1));
4225        let env_index = self.frames.len().checked_sub(1);
4226        let caller = caller_index.and_then(|index| self.frames.get(index));
4227        let (this, passed) = match caller {
4228            Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
4229            // No frame at all: the eval is running at the top level, so there is
4230            // nothing to inherit and the global receiver is right.
4231            None => (Value::Object(self.realm.global.clone()), Vec::new()),
4232        };
4233        // Innermost frame first, so the first binding found for a name is the one that
4234        // shadows the rest. A script frame (`<eval>`) contributes nothing.
4235        let mut bindings: Vec<EvalBinding> = Vec::new();
4236        // The calling function's own bindings, resolved by the compiler at the call
4237        // site. That table is the only reliable answer when a name is declared twice in
4238        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
4239        // body means, and guessing by declaration order picks the wrong one as soon as
4240        // two loops in a row use the same name.
4241        // Only a *direct* eval sees the caller's scope. The compiler records a site for
4242        // every direct call — a bare `eval(...)` callee — so finding one at the current
4243        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
4244        // callee to a value first and leave no site behind.
4245        let mut direct = false;
4246        let mut resolved_here = false;
4247        if let Some(frame) = self.frames.last() {
4248            let (line, column) = frame
4249                .code
4250                .code
4251                .position_at(frame.at as u32)
4252                .unwrap_or_default();
4253            // The nearest site at or before the current position, not an exact match:
4254            // the recorded position of the `call` instruction is the callee's, which
4255            // sits a few columns inside the call expression the compiler recorded. A
4256            // site is unique per call, so "the closest one behind us" identifies it.
4257            if let Some(site) = frame
4258                .code
4259                .code
4260                .eval_sites
4261                .iter()
4262                .filter(|site| (site.line, site.column) <= (line, column))
4263                .max_by_key(|site| (site.line, site.column))
4264            {
4265                direct = true;
4266                resolved_here = true;
4267                for binding in &site.bindings {
4268                    // An enclosing function's frame sits `owner` levels below the one
4269                    // running the call.
4270                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
4271                    else {
4272                        continue;
4273                    };
4274                    bindings.push(EvalBinding {
4275                        name: binding.name.clone(),
4276                        frame,
4277                        slot: if binding.is_arg {
4278                            EvalSlot::Arg
4279                        } else {
4280                            EvalSlot::Local
4281                        },
4282                        index: binding.index as usize,
4283                    });
4284                }
4285            }
4286        }
4287        for frame_index in (0..self.frames.len()).rev() {
4288            // Skip the innermost frame's flat scan when the compiler already answered
4289            // for it; an enclosing frame still needs one, because the eval resolves
4290            // those names dynamically.
4291            if resolved_here && frame_index == self.frames.len() - 1 {
4292                continue;
4293            }
4294            let frame = &self.frames[frame_index];
4295            for (index, arg) in frame.code.code.args.iter().enumerate() {
4296                bindings.push(EvalBinding {
4297                    name: arg.name.clone(),
4298                    frame: frame_index,
4299                    slot: EvalSlot::Arg,
4300                    index,
4301                });
4302            }
4303            for (index, local) in frame.code.code.vars.iter().enumerate() {
4304                bindings.push(EvalBinding {
4305                    name: local.name.clone(),
4306                    frame: frame_index,
4307                    slot: EvalSlot::Local,
4308                    index,
4309                });
4310            }
4311        }
4312        let mut seen = BTreeSet::new();
4313        bindings.retain(|binding| seen.insert(binding.name.clone()));
4314
4315        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4316        // elements is all the spec's ordinary uses need.
4317        //
4318        // Known divergence: this is bound for a *global* eval too, where there is no
4319        // caller and the reference throws `'arguments' is not defined`. Deciding properly
4320        // needs "does the calling frame have an `arguments` of its own", which is not
4321        // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4322        // script or eval body does not, and `eval(b)` passes the callee as a value so even
4323        // the call-site detection does not answer it. Modelled as a binding in the caller's
4324        // variable environment, this would fall out; that is a larger change than the one
4325        // this comment is attached to.
4326        let arguments = Value::Object(self.new_array(passed));
4327
4328        // Only a *strict* eval gets a variable environment of its own. A sloppy one
4329        // declares its `var`s in the caller's — which for a top-level eval is the global
4330        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4331        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4332        // vanish into a scope nobody reads back from.
4333        let previous_scope = if code_strict {
4334            self.eval_scope.replace(BTreeMap::new())
4335        } else {
4336            None
4337        };
4338        // Only a *direct* eval inherits the caller's arguments object. An indirect one runs
4339        // in global scope, where `arguments` means whatever the global object says — which
4340        // is why `var arguments = 1; class C { x = (0, eval)('arguments;') }` answers `1`
4341        // (`indirect-eval-contains-arguments`). Binding the caller's array there made it
4342        // answer the array instead.
4343        let previous_arguments = if direct {
4344            self.eval_arguments.replace(arguments)
4345        } else {
4346            None
4347        };
4348        let previous_with = self.eval_with.replace(self.with_objects());
4349        let inherited_new_target = self
4350            .frames
4351            .iter()
4352            .rev()
4353            .find(|frame| !frame.code.code.is_arrow)
4354            .map(|frame| frame.new_target.clone());
4355        let previous_new_target = self
4356            .eval_new_target
4357            .replace(inherited_new_target.unwrap_or(Value::Undefined));
4358        let eval_cells = self.eval_cells_for(&bindings);
4359        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4360        // A sloppy direct eval declares its `var`s in the caller's variable environment;
4361        // `declare_eval_local` needs to know which frame that is.
4362        // An indirect eval gets the global environment, so nothing of the caller's is
4363        // recorded as the place its `var`s belong.
4364        let previous_caller = self
4365            .eval_caller
4366            .replace(if direct { env_index } else { None });
4367        // The cell-based view of the same bindings, which is what a closure created
4368        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4369        // whose compiler did not put a binding in a cell simply does not appear here —
4370        // reads and writes still work through `eval_bindings`, they just cannot outlive
4371        // the eval.
4372        let previous_eval_scope = self
4373            .active_eval_scope
4374            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4375        let compiled = Gc::new(self.heap, CompiledCode::new(code));
4376        let closure_vars = compiled.code.closure_vars.clone();
4377        // Declaration instantiation is where this belongs: the check needs the caller frame
4378        // (recorded just above) and the eval's own var names, and it raises before any of
4379        // the eval's code runs.
4380        self.check_eval_var_named_arguments(&closure_vars, code_strict)?;
4381        let env = self.global_env(&closure_vars);
4382        let callee = Value::Undefined;
4383        // An async body does not run here: it becomes a coroutine and answers a promise,
4384        // which is what makes `await` legal in it. `this` still has to be the caller's
4385        // (for a global eval, the global object), because `this` is not part of `await`.
4386        let result = if compiled.code.kind.is_async() {
4387            self.run_async_body(compiled, env, this)
4388        } else {
4389            self.execute(compiled, env, this, Vec::new(), callee)
4390        };
4391        self.eval_scope = previous_scope;
4392        self.eval_arguments = previous_arguments;
4393        self.eval_with = previous_with;
4394        self.eval_new_target = previous_new_target;
4395        self.eval_bindings = previous_bindings;
4396        self.eval_caller = previous_caller;
4397        self.active_eval_scope = previous_eval_scope;
4398        result
4399    }
4400
4401    /// The declarations an eval cannot instantiate: they are `SyntaxError`/`TypeError`
4402    /// rather than bindings.
4403    ///
4404    /// Two rules, both from `EvalDeclarationInstantiation` (§19.2.1.3) and both about a
4405    /// declaration that cannot exist:
4406    ///
4407    /// * **`var arguments` in a function's parameter scope.** §10.2.1.3 gives a function with
4408    ///   parameter expressions a separate parameter environment, and `arguments` is bound
4409    ///   implicitly there, so a `var` of that name collides. An arrow that binds no
4410    ///   `arguments` of its own has nothing to collide with and is allowed — see the table in
4411    ///   [`Interp::check_eval_var_named_arguments`].
4412    /// * **A global `var` on a non-extensible global object**, where `CanDeclareGlobalVar` is
4413    ///   false; the operation is a `TypeError`, and `eval("var x")` with
4414    ///   `Object.preventExtensions(this)` must raise rather than quietly do nothing
4415    ///   (`non-definable-global-var` and its four siblings).
4416    fn check_eval_var_named_arguments(
4417        &self,
4418        closure_vars: &[js_compile::bytecode::ClosureVar],
4419        strict: bool,
4420    ) -> JsResult<()> {
4421        if strict {
4422            return Ok(());
4423        }
4424        // A `var` this eval would declare on the global object, where there is no room for it.
4425        let global = &self.realm.global;
4426        if !global.is_extensible() {
4427            for var in closure_vars {
4428                if var.is_lexical || var.name == "*default*" {
4429                    continue;
4430                }
4431                let declare = matches!(
4432                    var.closure_type,
4433                    js_compile::bytecode::ClosureType::GlobalDecl
4434                );
4435                if declare && global.own_property(&var.name).is_none() {
4436                    return Err(Signal::Throw(self.make_error(
4437                        "TypeError",
4438                        "cannot declare a global in a non-extensible global object",
4439                    )));
4440                }
4441            }
4442        }
4443        // Only a *direct* eval declares into a caller's environment; an indirect one gets the
4444        // global environment, where `var arguments` is an ordinary global.
4445        let Some(caller) = self.eval_caller.flatten() else {
4446            return Ok(());
4447        };
4448        // §19.2.1.1 step 8: in a sloppy eval, a `var` name that the *running lexical
4449        // environment* already binds is a `SyntaxError`. While a default expression is being
4450        // evaluated that environment is the **parameter** scope, so
4451        // `function(a = eval("var a = 42")){}` throws rather than writing to the parameter —
4452        // the eval would otherwise declare into an environment that is about to be copied
4453        // into the body. A *different* name is fine, and so is the same name in a function
4454        // with a simple parameter list, where there is no separate parameter environment and
4455        // the `var` belongs to the function's own.
4456        //
4457        // The names come from `args`, which is exactly the plain-identifier parameters. A
4458        // pattern parameter's bindings are also in that scope but are not recoverable from
4459        // the bytecode, so `function([a] = eval("var a")){}` is still accepted; that gap is
4460        // narrower than the one this closes and needs the parameter scope published in the
4461        // compiled function to fix.
4462        if self.in_parameter_list_at(caller) {
4463            let parameter_names: Vec<String> = self
4464                .frames
4465                .get(caller)
4466                .map(|frame| {
4467                    frame
4468                        .code
4469                        .code
4470                        .args
4471                        .iter()
4472                        .map(|arg| arg.name.clone())
4473                        .collect()
4474                })
4475                .unwrap_or_default();
4476            let collides = closure_vars.iter().any(|var| {
4477                !var.is_lexical && var.name != "*default*" && parameter_names.contains(&var.name)
4478            });
4479            if collides {
4480                return Err(Signal::Throw(self.make_error(
4481                    "SyntaxError",
4482                    "eval declares a var that the parameter scope already binds",
4483                )));
4484            }
4485        }
4486        if !closure_vars
4487            .iter()
4488            .any(|var| var.name == "arguments" && !var.is_lexical)
4489        {
4490            return Ok(());
4491        }
4492        // The body of a function is a different environment from its parameter list, and only
4493        // the parameter list is separate from `arguments`.
4494        if !self.in_parameter_list_at(caller) {
4495            return Ok(());
4496        }
4497        let caller_is_arrow = self
4498            .frames
4499            .get(caller)
4500            .is_some_and(|frame| frame.code.code.is_arrow);
4501        // A *parameter* named `arguments`, not merely a binding of that name: a body
4502        // `let arguments` is in the body's environment, which is the one that is separate and
4503        // therefore cannot collide. The slot tells them apart — an argument lives in
4504        // `EvalSlot::Arg`, a lexical in `EvalSlot::Local`.
4505        let parameter_scope_binds_arguments = self.eval_bindings.iter().any(|binding| {
4506            binding.frame == caller
4507                && binding.name == "arguments"
4508                && matches!(binding.slot, EvalSlot::Arg)
4509        });
4510        if caller_is_arrow && !parameter_scope_binds_arguments {
4511            return Ok(());
4512        }
4513        Err(Signal::Throw(self.make_error(
4514            "SyntaxError",
4515            "eval declares 'arguments' in a function's parameter scope",
4516        )))
4517    }
4518
4519    /// The cell-backed subset of `bindings`, in the same priority order.
4520    ///
4521    /// Both lookup routes have to agree — the eval's own reads go through
4522    /// [`Interp::eval_binding_value`] and the closures it builds go through
4523    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4524    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4525    /// is not in a cell simply does not appear: reads and writes still work, they just
4526    /// cannot be handed to a closure that outlives the eval.
4527    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4528        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4529        for binding in bindings {
4530            let Some(frame) = self.frames.get(binding.frame) else {
4531                continue;
4532            };
4533            let cell = match binding.slot {
4534                EvalSlot::Arg => frame
4535                    .code
4536                    .arg_cell
4537                    .get(binding.index)
4538                    .copied()
4539                    .unwrap_or(-1),
4540                EvalSlot::Local => frame
4541                    .code
4542                    .loc_cell
4543                    .get(binding.index)
4544                    .copied()
4545                    .unwrap_or(-1),
4546            };
4547            if cell < 0 {
4548                continue;
4549            }
4550            if let Some(cell) = frame.cells.get(cell as usize) {
4551                names.push((binding.name.clone(), cell.clone()));
4552            }
4553        }
4554        names
4555    }
4556
4557    /// A `SyntaxError` that reports where in the source it happened.
4558    ///
4559    /// Compile-time failures never run, so they have no frame of their own; the
4560    /// reference still puts the position first in the trace, with no function name and
4561    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4562    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4563    /// reference borrows), which is how a script reads the position without parsing
4564    /// the trace.
4565    /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4566    ///
4567    /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4568    /// `columnNumber`, which is how the reference prints one. A positionless error
4569    /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4570    /// the reference raises it from `js_resolve_module`, where there is no position.
4571    pub(crate) fn syntax_error_plain(
4572        &mut self,
4573        error: &js_parse::SyntaxError,
4574        file: &str,
4575    ) -> Value {
4576        if error.positionless {
4577            return self.make_error("SyntaxError", &error.message);
4578        }
4579        self.syntax_error_at(
4580            file,
4581            error.span.start.line,
4582            error.span.start.column,
4583            &error.message,
4584        )
4585    }
4586
4587    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4588        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
4589        let value = self.make_error("SyntaxError", message);
4590        if let Value::Object(object) = &value {
4591            let text = self.string(blamed);
4592            // `stack` is an own data property, and the reference keeps it
4593            // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4594            object.define("stack", Property::with_attributes(text, true, false));
4595            let name = self.string(file);
4596            object.define("fileName", Property::with_attributes(name, true, true));
4597            object.define(
4598                "lineNumber",
4599                Property::with_attributes(Value::Int(line as i32), true, true),
4600            );
4601            object.define(
4602                "columnNumber",
4603                Property::with_attributes(Value::Int(column as i32), true, true),
4604            );
4605        }
4606        value
4607    }
4608
4609    /// Run a compiled script whose completion value is a function, returning it.
4610    ///
4611    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4612    /// get the closure out, which keeps the constant-pool plumbing in one place.
4613    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4614        self.run_script(code)
4615    }
4616
4617    /// The environment of a script or of any function compiled at global scope:
4618    /// every entry is a global binding, so each one resolves to the realm's cell.
4619    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4620        let mut cells = Vec::with_capacity(closure_vars.len());
4621        for closure_var in closure_vars {
4622            let cell = match closure_var.closure_type {
4623                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4624                    if closure_var.is_lexical =>
4625                {
4626                    // A lexical declaration: the cell is created here holding the
4627                    // dead-zone marker, which is what makes the binding exist and
4628                    // unreadable before its initialiser runs.
4629                    self.declare_global(&closure_var.name, closure_var.is_const);
4630                    self.realm.globals[&closure_var.name].clone()
4631                }
4632                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4633                    // A `var` or function declaration becomes a property of the global
4634                    // object, and it exists from here on — which is why
4635                    // `print(v); var v = 1` prints `undefined` instead of raising.
4636                    // Declaring it at instantiation time (rather than at the
4637                    // initialiser) is also what makes it non-configurable: the store
4638                    // then lands on an existing property instead of creating one.
4639                    self.declare_var_global(&closure_var.name);
4640                    // The cell is a placeholder that nothing indexes; it cannot be
4641                    // omitted because the slot has to hold something.
4642                    self.new_cell(Value::Undefined)
4643                }
4644                _ => {
4645                    // An undeclared global is read by name; the cell is a
4646                    // placeholder that nothing indexes.
4647                    self.new_cell(Value::Undefined)
4648                }
4649            };
4650            cells.push(cell);
4651        }
4652        Gc::new(
4653            self.heap,
4654            ClosureEnv {
4655                cells,
4656                eval_scope: None,
4657                local_vars: None,
4658                local_phase: 1,
4659            },
4660        )
4661    }
4662
4663    /// Push a frame and run until it returns.
4664    pub(crate) fn execute(
4665        &mut self,
4666        code: Gc<CompiledCode>,
4667        env: Gc<ClosureEnv>,
4668        this: Value,
4669        args: Vec<Value>,
4670        callee: Value,
4671    ) -> JsResult<Value> {
4672        let depth = self.frames.len();
4673        if depth == 0 {
4674            // A throw that reached the host ends the *active* mode: the next one is catchable
4675            // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4676            // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4677            // for the throw that evaluation will raise.
4678            self.uncatchable = false;
4679        }
4680        self.push_frame(code, env, this, args, callee)?;
4681        loop {
4682            // The fast loop first: it runs whole runs of records with `pc` in a register.
4683            //
4684            // `step`'s `pc` lives in the frame, so every instruction writes it back and
4685            // reads it again — a store, a load and two bounds checks that a loop body does
4686            // not need, because nothing outside the loop can run in between. This is the
4687            // classic split: advance a register, and only spill it when leaving.
4688            //
4689            // `Some(value)` means the function ended by running off the end of its
4690            // instruction array, which is a normal return.
4691            let step = match self.run_fast() {
4692                Ok(Some(value)) => Ok(Step::Return(value)),
4693                Ok(None) => self.step(),
4694                Err(signal) => Err(signal),
4695            };
4696            match step {
4697                Ok(Step::Continue) => {}
4698                Ok(Step::Return(value)) => {
4699                    self.pop_frame();
4700                    // A frame that ended in a `tail_call` hands its value straight to
4701                    // its caller: nothing after the call can run, so every frame above
4702                    // the callee unwinds with the same value. See [`Frame::tail`] —
4703                    // the reference does not reuse frames either, so recursion depth
4704                    // and the stack-overflow limit behave the same way.
4705                    while self.frames.len() > depth && self.frame().tail {
4706                        self.pop_frame();
4707                    }
4708                    if self.frames.len() == depth {
4709                        return Ok(value);
4710                    }
4711                    // The caller resumes with the value on its stack.
4712                    self.frames
4713                        .last_mut()
4714                        .expect("a caller is live")
4715                        .stack
4716                        .push(value);
4717                }
4718                Err(Signal::Throw(value)) => {
4719                    // The host's standing request becomes the active mode for this unwind,
4720                    // and is consumed here so it does not leak into the next throw.
4721                    if self.uncatchable_next {
4722                        self.uncatchable_next = false;
4723                        self.uncatchable = true;
4724                    }
4725                    // An uncatchable throw walks past every `catch` on the way out. The
4726                    // frames are still popped, because the values they hold have to be
4727                    // dropped — only the search for a handler is skipped.
4728                    if self.uncatchable {
4729                        while self.frames.len() > depth {
4730                            self.frames.pop();
4731                        }
4732                        return Err(Signal::Throw(value));
4733                    }
4734                    // A handler lives on the stack of the frame that is throwing —
4735                    // `catch` pushed it there — so this frame gets the first chance
4736                    // to catch before it is popped.
4737                    let mut value = value;
4738                    loop {
4739                        if self.frames.len() <= depth {
4740                            return Err(Signal::Throw(value));
4741                        }
4742                        if self.catch_here(&mut value).is_some() {
4743                            break;
4744                        }
4745                        self.frames.pop();
4746                    }
4747                }
4748                // A `yield` in a frame that `execute` is running directly means a
4749                // generator body was entered as an ordinary call, which only happens if
4750                // the generator check in `call_or_push` was bypassed.
4751                Ok(Step::Suspend(_)) => {
4752                    return Err(Signal::Throw(self.make_error(
4753                        "InternalError",
4754                        "a generator body ran as an ordinary call",
4755                    )));
4756                }
4757                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4758            }
4759        }
4760    }
4761
4762    /// Install a handler for `value` if this frame has one, resuming at it.
4763    ///
4764    /// The scan is the reference's: walk the frame's stack downwards looking for the
4765    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset `0` is an
4766    /// enumerator marker rather than a handler — `for of` keeps one under its record so
4767    /// that `break` and `return` can find the iterator — and an exception reaching one
4768    /// **closes that iterator** before the unwinding continues.
4769    ///
4770    /// Skipping the marker instead leaked the iterator of every `for of` whose body threw:
4771    /// `for (const x of xs) { throw new Error }` never called `return`. It was also the
4772    /// whole of a nineteen-case `dstr` cluster, where `[ {}[thrower()] ] = iterable` has to
4773    /// close the iterator while the reference to store into is being worked out.
4774    ///
4775    /// `value` is `&mut` because closing the iterator may replace it: see
4776    /// [`Interp::close_iterator_on_throw`] for which of the two exceptions wins.
4777    fn catch_here(&mut self, value: &mut Value) -> Option<()> {
4778        loop {
4779            // Popped one at a time so no frame borrow is held across the close below.
4780            let top = self.frames.last_mut()?.stack.pop()?;
4781            let Value::CatchOffset(offset) = top else {
4782                continue;
4783            };
4784            if offset != 0 {
4785                let frame = self.frames.last_mut().expect("the frame was just read");
4786                frame.stack.push(value.clone());
4787                frame.pc = offset as usize;
4788                return Some(());
4789            }
4790            // The record's `iter` and `next` sit directly below the marker.
4791            let close = {
4792                let frame = self.frames.last_mut().expect("the frame was just read");
4793                let next = frame.stack.pop();
4794                let iterator = frame.stack.pop();
4795                match (iterator, next) {
4796                    (Some(iterator), Some(_next)) => Some(iterator),
4797                    // A malformed record cannot be closed, but unwinding still has to go
4798                    // on: this is not a handler, so there is nothing to resume at.
4799                    _ => None,
4800                }
4801            };
4802            if let Some(iterator) = close {
4803                self.close_iterator_on_throw(iterator);
4804            }
4805        }
4806    }
4807
4808    /// `IteratorClose` on the exception path — §7.4.6 reached with a *throw* completion.
4809    ///
4810    /// Two things differ from the ordinary close, both from the spec's step ordering:
4811    ///
4812    /// * the original exception **wins**. Step 4 (`If completion is a throw completion,
4813    ///   return ? completion`) comes before step 5, so an exception raised by `return()`
4814    ///   itself — or by reading it — is discarded;
4815    /// * a non-object result is **not** a `TypeError`, because step 6 is never reached.
4816    ///
4817    /// The reference does exactly this in `JS_IteratorClose(…, is_exception_pending=TRUE)`:
4818    /// it saves the pending exception, clears the slot, and re-throws the saved one from
4819    /// `done:` no matter what happened in between.
4820    fn close_iterator_on_throw(&mut self, iterator: Value) {
4821        if matches!(iterator, Value::Undefined) {
4822            return;
4823        }
4824        let Ok(method) = self.read_field(&iterator, "return") else {
4825            return;
4826        };
4827        if matches!(method, Value::Undefined | Value::Null) {
4828            return;
4829        }
4830        // A throw from `return()` replaces nothing: the exception already being unwound is
4831        // the one that propagates.
4832        let _ = self.call_value(method, iterator, Vec::new());
4833    }
4834
4835    fn push_frame(
4836        &mut self,
4837        code: Gc<CompiledCode>,
4838        env: Gc<ClosureEnv>,
4839        this: Value,
4840        mut args: Vec<Value>,
4841        callee: Value,
4842    ) -> JsResult<()> {
4843        // Two bounds, and the byte budget is the one that decides in practice. The
4844        // reference's message is `stack overflow` on an `InternalError`, not V8's
4845        // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4846        // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4847        let frame_cost = Self::frame_cost(&code);
4848        let stack_base = self.stack_used();
4849        if self.frames.len() >= self.max_frames
4850            || stack_base.saturating_add(frame_cost) > self.stack_limit
4851        {
4852            return Err(Signal::Throw(
4853                self.make_error("InternalError", "stack overflow"),
4854            ));
4855        }
4856        let arg_count = code.code.args.len();
4857        // How many were actually passed, which `arguments.length` reports and
4858        // `assert(x)` depends on: a call with one argument must not look like a call
4859        // with one argument and an explicit `undefined`.
4860        let passed = args.len();
4861        // Missing arguments are `undefined` in their slots; extra ones are dropped
4862        // from the slots but still reachable through `arguments`.
4863        //
4864        // A call that passes no more than the declared parameters needs **no** copy:
4865        // after the resize below, `args[..passed]` *is* the passed values. Only the
4866        // extra ones — which `truncate` is about to drop — have to be kept, and they are
4867        // the rare case. This used to copy every call: one `Value` clone per argument
4868        // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4869        let passed_overflow = (passed > arg_count).then(|| {
4870            let mut values = self.take_values(passed, Value::Undefined);
4871            values[..passed].clone_from_slice(&args[..passed]);
4872            values
4873        });
4874        // Only when the counts differ, which for the overwhelmingly common call — as many
4875        // arguments as parameters — is never. `resize` followed by `truncate` on equal
4876        // lengths is two length compares and nothing else, but this is the hottest few
4877        // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4878        if passed != arg_count {
4879            args.resize(arg_count, Value::Undefined);
4880            args.truncate(arg_count);
4881        }
4882        let cell_count = code.code.var_ref_count as usize;
4883        let mut cells = Vec::with_capacity(cell_count);
4884        for _ in 0..cell_count {
4885            cells.push(self.new_cell(Value::Undefined));
4886        }
4887        let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4888        // A captured argument lives in its cell, not in the argument slot, so the
4889        // incoming value has to be moved there before the body runs.
4890        for (slot, cell) in code.arg_cell.iter().enumerate() {
4891            if *cell >= 0
4892                && let Some(value) = args.get(slot).cloned()
4893            {
4894                cells[*cell as usize].set(value);
4895            }
4896        }
4897        // Sloppy mode substitutes the global object for a missing receiver and boxes a
4898        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4899        // reports `object`. Strict mode passes the value through untouched.
4900        let this = if code.code.strict {
4901            this
4902        } else if this.is_nullish() {
4903            Value::Object(self.realm.global.clone())
4904        } else if matches!(this, Value::Object(_)) {
4905            this
4906        } else {
4907            match crate::builtins::this_object(self, &this) {
4908                Ok(boxed) => Value::Object(boxed),
4909                Err(_) => this,
4910            }
4911        };
4912        let stack_depth = code.code.stack_size as usize + 1;
4913        // Taken before the `push` borrows `self.frames`, because the operand stack comes
4914        // out of the same recycle pool the locals did.
4915        let stack = self.take_values(stack_depth, Value::Undefined);
4916        self.frames.push(Frame {
4917            code,
4918            env,
4919            this,
4920            args,
4921            passed_count: passed,
4922            passed_overflow: passed_overflow.map(Box::new),
4923            locals,
4924            cells,
4925            local_vars: None,
4926            // Exactly the depth the compiler computed, so the operand stack never
4927            // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4928            // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4929            // the buffer between calls, so "exactly" costs nothing after the first one.
4930            stack,
4931            pc: 0,
4932            at: 0,
4933            callee,
4934            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4935            cost: frame_cost,
4936            stack_base,
4937            tail: false,
4938        });
4939        Ok(())
4940    }
4941
4942    /// A value buffer of `len` slots, from the recycle pool when there is one.
4943    ///
4944    /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4945    fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4946        // A frame with no locals asks for nothing, and that is most frames: taking a
4947        // buffer out of the pool, clearing it and resizing it to zero is four operations
4948        // and a pool pop for an empty `Vec`, which is free to construct.
4949        if len == 0 {
4950            return Vec::new();
4951        }
4952        let mut buffer = self.free_values.pop().unwrap_or_default();
4953        buffer.clear();
4954        buffer.resize(len, fill);
4955        buffer
4956    }
4957
4958    /// Return a finished frame's value buffers for the next call to reuse.
4959    fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4960        for mut buffer in [
4961            std::mem::take(&mut frame.locals),
4962            frame
4963                .passed_overflow
4964                .take()
4965                .map(|buffer| *buffer)
4966                .unwrap_or_default(),
4967            std::mem::take(&mut frame.stack),
4968        ] {
4969            // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4970            // GC root: it kept every value the frame held reachable, which is invisible
4971            // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4972            // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4973            // exactly that within one run — the target `{}` of a finished IIFE was still
4974            // in its operand stack, in the pool.
4975            buffer.clear();
4976            // A buffer with no capacity is what `Vec::new` is; putting it back would just
4977            // fill the pool with nothing to offer.
4978            if free_values.len() < RECYCLE_SLOTS
4979                && buffer.capacity() > 0
4980                && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4981            {
4982                free_values.push(buffer);
4983            }
4984        }
4985    }
4986
4987    /// Pop a finished frame and keep its buffers.
4988    ///
4989    /// Every place that drops a frame goes through here: a recycled buffer is also where
4990    /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4991    /// nothing but the reuse.
4992    fn pop_frame(&mut self) -> Option<()> {
4993        // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4994        // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4995        let last = self.frames.len().checked_sub(1)?;
4996        Self::recycle(&mut self.free_values, &mut self.frames[last]);
4997        self.frames.truncate(last);
4998        Some(())
4999    }
5000
5001    /// Poll the host's interrupt handler, if one is installed.
5002    ///
5003    /// The counter is what keeps this off the hot path when nobody asked: the early return is
5004    /// one `Option` test, and with no handler installed the whole function is that test —
5005    /// `check_memory` next door already costs more, so this cannot be what shows up in a
5006    /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
5007    #[inline]
5008    fn check_interrupt(&mut self) -> JsResult<()> {
5009        if self.interrupt.is_none() {
5010            return Ok(());
5011        }
5012        if self.interrupt_counter > 0 {
5013            self.interrupt_counter -= 1;
5014            return Ok(());
5015        }
5016        self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
5017        // The closure is taken out for the duration so that a handler which re-enters the
5018        // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
5019        let mut handler = self.interrupt.take().expect("checked above");
5020        let abort = handler();
5021        self.interrupt = Some(handler);
5022        if abort {
5023            // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
5024            // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
5025            // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
5026            // documentation says.
5027            self.uncatchable = true;
5028            return Err(Signal::Throw(
5029                self.make_error("InternalError", "interrupted"),
5030            ));
5031        }
5032        Ok(())
5033    }
5034
5035    /// A memory checkpoint: does the heap still fit under its limit?
5036    ///
5037    /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
5038    /// a `Cell` read and a predictable branch, and the point of asking that often is that
5039    /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
5040    /// only at calls would let it run until the machine died, which is the exact failure
5041    /// `--memory-limit` exists to prevent.
5042    ///
5043    /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
5044    /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
5045    /// script that catches it, drops the reference and carries on is legitimate: measured
5046    /// on `qjs --memory-limit 1M`, the engine recovers.
5047    fn check_memory(&mut self) -> JsResult<()> {
5048        // One `Cell` read and a predictable branch when no limit is set, and an integer
5049        // compare when one is. Containers report their own growth as it happens
5050        // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
5051        // walking it here was the first version and it was O(live) per 256 instructions,
5052        // which turned a 100k-element push loop into a five-minute one.
5053        let Some(limit) = self.heap.memory_limit() else {
5054            return Ok(());
5055        };
5056        let used = self.heap.used_bytes();
5057        if used <= limit {
5058            // Back under the limit — a collection or a dropped reference did it. The next
5059            // time it goes over is a new failure, not a repeat of this one.
5060            self.oom_reported_at = 0;
5061            return Ok(());
5062        }
5063        // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
5064        // block runs normally after `out of memory` — it allocates nothing, so nothing
5065        // fails. A check that re-fired on every instruction made the handler itself throw,
5066        // which is a dead end: the error became unobservable from script.
5067        //
5068        // Comparing against the total at the last report gives the same behaviour: the
5069        // handler runs while the total is unchanged, and the very next allocation over the
5070        // limit fails.
5071        if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
5072        {
5073            return Ok(());
5074        }
5075        self.oom_reported_at = used;
5076        Err(Signal::Throw(
5077            self.make_error("InternalError", "out of memory"),
5078        ))
5079    }
5080
5081    /// Fail before allocating `payload` bytes, if they would not fit.
5082    ///
5083    /// For the allocations whose size comes from script data — `new Array(n)`,
5084    /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
5085    /// is what takes the machine down. The reference has the same shape, with `js_malloc`
5086    /// answering NULL for the one big request.
5087    pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
5088        if self.heap.fits(payload) {
5089            return Ok(());
5090        }
5091        Err(Signal::Throw(
5092            self.make_error("InternalError", "out of memory"),
5093        ))
5094    }
5095
5096    /// Bytes of frame state the live call chain accounts for.
5097    pub fn stack_used(&self) -> usize {
5098        match self.frames.last() {
5099            Some(frame) => frame.stack_base + frame.cost,
5100            None => 0,
5101        }
5102    }
5103
5104    /// What one frame of `code` costs: the frame itself plus the slots it allocates.
5105    ///
5106    /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
5107    /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
5108    /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
5109    /// instead. That is the whole difference between the two models: it rations C stack, we
5110    /// ration frame state, and both quantities are dominated by the value slots — which is
5111    /// why the two depths come out comparable rather than merely proportional.
5112    fn frame_cost(code: &CompiledCode) -> usize {
5113        let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
5114        std::mem::size_of::<Frame>()
5115            + std::mem::size_of::<Value>() * slots
5116            + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
5117    }
5118
5119    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
5120    ///
5121    /// Only names the eval created are here: a name the frame already declared statically
5122    /// is written through to its own slot instead, so this cannot shadow a real local.
5123    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
5124        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
5125        let (local_vars, phase) = self.visible_local_vars()?;
5126        if !local_vars.contains(name) {
5127            return None;
5128        }
5129        local_vars.get(name, phase)
5130    }
5131
5132    /// The variables a direct `eval` declared, as the code currently running sees them.
5133    ///
5134    /// Inside an eval that is the *caller's* set — the eval's own variable environment
5135    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
5136    /// else it is the current frame's, falling back to the frame the closure was created
5137    /// in.
5138    /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
5139    ///
5140    /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
5141    /// which runs on every global read — and the `Option` it was handed cost two `Gc`
5142    /// refcount operations (the clone out of the frame, the drop at the end of the match)
5143    /// just to be asked `is_none`.
5144    fn has_visible_local_vars(&self) -> bool {
5145        let index = match self.eval_caller.flatten() {
5146            Some(caller) => caller,
5147            None => match self.frames.len().checked_sub(1) {
5148                Some(top) => top,
5149                None => return false,
5150            },
5151        };
5152        match self.frames.get(index) {
5153            Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
5154            None => false,
5155        }
5156    }
5157
5158    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
5159        // While an `eval` runs, its own frame is on top but its variable environment is
5160        // the *caller's* — so the caller is what the lookup has to start from.
5161        let (index, phase) = match self.eval_caller.flatten() {
5162            Some(caller) => (
5163                caller,
5164                if self.in_parameter_list_at(caller) {
5165                    0
5166                } else {
5167                    1
5168                },
5169            ),
5170            None => (
5171                self.frames.len().checked_sub(1)?,
5172                if self.in_parameter_list() { 0 } else { 1 },
5173            ),
5174        };
5175        let frame = self.frames.get(index)?;
5176        // The frame's own variables, or — for an arrow, which has no variable environment
5177        // of its own — the one it was created in, which `ClosureEnv` carries.
5178        if let Some(local_vars) = frame.local_vars.clone() {
5179            return Some((local_vars, phase));
5180        }
5181        frame
5182            .env
5183            .local_vars
5184            .clone()
5185            .map(|local_vars| (local_vars, frame.env.local_phase))
5186    }
5187
5188    /// Whether the innermost frame is still evaluating its parameter list.
5189    ///
5190    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
5191    /// and a closure created there may only see that much of [`LocalVars`].
5192    fn in_parameter_list(&self) -> bool {
5193        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
5194    }
5195
5196    /// [`Interp::in_parameter_list`] for a specific frame.
5197    fn in_parameter_list_at(&self, frame: usize) -> bool {
5198        let Some(frame) = self.frames.get(frame) else {
5199            return false;
5200        };
5201        let code = &frame.code.code;
5202        if !code.has_parameter_expressions {
5203            return false;
5204        }
5205        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
5206        // function as its body and let a direct `eval` act accordingly.
5207        if code.body_start == (0, 0) {
5208            return false;
5209        }
5210        match code.position_at(frame.at as u32) {
5211            Some(position) => position < code.body_start,
5212            None => false,
5213        }
5214    }
5215
5216    fn frame(&self) -> &Frame {
5217        self.frames.last().expect("a frame is live")
5218    }
5219
5220    fn frame_mut(&mut self) -> &mut Frame {
5221        self.frames.last_mut().expect("a frame is live")
5222    }
5223
5224    // -- slot access --------------------------------------------------------
5225
5226    /// Move a local's value out, leaving `undefined` in the slot.
5227    ///
5228    /// `None` for a captured slot: its value lives in a cell shared with every closure
5229    /// that closed over it, so it can never be exclusively ours and must not be taken.
5230    ///
5231    /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
5232    /// for every read and fatal for this one — a clone is exactly the second handle that
5233    /// rules out growing the string in place.
5234    fn take_loc(&mut self, slot: usize) -> Option<Value> {
5235        let frame = self.frames.last_mut()?;
5236        if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
5237            return None;
5238        }
5239        frame
5240            .locals
5241            .get_mut(slot)
5242            .map(|value| std::mem::replace(value, Value::Undefined))
5243    }
5244
5245    /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
5246    /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
5247    ///
5248    /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
5249    /// it** — the value is put back before the general path runs — so a `valueOf` that
5250    /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
5251    /// error as it would have without the fusion. This is why the in-place attempt is a
5252    /// `take` and not a `get`: an optimisation that changes what an exception observes is
5253    /// a wrong answer with a good excuse.
5254    fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
5255        // The take is `matches!`-guarded on the *right* operand only, and the taken value
5256        // is put back on every path that does not append. An earlier version wrote the two
5257        // conditions as one `if let` chain — `if right is a string && let Some(Value::String
5258        // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
5259        // through with its value already taken and dropped: the general path below then
5260        // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
5261        // A wrong answer, from an optimisation, with every test green.
5262        if matches!(right, Value::String(_))
5263            && let Some(taken) = self.take_loc(slot)
5264        {
5265            if let Value::String(mut left) = taken {
5266                let appended = match left.get_mut() {
5267                    Some(string) => string.append_in_place(
5268                        // The pattern is the one `matches!` just checked.
5269                        match &right {
5270                            Value::String(text) => text,
5271                            _ => unreachable!("guarded above"),
5272                        },
5273                    ),
5274                    None => None,
5275                };
5276                self.put_loc(slot, Value::String(left));
5277                if let Some(added) = appended {
5278                    // The buffer grew where it stood, so the heap's running total has to
5279                    // be told: `measure_used` would report the new length, and the two must
5280                    // agree or the subtraction at free time leaves the counter wrong.
5281                    self.heap.adjust_payload(added as isize);
5282                    return Ok(());
5283                }
5284            } else {
5285                self.put_loc(slot, taken);
5286            }
5287        }
5288        // The two-number case, without an operand stack round trip. Everything below
5289        // this point is the *general* path: push both, call `binary_add`, pop the answer,
5290        // store it — five operations and two `Value` clones for what is one integer add.
5291        // `AddImmLoc` already answers this shape that way; the fusion above it was written
5292        // for string append and never got the numeric half, so `t += i` — a counting loop
5293        // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
5294        let left = self.get_loc(slot);
5295        if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
5296            self.put_loc(
5297                slot,
5298                match a.checked_add(*b) {
5299                    Some(sum) => Value::Int(sum),
5300                    None => Value::Float(*a as f64 + *b as f64),
5301                },
5302            );
5303            return Ok(());
5304        }
5305        self.push(left);
5306        self.push(right);
5307        self.binary_add()?;
5308        let value = self.pop();
5309        self.put_loc(slot, value);
5310        Ok(())
5311    }
5312
5313    fn get_arg(&self, slot: usize) -> Value {
5314        self.frame().read_arg(slot)
5315    }
5316
5317    fn put_arg(&mut self, slot: usize, value: Value) {
5318        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
5319        if cell == -1 {
5320            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
5321                *slot = value;
5322            }
5323        } else {
5324            self.frame().cells[cell as usize].set(value);
5325        }
5326    }
5327
5328    fn get_loc(&self, slot: usize) -> Value {
5329        // The cell mapping is `-1` for every slot that was not captured — which is all of
5330        // them in a function that creates no closure. `Frame::read_loc` tests that first,
5331        // so the common case is one array read and a clone: 20% of every loop iteration
5332        // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
5333        // sample of `dispatch:arith`).
5334        self.frame().read_loc(slot)
5335    }
5336
5337    fn put_loc(&mut self, slot: usize, value: Value) {
5338        // One borrow instead of three, and the cell check on the frame we already hold.
5339        let frame = self.frames.last_mut().expect("a frame is live");
5340        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
5341        if cell < 0 {
5342            if let Some(slot) = frame.locals.get_mut(slot) {
5343                *slot = value;
5344            }
5345        } else if let Some(cell) = frame.cells.get(cell as usize) {
5346            cell.set(value);
5347        }
5348    }
5349
5350    // -- globals ------------------------------------------------------------
5351
5352    /// The name a global-slot operand refers to.
5353    fn global_name(&self, slot: usize) -> String {
5354        self.frame()
5355            .code
5356            .code
5357            .closure_vars
5358            .get(slot)
5359            .map(|c| c.name.clone())
5360            .unwrap_or_default()
5361    }
5362
5363    /// The facts about a global binding that decide where it lives.
5364    ///
5365    /// A script's globals split in two, and the split is observable: `var` and
5366    /// function declarations become properties of the global object (`globalThis.v`
5367    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
5368    /// declarations live in the global *lexical* environment and are invisible there
5369    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
5370    /// `is_lexical` flag means the answer is already in the bytecode.
5371    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
5372        let name = self.global_name(slot);
5373        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
5374        // while forwarding a reference through a nested function is built with the
5375        // flags cleared, so `const c` would look like an ordinary `var` from inside a
5376        // closure. Presence in the realm's lexical table is the same fact, recorded
5377        // once, and every slot sees it.
5378        let lexical = self.realm.globals.contains_key(&name);
5379        let is_const = self.realm.lexical_consts.contains(&name);
5380        (name, lexical, is_const)
5381    }
5382
5383    /// The value of `name` in the innermost active `with` object, if any.
5384    ///
5385    /// The active objects are the [`VarKind::With`] locals of every frame still running,
5386    /// innermost frame first and innermost block first within one. Walking frames rather
5387    /// than keeping a separate stack is what makes a closure called from inside a `with`
5388    /// see it, and what keeps the object alive only as long as the block is.
5389    /// The innermost active `with` object that has `name`, if any.
5390    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
5391        let objects = self.eval_with.clone().unwrap_or_default();
5392        for object in objects {
5393            let key = self.string(name.to_string());
5394            if self
5395                .has_property(&key, &Value::Object(object.clone()))
5396                .ok()?
5397            {
5398                return Some(object);
5399            }
5400        }
5401        None
5402    }
5403
5404    /// Every active `with` object, innermost first.
5405    fn with_objects(&self) -> Vec<Gc<JsObject>> {
5406        let mut objects = Vec::new();
5407        for frame in self.frames.iter().rev() {
5408            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
5409                if var.kind != js_compile::VarKind::With {
5410                    continue;
5411                }
5412                // A captured binding lives in its cell and not in the slot list, so the
5413                // cell is consulted first — a closure created inside the block is exactly
5414                // what makes the object captured. Before the store runs the slot still
5415                // holds `undefined`, and a `with` object is always boxed, so a non-object
5416                // entry is simply not in scope yet.
5417                let value = frame
5418                    .code
5419                    .loc_cell
5420                    .get(index)
5421                    .copied()
5422                    .filter(|cell| *cell >= 0)
5423                    .and_then(|cell| frame.cells.get(cell as usize))
5424                    .map(|cell| cell.get())
5425                    .or_else(|| frame.locals.get(index).cloned());
5426                if let Some(Value::Object(object)) = value {
5427                    objects.push(object);
5428                }
5429            }
5430        }
5431        objects
5432    }
5433
5434    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
5435        for object in self.eval_with.clone().unwrap_or_default() {
5436            let key = self.string(name.to_string());
5437            if self.has_property(&key, &Value::Object(object.clone()))? {
5438                return Ok(Some(self.read_field(&Value::Object(object), name)?));
5439            }
5440        }
5441        Ok(None)
5442    }
5443
5444    /// Whether every scope between here and the global object is an ordinary one.
5445    ///
5446    /// `eval` and `with` install extra scopes, and each of them may shadow the name the
5447    /// bytecode resolved; when any is live the general path has to run in full order. When
5448    /// none is — every ordinary program — a global read is a property read and nothing
5449    /// else, and that is worth caching.
5450    fn scopes_are_plain(&self) -> bool {
5451        self.eval_caller.is_none()
5452            && self.eval_with.is_none()
5453            && self.eval_arguments.is_none()
5454            && self.eval_bindings.is_empty()
5455            && self.eval_scope.is_none()
5456            // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
5457            // that ran a direct `eval("var z = 1")` inherits the eval's variables through
5458            // its `ClosureEnv`, so the test has to be the same one the general path makes.
5459            // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
5460            // upstream corpus caught and no unit test did.
5461            && !self.has_visible_local_vars()
5462            && self.frame().env.eval_scope.is_none()
5463    }
5464
5465    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
5466        // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
5467        // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
5468        // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
5469        // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
5470        // borrow outlive the `&mut self` the lookup needs.
5471        //
5472        // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
5473        // forwarded through a nested function has its flags cleared, so the flag cannot
5474        // be believed.
5475        let code = self.frame().code.clone();
5476        let name = code
5477            .code
5478            .closure_vars
5479            .get(slot)
5480            .map(|c| c.name.as_str())
5481            .unwrap_or_default();
5482        let lexical = self.realm.globals.contains_key(name);
5483        // The common case, first: an ordinary global `var`, with a cache in front of the
5484        // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
5485        // cannot apply when `scopes_are_plain` — and when it does not apply we take the
5486        // cache hit and return without touching any of it.
5487        if !lexical && self.scopes_are_plain() {
5488            return self.get_plain_global(name, slot);
5489        }
5490        if name == "arguments"
5491            && let Some(arguments) = &self.eval_arguments
5492        {
5493            return Ok(arguments.clone());
5494        }
5495        // A `with` block around the *call site* is part of the scope an `eval` sees, so
5496        // the objects live when the eval started are consulted before anything else. The
5497        // snapshot is taken at entry rather than scanning the frames on every read: a
5498        // block that has already finished still leaves its object in the slot, and a
5499        // bytecode read outside the block must not see it.
5500        if let Some(value) = self.with_lookup(name)? {
5501            return Ok(value);
5502        }
5503        // A variable a direct `eval` declared shadows everything the compiler resolved,
5504        // including an enclosing function's binding: the eval put it in the caller's own
5505        // variable environment, which is nearer than any captured scope.
5506        if let Some((local_vars, phase)) = self.visible_local_vars()
5507            && let Some(cell) = local_vars.get(name, phase)
5508        {
5509            return Ok(cell.get());
5510        }
5511        // The frame that called `eval` is the innermost scope the eval'd code sees, so
5512        // its local `a` wins over a global `a`.
5513        if let Some(value) = self.eval_binding_value(name) {
5514            return Ok(value);
5515        }
5516        // A closure created by an `eval` resolves its free names against the bindings
5517        // that eval saw, even after the eval (and its frames) are gone.
5518        if let Some(cell) = self
5519            .frame()
5520            .env
5521            .eval_scope
5522            .as_ref()
5523            .and_then(|scope| scope.get(name))
5524        {
5525            let value = cell.get();
5526            if matches!(value, Value::Uninitialized) {
5527                return Err(self.throw_reference(name));
5528            }
5529            return Ok(value);
5530        }
5531        // A binding declared by the strict `eval` currently running shadows anything
5532        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5533        if let Some(scope) = &self.eval_scope
5534            && let Some(value) = scope.get(name)
5535        {
5536            return Ok(value.clone());
5537        }
5538        if lexical {
5539            // A lexical global is a binding in a side table, so the dead zone is
5540            // visible and it is nowhere on the global object.
5541            if let Some(cell) = self.realm.globals.get(name) {
5542                let value = cell.get();
5543                if matches!(value, Value::Uninitialized) {
5544                    return Err(self.throw_reference(name));
5545                }
5546                return Ok(value);
5547            }
5548            return Err(self.throw_reference(name));
5549        }
5550        // A `var` global is an ordinary property, so the prototype chain and the
5551        // global object's own builtins are all reachable through it.
5552        match self.get_property(&self.realm.global.clone(), name)? {
5553            Some(value) => Ok(value),
5554            None => Err(self.throw_reference(name)),
5555        }
5556    }
5557
5558    /// Read a plain global `var`: a cached own data property, or the full lookup.
5559    ///
5560    /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5561    /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5562    fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5563        let object = self.realm.global.clone();
5564        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5565        if let Some(cached) = &self.global_cache[site]
5566            && object.upgrades_to(&cached.object)
5567            && let Some(value) = object.data_property_at(cached.index, name)
5568        {
5569            return Ok(value);
5570        }
5571        // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5572        // chain exactly as before, then remember the answer if it is worth remembering.
5573        let Some(value) = self.get_property(&object, name)? else {
5574            return Err(self.throw_reference(name));
5575        };
5576        if let Some(index) = object.own_data_index(name) {
5577            self.global_cache[site] = Some(GlobalCache {
5578                object: object.downgrade(),
5579                index,
5580            });
5581        }
5582        Ok(value)
5583    }
5584
5585    /// Store to a global binding.
5586    ///
5587    /// Returns a signal when the store is refused: a `const` global may only be
5588    /// written by its initialiser, and a non-configurable `var` global may not be
5589    /// deleted but is always writable.
5590    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5591        let (name, lexical, is_const) = self.global_binding(slot);
5592
5593        // An assignment inside a `with` writes through to the object that supplies the
5594        // name, which for an `eval` means consulting the same chain `get_global` does.
5595        if let Some(owner) = self.with_owner(&name) {
5596            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5597            return Ok(());
5598        }
5599        // A variable the running eval *declared* takes the write before any caller
5600        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5601        // environment even when an enclosing function has a `var c` of its own.
5602        if self.eval_caller.flatten().is_some()
5603            && let Some((local_vars, phase)) = self.visible_local_vars()
5604            && local_vars.contains(&name)
5605            && let Some(cell) = local_vars.get(&name, phase)
5606        {
5607            cell.set(value);
5608            return Ok(());
5609        }
5610        // A binding of the frame that called `eval` takes the write, which is what
5611        // makes `f("a = 3")` change the caller's `a`.
5612        if self.set_eval_binding(&name, &value)? {
5613            return Ok(());
5614        }
5615        // A closure that outlived its `eval` writes through to the same cell it reads.
5616        if let Some(cell) = self
5617            .frame()
5618            .env
5619            .eval_scope
5620            .as_ref()
5621            .and_then(|scope| scope.get(&name))
5622            .cloned()
5623        {
5624            cell.set(value);
5625            return Ok(());
5626        }
5627        // Inside a strict `eval`, a name it declared itself is stored there. An
5628        // *assignment* to a name nobody declared is not a declaration, so it falls
5629        // through: strict mode raises `ReferenceError` for it, which is what
5630        // `eval("1 + (@not_def = 1)")` has to do.
5631        if let Some(scope) = self.eval_scope.as_mut()
5632            && scope.contains_key(&name)
5633        {
5634            scope.insert(name, value);
5635            return Ok(());
5636        }
5637        if lexical {
5638            if let Some(cell) = self.realm.globals.get(&name).cloned() {
5639                // A lexical global starts out `Uninitialized` and only `init_global` ends
5640                // that, so a store reaching here is either a plain assignment to a slot
5641                // still in its dead zone — `x = 1; let x` at the top level, a
5642                // `ReferenceError` — or a write to a `const` whose initialiser already ran.
5643                if matches!(cell.get(), Value::Uninitialized) {
5644                    return Err(self.dead_zone_global(&name));
5645                }
5646                if is_const {
5647                    return Err(self.read_only_global(&name));
5648                }
5649                cell.set(value);
5650                return Ok(());
5651            }
5652            // Writing an undeclared lexical global is a `ReferenceError` in strict
5653            // mode and a silent global creation otherwise; creating the cell here
5654            // keeps both paths from losing the value.
5655            let cell = self.new_cell(value);
5656            self.realm.globals.insert(name, cell);
5657            return Ok(());
5658        }
5659        // A variable a direct `eval` declared in this call shadows the global object, even
5660        // when the global already has a property of that name — `var c = "global"` at the
5661        // top level must not capture `eval("var c = 1")` inside a function.
5662        if let Some((local_vars, phase)) = self.visible_local_vars()
5663            && local_vars.contains(&name)
5664            && let Some(cell) = local_vars.get(&name, phase)
5665        {
5666            cell.set(value);
5667            return Ok(());
5668        }
5669        // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5670        // remembered a global's slot index since M12b, but the *store* side never did: it
5671        // converted the name to a `PropertyKey` (two allocations) and then scanned the
5672        // global object's whole table — which holds every builtin — on every assignment to
5673        // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5674        // full global lookup per iteration; measured with a counter, `s` as a global made
5675        // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5676        //
5677        // Re-validated exactly like the read: same object, same index, still the name, and
5678        // — the one extra check a store needs — still writable. A global that is an
5679        // accessor, non-writable, or inherited fails here and falls through to the full
5680        // path below, which reports the failure the way it always did.
5681        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5682        let global = self.realm.global.clone();
5683        if let Some(cached) = &self.global_cache[site]
5684            && global.upgrades_to(&cached.object)
5685            && global.write_data_at(cached.index, &name, value.clone())
5686        {
5687            return Ok(());
5688        }
5689        match global.own_property(&name) {
5690            // A `var` global is writable, so the store goes straight through — but
5691            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5692            // store (a non-writable or accessor-without-setter global) is a silent
5693            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5694            // split every other assignment has.
5695            Some(_) => {
5696                let on_failure = if self.current_strict() {
5697                    DeleteFailure::Throw
5698                } else {
5699                    DeleteFailure::Ignore
5700                };
5701                let result = self.set_property_with(&global, &name, value, on_failure);
5702                // Teach the cache the slot for a plain writable own data property, which is
5703                // what a declared `var` is. Without this the fast path above could never
5704                // fire for a global that is only ever *written* — its entry would have to
5705                // be put there by a read of the same slot, and a write-only loop has none.
5706                if result.is_ok()
5707                    && let Some(index) = global.own_data_index(&name)
5708                {
5709                    self.global_cache[site] = Some(GlobalCache {
5710                        object: global.downgrade(),
5711                        index,
5712                    });
5713                }
5714                result
5715            }
5716            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5717            // declaration creates a *configurable* property, which is what makes it
5718            // deletable and is the one way a global differs from a declared `var`.
5719            // In strict mode the same store is a `ReferenceError` instead: that is the
5720            // whole point of strict mode, and creating the global silently meant
5721            // `"use strict"; x = 1` looked like it worked.
5722            None => {
5723                if self.current_strict() {
5724                    return Err(self.throw_reference(&name));
5725                }
5726                // A direct eval declares here rather than on the global object: its
5727                // `var`s belong to the caller's variable environment. `declare_eval_local`
5728                // also covers a plain assignment to a variable an earlier eval made.
5729                if let Some(cell) = self.declare_eval_local(&name) {
5730                    cell.set(value);
5731                    return Ok(());
5732                }
5733                global.define_data(&name, value);
5734                Ok(())
5735            }
5736        }
5737    }
5738
5739    /// The value of a binding of the frame that called `eval`, if there is one.
5740    fn eval_binding_value(&self, name: &str) -> Option<Value> {
5741        let binding = self
5742            .eval_bindings
5743            .iter()
5744            .find(|binding| binding.name == name)?;
5745        let owner = self.frames.get(binding.frame)?;
5746        let (slot, index) = (binding.slot, binding.index);
5747        Some(match slot {
5748            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5749                cell if cell >= 0 => owner
5750                    .cells
5751                    .get(cell as usize)
5752                    .map(|cell| cell.get())
5753                    .unwrap_or(Value::Undefined),
5754                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5755            },
5756            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5757                cell if cell >= 0 => owner
5758                    .cells
5759                    .get(cell as usize)
5760                    .map(|cell| cell.get())
5761                    .unwrap_or(Value::Undefined),
5762                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5763            },
5764        })
5765    }
5766
5767    /// Write to a binding of the frame that called `eval`.
5768    ///
5769    /// `Ok(false)` means no binding matched and the caller should keep looking. A
5770    /// matched binding can still refuse the store, which is why this is fallible: a
5771    /// `const` is read-only everywhere, and a named function expression's own name is
5772    /// read-only in strict mode.
5773    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5774        let Some(binding) = self
5775            .eval_bindings
5776            .iter()
5777            .find(|binding| binding.name == name)
5778        else {
5779            return Ok(false);
5780        };
5781        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5782        let strict = self.current_strict();
5783        let Some(owner) = self.frames.get_mut(frame) else {
5784            return Ok(false);
5785        };
5786        match slot {
5787            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5788                cell if cell >= 0 => {
5789                    if let Some(cell) = owner.cells.get(cell as usize) {
5790                        cell.set(value.clone());
5791                    }
5792                }
5793                _ => {
5794                    if let Some(slot) = owner.args.get_mut(index) {
5795                        *slot = value.clone();
5796                    }
5797                }
5798            },
5799            EvalSlot::Local => {
5800                let declared = owner.code.code.vars.get(index);
5801                // A `const` is read-only even through `eval`. The realm records this for
5802                // globals (see `lexical_consts`), but a local's `const`-ness is only in
5803                // the bytecode, so this is where it has to be enforced.
5804                if declared.is_some_and(|var| var.is_const) {
5805                    return Err(self.read_only_local(name));
5806                }
5807                // The name of a named function expression is read-only too, but only
5808                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5809                // such a name is ignored, the same as a direct store would be.
5810                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5811                    return if strict {
5812                        Err(self.read_only_local(name))
5813                    } else {
5814                        Ok(true)
5815                    };
5816                }
5817                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5818                    cell if cell >= 0 => {
5819                        if let Some(cell) = owner.cells.get(cell as usize) {
5820                            cell.set(value.clone());
5821                        }
5822                    }
5823                    _ => {
5824                        if let Some(slot) = owner.locals.get_mut(index) {
5825                            *slot = value.clone();
5826                        }
5827                    }
5828                }
5829            }
5830        }
5831        Ok(true)
5832    }
5833
5834    /// The `TypeError` an assignment to a read-only binding raises.
5835    fn read_only_local(&self, name: &str) -> Signal {
5836        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5837    }
5838
5839    /// Declare `name` as a variable of the frame that called the running `eval`.
5840    ///
5841    /// `None` when there is no direct eval in progress, or it was called from the top
5842    /// level — then the caller's variable environment *is* the global one and the
5843    /// existing path is right.
5844    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5845        let caller = self.eval_caller.flatten()?;
5846        // The bottom frame is the top-level script, whose variable environment *is* the
5847        // global one — so `eval("var x = 1")` at the top level still creates a global.
5848        if caller == 0 {
5849            return None;
5850        }
5851        // A name the eval's *own* variable environment already binds is not a new
5852        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5853        // `arguments`, and creating a second binding would leave the first — the one
5854        // closures read — untouched. A binding of an *outer* frame does not count: a
5855        // declaration shadows it rather than writing through.
5856        if self
5857            .eval_bindings
5858            .iter()
5859            .any(|binding| binding.name == name && binding.frame == caller)
5860        {
5861            return None;
5862        }
5863        let phase = if self.in_parameter_list_at(caller) {
5864            0
5865        } else {
5866            1
5867        };
5868        self.frame_local_vars(caller)?;
5869        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5870        if let Some(cell) = local_vars.get(name, 1) {
5871            return Some(cell);
5872        }
5873        let cell = self.new_cell(Value::Undefined);
5874        Some(local_vars.declare(name, phase, cell))
5875    }
5876
5877    /// Make sure `frame` has a `LocalVars`, creating it on demand.
5878    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5879        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5880            return Some(local_vars.clone());
5881        }
5882        let local_vars = Gc::new(self.heap, LocalVars::new());
5883        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5884        Some(local_vars)
5885    }
5886
5887    /// Whether the realm already has a binding for `name`, lexically or as an *own*
5888    /// property of the global object. Used to decide whether a store inside an
5889    /// `eval` writes through to the realm or declares a binding of its own.
5890    ///
5891    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5892    /// write to `Object.prototype.toString`, and must not shadow it either.
5893    fn global_knows(&mut self, name: &str) -> bool {
5894        if self.realm.globals.contains_key(name) {
5895            return true;
5896        }
5897        self.realm.global.own_property(name).is_some()
5898    }
5899
5900    /// Whether the code currently running is strict.
5901    ///
5902    /// Read off the frame's function, which is where the parser's answer ended up; a
5903    /// native function never runs strict-only checks, and there is no frame at all
5904    /// before the first script.
5905    pub fn current_strict(&self) -> bool {
5906        self.frames
5907            .last()
5908            .is_some_and(|frame| frame.code.code.strict)
5909    }
5910
5911    /// Initialise a declared global, which is what ends its dead zone.
5912    ///
5913    /// A `var` global becomes a property of the global object: writable, so a later
5914    /// assignment goes through, and non-configurable, so `delete` refuses.
5915    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5916        let (name, lexical, _) = self.global_binding(slot);
5917        // A `var` declared by the strict `eval` currently running belongs to the
5918        // eval's scope, not to the global object: `eval("var v = 1")` must not make
5919        // `typeof v` answer `"number"` afterwards. A name the realm already has is
5920        // initialised in place, which is what a re-declaration inside eval does.
5921        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5922            self.eval_scope
5923                .as_mut()
5924                .expect("checked above")
5925                .insert(name, value);
5926            return Ok(());
5927        }
5928        if let Some(scope) = self.eval_scope.as_mut()
5929            && scope.contains_key(&name)
5930        {
5931            scope.insert(name, value);
5932            return Ok(());
5933        }
5934        if lexical {
5935            // The cell exists (created at declaration time) holding the dead-zone
5936            // marker; storing the value is what makes the binding readable.
5937            if let Some(cell) = self.realm.globals.get(&name).cloned() {
5938                cell.set(value);
5939                return Ok(());
5940            }
5941            let cell = self.new_cell(value);
5942            self.realm.globals.insert(name, cell);
5943            return Ok(());
5944        }
5945        let global = self.realm.global.clone();
5946        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5947        // to answer `false` and leave the binding in place. `with_attributes` ties
5948        // `configurable` to `writable`, so the property is built field by field.
5949        global.define(
5950            &name,
5951            Property {
5952                value: Some(value),
5953                writable: true,
5954                enumerable: true,
5955                configurable: false,
5956                ..Property::default()
5957            },
5958        );
5959        Ok(())
5960    }
5961
5962    /// The `TypeError` a store to a `const` global raises.
5963    fn read_only_global(&self, name: &str) -> Signal {
5964        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5965    }
5966
5967    /// The `ReferenceError` a store to a not-yet-initialised lexical global raises.
5968    fn dead_zone_global(&self, name: &str) -> Signal {
5969        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not initialized")))
5970    }
5971
5972    // -- properties ---------------------------------------------------------
5973
5974    /// Read `object[key]`, following the prototype chain.
5975    ///
5976    /// An inherited accessor runs with the *receiver* as `this`, which is why the
5977    /// lookup returns the owner rather than just the value.
5978    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5979        self.get_property_key(object, &PropertyKey::from(key))
5980    }
5981
5982    /// [`Interp::get_property`] with a key that may be a symbol.
5983    pub fn get_property_key(
5984        &mut self,
5985        object: &Gc<JsObject>,
5986        key: &PropertyKey,
5987    ) -> JsResult<Option<Value>> {
5988        self.get_property_key_for(object, None, key)
5989    }
5990
5991    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5992    ///
5993    /// The receiver matters when the property is found on a *prototype*: a getter has to
5994    /// see the object the read started from. For a primitive that is the primitive
5995    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5996    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5997    /// the owner.
5998    pub fn get_property_key_for(
5999        &mut self,
6000        object: &Gc<JsObject>,
6001        receiver: Option<&Value>,
6002        key: &PropertyKey,
6003    ) -> JsResult<Option<Value>> {
6004        // A proxy answers for itself, before any of the shortcuts below: `new
6005        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
6006        // have.
6007        if object.proxy_state().is_some() {
6008            let receiver = receiver
6009                .cloned()
6010                .unwrap_or_else(|| Value::Object(object.clone()));
6011            return self.proxy_get(object, &receiver, key);
6012        }
6013        // A host class's `get_property` trap replaces the whole read, prototype walk
6014        // included — that is what makes a native accessor free rather than a JavaScript
6015        // getter call.
6016        if let Some(exotic) = object.exotic() {
6017            let receiver_value = receiver
6018                .cloned()
6019                .unwrap_or_else(|| Value::Object(object.clone()));
6020            if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
6021                return Ok(Some(value));
6022            }
6023            // With no `get_property` trap, a `get_own_property` trap still answers for the
6024            // object itself: `[[Get]]` asks each object in the chain for its own descriptor
6025            // and the hook lives exactly there. A key the trap reports as absent is still
6026            // looked for on the prototype, which is why the search resumes *above*.
6027            if let Some(property) = exotic.get_own_property(self, object, key)? {
6028                return match property {
6029                    Some(property) => self.read_property(property, object, receiver),
6030                    None => match lookup_key_above(object, key) {
6031                        Some((_, property)) => self.read_property(property, object, receiver),
6032                        None => Ok(None),
6033                    },
6034                };
6035            }
6036        }
6037        // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
6038        // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
6039        // The `[[Get]]` short-circuit therefore belongs to this one arm.
6040        //
6041        // Constructibility is exactly the split the reference makes: `function f(){}` and
6042        // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
6043        // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
6044        // function" — it *is* the predicate, which is why no extra marker is needed.
6045        if let Some(text) = key.as_str()
6046            && (text == "caller" || text == "arguments")
6047            && object.is_constructor()
6048            && object.is_callable()
6049            && !object.is_bound_function()
6050            // …and only when the body is **sloppy**. A strict body reaches the
6051            // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
6052            // whole `Function/15.3.5.4_2-*gs` family is written against
6053            // (`onlyStrict`, so every function in them is strict).
6054            && !object.function_is_strict()
6055            && object.own_property(text).is_none()
6056        {
6057            return Ok(Some(Value::Undefined));
6058        }
6059        // The element-vector and `length` shortcuts are string-only: an array index
6060        // has no symbol spelling.
6061        if let Some(text) = key.as_str() {
6062            if let Some(value) = self.own_element(object, text) {
6063                return Ok(Some(value));
6064            }
6065            // `length` is not stored as a property: an array's length is its element
6066            // count, and keeping one copy of it is what makes `push`/`pop` and
6067            // `a.length = n` agree.
6068            if let Some(length) = object.array_length()
6069                && text == "length"
6070            {
6071                // Not `Value::Int(length as i32)`: see [`length_value`].
6072                return Ok(Some(crate::object::length_value(length)));
6073            }
6074        }
6075        // A proxy or a hooked exotic object anywhere above `object` makes the static
6076        // table walk below wrong: a proxy's own table is *empty by design* (the properties
6077        // live on its target), so the walk skipped that link entirely and everything behind
6078        // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
6079        // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
6080        // -target-is-proxy.js` are the four.
6081        if Self::chain_needs_dispatch(object) {
6082            return self.walk_get(object, receiver, key);
6083        }
6084        match lookup_key(object, key) {
6085            Some((_, property)) => self.read_property(property, object, receiver),
6086            None => Ok(None),
6087        }
6088    }
6089
6090    /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
6091    /// answer for itself.
6092    ///
6093    /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
6094    /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
6095    /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
6096    /// an inherited getter the object the read started from.
6097    fn walk_get(
6098        &mut self,
6099        start: &Gc<JsObject>,
6100        receiver: Option<&Value>,
6101        key: &PropertyKey,
6102    ) -> JsResult<Option<Value>> {
6103        let receiver = receiver
6104            .cloned()
6105            .unwrap_or_else(|| Value::Object(start.clone()));
6106        let mut current = Some(start.clone());
6107        while let Some(holder) = current {
6108            // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
6109            // has to ask it, not read its (empty) own-property table. `Object.create(new
6110            // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
6111            // instead found nothing.
6112            if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
6113                return Ok(Some(value));
6114            }
6115            // A host class's `get_property` trap replaces the whole read for that holder,
6116            // prototype walk included — the same rule `get_property_key_for` applies to the
6117            // first object.
6118            if let Some(exotic) = holder.exotic()
6119                && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
6120            {
6121                return Ok(Some(value));
6122            }
6123            if let Some(property) = self.object_get_own_property(&holder, key)? {
6124                return self.read_property(property, &holder, Some(&receiver));
6125            }
6126            current = self.object_prototype_of(&holder)?;
6127        }
6128        Ok(None)
6129    }
6130
6131    /// Whether `object` or anything above it has properties that cannot be read out of a
6132    /// property table — a proxy, or an exotic object with a `get_own_property` hook.
6133    ///
6134    /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
6135    /// is the hot path for every property read; this is the check that decides whether it
6136    /// is safe to take it.
6137    fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
6138        object
6139            .chain()
6140            .iter()
6141            .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
6142    }
6143
6144    /// The value a property read answers.
6145    ///
6146    /// One place rather than three, because an accessor has to run with the *receiver* as
6147    /// `this` whether the descriptor came from the property table, an exotic
6148    /// `get_own_property` trap, or a prototype above one.
6149    fn read_property(
6150        &mut self,
6151        property: Property,
6152        object: &Gc<JsObject>,
6153        receiver: Option<&Value>,
6154    ) -> JsResult<Option<Value>> {
6155        if property.is_accessor() {
6156            match &property.getter {
6157                Some(getter) if !matches!(getter, Value::Undefined) => {
6158                    let receiver = receiver
6159                        .cloned()
6160                        .unwrap_or_else(|| Value::Object(object.clone()));
6161                    self.call_value(getter.clone(), receiver, Vec::new())
6162                        .map(Some)
6163                }
6164                // An accessor with no getter reads as `undefined`.
6165                _ => Ok(Some(Value::Undefined)),
6166            }
6167        } else {
6168            Ok(property.value)
6169        }
6170    }
6171
6172    /// `super.key` — start the search at `proto`, but report to `receiver`.
6173    ///
6174    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
6175    /// found on the prototype of a class has to see the *instance* as `this`, and a
6176    /// plain property read off `proto` would lose that.
6177    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
6178        let start = self.require_object(proto)?;
6179        let key = self.propkey(key)?;
6180        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
6181        if matches!(proto, Value::Null) {
6182            return Ok(Value::Undefined);
6183        }
6184        match lookup_key(&start, &key) {
6185            Some((_, property)) if property.is_accessor() => match &property.getter {
6186                Some(getter) if !matches!(getter, Value::Undefined) => {
6187                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
6188                }
6189                _ => Ok(Value::Undefined),
6190            },
6191            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
6192            None => Ok(Value::Undefined),
6193        }
6194    }
6195
6196    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
6197    ///
6198    /// A setter found on the prototype runs with `receiver` as `this`; a data property
6199    /// is shadowed by a new own property on the receiver, the same rule an ordinary
6200    /// assignment follows.
6201    fn super_write(
6202        &mut self,
6203        receiver: &Value,
6204        proto: &Value,
6205        key: &Value,
6206        value: Value,
6207    ) -> JsResult<()> {
6208        let target = self.require_object(receiver)?;
6209        let key = self.propkey(key)?;
6210        if !matches!(proto, Value::Null)
6211            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
6212        {
6213            if property.is_accessor() {
6214                if let Some(setter) = &property.setter
6215                    && !matches!(setter, Value::Undefined)
6216                {
6217                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
6218                }
6219                return Ok(());
6220            }
6221            // A data property on the prototype is writable or not; reading `owner` at
6222            // all is only for the attribute check.
6223            if !property.writable {
6224                return Err(self.type_error(format!("'{key}' is read-only")));
6225            }
6226            let _ = owner;
6227        }
6228        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
6229    }
6230
6231    /// The object a `super` operation needs, or the `TypeError` the spec raises.
6232    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
6233        match value.as_object() {
6234            Some(object) => Ok(object.clone()),
6235            None => Err(Signal::Throw(
6236                self.make_error("TypeError", "value is not an object"),
6237            )),
6238        }
6239    }
6240
6241    /// Build the class object `define_class` produces.
6242    ///
6243    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
6244    /// whose prototype property is a fresh object inheriting from the parent's
6245    /// prototype, and whose own prototype is the parent constructor — which is what makes
6246    /// a static method inherited too.
6247    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
6248        let ctor = self.pop();
6249        let parent = self.pop();
6250        let Value::Object(function) = &ctor else {
6251            return Err(Signal::Throw(
6252                self.make_error("TypeError", "class constructor must be a function"),
6253            ));
6254        };
6255        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
6256        // but gives the instances no prototype at all.
6257        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
6258            match &parent {
6259                Value::Null => (Some(self.realm.function_proto.clone()), None),
6260                Value::Object(parent_class) => {
6261                    // `IsConstructor`, not `IsCallable`: §15.7.14 ClassDefinitionEvaluation
6262                    // step 9 rejects a heritage without `[[Construct]]` *before* reading
6263                    // `superclass.prototype`, so an arrow function and a generator — both
6264                    // callable, neither constructible — are a `TypeError` and their
6265                    // `prototype` getter must never run
6266                    // (`subclass/superclass-arrow-function`, `…-generator-function`).
6267                    if !parent_class.is_constructor() {
6268                        return Err(Signal::Throw(
6269                            self.make_error("TypeError", "parent class must be constructor"),
6270                        ));
6271                    }
6272                    let proto = self.get_property(parent_class, "prototype")?;
6273                    match proto {
6274                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
6275                        Some(Value::Null) => (Some(parent_class.clone()), None),
6276                        _ => {
6277                            return Err(Signal::Throw(self.make_error(
6278                                "TypeError",
6279                                "parent prototype must be an object or null",
6280                            )));
6281                        }
6282                    }
6283                }
6284                _ => {
6285                    return Err(Signal::Throw(
6286                        self.make_error("TypeError", "parent class must be constructor"),
6287                    ));
6288                }
6289            }
6290        } else {
6291            (
6292                Some(self.realm.function_proto.clone()),
6293                Some(self.realm.object_proto.clone()),
6294            )
6295        };
6296        let proto = self.new_object(parent_proto);
6297        function.set_proto(parent_ctor);
6298        // A class is not callable without `new`, and its `prototype` is not writable —
6299        // both follow from being a class and are what `class A {}; A()` throws on.
6300        function.set_class_constructor(true);
6301        function.set_home_object(None);
6302        self.set_function_name(&ctor, name);
6303        self.define_class_properties(function, &ctor, &proto)?;
6304        Ok((ctor, proto))
6305    }
6306
6307    /// Give the constructor its `prototype` and `length`, and the prototype its
6308    /// `constructor` back-pointer.
6309    fn define_class_properties(
6310        &mut self,
6311        function: &Gc<JsObject>,
6312        ctor: &Value,
6313        proto: &Gc<JsObject>,
6314    ) -> JsResult<()> {
6315        proto.define(
6316            "constructor",
6317            Property::with_attributes(ctor.clone(), true, false),
6318        );
6319        function.define(
6320            "prototype",
6321            Property::prototype_of(Value::Object(proto.clone()), false),
6322        );
6323        if let Some((code, _)) = bytecode_of(function) {
6324            let length = code.code.defined_args;
6325            function.define(
6326                "length",
6327                Property::name_or_length(Value::Int(length as i32)),
6328            );
6329        }
6330        Ok(())
6331    }
6332
6333    /// The own array element `key` names, if this object has one.
6334    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
6335        // A typed array's elements live in its buffer, not in a property list: reading one
6336        // goes through the view's element type so a bounds check and a detached buffer are
6337        // both handled there.
6338        //
6339        // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
6340        // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
6341        // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
6342        // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
6343        // consulted. Testing with `array_index` rejected all three, which let a throwing
6344        // getter installed on `TypedArray.prototype["-1"]` run.
6345        if object.typed_array_parts().is_some() {
6346            let property_key = PropertyKey::from(key);
6347            let numeric = canonical_numeric_index(&property_key)?;
6348            if typed_array_index_is_valid(object, numeric) {
6349                return object.typed_array_element(numeric as usize);
6350            }
6351            // Canonical, but not a valid index: `undefined`, and *final*.
6352            return Some(Value::Undefined);
6353        }
6354        let index = array_index(key)?;
6355        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
6356        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
6357        // search early, which is why `Array.prototype[1] = 9` could not be seen through
6358        // `[1,,3][1]`.
6359        match object.array_get(index as usize) {
6360            Some(Value::Hole) | None => None,
6361            other => other,
6362        }
6363    }
6364
6365    /// Store `object[key] = value`, honouring setters and inherited properties.
6366    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
6367        self.set_property_with(object, key, value, DeleteFailure::Throw)
6368    }
6369
6370    /// Store a property, choosing what to do when the object refuses.
6371    ///
6372    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
6373    /// mode, which is the one place assignment differs by mode. Native code (the array
6374    /// methods, `JSON`) always asks for the throw.
6375    pub fn set_property_with(
6376        &mut self,
6377        object: &Gc<JsObject>,
6378        key: &str,
6379        value: Value,
6380        on_failure: DeleteFailure,
6381    ) -> JsResult<()> {
6382        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
6383    }
6384
6385    /// [`Interp::set_property_with`] with a key that may be a symbol.
6386    pub fn set_property_with_key(
6387        &mut self,
6388        object: &Gc<JsObject>,
6389        key: &PropertyKey,
6390        value: Value,
6391        on_failure: DeleteFailure,
6392    ) -> JsResult<()> {
6393        self.set_property_with_key_receiver_aware(object, key, value, on_failure)
6394    }
6395
6396    /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
6397    ///
6398    /// The receiver split lives one level up, in
6399    /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
6400    /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
6401    /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
6402    /// stores into `object` itself, which is why the element branch below converts `V`
6403    /// before asking whether the index is valid: `V` may put it back in bounds
6404    /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
6405    fn set_property_with_key_receiver_aware(
6406        &mut self,
6407        object: &Gc<JsObject>,
6408        key: &PropertyKey,
6409        value: Value,
6410        on_failure: DeleteFailure,
6411    ) -> JsResult<()> {
6412        // §10.4.6.7: a module namespace's `[[Set]]` **always** returns false — for an
6413        // exported name, for a name that is not exported, and for `@@toStringTag` alike.
6414        // Nothing about the receiver or the value changes that, so the whole operation is
6415        // one answer.
6416        //
6417        // Not implementing it explicitly left the ordinary algorithm in charge, and that
6418        // says "true" for names the namespace does not own as soon as the value matches or
6419        // the key is writable, so `Reflect.set(ns, 'local1', …)` answered `true` and strict
6420        // assignment stopped throwing (`await-ns-set-strict`).
6421        if object.module_namespace_marker() {
6422            return match on_failure {
6423                DeleteFailure::Ignore => Ok(()),
6424                DeleteFailure::Throw => Err(self.type_error(format!(
6425                    "cannot assign to property '{key}' of a module namespace object"
6426                ))),
6427            };
6428        }
6429        // A proxy's `set` trap decides, and its `false` means the same thing an
6430        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
6431        if object.proxy_state().is_some() {
6432            let receiver = Value::Object(object.clone());
6433            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
6434                return match (accepted, on_failure) {
6435                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6436                    (false, DeleteFailure::Throw) => {
6437                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
6438                    }
6439                };
6440            }
6441        }
6442        // A host class's `set_property` trap decides for itself. `Some(false)` is a
6443        // refusal and means exactly what a proxy's `false` means.
6444        if let Some(exotic) = object.exotic() {
6445            let receiver = Value::Object(object.clone());
6446            if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
6447                return match (accepted, on_failure) {
6448                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6449                    (false, DeleteFailure::Throw) => {
6450                        Err(self.type_error(format!("property '{key}' is read-only")))
6451                    }
6452                };
6453            }
6454        }
6455        // The element and `length` shortcuts only exist for string keys: an array
6456        // index has no symbol spelling, and a symbol named `length` is an ordinary
6457        // property.
6458        let text = key.as_str();
6459        // A typed array's elements are a window onto its buffer: the store has to go
6460        // through the view's element type so the value is wrapped (or clamped) and so an
6461        // out-of-range or detached write is a silent no-op, as the spec says.
6462        //
6463        // The key test is `CanonicalNumericIndexString`, like every other index operation
6464        // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
6465        // does not exist, so they do nothing and leave no own property behind
6466        // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
6467        // path, which created a property named `"-0"`.
6468        //
6469        // The conversion comes **first**, before the index is checked at all, and that
6470        // order is observable twice over:
6471        //
6472        // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
6473        //   has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
6474        //   then store the converted value;
6475        // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
6476        //   `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
6477        //   run and its exception to escape.
6478        //
6479        // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
6480        // validity check, not a validity check that skips the conversion. The store itself
6481        // is a no-op when the index is invalid by then, which is why no extra guard is
6482        // needed around `typed_array_set`.
6483        if let Some(element) = object.typed_array_element_type()
6484            && let Some(numeric) = canonical_numeric_index(key)
6485        {
6486            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
6487            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
6488            // in `Interp`, because it is script-observable and the storage borrow inside
6489            // `typed_array_set` must not be held across it.
6490            let stored = self.element_value(element, value)?;
6491            if typed_array_index_is_valid(object, numeric)
6492                && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
6493            {
6494                return Err(self.type_error(reason));
6495            }
6496            return Ok(());
6497        }
6498        if let Some(text) = text
6499            && let Some(index) = array_index(text)
6500            && object.is_array()
6501        {
6502            // An accessor defined on an index lives in the property table while the
6503            // element slot is a hole, so the store has to go through the property first.
6504            // Writing the vector directly skipped the setter entirely.
6505            if let Some(existing) = object.own_property_key(key) {
6506                if existing.is_accessor() {
6507                    return match existing.setter.clone() {
6508                        Some(setter) if !matches!(setter, Value::Undefined) => {
6509                            let receiver = Value::Object(object.clone());
6510                            self.call_value(setter, receiver, vec![value]).map(|_| ())
6511                        }
6512                        _ => match on_failure {
6513                            DeleteFailure::Throw => Err(self.type_error(format!(
6514                                "cannot set property '{text}', it has only a getter"
6515                            ))),
6516                            DeleteFailure::Ignore => Ok(()),
6517                        },
6518                    };
6519                }
6520                if !existing.writable {
6521                    return match on_failure {
6522                        DeleteFailure::Throw => {
6523                            Err(self.type_error(format!("'{text}' is read-only")))
6524                        }
6525                        DeleteFailure::Ignore => Ok(()),
6526                    };
6527                }
6528            }
6529            {
6530                // Growing the array needs a writable `length`.
6531                if (index as usize) >= object.array_length().unwrap_or(0)
6532                    && !object.length_writable()
6533                {
6534                    return match on_failure {
6535                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6536                        DeleteFailure::Ignore => Ok(()),
6537                    };
6538                }
6539                // Adding an index past the end makes the array longer, which a
6540                // non-extensible array refuses.
6541                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6542                    return match on_failure {
6543                        DeleteFailure::Throw => Err(self.type_error(format!(
6544                            "cannot add property '{key}', object is not extensible"
6545                        ))),
6546                        DeleteFailure::Ignore => Ok(()),
6547                    };
6548                }
6549                if object.element_is_locked(index) {
6550                    return match on_failure {
6551                        DeleteFailure::Throw => {
6552                            Err(self.type_error(format!("'{key}' is read-only")))
6553                        }
6554                        DeleteFailure::Ignore => Ok(()),
6555                    };
6556                }
6557                // The element vector is only half of `[[Set]]` for an index: the
6558                // prototype chain is consulted first, and a setter there answers instead
6559                // of the element store. This branch used to write the element directly, so
6560                // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6561                // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6562                // the reference calls the setter and the array keeps no own index.
6563                //
6564                // An *exotic* prototype has no entry to find, because its indices live
6565                // outside the property table — `Object.setPrototypeOf([], typedArray)`
6566                // then looked like "nothing on the chain" and the store created the
6567                // element, where the view's `[[Set]]` answers `true` and does nothing for
6568                // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6569                // checks the array's `length` stays 0). So the dispatch comes first.
6570                if !object.has_own_key(key)
6571                    && let Some(proto) = object.proto()
6572                    && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6573                {
6574                    let receiver = Value::Object(object.clone());
6575                    let accepted =
6576                        self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6577                    return if accepted {
6578                        Ok(())
6579                    } else {
6580                        match on_failure {
6581                            DeleteFailure::Throw => {
6582                                Err(self.type_error(format!("'{key}' is read-only")))
6583                            }
6584                            DeleteFailure::Ignore => Ok(()),
6585                        }
6586                    };
6587                }
6588                if let Some((owner, property)) = lookup_key(object, key)
6589                    && !owner.ptr_eq(object)
6590                {
6591                    match &property {
6592                        property if property.is_accessor() => {
6593                            match &property.setter {
6594                                Some(setter) if !matches!(setter, Value::Undefined) => {
6595                                    let receiver = Value::Object(object.clone());
6596                                    self.call_value(setter.clone(), receiver, vec![value])?;
6597                                }
6598                                _ => {
6599                                    return match on_failure {
6600                                        DeleteFailure::Throw => Err(self.type_error(format!(
6601                                            "cannot set property '{text}', it has only a getter"
6602                                        ))),
6603                                        DeleteFailure::Ignore => Ok(()),
6604                                    };
6605                                }
6606                            }
6607                            return Ok(());
6608                        }
6609                        property if !property.writable => {
6610                            return match on_failure {
6611                                DeleteFailure::Throw => {
6612                                    Err(self.type_error(format!("'{text}' is read-only")))
6613                                }
6614                                DeleteFailure::Ignore => Ok(()),
6615                            };
6616                        }
6617                        _ => {}
6618                    }
6619                }
6620                if object.array_set(self.heap, index as usize, value.clone()) {
6621                    return Ok(());
6622                }
6623                // Past the dense limit the slot is too far out to be worth one `Value`
6624                // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6625                // constant time by keeping the index as an ordinary property. The store
6626                // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6627                // to a legal program.
6628                object.define_key(key, Property::with_attributes(value, true, true));
6629                // Extend, never shorten: the index may be *inside* the current length (a
6630                // huge `length` with a sparse store), and shortening would delete the
6631                // sparse properties above it — including the one just stored.
6632                if index as usize + 1 > object.array_length().unwrap_or(0) {
6633                    object.array_set_length(self.heap, index as usize + 1);
6634                }
6635                return Ok(());
6636            }
6637        }
6638        if text == Some("length") && object.is_array() {
6639            // §10.4.2.4 steps 3–5: **two** `ToNumber` conversions, then the writability
6640            // test. A `valueOf` that locks `length` on its second call therefore turns the
6641            // store into a refused write rather than a silent success
6642            // (`length/define-own-prop-length-coercion-order-set`).
6643            let rounded = self.coerce_array_length_twice(&value)?;
6644            if !object.length_writable() {
6645                return match on_failure {
6646                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6647                    DeleteFailure::Ignore => Ok(()),
6648                };
6649            }
6650            // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6651            // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6652            // answered `NaN`, which left the assignment silently ignored
6653            // (`S15.4.5.2_A3_T2`).
6654            let _ = rounded;
6655            let length = self.to_js_number(&value)?;
6656            // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6657            // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6658            // `RangeError`s; the old code only tested "finite and non-negative" and then
6659            // truncated, so `[].length = 4294967297` quietly produced a length no array can
6660            // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6661            let valid = length.is_finite()
6662                && length >= 0.0
6663                && length.fract() == 0.0
6664                && length <= u32::MAX as f64;
6665            if !valid {
6666                return Err(self.range_error("invalid array length"));
6667            }
6668            {
6669                let length = length as usize;
6670                // `a.length = n` with `n` below a non-configurable element cannot
6671                // drop that element, so the whole assignment fails. The spec makes
6672                // this a `TypeError` rather than a silent no-op, in any mode.
6673                if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6674                    // Sloppy mode stops the truncation at the blocking element
6675                    // instead of failing; strict mode raises.
6676                    // Both modes stop at the blocking element; they differ in
6677                    // whether that is reported. The reference truncates *then*
6678                    // throws, so the array is left in the shortened state.
6679                    object.array_truncate(self.heap, blocked + 1);
6680                    return match on_failure {
6681                        DeleteFailure::Throw => {
6682                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
6683                        }
6684                        DeleteFailure::Ignore => Ok(()),
6685                    };
6686                }
6687                object.array_set_length(self.heap, length);
6688                return Ok(());
6689            }
6690        }
6691        // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6692        // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6693        // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6694        //
6695        // The prototype step is a dispatch, not a lookup. Walking the chain here and
6696        // applying whatever came back is the same thing for an ordinary prototype and
6697        // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6698        // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6699        // answers "not mine, the receiver is not me" without touching the buffer. This
6700        // code used to find nothing owned by `o`, find no property on the view either,
6701        // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6702        // object and never converted (`key-is-valid-index-prototype-chain-set`,
6703        // `key-is-canonical-invalid-index-prototype-chain-set`).
6704        //
6705        // The read-only and accessor rules of step 1 are what make
6706        // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6707        // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6708        let own = match self.lookup_for_write(object, key)? {
6709            Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6710            _ => None,
6711        };
6712        if let Some(property) = own {
6713            if property.is_accessor() {
6714                return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6715                    Some(setter) => {
6716                        let receiver = Value::Object(object.clone());
6717                        self.call_value(setter, receiver, vec![value])?;
6718                        Ok(())
6719                    }
6720                    // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6721                    // Sloppy code swallows that refusal, strict code raises — the same
6722                    // rule the read-only *data* property below follows, and skipping it
6723                    // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6724                    // return silently. The reference answers `TypeError: 'x' is
6725                    // read-only`.
6726                    None => match on_failure {
6727                        DeleteFailure::Throw => {
6728                            Err(self.type_error(format!("'{key}' is read-only")))
6729                        }
6730                        DeleteFailure::Ignore => Ok(()),
6731                    },
6732                };
6733            }
6734            // An own non-writable data property stops here: nothing may change it.
6735            if !property.writable {
6736                return match on_failure {
6737                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6738                    DeleteFailure::Ignore => Ok(()),
6739                };
6740            }
6741            // An existing writable own property keeps its attributes: only the value
6742            // moves. Redefining instead would reset them, which is how a
6743            // non-configurable global `var` used to become deletable.
6744            if object.write_value_key(key, value.clone()) {
6745                return Ok(());
6746            }
6747        }
6748        // Step 2: hand the store to the prototype, with `object` as the receiver.
6749        if let Some(proto) = object.proto() {
6750            let receiver = Value::Object(object.clone());
6751            let accepted =
6752                self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6753            return if accepted {
6754                Ok(())
6755            } else {
6756                match on_failure {
6757                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6758                    DeleteFailure::Ignore => Ok(()),
6759                }
6760            };
6761        }
6762        // Step 3: create one, and a non-extensible object cannot.
6763        if !object.is_extensible() {
6764            return match on_failure {
6765                DeleteFailure::Throw => Err(self.type_error(format!(
6766                    "cannot add property {key}, object is not extensible"
6767                ))),
6768                DeleteFailure::Ignore => Ok(()),
6769            };
6770        }
6771        object.define_data_key(key, value);
6772        Ok(())
6773    }
6774
6775    /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6776    ///
6777    /// The distinction the fast path above does not need: it is called with the store's
6778    /// receiver already being the object it writes to. Here `object` is the one whose
6779    /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6780    /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6781    /// and not a write to `object`.
6782    ///
6783    /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6784    /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6785    /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6786    /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6787    /// descriptor on the prototype refuses instead, which is the same rule that keeps
6788    /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6789    ///
6790    /// Answers `false` where the spec says `false`; the caller turns that into the
6791    /// strict-mode `TypeError` or the sloppy-mode silence.
6792    fn ordinary_set_with_receiver(
6793        &mut self,
6794        object: &Gc<JsObject>,
6795        receiver: &Value,
6796        key: &PropertyKey,
6797        value: Value,
6798        on_failure: DeleteFailure,
6799    ) -> JsResult<bool> {
6800        // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6801        if object.proxy_state().is_some() {
6802            return Ok(self
6803                .proxy_set(object, key, value, receiver)?
6804                .unwrap_or(true));
6805        }
6806        // A host class decides for itself, with the receiver the caller named.
6807        if let Some(exotic) = object.exotic()
6808            && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6809        {
6810            return Ok(accepted);
6811        }
6812        // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6813        // rather than the receiver, but the receiver may still *be* the view:
6814        // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6815        // itself as receiver, and then the first half applies — convert `V` once, store
6816        // if the index is valid, answer `true` either way. The conversion is the observable
6817        // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6818        //
6819        // Only the second half, a view that is *not* the receiver, skips the conversion
6820        // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6821        // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6822        // below with the value still unconverted.
6823        if object.typed_array_element_type().is_some()
6824            && let Some(numeric) = canonical_numeric_index(key)
6825        {
6826            if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6827                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6828                return Ok(true);
6829            }
6830            if !typed_array_index_is_valid(object, numeric) {
6831                return Ok(true);
6832            }
6833        }
6834        let own = self.object_get_own_property(object, key)?;
6835        if let Some(own) = own {
6836            if own.is_accessor() {
6837                return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6838                    Some(setter) => {
6839                        self.call_value(setter, receiver.clone(), vec![value])?;
6840                        Ok(true)
6841                    }
6842                    None => Ok(false),
6843                };
6844            }
6845            // A non-writable data descriptor refuses, own or inherited. Either way the
6846            // receiver must not gain a shadowing property.
6847            if !own.writable {
6848                return Ok(false);
6849            }
6850            // Step 1.d: the *receiver's* own descriptor decides whether it can be
6851            // created or written, and it is created as an ordinary data property.
6852            let Some(receiver_object) = receiver.as_object().cloned() else {
6853                return Ok(false);
6854            };
6855            return match self.object_get_own_property(&receiver_object, key)? {
6856                Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6857                Some(existing) => self.object_define_own_property(
6858                    &receiver_object,
6859                    key,
6860                    Property {
6861                        value: Some(value),
6862                        ..existing
6863                    },
6864                ),
6865                None => {
6866                    self.object_define_own_property(&receiver_object, key, Property::data(value))
6867                }
6868            };
6869        }
6870        // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6871        if let Some(proto) = object.proto() {
6872            return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6873        }
6874        // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6875        // *default* data descriptor here, so control falls into step 2 exactly as if the
6876        // target had owned a writable property — which means the **receiver's** own
6877        // descriptor is asked for before the write. Skipping that question went straight to
6878        // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6879        // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6880        // exactly those calls).
6881        let Some(receiver_object) = receiver.as_object().cloned() else {
6882            return Ok(false);
6883        };
6884        match self.object_get_own_property(&receiver_object, key)? {
6885            Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6886            Some(existing) => self.object_define_own_property(
6887                &receiver_object,
6888                key,
6889                Property {
6890                    value: Some(value),
6891                    ..existing
6892                },
6893            ),
6894            None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6895        }
6896    }
6897
6898    /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6899    ///
6900    /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6901    /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6902    /// a virtual accessor gets its setter run without implementing `set_property` at all.
6903    /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6904    /// the prototype, so the walk resumes above the object.
6905    fn lookup_for_write(
6906        &mut self,
6907        object: &Gc<JsObject>,
6908        key: &PropertyKey,
6909    ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6910        let Some(exotic) = object.exotic() else {
6911            return Ok(lookup_key(object, key));
6912        };
6913        Ok(match exotic.get_own_property(self, object, key)? {
6914            Some(Some(property)) => Some((object.clone(), property)),
6915            Some(None) => lookup_key_above(object, key),
6916            None => lookup_key(object, key),
6917        })
6918    }
6919
6920    /// Delete `object[key]`.
6921    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6922        self.delete_property_key(object, &PropertyKey::from(key))
6923    }
6924
6925    /// [`Interp::delete_property`] with a key that may be a symbol.
6926    pub fn delete_property_key(
6927        &mut self,
6928        object: &Gc<JsObject>,
6929        key: &PropertyKey,
6930    ) -> JsResult<bool> {
6931        // A proxy decides for itself, and may even throw; the invariant checks live in
6932        // `proxy_delete`.
6933        if let Some(answer) = self.proxy_delete(object, key)? {
6934            return Ok(answer);
6935        }
6936        // A host class's `delete_property` trap decides; `false` is a refusal, which the
6937        // caller reports as a failed delete.
6938        if let Some(exotic) = object.exotic()
6939            && let Some(answer) = exotic.delete_property(self, object, key)?
6940        {
6941            return Ok(answer);
6942        }
6943        // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6944        // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6945        // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6946        // one answers `false` because the elements are non-configurable. The prototype
6947        // chain is not consulted either, which is what makes a throwing getter on
6948        // `TypedArray.prototype["-1"]` stay unrun.
6949        if object.typed_array_parts().is_some()
6950            && object.proxy_state().is_none()
6951            && let Some(numeric) = canonical_numeric_index(key)
6952        {
6953            return Ok(!typed_array_index_is_valid(object, numeric));
6954        }
6955        let mapped_index = key.as_str().and_then(array_index);
6956        if let Some(index) = mapped_index
6957            && let Some(length) = object.array_length()
6958            && (index as usize) < length
6959        {
6960            // An accessor defined on an index lives in the property table rather than the
6961            // element vector, so both have to be cleared: `delete` after
6962            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6963            object.delete_key(key);
6964            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6965            // index stops answering `in`.
6966            if object.element_is_undeletable(index) {
6967                return Ok(false);
6968            }
6969            // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6970            // so a later `defineProperty(arguments, "0", {value})` writes to the object
6971            // and no longer through to the parameter. A refused delete leaves the
6972            // mapping alone.
6973            object.drop_mapped_argument(index as usize);
6974            object.array_set(self.heap, index as usize, Value::Hole);
6975            return Ok(true);
6976        }
6977        // An array's `length` is a non-configurable own property that lives outside the
6978        // property table, so `delete_key` finds nothing and reports success — `Reflect
6979        // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6980        // §10.4.4.1 step 3 refuses it.
6981        if key.as_str() == Some("length") && object.array_length().is_some() {
6982            return Ok(false);
6983        }
6984        // The same for an object that is not an array: only a delete that actually
6985        // removed the property ends the alias.
6986        let deleted = object.delete_key(key);
6987        if deleted && let Some(index) = mapped_index {
6988            object.drop_mapped_argument(index as usize);
6989        }
6990        Ok(deleted)
6991    }
6992
6993    // -- proxy traps --------------------------------------------------------
6994    //
6995    // A proxy's internal methods all look the same: ask the handler for the trap, call it
6996    // with the target and the operation's own arguments, then check the answer against
6997    // the target. The checks are not decoration — they are what stops a proxy from
6998    // reporting a `non-configurable` property as missing, which would let a frozen object
6999    // be rewritten by standing in front of it.
7000
7001    /// The target and handler of `object`, or `None` when it is not a proxy.
7002    ///
7003    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
7004    /// one has to fail: the slots the traps would have been read from are gone.
7005    pub(crate) fn proxy_parts(
7006        &mut self,
7007        object: &Gc<JsObject>,
7008    ) -> JsResult<Option<(Gc<JsObject>, Value)>> {
7009        let Some(state) = object.proxy_state() else {
7010            return Ok(None);
7011        };
7012        let state = state.borrow();
7013        match (&state.target, &state.handler) {
7014            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
7015            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
7016        }
7017    }
7018
7019    /// Call `handler[name]`, or answer `None` when the trap is absent.
7020    ///
7021    /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
7022    /// and only a value that is neither is `IsCallable`-checked and refused. Treating
7023    /// `null` as "present but not callable" made every `{ get: null }` proxy throw
7024    /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
7025    /// one per trap plus the `target-is-proxy` variants.
7026    ///
7027    /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
7028    /// this cannot simply be "any non-callable means no trap".
7029    fn proxy_trap(
7030        &mut self,
7031        handler: &Value,
7032        name: &str,
7033        args: Vec<Value>,
7034    ) -> JsResult<Option<Value>> {
7035        let Value::Object(table) = handler else {
7036            return Err(self.type_error("proxy handler is not an object"));
7037        };
7038        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
7039        match trap {
7040            Value::Undefined | Value::Null => Ok(None),
7041            Value::Object(function) if function.is_callable() => {
7042                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
7043                Ok(Some(answer))
7044            }
7045            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
7046        }
7047    }
7048
7049    /// Whether the target's own property `key` is one it refuses to lose.
7050    ///
7051    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
7052    /// its value behind the target's back.
7053    ///
7054    /// A **method**, not a free function, because §10.5.1's invariants say
7055    /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
7056    /// property table directly finds nothing (a proxy's table is empty by design), so every
7057    /// invariant check silently passed for a proxy target. That is what
7058    /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
7059    /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
7060    /// where an array's elements and its `length` — both fixed, both outside the table —
7061    /// are covered.
7062    fn fixed_property(
7063        &mut self,
7064        target: &Gc<JsObject>,
7065        key: &PropertyKey,
7066    ) -> JsResult<Option<Property>> {
7067        Ok(self
7068            .object_get_own_property(target, key)?
7069            .filter(|property| !property.configurable))
7070    }
7071
7072    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
7073    fn proxy_get(
7074        &mut self,
7075        object: &Gc<JsObject>,
7076        receiver: &Value,
7077        key: &PropertyKey,
7078    ) -> JsResult<Option<Value>> {
7079        let Some((target, handler)) = self.proxy_parts(object)? else {
7080            return Ok(None);
7081        };
7082        let key_value = self.key_value(key);
7083        let Some(result) = self.proxy_trap(
7084            &handler,
7085            "get",
7086            vec![Value::Object(target.clone()), key_value, receiver.clone()],
7087        )?
7088        else {
7089            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
7090            // inherited getter still sees the proxy.
7091            return Ok(Some(
7092                self.get_property_key_for(&target, Some(receiver), key)?
7093                    .unwrap_or(Value::Undefined),
7094            ));
7095        };
7096        if let Some(fixed) = self.fixed_property(&target, key)? {
7097            if fixed.is_accessor() {
7098                // A fixed accessor with no getter must read as `undefined`.
7099                let has_getter = fixed
7100                    .getter
7101                    .as_ref()
7102                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
7103                if !has_getter && !matches!(result, Value::Undefined) {
7104                    return Err(self.type_error(format!(
7105                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
7106                    )));
7107                }
7108            } else if !fixed.writable {
7109                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7110                if !fixed_value.same_value(&result) {
7111                    return Err(self.type_error(format!(
7112                        "proxy 'get' disagrees with the non-configurable property '{key}'"
7113                    )));
7114                }
7115            }
7116        }
7117        Ok(Some(result))
7118    }
7119
7120    /// `[[Set]]` on a proxy.
7121    ///
7122    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
7123    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
7124    /// read-only store has.
7125    fn proxy_set(
7126        &mut self,
7127        object: &Gc<JsObject>,
7128        key: &PropertyKey,
7129        value: Value,
7130        receiver: &Value,
7131    ) -> JsResult<Option<bool>> {
7132        let Some((target, handler)) = self.proxy_parts(object)? else {
7133            return Ok(None);
7134        };
7135        let key_value = self.key_value(key);
7136        let Some(result) = self.proxy_trap(
7137            &handler,
7138            "set",
7139            vec![
7140                Value::Object(target.clone()),
7141                key_value,
7142                value.clone(),
7143                receiver.clone(),
7144            ],
7145        )?
7146        else {
7147            // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
7148            // given — not the target. `OrdinarySet` step 3 is
7149            // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
7150            // object whose prototype is a typed array has to reach the proxy's own
7151            // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
7152            // calls and expects exactly one. Storing on the target instead put the value
7153            // in the target and never consulted the trap.
7154            let accepted = self.ordinary_set_with_receiver(
7155                &target,
7156                receiver,
7157                key,
7158                value,
7159                DeleteFailure::Ignore,
7160            )?;
7161            return Ok(Some(accepted));
7162        };
7163        if !result.to_boolean() {
7164            return Ok(Some(false));
7165        }
7166        if let Some(fixed) = self.fixed_property(&target, key)? {
7167            if fixed.is_accessor() {
7168                let has_setter = fixed
7169                    .setter
7170                    .as_ref()
7171                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
7172                if !has_setter {
7173                    return Err(self.type_error(format!(
7174                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
7175                    )));
7176                }
7177            } else if !fixed.writable {
7178                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7179                if !fixed_value.same_value(&value) {
7180                    return Err(self.type_error(format!(
7181                        "proxy 'set' changed the non-configurable property '{key}'"
7182                    )));
7183                }
7184            }
7185        }
7186        // A new property cannot appear on a target that refuses new properties.
7187        if self.object_get_own_property(&target, key)?.is_none()
7188            && !self.object_is_extensible(&target)?
7189        {
7190            return Err(self.type_error(format!(
7191                "proxy 'set' added '{key}' to a non-extensible target"
7192            )));
7193        }
7194        Ok(Some(true))
7195    }
7196
7197    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
7198    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7199        let Some((target, handler)) = self.proxy_parts(object)? else {
7200            return Ok(None);
7201        };
7202        let key_value = self.key_value(key);
7203        let Some(result) = self.proxy_trap(
7204            &handler,
7205            "has",
7206            vec![Value::Object(target.clone()), key_value],
7207        )?
7208        else {
7209            return Ok(Some(self.has_own_or_inherited(&target, key)?));
7210        };
7211        if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7212            return Err(self.type_error(format!(
7213                "proxy 'has' denied the non-configurable property '{key}'"
7214            )));
7215        }
7216        // A non-extensible target cannot grow, so every own property it *has* is fixed.
7217        if !result.to_boolean()
7218            && !self.object_is_extensible(&target)?
7219            && self.object_get_own_property(&target, key)?.is_some()
7220        {
7221            return Err(self.type_error(format!(
7222                "proxy 'has' denied the own property '{key}' of a non-extensible target"
7223            )));
7224        }
7225        Ok(Some(result.to_boolean()))
7226    }
7227
7228    /// `[[Delete]]` on a proxy.
7229    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7230        let Some((target, handler)) = self.proxy_parts(object)? else {
7231            return Ok(None);
7232        };
7233        let key_value = self.key_value(key);
7234        let Some(result) = self.proxy_trap(
7235            &handler,
7236            "deleteProperty",
7237            vec![Value::Object(target.clone()), key_value],
7238        )?
7239        else {
7240            return Ok(Some(self.delete_property_key(&target, key)?));
7241        };
7242        if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7243            return Err(self.type_error(format!(
7244                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
7245            )));
7246        }
7247        if result.to_boolean()
7248            && !self.object_is_extensible(&target)?
7249            && self.object_get_own_property(&target, key)?.is_some()
7250        {
7251            return Err(self.type_error(format!(
7252                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
7253            )));
7254        }
7255        Ok(Some(result.to_boolean()))
7256    }
7257
7258    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
7259    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
7260        let Some((target, handler)) = self.proxy_parts(object)? else {
7261            return Ok(None);
7262        };
7263        let Some(result) =
7264            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
7265        else {
7266            // No trap: the target's own keys, already in the order an object reports.
7267            return Ok(Some(self.object_own_property_keys(&target)?));
7268        };
7269        // `CreateListFromArrayLike` with the string-or-symbol restriction.
7270        let list = self.list_from_array_like(&result, true)?;
7271        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
7272        for value in list {
7273            let key = self.propkey(&value)?;
7274            if keys.contains(&key) {
7275                return Err(self.type_error(format!(
7276                    "proxy 'ownKeys' returned the duplicate key '{key}'"
7277                )));
7278            }
7279            keys.push(key);
7280        }
7281        // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
7282        // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
7283        // table is empty, which made every check below vacuous.
7284        let target_keys = self.object_own_property_keys(&target)?;
7285        let extensible = self.object_is_extensible(&target)?;
7286        for key in &target_keys {
7287            if keys.contains(key) {
7288                continue;
7289            }
7290            if self.fixed_property(&target, key)?.is_some() {
7291                return Err(self.type_error(format!(
7292                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
7293                )));
7294            }
7295            if !extensible {
7296                return Err(self.type_error(format!(
7297                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
7298                )));
7299            }
7300        }
7301        if !extensible {
7302            // §10.5.11 step 12: the lists must match one for one, in any order.
7303            if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
7304            {
7305                return Err(
7306                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
7307                );
7308            }
7309        }
7310        Ok(Some(keys))
7311    }
7312
7313    /// `[[GetOwnProperty]]` on a proxy.
7314    fn proxy_get_own_property(
7315        &mut self,
7316        object: &Gc<JsObject>,
7317        key: &PropertyKey,
7318    ) -> JsResult<Option<Option<Property>>> {
7319        let Some((target, handler)) = self.proxy_parts(object)? else {
7320            return Ok(None);
7321        };
7322        let key_value = self.key_value(key);
7323        let Some(result) = self.proxy_trap(
7324            &handler,
7325            "getOwnPropertyDescriptor",
7326            vec![Value::Object(target.clone()), key_value],
7327        )?
7328        else {
7329            // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
7330            // property table. Two things ride on that choice: a target that is itself a
7331            // proxy has to re-dispatch (its own table is empty, so reading it reported
7332            // `undefined` for every key, `Object.keys` then dropped them all), and an array's
7333            // indices and `length` live outside the table and need the ordinary synthesis.
7334            // `object_get_own_property` does both.
7335            return Ok(Some(self.object_get_own_property(&target, key)?));
7336        };
7337        // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
7338        // `ToPropertyDescriptor` runs, because that operation would box the primitive
7339        // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
7340        // empty descriptor instead of refusing.
7341        if !matches!(result, Value::Undefined | Value::Object(_)) {
7342            return Err(self.type_error(
7343                "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
7344            ));
7345        }
7346        let target_desc = self.object_get_own_property(&target, key)?;
7347        let extensible = self.object_is_extensible(&target)?;
7348        let Some(descriptor) = (match result {
7349            Value::Undefined => None,
7350            _ => Some(self.property_from_descriptor(&result)?),
7351        }) else {
7352            // Steps 12.a–12.d: reporting absent is allowed only when the target's own
7353            // descriptor is configurable *and* the target can still grow back.
7354            if let Some(target_desc) = &target_desc {
7355                if !target_desc.configurable {
7356                    return Err(self.type_error(format!(
7357                        "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
7358                    )));
7359                }
7360                if !extensible {
7361                    return Err(self.type_error(format!(
7362                        "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
7363                    )));
7364                }
7365            }
7366            return Ok(Some(None));
7367        };
7368        // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
7369        // which is a stronger requirement than "the target is not contradicting it" — the
7370        // four branches below are each one test262 case.
7371        if !descriptor.configurable {
7372            let Some(target_desc) = &target_desc else {
7373                return Err(self.type_error(format!(
7374                    "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
7375                )));
7376            };
7377            if target_desc.configurable {
7378                return Err(self.type_error(format!(
7379                    "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
7380                )));
7381            }
7382            let target_is_data = !target_desc.is_accessor();
7383            let result_is_data = !descriptor.is_accessor();
7384            if result_is_data && !target_is_data {
7385                return Err(self.type_error(format!(
7386                    "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7387                )));
7388            }
7389            if target_is_data && !target_desc.writable {
7390                if !result_is_data {
7391                    return Err(self.type_error(format!(
7392                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7393                    )));
7394                }
7395                if descriptor.writable {
7396                    return Err(self.type_error(format!(
7397                        "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7398                    )));
7399                }
7400                let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7401                let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
7402                if !fixed_value.same_value(&reported) {
7403                    return Err(self.type_error(format!(
7404                        "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
7405                    )));
7406                }
7407            }
7408            // Step 16.d: a reported *read-only* data property needs a real read-only data
7409            // property behind it. Missing this let a trap bolt a frozen property onto a
7410            // writable target intent (`resultdesc-is-not-configurable-not-writable-
7411            // targetdesc-is-writable`).
7412            if result_is_data && !descriptor.writable {
7413                if !target_is_data {
7414                    return Err(self.type_error(format!(
7415                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7416                    )));
7417                }
7418                if target_desc.writable {
7419                    return Err(self.type_error(format!(
7420                        "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
7421                    )));
7422                }
7423            }
7424            if descriptor.is_accessor() {
7425                // Step 16.e: a getter the target does not have may not be invented, and
7426                // vice versa.
7427                let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7428                    (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7429                    (Some(a), Some(b)) => a.same_value(b),
7430                    _ => false,
7431                };
7432                if !same(&target_desc.getter, &descriptor.getter)
7433                    || !same(&target_desc.setter, &descriptor.setter)
7434                {
7435                    return Err(self.type_error(format!(
7436                        "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7437                    )));
7438                }
7439            }
7440        }
7441        // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
7442        // where the target's own is locked. Without it a handler could advertise
7443        // `{value: 1, configurable: true}` for a non-configurable property, and a caller
7444        // that believed it would try to redefine something it cannot.
7445        if descriptor.configurable
7446            && let Some(target_desc) = &target_desc
7447            && !target_desc.configurable
7448        {
7449            return Err(self.type_error(format!(
7450                "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
7451            )));
7452        }
7453        // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
7454        // through the trap either, however well-formed the descriptor is. This is the
7455        // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
7456        // the frozen target does not own.
7457        if !extensible {
7458            let Some(target_desc) = &target_desc else {
7459                return Err(self.type_error(format!(
7460                    "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
7461                )));
7462            };
7463            if target_desc.is_accessor() == descriptor.is_accessor() {
7464                let target_is_data = !target_desc.is_accessor();
7465                let result_is_data = !descriptor.is_accessor();
7466                if target_is_data && !target_desc.writable && descriptor.writable {
7467                    return Err(self.type_error(format!(
7468                        "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7469                    )));
7470                }
7471                if !result_is_data && !target_is_data {
7472                    let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7473                        (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7474                        (Some(a), Some(b)) => a.same_value(b),
7475                        _ => false,
7476                    };
7477                    if !same(&target_desc.getter, &descriptor.getter)
7478                        || !same(&target_desc.setter, &descriptor.setter)
7479                    {
7480                        return Err(self.type_error(format!(
7481                            "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7482                        )));
7483                    }
7484                }
7485            }
7486        }
7487        Ok(Some(Some(descriptor)))
7488    }
7489
7490    /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
7491    ///
7492    /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
7493    /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
7494    /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
7495    /// for a data property. `Property` cannot express "this field is absent", so the whole
7496    /// property path is skipped and the descriptor is assembled here field by field.
7497    ///
7498    /// `current` is the property the trap reported, used only to tell a data property from
7499    /// an accessor.
7500    pub fn proxy_seal_property(
7501        &mut self,
7502        object: &Gc<JsObject>,
7503        key: &PropertyKey,
7504        frozen: bool,
7505        current: &Property,
7506    ) -> JsResult<bool> {
7507        let Some((_target, handler)) = self.proxy_parts(object)? else {
7508            return Err(self.type_error("not a proxy"));
7509        };
7510        let descriptor = self.new_object(None);
7511        descriptor.define_data("configurable", Value::Bool(false));
7512        if frozen && !current.is_accessor() {
7513            descriptor.define_data("writable", Value::Bool(false));
7514        }
7515        let key_value = self.key_value(key);
7516        let target = object
7517            .proxy_state()
7518            .and_then(|state| state.borrow().target.clone());
7519        let Some(target) = target else {
7520            return Err(self.type_error("cannot use a proxy that has been revoked"));
7521        };
7522        let Some(result) = self.proxy_trap(
7523            &handler,
7524            "defineProperty",
7525            vec![Value::Object(target), key_value, Value::Object(descriptor)],
7526        )?
7527        else {
7528            // No trap means the definition belongs to the target; `false` is its answer.
7529            return Ok(false);
7530        };
7531        Ok(result.to_boolean())
7532    }
7533
7534    /// `[[DefineOwnProperty]]` on a proxy.
7535    fn proxy_define_property(
7536        &mut self,
7537        object: &Gc<JsObject>,
7538        key: &PropertyKey,
7539        property: Property,
7540    ) -> JsResult<Option<bool>> {
7541        let Some((target, handler)) = self.proxy_parts(object)? else {
7542            return Ok(None);
7543        };
7544        let key_value = self.key_value(key);
7545        let descriptor = self.descriptor_from_property(&property);
7546        let Some(result) = self.proxy_trap(
7547            &handler,
7548            "defineProperty",
7549            vec![Value::Object(target.clone()), key_value, descriptor],
7550        )?
7551        else {
7552            // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7553            // going" answer and `object_define_own_property` turns it into exactly that
7554            // forwarding — see the note there. (Reading it as "not a proxy" would define
7555            // the property on the proxy object itself, whose table is empty and which no
7556            // read ever consults.)
7557            return Ok(None);
7558        };
7559        if !result.to_boolean() {
7560            return Ok(Some(false));
7561        }
7562        // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7563        // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7564        // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7565        // and treating them alike made four cases pass a descriptor the target contradicts.
7566        let target_desc = self.object_get_own_property(&target, key)?;
7567        let extensible = self.object_is_extensible(&target)?;
7568        let named = property
7569            .descriptor_fields
7570            .unwrap_or(crate::object::DescriptorFields {
7571                value: false,
7572                writable: false,
7573                enumerable: false,
7574                configurable: false,
7575                get: false,
7576                set: false,
7577            });
7578        if named.configurable && !property.configurable {
7579            let Some(target_desc) = &target_desc else {
7580                return Err(self.type_error(format!(
7581                    "proxy 'defineProperty' invented the non-configurable '{key}'"
7582                )));
7583            };
7584            if target_desc.configurable {
7585                return Err(self.type_error(format!(
7586                    "proxy 'defineProperty' made '{key}' non-configurable"
7587                )));
7588            }
7589        }
7590        // Step 11's other half: reporting that a property was made *configurable* needs a
7591        // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7592        // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7593        // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7594        // target`).
7595        if named.configurable
7596            && property.configurable
7597            && let Some(target_desc) = &target_desc
7598            && !target_desc.configurable
7599        {
7600            return Err(
7601                self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7602            );
7603        }
7604        // Step 12: a property cannot be reported *made writable* when the target's copy is
7605        // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7606        // the trap is allowed to claim a definition it did not perform, as long as the
7607        // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7608        // legal, and refusing it broke the commonest way to seed a proxy).
7609        if named.writable
7610            && property.writable
7611            && let Some(target_desc) = &target_desc
7612            && !target_desc.writable
7613        {
7614            return Err(self.type_error(format!(
7615                "proxy 'defineProperty' made the read-only '{key}' writable"
7616            )));
7617        }
7618        // Step 13: making a property read-only needs an existing read-only property.
7619        if named.writable
7620            && !property.writable
7621            && let Some(target_desc) = &target_desc
7622            && !target_desc.is_accessor()
7623            && target_desc.writable
7624        {
7625            return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7626        }
7627        // Step 14: a non-writable, non-configurable property's value is fixed.
7628        if named.value
7629            && let Some(target_desc) = &target_desc
7630            && !target_desc.is_accessor()
7631            && !target_desc.writable
7632            && !target_desc.configurable
7633        {
7634            let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7635            let reported = property.value.clone().unwrap_or(Value::Undefined);
7636            if !fixed_value.same_value(&reported) {
7637                return Err(self.type_error(format!(
7638                    "proxy 'defineProperty' changed the value of '{key}'"
7639                )));
7640            }
7641        }
7642        // Step 15: a non-extensible target cannot grow.
7643        if target_desc.is_none() && !extensible {
7644            return Err(self.type_error(format!(
7645                "proxy 'defineProperty' added '{key}' to a non-extensible target"
7646            )));
7647        }
7648        Ok(Some(true))
7649    }
7650
7651    /// `[[GetPrototypeOf]]` on a proxy.
7652    fn proxy_get_prototype_of(
7653        &mut self,
7654        object: &Gc<JsObject>,
7655    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7656        let Some((target, handler)) = self.proxy_parts(object)? else {
7657            return Ok(None);
7658        };
7659        let Some(result) = self.proxy_trap(
7660            &handler,
7661            "getPrototypeOf",
7662            vec![Value::Object(target.clone())],
7663        )?
7664        else {
7665            // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7666            // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7667            // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7668            // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7669            // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7670            return Ok(Some(self.object_prototype_of(&target)?));
7671        };
7672        let proto = match &result {
7673            Value::Null => None,
7674            Value::Object(proto) => Some(proto.clone()),
7675            _ => {
7676                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7677            }
7678        };
7679        if !self.object_is_extensible(&target)? {
7680            let actual = self.object_prototype_of(&target)?;
7681            if !same_proto(proto.as_ref(), actual.as_ref()) {
7682                return Err(self.type_error(
7683                    "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7684                ));
7685            }
7686        }
7687        Ok(Some(proto))
7688    }
7689
7690    /// `[[SetPrototypeOf]]` on a proxy.
7691    fn proxy_set_prototype_of(
7692        &mut self,
7693        object: &Gc<JsObject>,
7694        proto: Option<Gc<JsObject>>,
7695    ) -> JsResult<Option<bool>> {
7696        let Some((target, handler)) = self.proxy_parts(object)? else {
7697            return Ok(None);
7698        };
7699        let proto_value = match &proto {
7700            Some(proto) => Value::Object(proto.clone()),
7701            None => Value::Null,
7702        };
7703        let Some(result) = self.proxy_trap(
7704            &handler,
7705            "setPrototypeOf",
7706            vec![Value::Object(target.clone()), proto_value],
7707        )?
7708        else {
7709            // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7710            // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7711            // its stored prototype overwritten behind its back.
7712            return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7713        };
7714        if result.to_boolean()
7715            && !self.object_is_extensible(&target)?
7716            && !same_proto(
7717                Some(&proto).and_then(|p| p.clone()).as_ref(),
7718                self.object_prototype_of(&target)?.as_ref(),
7719            )
7720        {
7721            return Err(self.type_error(
7722                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7723            ));
7724        }
7725        Ok(Some(result.to_boolean()))
7726    }
7727
7728    /// `[[IsExtensible]]` on a proxy.
7729    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7730        let Some((target, handler)) = self.proxy_parts(object)? else {
7731            return Ok(None);
7732        };
7733        let Some(result) = self.proxy_trap(
7734            &handler,
7735            "isExtensible",
7736            vec![Value::Object(target.clone())],
7737        )?
7738        else {
7739            return Ok(Some(self.object_is_extensible(&target)?));
7740        };
7741        // The answer is not the proxy's to invent: it must agree with the target, or a
7742        // script could learn `false` while the target keeps accepting new properties.
7743        if result.to_boolean() != self.object_is_extensible(&target)? {
7744            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7745        }
7746        Ok(Some(result.to_boolean()))
7747    }
7748
7749    /// `[[PreventExtensions]]` on a proxy.
7750    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7751        let Some((target, handler)) = self.proxy_parts(object)? else {
7752            return Ok(None);
7753        };
7754        let Some(result) = self.proxy_trap(
7755            &handler,
7756            "preventExtensions",
7757            vec![Value::Object(target.clone())],
7758        )?
7759        else {
7760            // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7761            // its answer can be `false`.
7762            return Ok(Some(self.object_prevent_extensions(&target)?));
7763        };
7764        if result.to_boolean() && self.object_is_extensible(&target)? {
7765            return Err(self.type_error(
7766                "proxy 'preventExtensions' reported success but the target is still extensible",
7767            ));
7768        }
7769        Ok(Some(result.to_boolean()))
7770    }
7771
7772    /// `[[Call]]` on a proxy, through the `apply` trap.
7773    fn proxy_apply(
7774        &mut self,
7775        object: &Gc<JsObject>,
7776        this: Value,
7777        args: Vec<Value>,
7778    ) -> JsResult<Option<Value>> {
7779        let Some((target, handler)) = self.proxy_parts(object)? else {
7780            return Ok(None);
7781        };
7782        // The trap gets the arguments as one array, which is the shape the spec passes
7783        // and the shape `apply` traps are written against (`args[0]` is the first one).
7784        let arguments = self.new_array(args.clone());
7785        let this_for_trap = this.clone();
7786        let Some(result) = self.proxy_trap(
7787            &handler,
7788            "apply",
7789            vec![
7790                Value::Object(target.clone()),
7791                this_for_trap,
7792                Value::Object(arguments),
7793            ],
7794        )?
7795        else {
7796            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7797        };
7798        Ok(Some(result))
7799    }
7800
7801    /// `[[Construct]]` on a proxy, through the `construct` trap.
7802    fn proxy_construct(
7803        &mut self,
7804        object: &Gc<JsObject>,
7805        args: Vec<Value>,
7806        new_target: &Value,
7807    ) -> JsResult<Option<Value>> {
7808        let Some((target, handler)) = self.proxy_parts(object)? else {
7809            return Ok(None);
7810        };
7811        if !target.is_callable() {
7812            return Err(self.type_error("proxy target is not a constructor"));
7813        }
7814        let arguments = self.new_array(args.clone());
7815        let Some(result) = self.proxy_trap(
7816            &handler,
7817            "construct",
7818            vec![
7819                Value::Object(target.clone()),
7820                Value::Object(arguments),
7821                new_target.clone(),
7822            ],
7823        )?
7824        else {
7825            return Ok(Some(self.construct(
7826                Value::Object(target),
7827                new_target.clone(),
7828                args,
7829            )?));
7830        };
7831        if !matches!(result, Value::Object(_)) {
7832            return Err(self.type_error("proxy 'construct' must return an object"));
7833        }
7834        Ok(Some(result))
7835    }
7836
7837    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7838    pub(crate) fn has_own_or_inherited(
7839        &mut self,
7840        object: &Gc<JsObject>,
7841        key: &PropertyKey,
7842    ) -> JsResult<bool> {
7843        // The object itself first: it may be a proxy, and then the answer is its trap's.
7844        if let Some(answer) = self.proxy_has(object, key)? {
7845            return Ok(answer);
7846        }
7847        // An integer-indexed exotic object answers a canonical numeric index from
7848        // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7849        // prototype chain. That is observable twice: a view the buffer has been resized
7850        // away from has no indices, so `2 in view` is `false` even when
7851        // `Object.getPrototypeOf(view)[2]` exists (what
7852        // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7853        // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7854        // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7855        // goes through here, which is why the same rule is repeated in `has_property_key`
7856        // rather than living only there.
7857        if object.typed_array_parts().is_some()
7858            && let Some(numeric) = canonical_numeric_index(key)
7859        {
7860            return Ok(typed_array_index_is_valid(object, numeric));
7861        }
7862        // A host class answers `in` for its own keys, which may live nowhere in a property
7863        // table — `"x" in point` is true because the class says so, not because a property
7864        // exists.
7865        if let Some(exotic) = object.exotic()
7866            && let Some(answer) = exotic.has_property(self, object, key)?
7867        {
7868            return Ok(answer);
7869        }
7870        // `has_own` rather than `own_property_key`: an array's elements and its derived
7871        // `length` are invisible to the property table, and `Array.prototype` is an array.
7872        // A host class's `get_own_property` counts too, because the reference's
7873        // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7874        // lives — a class with only `get_own_property` answers `in` through it.
7875        if self.exotic_has_own(object, key)? {
7876            return Ok(true);
7877        }
7878        // A hole is *not* the end of the search: the chain may still have the key, which
7879        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7880        for ancestor in object.chain() {
7881            // A proxy further up the chain answers for itself.
7882            if let Some(answer) = self.proxy_has(&ancestor, key)? {
7883                return Ok(answer);
7884            }
7885            // Same for a host class: a prototype may be one, and `in` reaches it.
7886            if let Some(exotic) = ancestor.exotic()
7887                && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7888            {
7889                return Ok(answer);
7890            }
7891            if self.exotic_has_own(&ancestor, key)? {
7892                return Ok(true);
7893            }
7894        }
7895        Ok(false)
7896    }
7897
7898    /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7899    /// trap included.
7900    ///
7901    /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7902    /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7903    fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7904        if let Some(exotic) = object.exotic()
7905            && let Some(answer) = exotic.get_own_property(self, object, key)?
7906        {
7907            return Ok(answer.is_some());
7908        }
7909        Ok(has_own(object, key))
7910    }
7911
7912    /// `CreateListFromArrayLike`, optionally restricted to property keys.
7913    ///
7914    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7915    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7916    /// `TypeError` instead of a property named `"1.5"`.
7917    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7918        let object = self.object_from(value)?;
7919        let length = self
7920            .get_property(&object, "length")?
7921            .map(|value| value.to_number())
7922            .unwrap_or(0.0);
7923        if !length.is_finite() || length < 0.0 {
7924            return Err(self.type_error("invalid array-like length"));
7925        }
7926        let length = length as usize;
7927        let mut items = Vec::with_capacity(length.min(1024));
7928        for index in 0..length {
7929            let item = self
7930                .get_property(&object, &index.to_string())?
7931                .unwrap_or(Value::Undefined);
7932            if keys_only && matches!(&item, Value::Symbol(_)) {
7933                items.push(item);
7934                continue;
7935            }
7936            if keys_only && !matches!(&item, Value::String(_)) {
7937                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7938            }
7939            items.push(item);
7940        }
7941        Ok(items)
7942    }
7943
7944    /// A `Property` from the descriptor object a trap returned.
7945    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7946        let object = self.object_from(value)?;
7947        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7948            interp.get_property(&object, name)
7949        };
7950        let getter = field(self, "get")?;
7951        let setter = field(self, "set")?;
7952        let accessor = getter.is_some() || setter.is_some();
7953        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7954            Ok(interp
7955                .get_property(&object, name)?
7956                .is_some_and(|value| value.to_boolean()))
7957        };
7958        let enumerable = boolean(self, "enumerable")?;
7959        let configurable = boolean(self, "configurable")?;
7960        if accessor {
7961            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7962                return Err(
7963                    self.type_error("a descriptor cannot be both a data property and an accessor")
7964                );
7965            }
7966            Ok(Property {
7967                getter: getter.or(Some(Value::Undefined)),
7968                setter: setter.or(Some(Value::Undefined)),
7969                enumerable,
7970                configurable,
7971                writable: false,
7972                value: None,
7973                descriptor_fields: None,
7974            })
7975        } else {
7976            Ok(Property {
7977                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7978                writable: boolean(self, "writable")?,
7979                enumerable,
7980                configurable,
7981                getter: None,
7982                setter: None,
7983                descriptor_fields: None,
7984            })
7985        }
7986    }
7987
7988    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7989    fn descriptor_from_property(&mut self, property: &Property) -> Value {
7990        let object = self.new_object(None);
7991        // A partial descriptor names only some fields, and the trap must see exactly those:
7992        // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7993        // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7994        // case, where every field is present.
7995        let fields = property.descriptor_fields;
7996        let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7997            fields.is_none_or(|fields| field(&fields))
7998        };
7999        if property.is_accessor() {
8000            let getter = property.getter.clone().unwrap_or(Value::Undefined);
8001            let setter = property.setter.clone().unwrap_or(Value::Undefined);
8002            object.define_data("get", getter);
8003            object.define_data("set", setter);
8004        } else {
8005            if names(|fields| fields.value) {
8006                let value = property.value.clone().unwrap_or(Value::Undefined);
8007                object.define_data("value", value);
8008            }
8009            if names(|fields| fields.writable) {
8010                object.define_data("writable", Value::Bool(property.writable));
8011            }
8012        }
8013        if names(|fields| fields.enumerable) {
8014            object.define_data("enumerable", Value::Bool(property.enumerable));
8015        }
8016        if names(|fields| fields.configurable) {
8017            object.define_data("configurable", Value::Bool(property.configurable));
8018        }
8019        Value::Object(object)
8020    }
8021
8022    // -- calling ------------------------------------------------------------
8023
8024    /// Call `callee` with `this` and `args`.
8025    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
8026        let Value::Object(function) = &callee else {
8027            // `typeof x === "function"` is not enough to make `x()` legal: only a
8028            // callable object is. `null` and `undefined` need no special wording
8029            // here — their `ToString` already reads the way the reference's does.
8030            let what = format!("{} is not a function", callee.to_js_string());
8031            return Err(Signal::Throw(self.make_error("TypeError", &what)));
8032        };
8033        // A proxy of a function is called through its `apply` trap. It has no
8034        // `ObjectKind::Function` of its own, so this has to come before the dispatch
8035        // below, and a proxy of a non-function has nothing to forward to.
8036        if function.proxy_state().is_some() {
8037            return match self.proxy_apply(function, this, args)? {
8038                Some(result) => Ok(result),
8039                None => Err(Signal::Throw(
8040                    self.make_error("TypeError", "proxy target is not callable"),
8041                )),
8042            };
8043        }
8044        let callable = function.with(|data| match &data.kind {
8045            ObjectKind::Function(callable) => match callable {
8046                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
8047                // The `Rc` is cloned out so the borrow of this object's data is released
8048                // before the closure runs: the closure may touch the same object.
8049                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
8050                Callable::Bound {
8051                    target,
8052                    this,
8053                    args: leading,
8054                } => Some(NativeCall::Bound {
8055                    target: target.clone(),
8056                    this: this.clone(),
8057                    leading: leading.clone(),
8058                }),
8059                Callable::Bytecode { code, env } => {
8060                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
8061                }
8062                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
8063                Callable::PromiseResolve(promise) => {
8064                    Some(NativeCall::PromiseResolve(promise.clone()))
8065                }
8066                Callable::PromiseReject(promise) => {
8067                    Some(NativeCall::PromiseReject(promise.clone()))
8068                }
8069                Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
8070                    state: state.clone(),
8071                }),
8072                Callable::ThenShim {
8073                    handler,
8074                    resolve,
8075                    reject,
8076                    fulfilled,
8077                } => Some(NativeCall::ThenShim {
8078                    handler: handler.clone(),
8079                    resolve: resolve.clone(),
8080                    reject: reject.clone(),
8081                    fulfilled: *fulfilled,
8082                }),
8083                Callable::AwaitResume {
8084                    coroutine,
8085                    promise,
8086                    kind,
8087                } => Some(NativeCall::AwaitResume {
8088                    coroutine: coroutine.clone(),
8089                    promise: promise.clone(),
8090                    kind: *kind,
8091                }),
8092                Callable::CombinatorSettle {
8093                    state,
8094                    index,
8095                    fulfilled,
8096                } => Some(NativeCall::CombinatorSettle {
8097                    state: state.clone(),
8098                    index: *index,
8099                    fulfilled: *fulfilled,
8100                }),
8101                Callable::FinallyShim {
8102                    callback,
8103                    fulfilled,
8104                    constructor,
8105                } => Some(NativeCall::FinallyShim {
8106                    callback: callback.clone(),
8107                    fulfilled: *fulfilled,
8108                    constructor: constructor.clone(),
8109                }),
8110                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
8111                Callable::CompletedReturn {
8112                    generator,
8113                    promise,
8114                    rejected,
8115                } => Some(NativeCall::CompletedReturn {
8116                    generator: generator.clone(),
8117                    promise: promise.clone(),
8118                    rejected: *rejected,
8119                }),
8120                Callable::YieldResult {
8121                    generator,
8122                    promise,
8123                    done,
8124                } => Some(NativeCall::YieldResult {
8125                    generator: generator.clone(),
8126                    promise: promise.clone(),
8127                    done: *done,
8128                }),
8129                Callable::DisposeStep {
8130                    remaining,
8131                    promise,
8132                    error,
8133                    rejected,
8134                    awaited,
8135                    needs_await,
8136                } => Some(NativeCall::DisposeStep {
8137                    remaining: remaining.clone(),
8138                    promise: promise.clone(),
8139                    error: error.clone(),
8140                    rejected: *rejected,
8141                    awaited: *awaited,
8142                    needs_await: *needs_await,
8143                }),
8144                Callable::GeneratorResume {
8145                    generator,
8146                    promise,
8147                    kind,
8148                } => Some(NativeCall::GeneratorResume {
8149                    generator: generator.clone(),
8150                    promise: promise.clone(),
8151                    kind: *kind,
8152                }),
8153                Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
8154                Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
8155                Callable::SettlePromise {
8156                    promise,
8157                    value,
8158                    rejected,
8159                } => Some(NativeCall::SettlePromise {
8160                    promise: promise.clone(),
8161                    value: value.clone(),
8162                    rejected: *rejected,
8163                }),
8164            },
8165            _ => None,
8166        });
8167        match callable {
8168            Some(NativeCall::Host(func)) => {
8169                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
8170                // function by name rather than stopping at the caller.
8171                let frame_less = function
8172                    .own_property("_frame_less")
8173                    .and_then(|property| property.value)
8174                    .is_some_and(|value| value.to_boolean());
8175                let outer = if frame_less {
8176                    None
8177                } else {
8178                    self.native_frames
8179                        .push((function.clone(), self.frames.len()));
8180                    Some(self.current_native.replace(function.clone()))
8181                };
8182                // Same frame bookkeeping as a `Native`, plus `new.target`: a host
8183                // constructor reads it through `current_new_target` because it is handed
8184                // `undefined` for `this`. Taking the parked value here is what stops a
8185                // *plain* call made from inside a constructor body from seeing the
8186                // enclosing `new.target`.
8187                let parked = self.pending_new_target.take();
8188                let result = {
8189                    let outer_new_target = std::mem::replace(
8190                        &mut self.active_new_target,
8191                        parked.unwrap_or(Value::Undefined),
8192                    );
8193                    let result = {
8194                        let mut body = func.borrow_mut();
8195                        body(self, this, &args)
8196                    };
8197                    self.active_new_target = outer_new_target;
8198                    result
8199                };
8200                if !frame_less {
8201                    self.native_frames.pop();
8202                    self.current_native = outer.flatten();
8203                }
8204                result
8205            }
8206            Some(NativeCall::Native(func)) => {
8207                // A function marked `_frame_less` is one the reference implements
8208                // without a call frame — `eval` is the only one so far.
8209                let frame_less = function
8210                    .own_property("_frame_less")
8211                    .and_then(|property| property.value)
8212                    .is_some_and(|value| value.to_boolean());
8213                let outer = if frame_less {
8214                    None
8215                } else {
8216                    self.native_frames
8217                        .push((function.clone(), self.frames.len()));
8218                    Some(self.current_native.replace(function.clone()))
8219                };
8220                let parked = self.pending_new_target.take();
8221                let outer_new_target = std::mem::replace(
8222                    &mut self.active_new_target,
8223                    parked.unwrap_or(Value::Undefined),
8224                );
8225                let result = func(self, this, &args);
8226                self.active_new_target = outer_new_target;
8227                if !frame_less {
8228                    self.native_frames.pop();
8229                    self.current_native = outer.flatten();
8230                }
8231                result
8232            }
8233            Some(NativeCall::Revoker(slots)) => {
8234                // Idempotent: revoking twice answers `undefined` again rather than
8235                // complaining, which is what the spec says and what a `finally` block
8236                // relies on.
8237                let mut state = slots.borrow_mut();
8238                state.target = None;
8239                state.handler = None;
8240                Ok(Value::Undefined)
8241            }
8242            Some(NativeCall::PromiseResolve(promise)) => {
8243                // §27.2.1.3.2 step 4: `[[AlreadyResolved]]` is checked **before** anything
8244                // else, so a resolve after a reject does nothing *and* a resolve after a
8245                // resolve-with-thenable does nothing — the promise is still `Pending` then,
8246                // because the adoption is a queued job.
8247                let value = args.first().cloned().unwrap_or(Value::Undefined);
8248                if !self.claim_resolution(&promise) {
8249                    return Ok(Value::Undefined);
8250                }
8251                // §27.2.1.3.2 steps 7–8: a self-resolution is **rejected, not thrown** —
8252                // the resolve function performs `RejectPromise` and returns `undefined`.
8253                // (`ResolvePromise` itself throws as well, so the engine's own callers see
8254                // it; only this wrapper swallows it.)
8255                let _ = self.resolve_promise_with(&promise, value);
8256                Ok(Value::Undefined)
8257            }
8258            Some(NativeCall::PromiseReject(promise)) => {
8259                let reason = args.first().cloned().unwrap_or(Value::Undefined);
8260                // §27.2.1.3.1 step 3: same one-shot record as `resolve`.
8261                if !self.claim_resolution(&promise) {
8262                    return Ok(Value::Undefined);
8263                }
8264                self.reject_promise(&promise, reason);
8265                Ok(Value::Undefined)
8266            }
8267            Some(NativeCall::ThenShim {
8268                handler,
8269                resolve,
8270                reject,
8271                fulfilled,
8272            }) => {
8273                // `PerformPromiseThen` with a capability: run the handler, then settle
8274                // through the capability's own pair. A throw from the handler is the
8275                // rejection, and a throw from the capability's `resolve` is not caught —
8276                // exactly the spec's `?`.
8277                let value = args.first().cloned().unwrap_or(Value::Undefined);
8278                match handler {
8279                    Some(handler) => {
8280                        match self.call_value(handler, Value::Undefined, vec![value]) {
8281                            Ok(result) => {
8282                                self.call_value(resolve, Value::Undefined, vec![result])?;
8283                            }
8284                            Err(Signal::Throw(reason)) => {
8285                                self.call_value(reject, Value::Undefined, vec![reason])?;
8286                            }
8287                            Err(signal) => return Err(signal),
8288                        }
8289                    }
8290                    None => {
8291                        let handler = if fulfilled { resolve } else { reject };
8292                        self.call_value(handler, Value::Undefined, vec![value])?;
8293                    }
8294                }
8295                Ok(Value::Undefined)
8296            }
8297            Some(NativeCall::CapabilityExecutor { state }) => {
8298                // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
8299                // slot holds a value yet. The test is on the *values*, not on a call count —
8300                // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
8301                // called-twice`'s first case does exactly that), while a second call after a
8302                // real pair is the `TypeError`.
8303                let defined = |name: &str| {
8304                    state
8305                        .own_property(name)
8306                        .and_then(|property| property.value)
8307                        .is_some_and(|value| !matches!(value, Value::Undefined))
8308                };
8309                if defined("resolve") || defined("reject") {
8310                    return Err(self.type_error("promise capability executor called twice"));
8311                }
8312                let resolve = args.first().cloned().unwrap_or(Value::Undefined);
8313                let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
8314                state.define_data("resolve", resolve);
8315                state.define_data("reject", reject);
8316                Ok(Value::Undefined)
8317            }
8318            Some(NativeCall::CombinatorSettle {
8319                state,
8320                index,
8321                fulfilled,
8322            }) => {
8323                let value = args.first().cloned().unwrap_or(Value::Undefined);
8324                self.settle_combinator(&state, index, fulfilled, value)?;
8325                Ok(Value::Undefined)
8326            }
8327            Some(NativeCall::AwaitResume {
8328                coroutine,
8329                promise,
8330                kind,
8331            }) => {
8332                // Resume *inline*, in the reaction that delivered the value. Deferring it
8333                // by another job inserts a tick between every `await` and its
8334                // continuation, which reorders `await` against unrelated `then` chains —
8335                // `f().then(g)` then runs before `f`'s own next statement.
8336                self.drive_async(
8337                    &coroutine,
8338                    &promise,
8339                    kind,
8340                    args.first().cloned().unwrap_or(Value::Undefined),
8341                )
8342                .map(|()| Value::Undefined)
8343            }
8344            Some(NativeCall::ReturnValue(value)) => Ok(value),
8345            Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
8346            Some(NativeCall::FinallyShim {
8347                callback,
8348                fulfilled,
8349                constructor,
8350            }) => {
8351                // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
8352                // own value is discarded; what the caller sees is the *original* outcome,
8353                // delayed until `PromiseResolve(C, result)` has settled.
8354                //
8355                // Two details are observable and both have a test:
8356                //
8357                // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
8358                //   `PerformPromiseThen`. A callback that returns a thenable with its own
8359                //   `then` must have that `then` called
8360                //   (`resolved-observable-then-calls` counts it);
8361                // * only the **fulfil** handler is supplied. A returned promise that
8362                //   *rejects* rejects the whole `finally`, rather than having its failure
8363                //   swallowed and the original value passed through.
8364                let original = args.first().cloned().unwrap_or(Value::Undefined);
8365                let result = match &callback {
8366                    Some(callback) => {
8367                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
8368                    }
8369                    None => Value::Undefined,
8370                };
8371                // `PromiseResolve(C, result)`: a `result` that is already a promise of this
8372                // constructor is reused rather than rewrapped, which is what keeps
8373                // `mp1.finally(() => mp2)` from gaining a layer.
8374                let resolved = self.promise_resolve_for(&constructor, result)?;
8375                let thunk = if fulfilled {
8376                    Callable::ReturnValue(original)
8377                } else {
8378                    Callable::ThrowValue(original)
8379                };
8380                // `length: 0` and `name: ""`, and **not** a constructor — the three things
8381                // `resolved-observable-then-calls-argument` reads off the thunk while it has
8382                // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
8383                // function with no `length` at all.
8384                let thunk = self.builtin_function("", 0, thunk);
8385                let then = self.read_field(&resolved, "then")?;
8386                if !matches!(&then, Value::Object(object) if object.is_callable()) {
8387                    return Err(self.type_error("then is not a function"));
8388                }
8389                self.call_value(then, resolved, vec![Value::Object(thunk)])
8390            }
8391            Some(NativeCall::DisposeStep {
8392                remaining,
8393                promise,
8394                error,
8395                rejected,
8396                awaited,
8397                needs_await,
8398            }) => {
8399                let error = if rejected {
8400                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
8401                    self.merge_dispose_error(reason, error)
8402                } else {
8403                    error
8404                };
8405                self.dispose_step(&remaining, &promise, error, awaited, needs_await)?;
8406                Ok(Value::Undefined)
8407            }
8408            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
8409            Some(NativeCall::CompletedReturn {
8410                generator,
8411                promise,
8412                rejected,
8413            }) => {
8414                let value = args.first().cloned().unwrap_or(Value::Undefined);
8415                let outcome = if rejected {
8416                    AsyncOutcome::Error(value)
8417                } else {
8418                    AsyncOutcome::Value(self.iterator_result(value, true)?)
8419                };
8420                self.settle_async_request(&generator, &promise, outcome)?;
8421                Ok(Value::Undefined)
8422            }
8423            Some(NativeCall::YieldResult {
8424                generator,
8425                promise,
8426                done,
8427            }) => {
8428                let value = args.first().cloned().unwrap_or(Value::Undefined);
8429                let result = self.iterator_result(value, done)?;
8430                self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
8431                Ok(Value::Undefined)
8432            }
8433            Some(NativeCall::GeneratorResume {
8434                generator,
8435                promise,
8436                kind,
8437            }) => {
8438                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
8439                // tick and reorders the generator against other chains.
8440                self.step_async_generator(
8441                    &generator,
8442                    &promise,
8443                    kind,
8444                    args.first().cloned().unwrap_or(Value::Undefined),
8445                )
8446                .map(|()| Value::Undefined)
8447            }
8448            Some(NativeCall::SettlePromise {
8449                promise,
8450                value,
8451                rejected,
8452            }) => {
8453                if rejected {
8454                    self.reject_promise(&promise, value);
8455                } else {
8456                    self.fulfill_promise(&promise, value);
8457                }
8458                Ok(Value::Undefined)
8459            }
8460            Some(NativeCall::Bound {
8461                target,
8462                this: bound_this,
8463                leading,
8464            }) => {
8465                let mut all = leading;
8466                all.extend(args);
8467                self.call_value(target, bound_this, all)
8468            }
8469            Some(NativeCall::Bytecode(code, env)) => {
8470                if code.code.kind.is_generator() {
8471                    return self.new_generator(callee, this, args);
8472                }
8473                if code.code.kind.is_async() {
8474                    // Same coroutine machinery as a generator; the difference is only in
8475                    // what the completion does — see `new_async_function`.
8476                    return self.new_async_function(callee, this, args);
8477                }
8478                self.execute(code, env, this, args, callee)
8479            }
8480            None => Err(Signal::Throw(
8481                self.make_error("TypeError", "not a function"),
8482            )),
8483        }
8484    }
8485
8486    /// Give a freshly built function its own `prototype` object.
8487    ///
8488    /// Every function that can be used with `new` carries one, and its
8489    /// `constructor` points back at the function — a reference cycle, which is
8490    /// exactly what the collector's cycle pass exists to reclaim.
8491    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
8492        self.install_function_prototype_with(function, None);
8493    }
8494
8495    /// [`Interp::install_function_prototype`] with an explicit parent for the new
8496    /// `prototype` object.
8497    ///
8498    /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
8499    /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
8500    /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
8501    /// `None` means `%Object.prototype%`.
8502    fn install_function_prototype_with(
8503        &mut self,
8504        function: &Gc<JsObject>,
8505        parent: Option<Gc<JsObject>>,
8506    ) {
8507        let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
8508        let prototype = self.new_object(Some(parent));
8509        let constructor = Value::Object(function.clone());
8510        prototype.define(
8511            "constructor",
8512            Property::with_attributes(constructor, true, false),
8513        );
8514        let value = Value::Object(prototype);
8515        function.define("prototype", Property::prototype_of(value, true));
8516    }
8517
8518    /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
8519    /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
8520    /// [`Interp::install_function_prototype`] — **no `constructor` property**.
8521    ///
8522    /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
8523    /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
8524    /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
8525    /// is `[]` there.
8526    fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
8527        let prototype = self.new_object(Some(parent));
8528        let value = Value::Object(prototype);
8529        function.define("prototype", Property::prototype_of(value, true));
8530    }
8531
8532    /// The `[[Prototype]]` a newly created generator object gets:
8533    /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
8534    ///
8535    /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
8536    /// function's `prototype` is writable, so a script can replace it with anything, and
8537    /// only an *object* is consulted.
8538    fn generator_instance_proto(
8539        &mut self,
8540        function: &Gc<JsObject>,
8541        default: Gc<JsObject>,
8542    ) -> JsResult<Gc<JsObject>> {
8543        match self.get_property(function, "prototype")? {
8544            Some(Value::Object(prototype)) => Ok(prototype),
8545            _ => Ok(default),
8546        }
8547    }
8548
8549    /// A getter or setter that reads or writes the reference cell behind a mapped
8550    /// `arguments` index.
8551    ///
8552    /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
8553    /// count — which is what the collector treats as "a reference from outside the
8554    /// heap". The closure therefore keeps the cell alive for exactly as long as the
8555    /// accessor is reachable, which is the same lifetime the arguments object has.
8556    ///
8557    /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8558    /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8559    /// parameter value and the arguments object reaches the closure, never the other
8560    /// way round. Nothing the collector has to see is hidden.
8561    fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8562        let name = if is_setter { "set" } else { "get" };
8563        let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8564            if is_setter {
8565                cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8566                Ok(Value::Undefined)
8567            } else {
8568                Ok(cell.get())
8569            }
8570        };
8571        self.new_host_function(name, 1, Box::new(func))
8572    }
8573
8574    /// The object `special_object` builds.
8575    ///
8576    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8577    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8578    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8579    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8580    /// write through `arguments` does not reach the parameter.
8581    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8582        match magic {
8583            0 | 1 => {
8584                let args = self.frame().passed().to_vec();
8585                let proto = self.realm.object_proto.clone();
8586                let object = self.new_object(Some(proto));
8587                // The marker `Object.prototype.toString` needs: an arguments object is an
8588                // ordinary object apart from reporting `[object Arguments]`, and that has
8589                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8590                // show up ahead of them in a key listing anyway — it is non-enumerable.
8591                self.internal_set(&object, "_class", self.string("Arguments"));
8592                // `length` is writable and configurable but neither enumerable nor a
8593                // plain data property: `Object.keys(arguments)` lists the indices only,
8594                // which is how `{...arguments}` copies them without the length.
8595                object.define(
8596                    "length",
8597                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
8598                );
8599                // `magic == 1` is sloppy mode, where each index is *mapped* to the
8600                // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8601                // change `a`, and assigning `a` has to change `arguments[0]`.
8602                //
8603                // The shared storage is the parameter's reference cell. The compiler
8604                // gives every parameter of such a function one (see
8605                // `provide_body_arguments`), and the cell outlives the frame, so this
8606                // keeps working after the arguments object escapes.
8607                //
8608                // The index becomes an accessor rather than a data property. A mapped
8609                // index reports as a plain writable/enumerable data property through
8610                // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8611                // the getter/setter pair is only the plumbing underneath.
8612                let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8613                    let frame = self.frame();
8614                    frame
8615                        .code
8616                        .arg_cell
8617                        .iter()
8618                        .map(|cell| {
8619                            (*cell >= 0)
8620                                .then(|| frame.cells.get(*cell as usize).cloned())
8621                                .flatten()
8622                        })
8623                        .collect()
8624                } else {
8625                    Vec::new()
8626                };
8627                // Tell the object which indices are mapped, so
8628                // `Object.getOwnPropertyDescriptor` can report them as the data
8629                // properties the spec describes instead of the accessors that
8630                // implement the aliasing.
8631                if magic == 1 {
8632                    let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8633                    for cell in &mapped_cells {
8634                        table.push(cell.clone());
8635                    }
8636                    object.set_mapped_arguments(table);
8637                }
8638                for (index, value) in args.into_iter().enumerate() {
8639                    match mapped_cells.get(index).cloned().flatten() {
8640                        Some(cell) => {
8641                            let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8642                            let setter = self.new_mapped_arguments_accessor(cell, true);
8643                            object.define(
8644                                &index.to_string(),
8645                                Property::accessor_with(
8646                                    Some(Value::Object(getter)),
8647                                    Some(Value::Object(setter)),
8648                                    true,
8649                                ),
8650                            );
8651                        }
8652                        None => object.define_data(&index.to_string(), value),
8653                    }
8654                }
8655                // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8656                // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8657                // non-enumerable and non-configurable. It is not a nicety — it is the only
8658                // documented way to reach `%ThrowTypeError%`:
8659                //
8660                //     Object.getOwnPropertyDescriptor(function(){"use strict";
8661                //         return arguments;}(), "callee").get
8662                //
8663                // and the whole `ThrowTypeError/` directory is written against that
8664                // expression. Without it 13 cases failed with `cannot read property 'get'
8665                // of undefined`, which reads like a test harness bug rather than a missing
8666                // accessor.
8667                //
8668                // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8669                // writable data property holding the function being called, and
8670                // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8671                // `hasOwnProperty("callee")` hold there.
8672                if magic == 1 {
8673                    let callee = self.frame().callee.clone();
8674                    // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8675                    object.define("callee", Property::with_attributes(callee, true, false));
8676                } else if let Some(thrower) = self.realm.throw_type_error.clone()
8677                    && object.own_property("callee").is_none()
8678                {
8679                    object.define(
8680                        "callee",
8681                        Property {
8682                            getter: Some(Value::Object(thrower.clone())),
8683                            setter: Some(Value::Object(thrower)),
8684                            enumerable: false,
8685                            configurable: false,
8686                            ..Property::default()
8687                        },
8688                    );
8689                }
8690                // An arguments object is iterable: `[...arguments]` and
8691                // `for (const a of arguments)` both work, through the *array* iterator
8692                // because the object is array-like. Without this the whole spread form
8693                // reported "not iterable".
8694                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8695                let values = self
8696                    .realm
8697                    .array_proto
8698                    .own_property("values")
8699                    .and_then(|property| property.value);
8700                if let Some(values) = values {
8701                    object.define_key(
8702                        &iterator_key,
8703                        Property::with_attributes(values, true, false),
8704                    );
8705                }
8706                Ok(Value::Object(object))
8707            }
8708            // `this.active_func`: the constructor `super()` resolves against.
8709            //
8710            // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8711            // own, so it inherits this from the function it was written in along with `this`
8712            // — and that is a lexical relationship, not a stack one: an arrow that escaped
8713            // the constructor and is called back later (`iter.return = () => super()`) has
8714            // the constructor nowhere on the stack. The compiler therefore reads it out of
8715            // a closure variable of the enclosing function, exactly as the reference does
8716            // with its `this_active_func` local.
8717            2 => Ok(self
8718                .current_callee()
8719                .map_or(Value::Undefined, Value::Object)),
8720            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8721            // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8722            // its own either, so the lookup walks out to the nearest non-arrow frame for
8723            // the same reason as `this.active_func` above — without that, `super()` inside
8724            // an arrow passed `undefined` as the new target and the parent constructor was
8725            // then rejected for being invoked without `new`.
8726            3 => Ok(self
8727                .eval_new_target
8728                .clone()
8729                .unwrap_or_else(|| self.frame().new_target.clone())),
8730            // `[[HomeObject]]` of the function being run: what `super` is relative to.
8731            // An arrow has none of its own, so the lookup walks out to the enclosing
8732            // method — which is why `super` works inside an arrow inside a method.
8733            4 => Ok(self
8734                .frames
8735                .iter()
8736                .rev()
8737                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8738                .map_or(Value::Undefined, Value::Object)),
8739            // `import.meta`: the innermost module body's meta object. Outside a module
8740            // the compiler never emits this, so an empty fallback is unreachable rather
8741            // than permissive.
8742            6 => {
8743                let name = self.module_stack.last().cloned();
8744                let meta = name
8745                    .and_then(|name| self.modules.get(&name).cloned())
8746                    .and_then(|module| module.with(|r| r.import_meta.clone()));
8747                Ok(meta.map_or(Value::Undefined, Value::Object))
8748            }
8749            other => Err(Signal::Throw(self.make_error(
8750                "InternalError",
8751                &format!("special_object {other} is not implemented yet"),
8752            ))),
8753        }
8754    }
8755
8756    /// `[[HomeObject]]` of the innermost function that has one, if any.
8757    ///
8758    /// An arrow has none, so the search walks out to the enclosing method — the same
8759    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8760    /// inside a method.
8761    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8762        self.frames
8763            .iter()
8764            .rev()
8765            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8766    }
8767
8768    /// The dispose method a `using` declaration should snapshot, or an error.
8769    ///
8770    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8771    /// is what makes a resource that only knows the synchronous protocol usable in both
8772    /// forms.
8773    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8774        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8775        if value.is_nullish() {
8776            return Ok(Value::Undefined);
8777        }
8778        let Some(object) = value.as_object() else {
8779            return Err(self.type_error("not an object"));
8780        };
8781        let mut method = if await_form {
8782            let found = self.get_property_key(
8783                object,
8784                &self.realm.well_known_key(WellKnown::AsyncDisposable),
8785            )?;
8786            match found {
8787                Some(found) if !found.is_nullish() => Some(found),
8788                _ => self
8789                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8790            }
8791        } else {
8792            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8793        };
8794        let Some(found) = method.take() else {
8795            return Err(self.type_error("value is not disposable"));
8796        };
8797        if found.is_nullish() {
8798            return Err(self.type_error("value is not disposable"));
8799        }
8800        let callable = found.as_object().is_some_and(|object| object.is_callable());
8801        if !callable {
8802            return Err(self.type_error("dispose method is not a function"));
8803        }
8804        Ok(found)
8805    }
8806
8807    /// Call one resource's disposer, folding a failure into `error_state`.
8808    ///
8809    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8810    /// because a captured `using` binding lives in its reference cell and the local slot is
8811    /// stale — a closure over the resource is legal and must not change what is disposed.
8812    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8813        let value = self.get_loc(slot);
8814        let method = self.get_loc(slot + 1);
8815        // A resource that was never initialised — its declaration threw — or that is
8816        // `null`/`undefined` has nothing to dispose.
8817        if value.is_nullish() || matches!(value, Value::Uninitialized) {
8818            return Ok(error_state);
8819        }
8820        if matches!(method, Value::Undefined | Value::Uninitialized) {
8821            return Ok(error_state);
8822        }
8823        match self.call_value(method, value, Vec::new()) {
8824            Ok(_) => Ok(error_state),
8825            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8826            Err(other) => Err(other),
8827        }
8828    }
8829
8830    /// Combine a disposal failure with whatever was already going wrong.
8831    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8832        if matches!(error_state, Value::Uninitialized) {
8833            return new_error;
8834        }
8835        self.new_suppressed_error(new_error, error_state)
8836    }
8837
8838    /// A `SuppressedError` instance built straight from its prototype.
8839    ///
8840    /// Not through the constructor: a script that rewrites
8841    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8842    /// error wrapping.
8843    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8844        let proto = self
8845            .realm
8846            .suppressed_error_proto
8847            .clone()
8848            .unwrap_or_else(|| self.realm.error_proto.clone());
8849        let object = self.new_object(Some(proto));
8850        object.define("error", Property::with_attributes(error, true, true));
8851        object.define(
8852            "suppressed",
8853            Property::with_attributes(suppressed, true, true),
8854        );
8855        object.define(
8856            "message",
8857            Property::with_attributes(self.string("SuppressedError"), true, true),
8858        );
8859        self.internal_set(&object, "_class", self.string("Error"));
8860        self.add_stack(&object);
8861        Value::Object(object)
8862    }
8863
8864    /// Call `callee`, or push its frame and let the main loop run it.
8865    ///
8866    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8867    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8868    /// continues, so `function f(){ return f() }` costs heap and stops at
8869    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8870    /// is entered directly, and natives do not re-enter JavaScript in this
8871    /// milestone.
8872    ///
8873    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8874    /// because the returning frame will.
8875    /// The elements of an array-like value, as a call argument list.
8876    ///
8877    /// `apply` accepts any array-like, not only a real array: the reference reads
8878    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8879    /// `ToIndex(value)`: `ToIntegerOrInfinity` and then the `2^53 - 1` bound.
8880    ///
8881    /// Used by the paths that take a *length* from script data — the typed-array
8882    /// constructor's array-like argument, `Array.from`. `ToIntegerOrInfinity` runs
8883    /// `ToNumber`, so a Symbol is a `TypeError`; a value past `2^53 - 1` is a
8884    /// `RangeError` rather than a silently clamped count.
8885    pub fn to_index(&mut self, value: &Value) -> JsResult<usize> {
8886        let number = self.to_js_number(value)?;
8887        if number.is_nan() {
8888            return Ok(0);
8889        }
8890        let number = number.trunc();
8891        if number < 0.0 || number > 9_007_199_254_740_991.0 {
8892            return Err(self.range_error("invalid length"));
8893        }
8894        Ok(number as usize)
8895    }
8896
8897    /// `CreateListFromArrayLike(value)`: the elements of an array-like, for `apply` and the
8898    /// other callers that take an argument list from script data.
8899    ///
8900    /// The length is `ToLength`, which *clamps* rather than refusing — the typed-array
8901    /// constructor and `Array.from` need `ToIndex` instead (see
8902    /// [`Interp::to_index`]), which is why they do not go through here.
8903    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8904        let Some(object) = value.as_object().cloned() else {
8905            if value.is_nullish() {
8906                // `f.apply(this, null)` passes no arguments at all.
8907                return Ok(Vec::new());
8908            }
8909            return Err(self.type_error("createListFromArrayLike called on non-object"));
8910        };
8911        let length = match self.get_property(&object, "length")? {
8912            Some(length) => length.to_number(),
8913            None => 0.0,
8914        };
8915        if !length.is_finite() || length <= 0.0 {
8916            return Ok(Vec::new());
8917        }
8918        let length = (length as usize).min(1_000_000);
8919        let mut args = Vec::with_capacity(length);
8920        for index in 0..length {
8921            let element = self.get_property(&object, &index.to_string())?;
8922            args.push(element.unwrap_or(Value::Undefined));
8923        }
8924        Ok(args)
8925    }
8926
8927    /// Turn a call to a generator function into a generator object.
8928    ///
8929    /// The frame is built exactly as an ordinary call would build it, then detached and
8930    /// stored in the generator before any body instruction runs — which is what makes
8931    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8932    /// is `initial_yield`, the first instruction of every suspending body.
8933    pub fn new_generator(
8934        &mut self,
8935        function: Value,
8936        this: Value,
8937        args: Vec<Value>,
8938    ) -> JsResult<Value> {
8939        let Some(object) = function.as_object().cloned() else {
8940            return Err(self.type_error("not a generator function"));
8941        };
8942        let Some((code, env)) = bytecode_of(&object) else {
8943            return Err(self.type_error("not a generator function"));
8944        };
8945        let is_async = code.code.kind.is_async();
8946        self.push_frame(code, env, this, args, function)?;
8947        let frame = self.frames.pop().expect("push_frame just pushed it");
8948        // A fresh generator is *suspended at start*: the body has not run, so a
8949        // `return`/`throw` on it finishes without executing anything.
8950        let mut state = GeneratorState {
8951            frame: Some(frame),
8952            phase: GeneratorPhase::SuspendedStart,
8953            parked_on_await: false,
8954            parked_on_yield_star: false,
8955            requests: std::collections::VecDeque::new(),
8956            async_busy: false,
8957            is_async,
8958        };
8959        // Run to the first suspension. For a generator that is `initial_yield`, so no
8960        // body code runs; for a malformed body it would be the first `yield`.
8961        // An `async function*` answers an async generator: same coroutine, but its
8962        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8963        let default_proto = if is_async {
8964            self.realm
8965                .async_generator_proto
8966                .clone()
8967                .unwrap_or_else(|| self.realm.generator_proto.clone())
8968        } else {
8969            self.realm.generator_proto.clone()
8970        };
8971        // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
8972        // `prototype` object when it is one, the intrinsic otherwise. Every generator having
8973        // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
8974        // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
8975        let proto = self.generator_instance_proto(&object, default_proto)?;
8976        let generator = self.new_object(Some(proto));
8977        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8978            Ok(_) => {}
8979            Err(error) => return Err(error),
8980        }
8981        generator.with_mut(|data| {
8982            data.kind = ObjectKind::Generator(Box::new(state));
8983        });
8984        Ok(Value::Object(generator))
8985    }
8986
8987    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8988    ///
8989    /// Returns the `{value, done}` object itself rather than the pair, because a
8990    /// `yield*` suspension already has one — the inner iterator's own result — and the
8991    /// protocol says to hand that straight through rather than nest it.
8992    /// Advance a generator and report *why* it parked.
8993    ///
8994    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
8995    /// "hand this value to the caller" — but an async generator does: an `await` has to
8996    /// settle before it can answer, while a `yield` is the answer.
8997    fn resume_generator_detailed(
8998        &mut self,
8999        generator: &Gc<JsObject>,
9000        kind: ResumeKind,
9001        value: Value,
9002    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9003        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
9004            ObjectKind::Generator(state) => {
9005                let is_async = state.is_async;
9006                Some(std::mem::replace(
9007                    state.as_mut(),
9008                    GeneratorState {
9009                        frame: None,
9010                        phase: GeneratorPhase::Executing,
9011                        parked_on_await: false,
9012                        parked_on_yield_star: false,
9013                        requests: std::collections::VecDeque::new(),
9014                        // **Busy while the body runs**, so a `next()` called *from inside*
9015                        // the body queues instead of being served. §27.6.3.7
9016                        // `AsyncGeneratorResumeNext` returns immediately for the state
9017                        // "executing", and the request is served once the body suspends;
9018                        // with `false` here the re-entrant call found an empty frame and
9019                        // rejected (`request-queue-order-state-executing`).
9020                        async_busy: is_async,
9021                        is_async,
9022                    },
9023                ))
9024            }
9025            _ => None,
9026        }) else {
9027            return Err(self.type_error("not a generator"));
9028        };
9029        let result = self.step_generator(&mut state, kind, value);
9030        // Requests queued *while* the body ran live on the placeholder, because the real
9031        // state is out of the object for the duration. They have to be folded back in
9032        // before the placeholder is overwritten, or the promise they carry never settles.
9033        let queued = generator.with_mut(|data| match &mut data.kind {
9034            ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
9035            _ => std::collections::VecDeque::new(),
9036        });
9037        state.requests.extend(queued);
9038        generator.with_mut(|data| {
9039            data.kind = ObjectKind::Generator(Box::new(state));
9040        });
9041        result
9042    }
9043
9044    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
9045    ///
9046    /// Returns the `{value, done}` object itself rather than the pair, because a
9047    /// `yield*` suspension already has one — the inner iterator's own result — and the
9048    /// protocol says to hand that straight through rather than nest it.
9049    pub fn resume_generator(
9050        &mut self,
9051        generator: &Gc<JsObject>,
9052        kind: ResumeKind,
9053        value: Value,
9054    ) -> JsResult<Value> {
9055        let (value, done, ready, _reason) =
9056            self.resume_generator_detailed(generator, kind, value)?;
9057        if ready {
9058            return Ok(value);
9059        }
9060        self.iterator_result(value, done)
9061    }
9062
9063    /// `next`/`return`/`throw` on an async generator, which answer a promise.
9064    ///
9065    /// The body is the same coroutine a sync generator runs; what changes is that an
9066    /// `await` inside it has to settle before the method can answer, so the step is
9067    /// driven off the job queue rather than returning inline.
9068    pub fn resume_async_generator(
9069        &mut self,
9070        generator: &Gc<JsObject>,
9071        kind: ResumeKind,
9072        value: Value,
9073    ) -> JsResult<Value> {
9074        let promise = self.new_promise();
9075        // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
9076        // that order, and the second value must reach the *second* `yield`.
9077        let idle = generator.with_mut(|data| match &mut data.kind {
9078            ObjectKind::Generator(state) => {
9079                state.requests.push_back(AsyncRequest {
9080                    kind,
9081                    value,
9082                    promise: promise.clone(),
9083                });
9084                !state.async_busy
9085            }
9086            _ => false,
9087        });
9088        if idle {
9089            self.next_async_request(generator)?;
9090        }
9091        Ok(Value::Object(promise))
9092    }
9093
9094    /// Serve the front queued request, if the generator is free to run one.
9095    ///
9096    /// A finished generator answers from the queue without running anything:
9097    /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
9098    /// first, and `throw(e)` rejects.
9099    fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
9100        enum Front {
9101            Idle,
9102            Run(ResumeKind, Value, Gc<JsObject>),
9103            Finished(ResumeKind, Value, Gc<JsObject>),
9104        }
9105        let front = generator.with_mut(|data| match &mut data.kind {
9106            ObjectKind::Generator(state) => {
9107                let Some(request) = state.requests.front() else {
9108                    return Front::Idle;
9109                };
9110                // Busy means a request is still in flight — awaiting inside the body, not
9111                // finished. Serving another now would interleave two requests.
9112                if state.async_busy && state.phase != GeneratorPhase::Completed {
9113                    return Front::Idle;
9114                }
9115                let kind = request.kind;
9116                let value = request.value.clone();
9117                let promise = request.promise.clone();
9118                state.async_busy = true;
9119                if state.phase == GeneratorPhase::Completed {
9120                    Front::Finished(kind, value, promise)
9121                } else {
9122                    Front::Run(kind, value, promise)
9123                }
9124            }
9125            _ => Front::Idle,
9126        });
9127        match front {
9128            Front::Idle => Ok(()),
9129            Front::Run(kind, value, promise) => {
9130                self.step_async_generator(generator, &promise, kind, value)
9131            }
9132            Front::Finished(kind, value, promise) => match kind {
9133                ResumeKind::Throw => {
9134                    self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
9135                }
9136                ResumeKind::Next | ResumeKind::Start => {
9137                    let result = self.iterator_result(Value::Undefined, true)?;
9138                    self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
9139                }
9140                ResumeKind::Return => {
9141                    // `js_async_generator_completed_return`: the value is awaited before it
9142                    // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
9143                    // finished generator answers `1`, not a promise.
9144                    let resolved = match self.promise_resolve_intrinsic(value) {
9145                        Ok(resolved) => resolved,
9146                        Err(Signal::Throw(reason)) => {
9147                            return self.settle_async_request(
9148                                generator,
9149                                &promise,
9150                                AsyncOutcome::Error(reason),
9151                            );
9152                        }
9153                        Err(other) => return Err(other),
9154                    };
9155                    let done = JsObject::function(
9156                        self.heap,
9157                        Some(self.realm.function_proto.clone()),
9158                        Callable::CompletedReturn {
9159                            generator: generator.clone(),
9160                            promise: promise.clone(),
9161                            rejected: false,
9162                        },
9163                    );
9164                    let failed = JsObject::function(
9165                        self.heap,
9166                        Some(self.realm.function_proto.clone()),
9167                        Callable::CompletedReturn {
9168                            generator: generator.clone(),
9169                            promise: promise.clone(),
9170                            rejected: true,
9171                        },
9172                    );
9173                    let Value::Object(resolved) = resolved else {
9174                        return self.settle_async_request(
9175                            generator,
9176                            &promise,
9177                            AsyncOutcome::Error(Value::Undefined),
9178                        );
9179                    };
9180                    self.perform_then(
9181                        &resolved,
9182                        Some(Value::Object(done)),
9183                        Some(Value::Object(failed)),
9184                    )?;
9185                    Ok(())
9186                }
9187            },
9188        }
9189    }
9190
9191    /// Settle the front request and start the next one.
9192    ///
9193    /// Every path out of [`Interp::step_async_generator`] goes through here, so the
9194    /// "busy" flag and the queue cannot drift: a promise settled without releasing the
9195    /// generator would strand every later request.
9196    fn settle_async_request(
9197        &mut self,
9198        generator: &Gc<JsObject>,
9199        promise: &Gc<JsObject>,
9200        outcome: AsyncOutcome,
9201    ) -> JsResult<()> {
9202        let settled = generator.with_mut(|data| match &mut data.kind {
9203            ObjectKind::Generator(state) => {
9204                let front = state.requests.front();
9205                debug_assert!(
9206                    front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
9207                    "a request settled outside its turn"
9208                );
9209                state.requests.pop_front();
9210                state.async_busy = false;
9211                true
9212            }
9213            _ => false,
9214        });
9215        if settled {
9216            match outcome {
9217                AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
9218                AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
9219            }
9220        }
9221        self.next_async_request(generator)
9222    }
9223
9224    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
9225    ///
9226    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
9227    /// disposer runs **synchronously** — the reference starts it before returning, which
9228    /// a test can observe by logging after the call — and the rest follow once their
9229    /// predecessor settles.
9230    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
9231        let promise = self.new_promise();
9232        // §24.4.3.6 `DisposeResources` step 1: `needsAwait` is true as soon as the stack holds
9233        // any resource at all, because every `await using` resource has the async-dispose
9234        // hint — including the null/undefined ones that have nothing to call. If none of them
9235        // turned out to be awaitable, step 4 still performs one `Await(undefined)`, which is
9236        // why `stack.use(null); stack.disposeAsync()` settles one microtask later rather than
9237        // in the tick it was called from (`disposeAsync/explicit-await-for-null`).
9238        let needs_await = !resources.is_empty();
9239        let mut pairs = Vec::with_capacity(resources.len());
9240        for (value, method) in resources {
9241            let pair = self.new_array(vec![value, method]);
9242            pairs.push(Value::Object(pair));
9243        }
9244        let remaining = self.new_array(pairs);
9245        self.dispose_step(
9246            &remaining,
9247            &promise,
9248            Value::Uninitialized,
9249            false,
9250            needs_await,
9251        )?;
9252        Ok(Value::Object(promise))
9253    }
9254
9255    /// One link of the `disposeAsync` chain.
9256    ///
9257    /// Loops while the disposers finish synchronously, and parks on the first thenable it
9258    /// meets — pushing itself back in as the continuation, with the accumulated error
9259    /// carried along so a later failure can still be folded into the `SuppressedError`.
9260    fn dispose_step(
9261        &mut self,
9262        remaining: &Gc<JsObject>,
9263        promise: &Gc<JsObject>,
9264        mut error: Value,
9265        awaited: bool,
9266        needs_await: bool,
9267    ) -> JsResult<()> {
9268        loop {
9269            let length = remaining.array_length().unwrap_or(0);
9270            if length == 0 {
9271                // Step 4: `needsAwait` true and `hasAwaited` false means one `Await(undefined)`
9272                // still has to happen. Re-entering this same step past an already-fulfilled
9273                // promise is exactly one tick, and it keeps the folding of `error` in one place.
9274                if needs_await && !awaited {
9275                    let finished = self.new_array(Vec::new());
9276                    let thunk = JsObject::function(
9277                        self.heap,
9278                        Some(self.realm.function_proto.clone()),
9279                        Callable::DisposeStep {
9280                            remaining: finished.clone(),
9281                            promise: promise.clone(),
9282                            error,
9283                            rejected: false,
9284                            awaited: true,
9285                            needs_await: false,
9286                        },
9287                    );
9288                    let tick = self.promise_resolve_value(Value::Undefined)?;
9289                    if let Value::Object(tick) = tick {
9290                        self.perform_then(
9291                            &tick,
9292                            Some(Value::Object(thunk.clone())),
9293                            Some(Value::Object(thunk)),
9294                        )?;
9295                    }
9296                    return Ok(());
9297                }
9298                if matches!(error, Value::Uninitialized) {
9299                    self.fulfill_promise(promise, Value::Undefined);
9300                } else {
9301                    self.reject_promise(promise, error);
9302                }
9303                return Ok(());
9304            }
9305            let Some(Value::Object(pair)) = remaining
9306                .array_get(length - 1)
9307                .filter(|v| !matches!(v, Value::Hole))
9308            else {
9309                remaining.array_truncate(self.heap, length - 1);
9310                continue;
9311            };
9312            remaining.array_truncate(self.heap, length - 1);
9313            let value = pair.array_get(0).unwrap_or(Value::Undefined);
9314            let Some(Value::Object(method)) = pair.array_get(1) else {
9315                continue;
9316            };
9317            if !method.is_callable() {
9318                continue;
9319            }
9320            match self.call_value(Value::Object(method), value, Vec::new()) {
9321                Ok(result) => {
9322                    if !self.is_thenable(&result)? {
9323                        // Finished synchronously; the next disposer is the next iteration.
9324                        continue;
9325                    }
9326                    let awaited = match self.promise_resolve_value(result) {
9327                        Ok(awaited) => awaited,
9328                        Err(Signal::Throw(reason)) => {
9329                            self.reject_promise(promise, reason);
9330                            return Ok(());
9331                        }
9332                        Err(other) => return Err(other),
9333                    };
9334                    let Value::Object(awaited) = awaited else {
9335                        continue;
9336                    };
9337                    let ok = JsObject::function(
9338                        self.heap,
9339                        Some(self.realm.function_proto.clone()),
9340                        Callable::DisposeStep {
9341                            remaining: remaining.clone(),
9342                            promise: promise.clone(),
9343                            error: error.clone(),
9344                            rejected: false,
9345                            awaited: true,
9346                            needs_await,
9347                        },
9348                    );
9349                    let failed = JsObject::function(
9350                        self.heap,
9351                        Some(self.realm.function_proto.clone()),
9352                        Callable::DisposeStep {
9353                            remaining: remaining.clone(),
9354                            promise: promise.clone(),
9355                            error,
9356                            rejected: true,
9357                            awaited: true,
9358                            needs_await,
9359                        },
9360                    );
9361                    self.perform_then(
9362                        &awaited,
9363                        Some(Value::Object(ok)),
9364                        Some(Value::Object(failed)),
9365                    )?;
9366                    return Ok(());
9367                }
9368                Err(Signal::Throw(thrown)) => {
9369                    error = self.merge_dispose_error(thrown, error);
9370                }
9371                Err(other) => return Err(other),
9372            }
9373        }
9374    }
9375
9376    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
9377    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
9378        let Value::Object(object) = value else {
9379            return Ok(false);
9380        };
9381        Ok(matches!(
9382            self.get_property(object, "then")?,
9383            Some(Value::Object(then)) if then.is_callable()
9384        ))
9385    }
9386
9387    /// One step of an async generator, settling `promise` with an `{value, done}` result.
9388    fn step_async_generator(
9389        &mut self,
9390        generator: &Gc<JsObject>,
9391        promise: &Gc<JsObject>,
9392        kind: ResumeKind,
9393        value: Value,
9394    ) -> JsResult<()> {
9395        // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
9396        // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
9397        // is abrupt — a `constructor` getter that throws — the generator is resumed with a
9398        // *throw* completion instead, so the body's own `try { yield } catch` sees it:
9399        // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
9400        // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
9401        // out of the same read, one as a rejection and one as a rethrow.
9402        //
9403        // Narrow on purpose: only a value that is *already a promise* is inspected, so
9404        // nothing changes for `return 1` and the extra read is a plain data-property
9405        // lookup on the intrinsic case.
9406        if kind == ResumeKind::Return
9407            && let Value::Object(object) = &value
9408            && self.promise_state(object).is_some()
9409            && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
9410        {
9411            return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
9412        }
9413        let stepped = self.resume_generator_detailed(generator, kind, value);
9414        let (value, done, ready, reason) = match stepped {
9415            Ok(stepped) => stepped,
9416            Err(Signal::Throw(reason)) => {
9417                return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
9418            }
9419            Err(other) => return Err(other),
9420        };
9421        // Only an `await` has to wait before the method can answer.
9422        if !done && reason == Some(SuspendKind::Await) {
9423            let awaited = match self.promise_resolve_value(value) {
9424                Ok(awaited) => awaited,
9425                Err(Signal::Throw(reason)) => {
9426                    return self.settle_async_request(
9427                        generator,
9428                        promise,
9429                        AsyncOutcome::Error(reason),
9430                    );
9431                }
9432                Err(other) => return Err(other),
9433            };
9434            let Value::Object(awaited) = awaited else {
9435                return Ok(());
9436            };
9437            let resumed = JsObject::function(
9438                self.heap,
9439                Some(self.realm.function_proto.clone()),
9440                Callable::GeneratorResume {
9441                    generator: generator.clone(),
9442                    promise: promise.clone(),
9443                    kind: ResumeKind::Next,
9444                },
9445            );
9446            let raised = JsObject::function(
9447                self.heap,
9448                Some(self.realm.function_proto.clone()),
9449                Callable::GeneratorResume {
9450                    generator: generator.clone(),
9451                    promise: promise.clone(),
9452                    kind: ResumeKind::Throw,
9453                },
9454            );
9455            self.perform_then(
9456                &awaited,
9457                Some(Value::Object(resumed)),
9458                Some(Value::Object(raised)),
9459            )?;
9460            return Ok(());
9461        }
9462        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
9463        // completes it — both arrive as the settled value rather than as the promise
9464        // object. A plain value skips the round trip, which is also what keeps `yield 1`
9465        // from costing an extra tick.
9466        let awaits_value = self.is_thenable(&value)?;
9467        if awaits_value {
9468            // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
9469            // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
9470            // value that merely gets `yield`ed is awaited by the body's own `Await`, where
9471            // no `PromiseResolve` appears, so that path keeps the shortcut.
9472            let awaited = match if done {
9473                self.promise_resolve_intrinsic(value)
9474            } else {
9475                self.promise_resolve_value(value)
9476            } {
9477                Ok(awaited) => awaited,
9478                Err(Signal::Throw(reason)) => {
9479                    return self.settle_async_request(
9480                        generator,
9481                        promise,
9482                        AsyncOutcome::Error(reason),
9483                    );
9484                }
9485                Err(other) => return Err(other),
9486            };
9487            let Value::Object(awaited) = awaited else {
9488                return Ok(());
9489            };
9490            // A rejected yield throws *at the yield* inside the body, so the rejection
9491            // resumes the generator rather than the method's promise.
9492            let answer = JsObject::function(
9493                self.heap,
9494                Some(self.realm.function_proto.clone()),
9495                Callable::YieldResult {
9496                    generator: generator.clone(),
9497                    promise: promise.clone(),
9498                    done,
9499                },
9500            );
9501            let raise = JsObject::function(
9502                self.heap,
9503                Some(self.realm.function_proto.clone()),
9504                Callable::GeneratorResume {
9505                    generator: generator.clone(),
9506                    promise: promise.clone(),
9507                    kind: ResumeKind::Throw,
9508                },
9509            );
9510            self.perform_then(
9511                &awaited,
9512                Some(Value::Object(answer)),
9513                Some(Value::Object(raise)),
9514            )?;
9515            return Ok(());
9516        }
9517        let result = if ready {
9518            // `yield*` handed back the inner iterator's own result object.
9519            value
9520        } else {
9521            self.iterator_result(value, done)?
9522        };
9523        self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
9524    }
9525
9526    /// The `{value, done}` object an iterator method answers with.
9527    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
9528        let result = self.new_object(Some(self.realm.object_proto.clone()));
9529        result.define_data("value", value);
9530        result.define_data("done", Value::Bool(done));
9531        Ok(Value::Object(result))
9532    }
9533
9534    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
9535    fn step_generator(
9536        &mut self,
9537        state: &mut GeneratorState,
9538        kind: ResumeKind,
9539        value: Value,
9540    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9541        match state.phase {
9542            GeneratorPhase::Executing => {
9543                return Err(self.type_error("cannot invoke a running generator"));
9544            }
9545            GeneratorPhase::Completed => {
9546                // A finished generator answers every resumption without running.
9547                return Ok(match kind {
9548                    ResumeKind::Throw => return Err(Signal::Throw(value)),
9549                    ResumeKind::Return => (value, true, false, None),
9550                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
9551                });
9552            }
9553            GeneratorPhase::SuspendedStart => {
9554                if kind != ResumeKind::Next && kind != ResumeKind::Start {
9555                    // The body never started, so there is nothing to unwind or return
9556                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
9557                    state.frame = None;
9558                    state.phase = GeneratorPhase::Completed;
9559                    return Ok(match kind {
9560                        ResumeKind::Throw => return Err(Signal::Throw(value)),
9561                        _ => (value, true, false, None),
9562                    });
9563                }
9564            }
9565            GeneratorPhase::SuspendedYield => {}
9566        }
9567
9568        let Some(mut frame) = state.frame.take() else {
9569            return Ok((Value::Undefined, true, false, None));
9570        };
9571        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
9572        // number that says which method resumed it; the emitted `if_false` branches on
9573        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
9574        let mut raised = None;
9575        match kind {
9576            ResumeKind::Next | ResumeKind::Start => {
9577                if state.phase == GeneratorPhase::SuspendedYield {
9578                    frame.stack.push(value);
9579                    // An `await` resumes with its value alone; only a `yield` gets the
9580                    // magic number that says which of `next`/`return` resumed it.
9581                    if !state.parked_on_await {
9582                        frame.stack.push(Value::Int(RESUME_NEXT));
9583                    }
9584                }
9585            }
9586            ResumeKind::Return => {
9587                // A `return` on a not-yet-started generator is handled above, so this is
9588                // always a real resumption.
9589                frame.stack.push(value);
9590                frame.stack.push(Value::Int(RESUME_RETURN));
9591            }
9592            ResumeKind::Throw => {
9593                // At a `yield*` the exception is *data* for the delegation: the compiled
9594                // code resumes with the value and magic `2` and calls the inner iterator's
9595                // `throw`. Everywhere else it is raised at the suspension point, so the
9596                // body's own handler sees it.
9597                if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
9598                    frame.stack.push(value);
9599                    frame.stack.push(Value::Int(RESUME_THROW));
9600                } else {
9601                    raised = Some(value);
9602                }
9603            }
9604        }
9605        state.phase = GeneratorPhase::Executing;
9606
9607        let depth = self.frames.len();
9608        self.frames.push(frame);
9609        // A `throw` unwinds from where the frame parked, exactly as if the exception had
9610        // happened at the `yield`.
9611        if let Some(mut exception) = raised {
9612            if self.catch_here(&mut exception).is_none() {
9613                self.pop_frame();
9614                state.phase = GeneratorPhase::Completed;
9615                return Err(Signal::Throw(exception));
9616            }
9617        }
9618
9619        // Only the generator's *own* frame ends the generator. The body may call ordinary
9620        // functions, and those push frames of their own: a `Step::Return` from one of them
9621        // is a nested call finishing, not the generator completing. Miscounting that is
9622        // silent — the generator reports the callee's value as its own result and marks
9623        // itself done — so the depth comparison is load-bearing, not defensive.
9624        let own_frame = depth + 1;
9625        loop {
9626            match self.step() {
9627                Ok(Step::Continue) => {}
9628                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9629                    let mut frame = self.frames.pop().expect("a frame is live");
9630                    // `yield` left the value on the stack; `initial_yield` left nothing.
9631                    let yielded = if reason == SuspendKind::Initial {
9632                        Value::Undefined
9633                    } else {
9634                        frame.stack.pop().unwrap_or(Value::Undefined)
9635                    };
9636                    state.frame = Some(frame);
9637                    state.parked_on_await = reason == SuspendKind::Await;
9638                    state.parked_on_yield_star =
9639                        matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9640                    state.phase = if reason == SuspendKind::Initial {
9641                        GeneratorPhase::SuspendedStart
9642                    } else {
9643                        GeneratorPhase::SuspendedYield
9644                    };
9645                    // `yield*` hands the inner iterator's own result object straight
9646                    // back, so the caller sees one `{value, done}` rather than a nested
9647                    // one — which is why the third field says "already a result".
9648                    return Ok((
9649                        yielded,
9650                        false,
9651                        reason == SuspendKind::YieldStar,
9652                        Some(reason),
9653                    ));
9654                }
9655                Ok(Step::Suspend(_)) => {
9656                    // A `yield` in a frame other than the generator's would mean a
9657                    // generator body entered as an ordinary call, which
9658                    // `call_or_push` prevents.
9659                    self.unwind_to(depth);
9660                    state.phase = GeneratorPhase::Completed;
9661                    return Err(Signal::Throw(self.make_error(
9662                        "InternalError",
9663                        "a generator body ran as an ordinary call",
9664                    )));
9665                }
9666                Ok(Step::Return(value)) => {
9667                    self.pop_frame();
9668                    if self.frames.len() > depth {
9669                        // A nested call finished: hand the value back to its caller and
9670                        // keep running the generator body.
9671                        self.frames
9672                            .last_mut()
9673                            .expect("a caller is live")
9674                            .stack
9675                            .push(value);
9676                        continue;
9677                    }
9678                    state.phase = GeneratorPhase::Completed;
9679                    // The reference closes the generator's closure variables here; ours
9680                    // live in cells the frame owned, which the drop below releases.
9681                    return Ok((value, true, false, None));
9682                }
9683                Err(Signal::Throw(exception)) => {
9684                    // The frame that threw gets the first chance to catch, exactly as in
9685                    // the ordinary call loop; a frame above the generator's is popped and
9686                    // the exception carries on down.
9687                    let mut exception = exception;
9688                    loop {
9689                        if self.frames.len() <= depth {
9690                            // The generator's own frame is gone, so nothing here caught it.
9691                            state.phase = GeneratorPhase::Completed;
9692                            return Err(Signal::Throw(exception));
9693                        }
9694                        if self.catch_here(&mut exception).is_some() {
9695                            break;
9696                        }
9697                        self.pop_frame();
9698                    }
9699                }
9700                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9701            }
9702        }
9703    }
9704
9705    /// Pop frames until `depth` are left, keeping their buffers.
9706    fn unwind_to(&mut self, depth: usize) {
9707        while self.frames.len() > depth {
9708            self.pop_frame();
9709        }
9710    }
9711    fn call_or_push(
9712        &mut self,
9713        callee: Value,
9714        this: Value,
9715        args: Vec<Value>,
9716    ) -> JsResult<Option<Value>> {
9717        if let Value::Object(function) = &callee
9718            && let Some((code, env)) = bytecode_of(function)
9719        {
9720            // Calling a generator function does not run anything: it captures the
9721            // arguments in a frame and hands back the generator object.
9722            if code.code.kind.is_generator() {
9723                return self.new_generator(callee, this, args).map(Some);
9724            }
9725            // An async function answers a promise and runs its body as a coroutine, so it
9726            // takes the same path as a plain call into it.
9727            if code.code.kind.is_async() {
9728                return self.new_async_function(callee, this, args).map(Some);
9729            }
9730            self.push_frame(code, env, this, args, callee)?;
9731            return Ok(None);
9732        }
9733        self.call_value(callee, this, args).map(Some)
9734    }
9735
9736    /// `new callee(args)`.
9737    ///
9738    /// A constructor differs from a plain call in three ways: it gets a fresh object
9739    /// as `this` whose prototype is the constructor's `prototype` property, its
9740    /// return value is *replaced* by that object unless it returns an object itself,
9741    /// and a native constructor is expected to initialise the object it is given
9742    /// rather than build one.
9743    pub fn construct(
9744        &mut self,
9745        callee: Value,
9746        new_target: Value,
9747        args: Vec<Value>,
9748    ) -> JsResult<Value> {
9749        // `new` on a bound function constructs its *target*, prepending the arguments
9750        // the bind fixed and ignoring the bound `this` — a bound function is a
9751        // constructor only when its target is one, and `new` always makes a fresh
9752        // object of the target's prototype rather than reusing the bound receiver.
9753        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9754        // ran the body with `this === null` and threw on `this.x = a`.
9755        let mut callee = callee;
9756        let mut new_target = new_target;
9757        let mut args = args;
9758        loop {
9759            let Some(object) = callee.as_object().cloned() else {
9760                return Err(Signal::Throw(
9761                    self.make_error("TypeError", "not a constructor"),
9762                ));
9763            };
9764            // A proxy of a function constructs through its `construct` trap, and the
9765            // trap's answer is the result directly — no fresh object is made here.
9766            if object.proxy_state().is_some() {
9767                return match self.proxy_construct(&object, args, &new_target)? {
9768                    Some(result) => Ok(result),
9769                    None => Err(Signal::Throw(
9770                        self.make_error("TypeError", "proxy target is not a constructor"),
9771                    )),
9772                };
9773            }
9774            // A generator function has no `[[Construct]]`, and the reference names it in
9775            // the message: `new (function* G(){})()` reports "G is not a constructor".
9776            if object.with(|data| match &data.kind {
9777                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9778                    code.code.kind.is_generator()
9779                }
9780                _ => false,
9781            }) {
9782                let name = object
9783                    .own_property("name")
9784                    .and_then(|property| property.value)
9785                    .map(|value| value.to_js_string())
9786                    .unwrap_or_default();
9787                return Err(Signal::Throw(
9788                    self.make_error("TypeError", &format!("{name} is not a constructor")),
9789                ));
9790            }
9791            let bound = object.with(|data| match &data.kind {
9792                ObjectKind::Function(Callable::Bound {
9793                    target,
9794                    args: leading,
9795                    ..
9796                }) => Some((target.clone(), leading.clone())),
9797                _ => None,
9798            });
9799            let Some((target, leading)) = bound else {
9800                // Not a bound function, so this object is the callee. §7.2.4
9801                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9802                // refusals above cover only the built-ins the reference also refuses by
9803                // name. Everything else — a method, an arrow, an async function — has no
9804                // `[[Construct]]` either, and answering "yes" here made
9805                // `new (Array.prototype.map)` build an object instead of throwing.
9806                if !object.is_constructor() {
9807                    let name = object
9808                        .own_property("name")
9809                        .and_then(|property| property.value)
9810                        .map(|value| value.to_js_string())
9811                        .unwrap_or_default();
9812                    return Err(Signal::Throw(
9813                        self.make_error("TypeError", &format!("{name} is not a constructor")),
9814                    ));
9815                }
9816                break;
9817            };
9818            let mut all = leading;
9819            all.extend(args);
9820            args = all;
9821            // A bound function that is its own `new.target` stands in for its target:
9822            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9823            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9824            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9825                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9826                _ => false,
9827            };
9828            if same_wrapper {
9829                new_target = target.clone();
9830            }
9831            callee = target;
9832        }
9833        let Value::Object(function) = &callee else {
9834            unreachable!("the loop above only breaks on an object");
9835        };
9836        // The fresh object's prototype comes from `new.target`, not from the callee: a
9837        // derived constructor reaches here through `super()`, and the instance must be a
9838        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9839        // an object inheriting `D.prototype` rather than `C.prototype`.
9840        let prototype_source = match new_target.as_object() {
9841            Some(target) => target.clone(),
9842            None => function.clone(),
9843        };
9844        // A native constructor builds its own instance, through `new_ctor_instance`, once it
9845        // has validated its arguments. Pre-building one here would read
9846        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9847        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9848        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9849        let is_native = function.native_creates_own_instance();
9850        let this = if is_native {
9851            Value::Undefined
9852        } else {
9853            let prototype = self.get_property(&prototype_source, "prototype")?;
9854            let prototype = match prototype {
9855                Some(Value::Object(proto)) => Some(proto),
9856                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
9857                // object, the answer is the realm's *intrinsic* prototype for this
9858                // constructor, not `%Object.prototype%`.
9859                _ => {
9860                    // `GetPrototypeFromConstructor` step 4 is `GetFunctionRealm(constructor)`,
9861                    // and that is a `TypeError` for a revoked proxy. Without it, `new
9862                    // revokedProxy()` quietly produced an `%Object.prototype%` instance —
9863                    // `base-ctor-revoked-proxy` revokes the proxy from inside its own `get`
9864                    // trap, so it is already revoked when this fallback runs.
9865                    if prototype_source.proxy_state().is_some() {
9866                        self.proxy_parts(&prototype_source)?;
9867                    }
9868                    let fallback = self.get_property(function, "prototype")?;
9869                    match fallback {
9870                        Some(Value::Object(proto)) => Some(proto),
9871                        _ => Some(self.realm.object_proto.clone()),
9872                    }
9873                }
9874            };
9875            Value::Object(self.new_object(prototype))
9876        };
9877        // `new.target` inside the body is the constructor that was written, so a bound
9878        // function's target sees itself rather than the bound wrapper.
9879        //
9880        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
9881        // `?`, so assigning `None` after the call would be skipped and the failed
9882        // `new.target` would stay visible to every later native call. The symptom was a
9883        // native constructor refusing a plain call — `var s = Symbol(); new
9884        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
9885        // "FinalizationRegistry is not a constructor".
9886        let outer_new_target = self.pending_new_target.replace(new_target);
9887        let callee = callee.clone();
9888        let result = self.call_value(callee, this.clone(), args);
9889        self.pending_new_target = outer_new_target;
9890        let result = result?;
9891        // A constructor that returns an object overrides `this`; any other return value
9892        // (including `undefined`) is ignored — **except** in a derived constructor, where
9893        // §15.7.1 step 12 makes a non-object return a `TypeError`
9894        // (`Function/internals/Construct/derived-return-val`).
9895        let derived = function.with(|data| match &data.kind {
9896            ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9897                code.code.is_derived_constructor
9898            }
9899            _ => false,
9900        });
9901        Ok(match result {
9902            Value::Object(_) => result,
9903            // A bare `return;` answers `undefined`, which is **legal** even in a derived
9904            // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
9905            Value::Undefined => this,
9906            _ if derived => {
9907                return Err(Signal::Throw(self.make_error(
9908                    "TypeError",
9909                    "derived constructor may only return an object or undefined",
9910                )));
9911            }
9912            _ => this,
9913        })
9914    }
9915
9916    /// `new.target` for the call currently being made.
9917    ///
9918    /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9919    /// it as `this`), but a *host* constructor that builds its own instance is handed
9920    /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9921    /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9922    /// it here.
9923    ///
9924    /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9925    /// receives for a plain call.
9926    pub fn current_new_target(&self) -> Value {
9927        self.active_new_target.clone()
9928    }
9929
9930    /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9931    ///
9932    /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9933    /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9934    pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9935        let constructor = self.realm.errors.get("AggregateError").cloned();
9936        let Some(constructor) = constructor else {
9937            return self.make_error("AggregateError", message);
9938        };
9939        let list = self.new_array(errors);
9940        match self.construct(
9941            Value::Object(constructor.clone()),
9942            Value::Object(constructor),
9943            vec![Value::Object(list), self.string(message)],
9944        ) {
9945            Ok(value) => value,
9946            // A user could have replaced `AggregateError` with something that throws; the
9947            // engine still owes the caller a rejection, so it falls back rather than
9948            // turning `Promise.any`'s rejection into a throw.
9949            Err(_) => self.make_error("AggregateError", message),
9950        }
9951    }
9952
9953    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9954    ///
9955    /// The error classes themselves arrive with the builtins milestone; what
9956    /// matters here is that the thrown value stringifies the way a script printing
9957    /// the caught value expects.
9958    ///
9959    /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9960    /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9961    /// rely on when they print a caught value.
9962    pub fn make_error(&self, name: &str, message: &str) -> Value {
9963        let proto = self
9964            .realm
9965            .errors
9966            .get(name)
9967            .map(|constructor| self.prototype_of(constructor))
9968            .unwrap_or_else(|| self.realm.error_proto.clone());
9969        let error = self.new_object(Some(proto));
9970        // `name` and `message` are own properties of the instance, which is what
9971        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9972        // `Error`.
9973        error.define(
9974            "name",
9975            Property::with_attributes(self.string(name), true, false),
9976        );
9977        error.define(
9978            "message",
9979            Property::with_attributes(self.string(message), true, false),
9980        );
9981        // The internal class, which is what tells a printer this is an error rather than a
9982        // plain object with `name` and `message` properties. The constructor path sets it
9983        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9984        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
9985        // literally `"Error"` in both places — the *name* is read from `name`, which is why
9986        // a `RangeError` still prints as `RangeError`.
9987        self.internal_set(&error, "_class", self.string("Error"));
9988        // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
9989        // answered `false` from `Error.isError` while a constructed one answered `true`,
9990        // because only the constructor set the slot. The reference answers `true` for both
9991        // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
9992        // accessor gated on this slot the omission stopped being cosmetic: `print_error`
9993        // tests `typeof stack === "string"` to decide on a trailing newline, so every
9994        // engine-thrown error lost its blank line.
9995        self.internal_set(&error, "_error_data", Value::Bool(true));
9996        // The trace is captured where the error is *made*, which is where the reference
9997        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
9998        // way out, so a caught engine error already has its stack even if the handler
9999        // never rethrows it.
10000        self.add_stack(&error);
10001        Value::Object(error)
10002    }
10003
10004    /// Give an error object its `stack` property, from the current frame stack.
10005    ///
10006    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
10007    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
10008    /// `stack` a script set, is not rewritten.
10009    pub fn add_stack(&self, object: &Gc<JsObject>) {
10010        self.add_stack_skipping(object, 0);
10011    }
10012
10013    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
10014    ///
10015    /// An `Error` constructor passes 1: the reference builds those traces with
10016    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
10017    /// constructor itself, while a `RangeError` raised inside `toISOString` does
10018    /// report `at toISOString (native)`.
10019    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
10020        if object.has_own("stack") {
10021            return;
10022        }
10023        // The trace is *captured* here but not installed as a property: `stack` is an
10024        // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
10025        // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
10026        // is kept in a hidden slot and the getter materialises it on first read.
10027        //
10028        // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
10029        // shows it — this is the same discipline `_error_data` and `_class` follow.
10030        let trace = self.stack_trace_skipping(skip);
10031        let text = self.string(trace);
10032        self.internal_set(object, "_stack_trace", text);
10033    }
10034
10035    /// The function object currently being called, if any.
10036    ///
10037    /// A native function is a bare `fn` pointer, so it cannot capture which class
10038    /// it belongs to; it reads that from the callee instead. This is also what a
10039    /// stack trace would use.
10040    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
10041        match &self.frames.last()?.callee {
10042            Value::Object(object) => Some(object.clone()),
10043            _ => None,
10044        }
10045    }
10046
10047    /// The `prototype` property of a constructor, falling back to
10048    /// `Object.prototype` for anything that is not shaped like one.
10049    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
10050        constructor
10051            .own_property("prototype")
10052            .and_then(|property| property.value)
10053            .and_then(|value| value.as_object().cloned())
10054            .unwrap_or_else(|| self.realm.object_proto.clone())
10055    }
10056
10057    /// Throw a `TypeError` carrying `message`.
10058    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
10059        Signal::Throw(self.make_error("TypeError", message.as_ref()))
10060    }
10061
10062    /// Throw a `RangeError` carrying `message`.
10063    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
10064        Signal::Throw(self.make_error("RangeError", message.as_ref()))
10065    }
10066
10067    /// A `ReferenceError`, as the value to throw.
10068    ///
10069    /// `throw` uses it for "called on a disposed stack": `DisposableStack.prototype.defer`
10070    /// and its siblings report a `ReferenceError` there, which is what
10071    /// `adopt|defer|move/throws-if-disposed` assert.
10072    pub fn reference_error(&self, message: impl AsRef<str>) -> Signal {
10073        Signal::Throw(self.make_error("ReferenceError", message.as_ref()))
10074    }
10075
10076    /// The `ReferenceError` a read of an uninitialised binding raises.
10077    /// The name of the binding `slot` refers to, for an error message.
10078    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
10079        match kind {
10080            VarSlot::Loc => self
10081                .frame()
10082                .code
10083                .code
10084                .vars
10085                .get(slot)
10086                .map(|v| v.name.clone()),
10087            VarSlot::Closure => self
10088                .frame()
10089                .code
10090                .code
10091                .closure_vars
10092                .get(slot)
10093                .map(|c| c.name.clone()),
10094        }
10095        .unwrap_or_default()
10096    }
10097
10098    /// Whether `slot` names a `const` binding, which rejects every store after its
10099    /// initialiser.
10100    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
10101        match kind {
10102            VarSlot::Loc => self
10103                .frame()
10104                .code
10105                .code
10106                .vars
10107                .get(slot)
10108                .is_some_and(|v| v.is_const),
10109            VarSlot::Closure => self
10110                .frame()
10111                .code
10112                .code
10113                .closure_vars
10114                .get(slot)
10115                .is_some_and(|c| c.is_const),
10116        }
10117    }
10118
10119    /// The `TypeError` a store to a `const` binding raises.
10120    ///
10121    /// `const` is enforced here rather than at compile time because the binding can be
10122    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
10123    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
10124    /// both halves of what "checked store" means: the dead zone is over, and the
10125    /// binding is writable.
10126    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
10127        let name = self.binding_name(slot, kind);
10128        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
10129    }
10130
10131    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
10132        let name = match kind {
10133            VarSlot::Loc => self
10134                .frame()
10135                .code
10136                .code
10137                .vars
10138                .get(slot)
10139                .map(|v| v.name.clone()),
10140            VarSlot::Closure => self
10141                .frame()
10142                .code
10143                .code
10144                .closure_vars
10145                .get(slot)
10146                .map(|c| c.name.clone()),
10147        }
10148        .unwrap_or_default();
10149        // The reference has a wording of its own for `this`, because the dead zone it sits
10150        // in is the derived constructor's rather than a `let`'s: `constructor(){ return; }`
10151        // reports `this is not initialized`.
10152        let message = if name == "this" {
10153            "this is not initialized".to_string()
10154        } else {
10155            format!("cannot access '{name}' before initialization")
10156        };
10157        Signal::Throw(self.make_error("ReferenceError", &message))
10158    }
10159
10160    fn throw_reference(&self, name: &str) -> Signal {
10161        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
10162    }
10163
10164    // -- the instruction loop -----------------------------------------------
10165
10166    // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
10167    // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
10168    // measured at 16% of a tight arithmetic loop's total time.
10169    #[inline(always)]
10170    fn step(&mut self) -> JsResult<Step> {
10171        // The instruction is already decoded (see [`crate::insn`]), so this is an index
10172        // and a `Copy` read rather than a table lookup plus a width switch. Only the
10173        // borrow lives across the boundary; nothing is cloned.
10174        // **One** borrow of the frame: fetch the record, then advance in the same scope.
10175        // The obvious version borrowed it three times (`last` to read, `last_mut` to
10176        // write, and once more inside the handler), and each is a bounds check plus an
10177        // `Option` unwrap — on the one path every instruction takes.
10178        let Some((insn, next)) = ({
10179            let frame = self
10180                .frames
10181                .last_mut()
10182                .expect("step() is only called with a live frame");
10183            // Past the last instruction is a normal return: the compiler ends a function
10184            // with `return`, and a jump to the end of a block lands here.
10185            let insn = frame.insns().get(frame.pc).copied();
10186            match insn {
10187                None => None,
10188                Some(insn) => {
10189                    // A fused record stands for the next few instructions, so the next
10190                    // `pc` is its width ahead — the instructions it replaces are never
10191                    // dispatched. `at` is the byte offset a stack trace reports; it stays
10192                    // an offset because the line table is keyed by bytes.
10193                    frame.at = insn.offset as usize;
10194                    frame.pc += insn.width();
10195                    Some((insn, frame.pc))
10196                }
10197            }
10198        }) else {
10199            return Ok(Step::Return(Value::Undefined));
10200        };
10201        self.check_memory()?;
10202        self.check_interrupt()?;
10203        if insn.fused == crate::insn::Fused::None {
10204            self.execute_instruction(insn.op, insn.a, insn.b, next)
10205        } else {
10206            self.execute_fused(insn)
10207        }
10208    }
10209
10210    /// Run a fused instruction: several bytecode instructions in one dispatch.
10211    ///
10212    /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
10213    /// it cannot throw and cannot allocate — and anything else falls back to the real
10214    /// instructions, in their real order, so an exception leaves the operand stack
10215    /// exactly as it would have been.
10216    #[inline]
10217    fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
10218        use crate::insn::Fused;
10219        let slot = insn.a as usize;
10220        match insn.fused {
10221            // `x = k`: `push k; put_loc x`.
10222            Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
10223            // `x += k`: `get_loc x; push k; add; put_loc x`.
10224            Fused::AddImmLoc => {
10225                let delta = insn.b as i32;
10226                match self.get_loc(slot) {
10227                    Value::Int(left) => {
10228                        // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
10229                        // that built two `Value`s, called a function, and matched on them
10230                        // again to reach this same `checked_add`. It is the innermost
10231                        // operation of every accumulator in every program.
10232                        let answer = match left.checked_add(delta) {
10233                            Some(sum) => Value::Int(sum),
10234                            None => Value::Float(left as f64 + delta as f64),
10235                        };
10236                        self.put_loc(slot, answer);
10237                    }
10238                    other => {
10239                        self.push(other);
10240                        self.push(Value::Int(delta));
10241                        self.binary_add()?;
10242                        let value = self.pop();
10243                        self.put_loc(slot, value);
10244                    }
10245                }
10246            }
10247            // `x += "literal"` and `x += y`: the two shapes that can append in place.
10248            Fused::AddAtomLoc => {
10249                let text = self.atom_wtf8(insn.b as usize);
10250                let right = self.string_wtf8(text);
10251                self.add_into_loc(slot, right)?;
10252            }
10253            Fused::AddLocLoc => {
10254                let source = (insn.a & 0xFFFF) as usize;
10255                let target = (insn.a >> 16) as usize;
10256                let right = self.get_loc(source);
10257                self.add_into_loc(target, right)?;
10258            }
10259            Fused::AddArgLoc => {
10260                let source = (insn.a & 0xFFFF) as usize;
10261                let target = (insn.a >> 16) as usize;
10262                let right = self.get_arg(source);
10263                self.add_into_loc(target, right)?;
10264            }
10265            // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
10266            Fused::PostIncLoc => match self.get_loc(slot) {
10267                Value::Int(left) => {
10268                    let answer = match left.checked_add(1) {
10269                        Some(sum) => Value::Int(sum),
10270                        None => Value::Float(left as f64 + 1.0),
10271                    };
10272                    self.put_loc(slot, answer);
10273                }
10274                other => {
10275                    self.push(other);
10276                    let raw = self.pop();
10277                    let (old, updated) = self.advance_numeric(raw, true)?;
10278                    self.push(old);
10279                    self.push(updated);
10280                    let value = self.pop();
10281                    self.put_loc(slot, value);
10282                    self.pop();
10283                }
10284            },
10285            // `if (!(x < arg)) goto target`: a loop header.
10286            //
10287            // The comparison is computed rather than replayed on the operand stack. That
10288            // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
10289            // that throws: the effects happen in the same order, and a handler truncates
10290            // the stack down to its marker, so the intermediate values are unobservable.
10291            Fused::LtLocArgJump => {
10292                let loc = (insn.a >> 16) as usize;
10293                let arg = (insn.a & 0xFFFF) as usize;
10294                let left = self.get_loc(loc);
10295                let right = self.get_arg(arg);
10296                let taken = match (&left, &right) {
10297                    (Value::Int(left), Value::Int(right)) => !(left < right),
10298                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10299                };
10300                if taken {
10301                    self.frame_mut().pc = insn.b as usize;
10302                }
10303            }
10304            // `i < k` in a loop header, where `k` is an integer literal.
10305            Fused::LtLocImmJump => {
10306                let left = self.get_loc(insn.a as usize);
10307                let right = Value::Int(insn.imm as i32);
10308                let taken = match &left {
10309                    Value::Int(left) => !(*left < insn.imm as i32),
10310                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10311                };
10312                if taken {
10313                    self.frame_mut().pc = insn.b as usize;
10314                }
10315            }
10316            Fused::None => unreachable!("only called for a fused record"),
10317        }
10318        Ok(Step::Continue)
10319    }
10320
10321    /// Run records that cannot call script, cannot throw and cannot change frames.
10322    ///
10323    /// Returns `Some(value)` when the function ran off the end of its instructions (a
10324    /// normal return), and `None` when it stopped in front of an instruction the slow path
10325    /// has to handle — `pc` is written back either way, so `step` resumes at the right
10326    /// place.
10327    ///
10328    /// **The invariant is the whole point.** Every arm here is restricted to work that
10329    /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
10330    /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
10331    /// that the memory limit has to see. An opcode whose operands turn out to need any of
10332    /// that **stops the loop** instead of trying, so the slow path gets the instruction
10333    /// untouched and with its operands still on the stack. That is why the fallback is a
10334    /// `break` and not a duplicated slow arm: a second implementation of the same
10335    /// semantics is how a wrong answer gets in with no test noticing.
10336    ///
10337    /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
10338    /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
10339    fn run_fast(&mut self) -> JsResult<Option<Value>> {
10340        use crate::insn::Fused;
10341        // The outer loop exists only so a `Call` can come back through here: once a
10342        // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
10343        // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
10344        // frame. Re-entering re-reads both from whichever frame is now on top. Every
10345        // other exit from the inner loop returns, so this costs one loop per call.
10346        'outer: loop {
10347            // One reference-count bump per *slow* instruction (a call, an allocation, a
10348            // property access), never one per instruction — that distinction is worth
10349            // two orders of magnitude and was measured as such.
10350            let (code, mut pc) = {
10351                let frame = self.frame();
10352                (frame.code.clone(), frame.pc)
10353            };
10354            let insns = &code.insns;
10355            loop {
10356                let Some(insn) = insns.get(pc).copied() else {
10357                    self.frame_mut().pc = pc;
10358                    return Ok(Some(Value::Undefined));
10359                };
10360                match insn.fused {
10361                    // `x = k`
10362                    Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
10363                    // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
10364                    // object — stops the loop so `binary_add` can decide.
10365                    Fused::AddImmLoc => {
10366                        let slot = insn.a as usize;
10367                        let delta = insn.b as i32;
10368                        let Value::Int(left) = self.get_loc(slot) else {
10369                            return Ok(self.stop(pc));
10370                        };
10371                        let sum = match left.checked_add(delta) {
10372                            Some(sum) => Value::Int(sum),
10373                            None => Value::Float(left as f64 + delta as f64),
10374                        };
10375                        self.put_loc(slot, sum);
10376                    }
10377                    // `x += "literal"` / `x += y`: the operand is a string, so the append
10378                    // either allocates one or grows one. Both are the slow path's business;
10379                    // the fusion's job is only to make the *slot* the sole owner, which is what
10380                    // `execute_fused` needs and what `get_loc` alone destroys.
10381                    Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
10382                        return Ok(self.stop(pc));
10383                    }
10384                    // `x++` on an integer, old value dropped.
10385                    Fused::PostIncLoc => {
10386                        // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
10387                        // value is read in place and overwritten in place, so the reference
10388                        // count it held is released by the same assignment that stores the
10389                        // new one. `get_loc` plus `put_loc` did two borrows, two table
10390                        // lookups and a clone, and this arm is the whole body of a counting
10391                        // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
10392                        let slot = insn.a as usize;
10393                        let frame = self.frames.last_mut().expect("a frame is live");
10394                        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
10395                        let target = if cell < 0 {
10396                            frame.locals.get_mut(slot)
10397                        } else {
10398                            None
10399                        };
10400                        let Some(target) = target else {
10401                            return Ok(self.stop(pc));
10402                        };
10403                        let Value::Int(left) = *target else {
10404                            return Ok(self.stop(pc));
10405                        };
10406                        *target = match left.checked_add(1) {
10407                            Some(sum) => Value::Int(sum),
10408                            None => Value::Float(left as f64 + 1.0),
10409                        };
10410                    }
10411                    // A loop header, `if (!(x < arg)) goto target`, with both sides already
10412                    // integers — which is every `for (i = 0; i < n; i++)` whose counter and
10413                    // bound stayed small integers.
10414                    Fused::LtLocArgJump => {
10415                        let loc = (insn.a >> 16) as usize;
10416                        let arg = (insn.a & 0xFFFF) as usize;
10417                        // One borrow for both slots: this arm *is* the whole loop of a
10418                        // `for (i = 0; i < n; i++)` with an argument bound, so a second
10419                        // `frames.last()` here is paid on every iteration. Measured 7.5% on
10420                        // `dispatch:empty-loop`.
10421                        let (left, right) = {
10422                            let frame = self.frame();
10423                            (frame.read_loc(loc), frame.read_arg(arg))
10424                        };
10425                        // Heavily measured: the bound is very often a `Float` even when the
10426                        // counter is an `Int` — anything that came from `+scriptArgs[2]`,
10427                        // `JSON.parse` or a division is one — so requiring both sides to be
10428                        // `Int` sent every iteration of those loops down the slow path. The
10429                        // comparison below is the same one `relational` makes for two numbers.
10430                        if !is_number(&left) || !is_number(&right) {
10431                            return Ok(self.stop(pc));
10432                        }
10433                        // `if_false` branches on the comparison being false, which is **not**
10434                        // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
10435                        // `>=` is also false and would keep it running forever. Clippy wants the
10436                        // negation folded; that would be a wrong answer.
10437                        let ordered = left.to_number() < right.to_number();
10438                        let take_branch = !ordered;
10439                        if take_branch {
10440                            pc = insn.b as usize;
10441                            continue;
10442                        }
10443                    }
10444                    // The same header with a literal bound: `if (!(x < k)) goto target`.
10445                    // The bound is an immediate, so only the counter needs a type test.
10446                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
10447                    Fused::LtLocImmJump => {
10448                        let left = self.get_loc(insn.a as usize);
10449                        if !is_number(&left) {
10450                            return Ok(self.stop(pc));
10451                        }
10452                        let take_branch = !(left.to_number() < insn.imm as i32 as f64);
10453                        if take_branch {
10454                            pc = insn.b as usize;
10455                            continue;
10456                        }
10457                    }
10458                    Fused::None => match insn.op {
10459                        // -- branches ---------------------------------------------------
10460                        // A jump is an assignment now, because the target is an instruction
10461                        // index. No arithmetic, no resolution table.
10462                        Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10463                            let target = insn.a as usize;
10464                            // A **back-edge** is a loop, and it is the only place an
10465                            // instruction-level checkpoint can stop one: `for(;;){}` compiles
10466                            // to a jump to itself and never leaves this loop, so the
10467                            // per-instruction checks in `step` never run. That is exactly the
10468                            // hole this arm closes — a host's `JS_SetInterruptHandler` did
10469                            // nothing to a `for(;;){}` until it did, which is what
10470                            // `tests/c/embed.c` is for.
10471                            //
10472                            // Polling here rather than on every instruction in this loop is
10473                            // also the reference's choice (`OP_goto` calls
10474                            // `js_poll_interrupts`), and it costs one compare per branch
10475                            // instead of one decrement per instruction.
10476                            if target <= pc {
10477                                self.frame_mut().pc = target;
10478                                self.check_memory()?;
10479                                self.check_interrupt()?;
10480                            }
10481                            pc = target;
10482                            continue;
10483                        }
10484                        // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
10485                        Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
10486                            let taken = self.pop().to_boolean();
10487                            let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
10488                            if taken == want {
10489                                pc = insn.a as usize;
10490                                continue;
10491                            }
10492                        }
10493                        // -- slot access -------------------------------------------------
10494                        // A load's slot is already an operand (see `insn::implicit_operand`);
10495                        // a captured one goes through its cell, which runs no script.
10496                        Opcode::GetLoc
10497                        | Opcode::GetLoc8
10498                        | Opcode::GetLoc0
10499                        | Opcode::GetLoc1
10500                        | Opcode::GetLoc2
10501                        | Opcode::GetLoc3 => {
10502                            let value = self.get_loc(insn.a as usize);
10503                            self.push(value);
10504                        }
10505                        Opcode::PutLoc
10506                        | Opcode::PutLoc8
10507                        | Opcode::PutLoc0
10508                        | Opcode::PutLoc1
10509                        | Opcode::PutLoc2
10510                        | Opcode::PutLoc3 => {
10511                            let value = self.pop();
10512                            self.put_loc(insn.a as usize, value);
10513                        }
10514                        Opcode::GetArg
10515                        | Opcode::GetArg0
10516                        | Opcode::GetArg1
10517                        | Opcode::GetArg2
10518                        | Opcode::GetArg3 => {
10519                            let value = self.get_arg(insn.a as usize);
10520                            self.push(value);
10521                        }
10522                        Opcode::PutArg
10523                        | Opcode::PutArg0
10524                        | Opcode::PutArg1
10525                        | Opcode::PutArg2
10526                        | Opcode::PutArg3 => {
10527                            let value = self.pop();
10528                            self.put_arg(insn.a as usize, value);
10529                        }
10530                        // `a[i]` with an integer index on a dense array: see `fast_array_get`
10531                        // for why a non-hole own element is exactly the slow path's answer.
10532                        // The two operands are *peeked*, so a miss leaves the stack as the
10533                        // slow path expects to find it.
10534                        Opcode::GetArrayEl => {
10535                            // One lookup, not two. The guard used `if …is_some()` and the arm
10536                            // then called it again to get the value — two `peek`s, two
10537                            // `array_get`s and two `Value` clones for one element.
10538                            // `fast_array_get` was 13.1% of `array:indexed`, and the same
10539                            // double call was the first version of the `get_field` fast path.
10540                            let Some(value) = self.fast_array_get() else {
10541                                return Ok(self.stop(pc));
10542                            };
10543                            // `a[i]` consumes both operands and leaves the element in their
10544                            // place: one `truncate` and one write, no `pop`/`push` pair.
10545                            let frame = self.frame_mut();
10546                            frame.stack.truncate(frame.stack.len() - 2);
10547                            frame.stack.push(value);
10548                        }
10549                        // `a[i] = v` on a dense array with an integer index: see
10550                        // `fast_array_set` for why the whole store is one step.
10551                        Opcode::PutArrayEl if self.fast_array_set() => {}
10552                        // `o.x` resolved from the inline cache without leaving the loop.
10553                        //
10554                        // The cache is keyed by `(receiver identity, atom, site)` and a
10555                        // monomorphic read re-validates the same chain every iteration, so
10556                        // each one used to cost a `stop(pc)` — a write of `pc` into the
10557                        // frame, a return out of this loop, a re-dispatch through `step` and
10558                        // a re-entry. `property:monomorphic` spent 18% in
10559                        // `read_field_cached` and 21% in `push`, both across that boundary.
10560                        //
10561                        // The site is `pc + width`, which is exactly the `next` the slow arm
10562                        // passes — the two must agree or every fast lookup misses and
10563                        // re-records the same entry forever.
10564                        //
10565                        // A miss leaves the stack untouched (`fast_field_get` peeks) so the
10566                        // slow arm finds the receiver where it expects it.
10567                        // `name` resolved from the global-variable cache inside the loop.
10568                        //
10569                        // Same shape as `get_field` above and for the same reason: `get_var`
10570                        // was not in the fast loop, so reading a global — which `fib` does
10571                        // once per recursive call, for its own name — cost a `stop(pc)`, a
10572                        // return out of the loop, a `step` re-dispatch and a re-entry, before
10573                        // `get_global` even started its `scopes_are_plain` checks.
10574                        //
10575                        // Everything here is exactly `get_global`'s first branch: not lexical,
10576                        // no `eval` scope, cache hit. Anything else leaves the stack untouched
10577                        // and lets the slow arm decide.
10578                        Opcode::GetVar => {
10579                            let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
10580                                return Ok(self.stop(pc));
10581                            };
10582                            self.push(value);
10583                        }
10584                        Opcode::GetField | Opcode::GetField2 => {
10585                            let Some(value) =
10586                                self.fast_field_get(insn.a as usize, pc + insn.width())
10587                            else {
10588                                return Ok(self.stop(pc));
10589                            };
10590                            if insn.op == Opcode::GetField2 {
10591                                // `get_field2` keeps the receiver for the `call_method` that
10592                                // follows.
10593                                self.push(value);
10594                            } else {
10595                                // `get_field` replaces the receiver, so this is one store over
10596                                // the top slot rather than a `pop` and a `push`: the length
10597                                // never changes, so neither `Vec` arm has a capacity check or a
10598                                // drop to run beyond the one the overwrite itself does.
10599                                let frame = self.frame_mut();
10600                                match frame.stack.last_mut() {
10601                                    Some(slot) => *slot = value,
10602                                    None => return Ok(self.stop(pc)),
10603                                }
10604                            }
10605                        }
10606                        // -- constants ---------------------------------------------------
10607                        Opcode::PushMinus1
10608                        | Opcode::Push0
10609                        | Opcode::Push1
10610                        | Opcode::Push2
10611                        | Opcode::Push3
10612                        | Opcode::Push4
10613                        | Opcode::Push5
10614                        | Opcode::Push6
10615                        | Opcode::Push7
10616                        | Opcode::PushI8
10617                        | Opcode::PushI16
10618                        | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
10619                        // -- stack shuffling ---------------------------------------------
10620                        Opcode::Drop => {
10621                            self.pop();
10622                        }
10623                        // -- arithmetic on two integers ----------------------------------
10624                        //
10625                        // The operands are *looked at* before they are popped, so a non-integer
10626                        // pair leaves the stack exactly as the slow path expects to find it.
10627                        Opcode::Add if self.numeric_pair() => {
10628                            let right = self.pop();
10629                            let left = self.pop();
10630                            // Exactly [`add_numbers`], which is what the slow arm reaches.
10631                            let answer = match (&left, &right) {
10632                                (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10633                                    Some(sum) => Value::Int(sum),
10634                                    None => Value::Float(*a as f64 + *b as f64),
10635                                },
10636                                _ => Value::Float(left.to_number() + right.to_number()),
10637                            };
10638                            self.push(answer);
10639                        }
10640                        Opcode::Sub
10641                        | Opcode::And
10642                        | Opcode::Or
10643                        | Opcode::Xor
10644                        | Opcode::Shl
10645                        | Opcode::Sar
10646                        | Opcode::Shr
10647                            if self.numeric_pair() =>
10648                        {
10649                            let right = self.pop();
10650                            let left = self.pop();
10651                            let answer =
10652                                arithmetic(insn.op, left, right).expect("numbers cannot throw");
10653                            self.push(answer);
10654                        }
10655                        Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10656                            if self.numeric_pair() =>
10657                        {
10658                            let right = self.pop();
10659                            let left = self.pop();
10660                            let answer = self
10661                                .relational(insn.op, left, right)
10662                                .expect("numbers cannot throw");
10663                            self.push(answer);
10664                        }
10665                        // -- calls -------------------------------------------------------
10666                        //
10667                        // A plain call: `callee(arg0, …, argN) -> result`.
10668                        //
10669                        // This arm exists because of one measurement. `call:recursion` had
10670                        // **20.4% of its profile in `execute_instruction`** — the *slow*
10671                        // executor — and `fib`'s recursive call is the only thing in that
10672                        // function which is not a fast arm. Every call therefore left this
10673                        // loop via `stop()`, went through `step()`'s dispatch and
10674                        // `execute_instruction`'s match over every opcode, and came back here
10675                        // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
10676                        //
10677                        // Two things make it safe to do here rather than only in the slow path:
10678                        //
10679                        // * the caller's `pc` is stored *before* the call, which is what
10680                        //   `step` does too — so when the callee returns, the caller resumes
10681                        //   after the call and not at it;
10682                        // * `check_memory` runs, because `step` calls it once per instruction
10683                        //   and a call allocates a frame, its locals and its cells. Skipping
10684                        //   the checkpoint here would let a `--memory-limit` script overshoot
10685                        //   by one call per instruction.
10686                        Opcode::Call
10687                        | Opcode::Call0
10688                        | Opcode::Call1
10689                        | Opcode::Call2
10690                        | Opcode::Call3 => {
10691                            let argc = self.argc_operand(insn.op, insn.a);
10692                            let next = pc + insn.width();
10693                            {
10694                                let frame = self
10695                                    .frames
10696                                    .last_mut()
10697                                    .expect("run_fast() is only called with a live frame");
10698                                // `at` is what a stack trace reports for this frame, so a throw
10699                                // inside the callee has to see the call site and not whatever
10700                                // the last `stop()` left there.
10701                                frame.at = insn.offset as usize;
10702                                frame.pc = next;
10703                            }
10704                            self.check_memory()?;
10705                            self.check_interrupt()?;
10706                            let args = self.pop_n(argc);
10707                            let callee = self.pop();
10708                            // A plain call has no receiver; the callee decides what to do with
10709                            // `undefined` (a sloppy function substitutes the global object).
10710                            if let Some(result) =
10711                                self.call_or_push(callee, Value::Undefined, args)?
10712                            {
10713                                // Native, host, generator, async, bound — no frame was pushed,
10714                                // so this loop is still describing the right function. `pc`
10715                                // is advanced by the loop tail like every other arm; only the
10716                                // frame's copy had to be written here, and it already was.
10717                                self.push(result);
10718                            } else {
10719                                // A bytecode callee: its frame is on top now, and `insns` and
10720                                // `pc` both belong to the caller. Start over on the new frame.
10721                                continue 'outer;
10722                            }
10723                        }
10724                        // -- return ------------------------------------------------------
10725                        Opcode::Return => {
10726                            let value = self.pop();
10727                            self.frame_mut().pc = pc + insn.width();
10728                            return Ok(Some(value));
10729                        }
10730                        Opcode::ReturnUndef => {
10731                            self.frame_mut().pc = pc + insn.width();
10732                            return Ok(Some(Value::Undefined));
10733                        }
10734                        // Everything else needs the slow path.
10735                        _ => return Ok(self.stop(pc)),
10736                    },
10737                }
10738                pc += insn.width();
10739            }
10740        }
10741    }
10742
10743    /// Whether the top two operand-stack values are both numbers.
10744    ///
10745    /// The guard the fast loop uses before it takes an arithmetic record: two numbers
10746    /// cannot run script, so the arm may not throw and may not change frames.
10747    fn numeric_pair(&self) -> bool {
10748        is_number(&self.peek(0)) && is_number(&self.peek(1))
10749    }
10750
10751    /// `a[i]` for a dense array and an integer index, without the string round trip.
10752    ///
10753    /// The slow path answers this by turning `i` into a string (`propkey` →
10754    /// `number_to_string`) and then parsing it straight back (`read_field_key` →
10755    /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
10756    /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
10757    /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
10758    /// without even the cheap `Int` formatting.
10759    ///
10760    /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
10761    /// unambiguously the one the slow path would give:
10762    ///
10763    /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
10764    ///   `2^32-1` is the length, not an index),
10765    /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
10766    ///   typed array or an ordinary object, all of which have their own rules),
10767    /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
10768    ///   starts walking the prototype chain, and `a[i]` on a hole must find
10769    ///   `Array.prototype[i]` if it exists rather than `undefined`.
10770    ///
10771    /// The last condition is the one that makes this safe rather than merely fast: an own
10772    /// element always wins over the prototype, so a non-hole hit needs no further lookup.
10773    /// `get_var` answered from the global-variable cache, or `None`.
10774    ///
10775    /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10776    /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10777    /// records nothing — the slow arm is about to walk the chain and record it.
10778    fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10779        let frame = self.frame();
10780        let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10781        // "Lexical" is presence in the realm's table, not the closure var's flag: a
10782        // `GlobalRef` forwarded through a nested function has its flags cleared.
10783        if self.realm.globals.contains_key(name) {
10784            return None;
10785        }
10786        if !self.scopes_are_plain() {
10787            return None;
10788        }
10789        let object = &self.realm.global;
10790        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10791        let cached = self.global_cache[site].as_ref()?;
10792        if !object.upgrades_to(&cached.object) {
10793            return None;
10794        }
10795        object.data_property_at(cached.index, name)
10796    }
10797
10798    /// `o.x` answered entirely from the inline cache, or `None`.
10799    ///
10800    /// Read-only on purpose: a miss must not record an entry, because the slow arm is
10801    /// about to do exactly that and recording it twice would rebuild the chain for every
10802    /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
10803    /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
10804    fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
10805        // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
10806        // an object receiver is a reference-count bump that the answer never needs.
10807        let frame = self.frame();
10808        let object = frame.stack.last()?;
10809        let Value::Object(target) = object else {
10810            return None;
10811        };
10812        // A proxy traps the lookup, so no cache entry ever describes it.
10813        if target.proxy_state().is_some() {
10814            return None;
10815        }
10816        let key = frame.code.atom_keys.get(atom)?;
10817        let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
10818        if cached.key != *key {
10819            return None;
10820        }
10821        Self::cached_hit(target, cached)
10822    }
10823
10824    fn fast_array_get(&self) -> Option<Value> {
10825        let Value::Int(index) = self.peek(0) else {
10826            return None;
10827        };
10828        // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
10829        // set for an `i32`.
10830        if index < 0 {
10831            return None;
10832        }
10833        let Value::Object(object) = self.peek(1) else {
10834            return None;
10835        };
10836        match object.array_get(index as usize) {
10837            Some(value) if !matches!(value, Value::Hole) => Some(value),
10838            _ => None,
10839        }
10840    }
10841
10842    /// `a[i] = v` on a dense array with an integer index, as one store.
10843    ///
10844    /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
10845    /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
10846    /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
10847    /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
10848    /// reference at the time it was measured (14.7x).
10849    ///
10850    /// Every condition here is one the slow path would also have to satisfy before
10851    /// storing into the element vector:
10852    ///
10853    /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
10854    ///   accepts as an index;
10855    /// * the target is an array whose elements are writable (`Object.freeze` clears it);
10856    /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
10857    ///   one inside a recorded descriptor, reports `false` and the caller stops.
10858    ///
10859    /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
10860    /// writes the own element too once `array_set` says it did.
10861    fn fast_array_set(&mut self) -> bool {
10862        // Every test runs *before* anything is popped: a refusal has to leave the stack
10863        // exactly as the slow path expects to find it. Popping first and reporting the
10864        // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
10865        // then ran the slow path with nothing to write.
10866        let Value::Int(index) = self.peek(1) else {
10867            return false;
10868        };
10869        // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
10870        if index < 0 {
10871            return false;
10872        }
10873        // Only a real array: a typed array's elements live in its buffer, a string-like
10874        // object has no element vector, and `array_set` on either does nothing.
10875        let Value::Object(object) = self.peek(2) else {
10876            return false;
10877        };
10878        if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
10879            return false;
10880        }
10881        // A non-extensible array reports `false` here, but the *slow* path has to decide
10882        // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
10883        // that with the key and the stack still intact.
10884        if !object.is_extensible() {
10885            return false;
10886        }
10887        // Inside the logical length, so the store cannot change `length`. Combined with
10888        // extensibility above, the only growth left for `array_set` is filling a hole in
10889        // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
10890        // shape this fast path exists for. A store past the length would grow the array,
10891        // and whether that is allowed is the slow path's question.
10892        if index as usize >= object.array_length().unwrap_or(0) {
10893            return false;
10894        }
10895        // Only an *own element* can take the inline store. A hole is not an own property,
10896        // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
10897        // trap or a setter decides, and where `new Array(1)` with a proxy above it must
10898        // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
10899        // the one case this path used to swallow.
10900        //
10901        // The cost is small: `array:indexed` only reads after a 64-element fill, and
10902        // `array:push` appends past the length, which this path already refused.
10903        if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
10904        {
10905            return false;
10906        }
10907        // The bound `array_set` refuses past. Checking it here keeps that arm from having
10908        // to report a failure after the operands are gone.
10909        if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
10910            return false;
10911        }
10912        let value = self.pop();
10913        self.pop();
10914        self.pop();
10915        object.array_store(self.heap, index as usize, value)
10916    }
10917
10918    /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
10919    fn stop(&mut self, pc: usize) -> Option<Value> {
10920        self.frame_mut().pc = pc;
10921        None
10922    }
10923
10924    fn push(&mut self, value: Value) {
10925        self.frame_mut().stack.push(value);
10926    }
10927
10928    fn pop(&mut self) -> Value {
10929        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10930    }
10931
10932    fn pop_n(&mut self, count: usize) -> Vec<Value> {
10933        let frame = self.frame_mut();
10934        let start = frame.stack.len().saturating_sub(count);
10935        frame.stack.split_off(start)
10936    }
10937
10938    fn peek(&self, back: usize) -> Value {
10939        let frame = self.frame();
10940        frame
10941            .stack
10942            .get(frame.stack.len().wrapping_sub(1 + back))
10943            .cloned()
10944            .unwrap_or(Value::Undefined)
10945    }
10946
10947    #[allow(clippy::too_many_lines)]
10948    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10949        use Opcode::*;
10950        match op {
10951            // -- constants and stack shuffling -----------------------------
10952            Nop => {}
10953            PushMinus1 => self.push(Value::Int(-1)),
10954            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10955                let value = match op {
10956                    Push0 => 0,
10957                    Push1 => 1,
10958                    Push2 => 2,
10959                    Push3 => 3,
10960                    Push4 => 4,
10961                    Push5 => 5,
10962                    Push6 => 6,
10963                    _ => 7,
10964                };
10965                self.push(Value::Int(value));
10966            }
10967            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
10968            PushBigintI32 => {
10969                // The immediate form of a `BigInt` literal; the reference has the same
10970                // split between this and a constant-pool entry.
10971                let value = crate::bigint::BigInt::from_i64(a as i64);
10972                self.push(self.bigint(value));
10973            }
10974            PushTrue => self.push(Value::Bool(true)),
10975            PushFalse => self.push(Value::Bool(false)),
10976            PushEmptyString => self.push(self.string("")),
10977            Undefined => self.push(Value::Undefined),
10978            Null => self.push(Value::Null),
10979            Object => {
10980                let proto = self.realm.object_proto.clone();
10981                self.push(Value::Object(self.new_object(Some(proto))));
10982            }
10983            PushThis => {
10984                let this = self.frame().this.clone();
10985                self.push(this);
10986            }
10987            PushConst | PushConst8 => {
10988                let value = self.constant(a as usize)?;
10989                self.push(value);
10990            }
10991            PushAtomValue => {
10992                let text = self.atom_wtf8(a as usize);
10993                self.push(self.string_wtf8(text));
10994            }
10995            Dup => {
10996                let value = self.peek(0);
10997                self.push(value);
10998            }
10999            Dup2 => {
11000                // `a b -> a b a b`
11001                let b = self.peek(0);
11002                let a = self.peek(1);
11003                self.push(a);
11004                self.push(b);
11005            }
11006            Dup3 => {
11007                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
11008                // prototype and key while reading the current value through them.
11009                let c = self.peek(0);
11010                let b = self.peek(1);
11011                let a = self.peek(2);
11012                self.push(a);
11013                self.push(b);
11014                self.push(c);
11015            }
11016            Swap => {
11017                // `a b -> b a`
11018                let bottom = self.pop();
11019                let top = self.pop();
11020                self.push(bottom);
11021                self.push(top);
11022            }
11023            Perm3 => {
11024                // `a b c -> b a c`, the reference's reordering for a spread method
11025                // call: `obj func array` becomes the `func this array` that `apply`
11026                // takes.
11027                let c = self.pop();
11028                let b = self.pop();
11029                let a = self.pop();
11030                self.push(b);
11031                self.push(a);
11032                self.push(c);
11033            }
11034            Dup1 => {
11035                let value = self.peek(1);
11036                self.push(value);
11037            }
11038            Drop => {
11039                self.pop();
11040            }
11041            Nip => {
11042                // `a b -> b`
11043                let top = self.pop();
11044                self.pop();
11045                self.push(top);
11046            }
11047            Perm4 => {
11048                // `obj prop a b -> a obj prop b`, the reference's reordering for a
11049                // postfix update of a computed element: it puts the *old* value
11050                // underneath the receiver and key so `put_array_el` can consume them
11051                // and leave the old value as the expression's result.
11052                let d = self.pop();
11053                let c = self.pop();
11054                let b = self.pop();
11055                let a = self.pop();
11056                self.push(c);
11057                self.push(a);
11058                self.push(b);
11059                self.push(d);
11060            }
11061            Insert2 => {
11062                // `obj a -> a obj a`
11063                let value = self.pop();
11064                let object = self.pop();
11065                self.push(value.clone());
11066                self.push(object);
11067                self.push(value);
11068            }
11069            Insert3 => {
11070                // `obj prop a -> a obj prop a`
11071                let value = self.pop();
11072                let key = self.pop();
11073                let object = self.pop();
11074                self.push(value.clone());
11075                self.push(object);
11076                self.push(key);
11077                self.push(value);
11078            }
11079            Insert4 => {
11080                // `this obj prop a -> a this obj prop a`
11081                //
11082                // `put_super_value` consumes all four and yields nothing, so the copy
11083                // underneath is what leaves the assignment an expression value.
11084                let value = self.pop();
11085                let key = self.pop();
11086                let object = self.pop();
11087                let receiver = self.pop();
11088                self.push(value.clone());
11089                self.push(receiver);
11090                self.push(object);
11091                self.push(key);
11092                self.push(value);
11093            }
11094            Swap2 => {
11095                // `a b c d -> c d a b`
11096                let d = self.pop();
11097                let c = self.pop();
11098                let b = self.pop();
11099                let a = self.pop();
11100                self.push(c);
11101                self.push(d);
11102                self.push(a);
11103                self.push(b);
11104            }
11105            Rot3l => {
11106                // `x a b -> a b x`
11107                let b = self.pop();
11108                let a = self.pop();
11109                let x = self.pop();
11110                self.push(a);
11111                self.push(b);
11112                self.push(x);
11113            }
11114            Rot3r => {
11115                // `a b c -> c a b`
11116                let c = self.pop();
11117                let b = self.pop();
11118                let a_value = self.pop();
11119                self.push(c);
11120                self.push(a_value);
11121                self.push(b);
11122            }
11123
11124            Rest => {
11125                // `...rest` in a parameter list: the arguments from index `a` on, as a
11126                // real array. It takes nothing off the stack — the arguments are in the
11127                // frame, not on it.
11128                let frame = self.frame();
11129                let from = a as usize;
11130                let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
11131                let array = self.new_array(collected);
11132                self.push(Value::Object(array));
11133            }
11134
11135            // -- slots ------------------------------------------------------
11136            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
11137                let slot = self.slot_operand(op, a);
11138                let value = self.get_loc(slot);
11139                self.push(value);
11140            }
11141            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
11142                let slot = self.slot_operand(op, a);
11143                let value = self.pop();
11144                self.put_loc(slot, value);
11145            }
11146            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
11147                let slot = self.slot_operand(op, a);
11148                let value = self.pop();
11149                self.put_loc(slot, value.clone());
11150                self.push(value);
11151            }
11152            // The `_check` forms are the temporal dead zone: they throw when the
11153            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
11154            // *reads*, so only the two writes may pop — mishandling that quietly
11155            // consumes the value the caller pushed just before.
11156            GetLocCheck => {
11157                let slot = self.slot_operand(op, a);
11158                let value = self.get_loc(slot);
11159                if matches!(value, Value::Uninitialized) {
11160                    return Err(self.dead_zone(slot, VarSlot::Loc));
11161                }
11162                self.push(value);
11163            }
11164            PutLocCheck | SetLocCheck => {
11165                let slot = self.slot_operand(op, a);
11166                let value = self.pop();
11167                // The dead zone is a property of the **slot**, not of the value being
11168                // stored: `x = 1; let x` is a `ReferenceError` because `x` has not been
11169                // initialised yet. Testing the value instead — which is never
11170                // `Uninitialized` in practice — let every such store through, so the check
11171                // only ever fired for an explicit `x = undefined`-shaped accident. Reads
11172                // (`get_loc_check`) were already asking the slot, which is why
11173                // `print(x); let x` threw while `x = 1; let x` did not.
11174                if matches!(self.get_loc(slot), Value::Uninitialized) {
11175                    return Err(self.dead_zone(slot, VarSlot::Loc));
11176                }
11177                // The initialiser goes through `put_loc`, not this, so any store that
11178                // reaches here is a later assignment — which a `const` refuses.
11179                if self.is_read_only(slot, VarSlot::Loc) {
11180                    return Err(self.read_only(slot, VarSlot::Loc));
11181                }
11182                if op == SetLocCheck {
11183                    self.put_loc(slot, value.clone());
11184                    self.push(value);
11185                } else {
11186                    self.put_loc(slot, value);
11187                }
11188            }
11189            PutLocCheckInit => {
11190                // The one store that *initialises* a lexical slot: `this` in a derived
11191                // constructor, which only exists after `super()` has run. A second
11192                // initialisation is the error the reference reports as
11193                // "'this' can be initialized only once".
11194                let slot = self.slot_operand(op, a);
11195                let value = self.pop();
11196                if !matches!(self.get_loc(slot), Value::Uninitialized) {
11197                    return Err(Signal::Throw(self.make_error(
11198                        "ReferenceError",
11199                        "'this' can be initialized only once",
11200                    )));
11201                }
11202                self.put_loc(slot, value);
11203            }
11204            CheckCtor => {
11205                // A class constructor may only run under `new`, which is what makes
11206                // `class A {}; A()` a TypeError.
11207                if matches!(self.frame().new_target, Value::Undefined) {
11208                    return Err(Signal::Throw(self.make_error(
11209                        "TypeError",
11210                        "class constructors must be invoked with 'new'",
11211                    )));
11212                }
11213            }
11214            InitCtor => {
11215                // The body a derived class gets when it declares no constructor:
11216                // forward every argument to the parent constructor, keeping `new.target`.
11217                if matches!(self.frame().new_target, Value::Undefined) {
11218                    return Err(Signal::Throw(self.make_error(
11219                        "TypeError",
11220                        "class constructors must be invoked with 'new'",
11221                    )));
11222                }
11223                let Some(callee) = self.current_callee() else {
11224                    return Err(Signal::Throw(
11225                        self.make_error("TypeError", "no constructor to inherit from"),
11226                    ));
11227                };
11228                let parent = callee.proto().map_or(Value::Null, Value::Object);
11229                let new_target = self.frame().new_target.clone();
11230                let args = self.frame().passed().to_vec();
11231                let result = self.construct(parent, new_target, args)?;
11232                self.push(result);
11233            }
11234            SetLocUninitialized => {
11235                let slot = self.slot_operand(op, a);
11236                self.put_loc(slot, Value::Uninitialized);
11237            }
11238            CloseLoc => {
11239                // "Close" a binding: give it a *fresh* cell holding the current
11240                // value. Closures created before this point keep the old cell and the
11241                // ones created after see the new one, which is what makes every
11242                // iteration of `for (let i ...)` capture its own `i`, and what freezes
11243                // a block-scoped binding when the block ends.
11244                //
11245                // Clearing the slot instead (which this used to do) broke both: a
11246                // closure over a captured block variable read `undefined`, and a loop
11247                // terminated after one iteration.
11248                let slot = self.slot_operand(op, a);
11249                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
11250                if index >= 0 {
11251                    let current = self.frame().cells[index as usize].get();
11252                    let fresh = self.new_cell(current);
11253                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
11254                        *cell = fresh;
11255                    }
11256                }
11257            }
11258            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
11259                let slot = self.slot_operand(op, a);
11260                let value = self.get_arg(slot);
11261                self.push(value);
11262            }
11263            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
11264                let slot = self.slot_operand(op, a);
11265                let value = self.pop();
11266                self.put_arg(slot, value);
11267            }
11268            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
11269                let slot = self.slot_operand(op, a);
11270                let value = self.pop();
11271                self.put_arg(slot, value.clone());
11272                self.push(value);
11273            }
11274
11275            // -- closure variables ------------------------------------------
11276            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
11277                let slot = self.slot_operand(op, a);
11278                // A name a direct `eval` created shadows the binding the compiler chose.
11279                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
11280                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
11281                // and only a runtime lookup can know that.
11282                if let Some(cell) = self.eval_created_local(slot) {
11283                    self.push(cell.get());
11284                    return self.step();
11285                }
11286                let value = self.cell_value(slot)?;
11287                self.push(value);
11288            }
11289            GetVarRefCheck => {
11290                let slot = self.slot_operand(op, a);
11291                let value = self.cell_value(slot)?;
11292                if matches!(value, Value::Uninitialized) {
11293                    return Err(self.dead_zone(slot, VarSlot::Closure));
11294                }
11295                self.push(value);
11296            }
11297            PutVarRefCheckInit => {
11298                // The captured-form twin of `PutLocCheckInit`. Both exist because `super()`
11299                // may be written inside an arrow, and there `this` is a var-ref rather than
11300                // a local.
11301                let slot = self.slot_operand(op, a);
11302                let value = self.pop();
11303                // The wording differs from the local form because the reference reaches
11304                // this case through `get_var_ref_checkthis`, which reports the dead zone
11305                // rather than the double initialisation.
11306                if !matches!(self.cell_value(slot)?, Value::Uninitialized) {
11307                    return Err(Signal::Throw(
11308                        self.make_error("ReferenceError", "this is not initialized"),
11309                    ));
11310                }
11311                self.set_cell(slot, value)?;
11312            }
11313            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
11314                let slot = self.slot_operand(op, a);
11315                let value = self.pop();
11316                if let Some(cell) = self.eval_created_local(slot) {
11317                    cell.set(value);
11318                    return self.step();
11319                }
11320                // Same two rules as `PutLocCheck`: a checked store to a captured binding
11321                // asks the cell about the dead zone, then refuses a `const` whose
11322                // initialiser has already run.
11323                if op == PutVarRefCheck {
11324                    let current = self.cell_value(slot)?;
11325                    if matches!(current, Value::Uninitialized) {
11326                        return Err(self.dead_zone(slot, VarSlot::Closure));
11327                    }
11328                    if self.is_read_only(slot, VarSlot::Closure) {
11329                        return Err(self.read_only(slot, VarSlot::Closure));
11330                    }
11331                }
11332                self.set_cell(slot, value)?;
11333            }
11334            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
11335                let slot = self.slot_operand(op, a);
11336                let value = self.pop();
11337                if let Some(cell) = self.eval_created_local(slot) {
11338                    cell.set(value.clone());
11339                    self.push(value);
11340                    return self.step();
11341                }
11342                self.set_cell(slot, value.clone())?;
11343                self.push(value);
11344            }
11345
11346            // -- globals ----------------------------------------------------
11347            GetVar => {
11348                let value = self.get_global(a as usize)?;
11349                self.push(value);
11350            }
11351            GetVarUndef => {
11352                let slot = a as usize;
11353                // `typeof undeclared` answers `"undefined"`; `typeof x` where `x` is in its
11354                // **dead zone** still throws (§13.5.3 evaluates the operand as a Reference
11355                // and `GetValue`s it, and only the unresolvable case is forgiven).
11356                //
11357                // The distinction is made by asking whether a binding exists at all: a name
11358                // in the realm's lexical table is declared, so a `ReferenceError` from
11359                // reading it is the dead zone talking. Swallowing every error made
11360                // `eval("typeof x; let x;")` print `"undefined"`.
11361                let declared = self.realm.globals.contains_key(&self.global_name(slot));
11362                let value = if declared {
11363                    self.get_global(slot)?
11364                } else {
11365                    match self.get_global(slot) {
11366                        Ok(value) => value,
11367                        Err(Signal::Throw(_)) => Value::Undefined,
11368                        Err(other) => return Err(other),
11369                    }
11370                };
11371                self.push(value);
11372            }
11373            DeleteVar => {
11374                // `delete name` for a name that is not a declared binding. A lexical
11375                // global lives in the reference table and cannot be deleted; anything
11376                // reachable only as a property of the global object is *implicit* —
11377                // `x = 1` with no declaration — and goes away if it is configurable,
11378                // which is what `delete` on an implicit global answers.
11379                let name = self.atom_text(a as usize);
11380                let global = self.realm.global.clone();
11381                let deleted = if self.realm.globals.contains_key(&name) {
11382                    false
11383                } else if global.own_property(&name).is_some() {
11384                    self.delete_property(&global, &name)?
11385                } else {
11386                    true
11387                };
11388                self.push(Value::Bool(deleted));
11389            }
11390            PutVar => {
11391                let value = self.pop();
11392                self.put_global(a as usize, value)?;
11393            }
11394            PutVarInit => {
11395                let slot = a as usize;
11396                let value = self.pop();
11397                self.init_global(slot, value)?;
11398            }
11399
11400            // -- arithmetic -------------------------------------------------
11401            Add => self.binary_add()?,
11402            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
11403                let raw_right = self.pop();
11404                let raw_left = self.pop();
11405                // Two numbers need no `ToPrimitive` at all, which is every `x - y` and
11406                // `flags | mask` in real code.
11407                if is_number(&raw_left) && is_number(&raw_right) {
11408                    self.push(arithmetic(op, raw_left, raw_right)?);
11409                } else {
11410                    // §13.15.3 steps 1–3: **both** operands are made primitive before the
11411                    // disjointness check, left first. Getting the order wrong was observable
11412                    // — `ToPrimitive` on the right ran first, so a `valueOf` log read `b,a`
11413                    // and a throw from the *left* operand never happened
11414                    // (`S11.10.1_A2.3_T1`, `order-of-evaluation`).
11415                    //
11416                    // Doing the check on the *primitives* rather than on the raw values is
11417                    // the second half: `Object(5n) & Object(3n)` has a bigint on neither
11418                    // side of the stack yet, so the old check sent it down the `ToNumber`
11419                    // path and raised "cannot convert bigint to number"
11420                    // (`bigint-non-primitive`).
11421                    let left = self.primitive_of(raw_left)?;
11422                    let right = self.primitive_of(raw_right)?;
11423                    // BigInt arithmetic is a separate path, and not only for the type of
11424                    // the result: `ToNumber` of a bigint throws, so mixing the two must be
11425                    // an error rather than a silent conversion.
11426                    if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
11427                        let value = self.bigint_arithmetic(op, left, right)?;
11428                        self.push(value);
11429                    } else {
11430                        let right = self.numeric(right)?;
11431                        let left = self.numeric(left)?;
11432                        self.push(arithmetic(op, left, right)?);
11433                    }
11434                }
11435            }
11436            Neg => {
11437                let raw = self.pop();
11438                match raw {
11439                    // A bigint negates exactly, however wide it is.
11440                    Value::BigInt(big) => {
11441                        let negated = big.negate();
11442                        self.push(self.bigint(negated));
11443                    }
11444                    other => {
11445                        let value = self.numeric_operand(other)?;
11446                        if let Value::BigInt(big) = &value {
11447                            let negated = big.negate();
11448                            self.push(self.bigint(negated));
11449                        } else {
11450                            self.push(negate(value));
11451                        }
11452                    }
11453                }
11454            }
11455            Plus => {
11456                let value = self.pop();
11457                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
11458                // unary plus is defined to produce a *number*, which a bigint cannot
11459                // become without loss. It used to fall through to `NaN`.
11460                if matches!(value, Value::BigInt(_)) {
11461                    return Err(self.type_error("cannot convert bigint to number"));
11462                }
11463                let numeric = self.numeric_of(value)?;
11464                self.push(numeric);
11465            }
11466            Inc => {
11467                let raw = self.pop();
11468                let (_, updated) = self.advance_numeric(raw, true)?;
11469                self.push(updated);
11470            }
11471            Dec => {
11472                let raw = self.pop();
11473                let (_, updated) = self.advance_numeric(raw, false)?;
11474                self.push(updated);
11475            }
11476            PostInc | PostDec => {
11477                // `x -> x x+1`: the *new* value ends up on top, so the store the
11478                // compiler emits right after (`put_var`) writes the incremented
11479                // one, while the old value stays underneath for the expression's
11480                // own result. Getting this backwards makes `i++` a no-op, which
11481                // turns `while (i < 3)` into an infinite loop.
11482                let raw = self.pop();
11483                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
11484                self.push(old);
11485                self.push(updated);
11486            }
11487            Not => {
11488                let raw = self.pop();
11489                match raw {
11490                    // `~x` on a bigint is `-x - 1`, exact at any width.
11491                    Value::BigInt(big) => {
11492                        let inverted = big.bitnot();
11493                        self.push(self.bigint(inverted));
11494                    }
11495                    other => {
11496                        let value = self.numeric_operand(other)?;
11497                        if let Value::BigInt(big) = &value {
11498                            let inverted = big.bitnot();
11499                            self.push(self.bigint(inverted));
11500                        } else {
11501                            self.push(Value::Int(!value.to_int32()));
11502                        }
11503                    }
11504                }
11505            }
11506            Lnot => {
11507                let value = self.pop();
11508                self.push(Value::Bool(!value.to_boolean()));
11509            }
11510
11511            // -- comparison -------------------------------------------------
11512            Lt | Lte | Gt | Gte => {
11513                let right = self.pop();
11514                let left = self.pop();
11515                let answer = self.relational(op, left, right)?;
11516                self.push(answer);
11517            }
11518            Eq | Neq => {
11519                let right = self.pop();
11520                let left = self.pop();
11521                let equal = self.abstract_equals(left, right)?;
11522                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
11523            }
11524            StrictEq => {
11525                let right = self.pop();
11526                let left = self.pop();
11527                self.push(Value::Bool(left.strict_equals(&right)));
11528            }
11529            StrictNeq => {
11530                let right = self.pop();
11531                let left = self.pop();
11532                self.push(Value::Bool(!left.strict_equals(&right)));
11533            }
11534            IsUndefined => {
11535                // `=== undefined`, which is what a destructuring default tests. It is
11536                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
11537                let value = self.pop();
11538                self.push(Value::Bool(matches!(value, Value::Undefined)));
11539            }
11540            IsUndefinedOrNull => {
11541                let value = self.pop();
11542                self.push(Value::Bool(value.is_nullish()));
11543            }
11544            Typeof => {
11545                let value = self.pop();
11546                self.push(self.string(value.type_of()));
11547            }
11548            ToObject => {
11549                // A destructuring *object* pattern starts here, which is why
11550                // `var {} = null` throws. Only `undefined` and `null` are refused; a
11551                // primitive is boxed.
11552                let value = self.pop();
11553                let object = self.object_from(&value)?;
11554                self.push(Value::Object(object));
11555            }
11556            Instanceof => {
11557                let constructor = self.pop();
11558                let object = self.pop();
11559                // `InstanceofOperator`, not `OrdinaryHasInstance`: the operator consults
11560                // `Symbol.hasInstance` first and throws for a right-hand side that is not an
11561                // object (step 1) or not callable (step 4). Calling `instance_of` directly
11562                // skipped both the protocol and the two `TypeError`s.
11563                let answer = self.instance_of_operator(&object, &constructor)?;
11564                self.push(Value::Bool(answer));
11565            }
11566            In => {
11567                let object = self.pop();
11568                let key = self.pop();
11569                let answer = self.has_property(&key, &object)?;
11570                self.push(Value::Bool(answer));
11571            }
11572            WithHasVar => {
11573                // `obj -> bool`: does this `with` object bind the name?
11574                //
11575                // §9.1.1.2.1 `HasBinding` for an Object Environment Record is **not**
11576                // `HasProperty`: step 2 skips the property entirely when the object's
11577                // `Symbol.unscopables` lists it. So `globalThis[Symbol.unscopables] = {v:
11578                // true}` makes `with (globalThis) { v }` read the *outer* `v`, which is what
11579                // the thirty-odd `unscopables-with` cases assert.
11580                //
11581                // One instruction rather than a hand-expanded sequence of `in`, a
11582                // `Symbol.unscopables` lookup and a second `in`: the same question is asked
11583                // by both the read/write guard and `delete`, and a compiler-side expansion
11584                // would be about ten instructions per name per `with` object.
11585                let object = self.pop();
11586                let name = self.atom_text(a as usize);
11587                let bound = self.with_has_binding(&object, &name)?;
11588                self.push(Value::Bool(bound));
11589            }
11590            WithGetVar => {
11591                // `obj -> value`: the second half of `GetBindingValue`.
11592                let object = self.pop();
11593                let name = self.atom_text(a as usize);
11594                let value = self.with_get_binding(&object, &name)?;
11595                self.push(value);
11596            }
11597            WithPutVar => {
11598                // `obj value ->`: the second half of `SetMutableBinding`. The operand order
11599                // is `put_field`'s (value on top), not the reference's, so that the
11600                // read-modify-write shapes (`perm3`/`insert2`) can be shared with the
11601                // member-expression forms.
11602                let value = self.pop();
11603                let object = self.pop();
11604                let name = self.atom_text(a as usize);
11605                self.with_put_binding(&object, &name, value)?;
11606            }
11607
11608            // -- control flow -----------------------------------------------
11609            Goto | Goto8 | Goto16 => {
11610                self.frame_mut().pc = a as usize;
11611            }
11612            IfTrue | IfTrue8 => {
11613                let value = self.pop();
11614                if value.to_boolean() {
11615                    self.frame_mut().pc = a as usize;
11616                }
11617            }
11618            IfFalse | IfFalse8 => {
11619                let value = self.pop();
11620                if !value.to_boolean() {
11621                    self.frame_mut().pc = a as usize;
11622                }
11623            }
11624            Catch => {
11625                // Pushes the handler target onto the value stack; `unwind` finds it.
11626                self.push(Value::CatchOffset(a));
11627            }
11628            Gosub => {
11629                self.push(Value::ReturnAddress(next as u32));
11630                self.frame_mut().pc = a as usize;
11631            }
11632            Ret => {
11633                let value = self.pop();
11634                match value {
11635                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
11636                    _ => {
11637                        return Err(Signal::Throw(
11638                            self.make_error("InternalError", "invalid return address"),
11639                        ));
11640                    }
11641                }
11642            }
11643            NipCatch => {
11644                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
11645                // including the marker, keeping the top value.
11646                let top = self.pop();
11647                loop {
11648                    match self.pop() {
11649                        Value::CatchOffset(_) | Value::Undefined => break,
11650                        _ => {}
11651                    }
11652                    if self.frame().stack.is_empty() {
11653                        break;
11654                    }
11655                }
11656                self.push(top);
11657            }
11658            Throw => {
11659                let value = self.pop();
11660                return Err(Signal::Throw(value));
11661            }
11662            ThrowError => {
11663                let name = self.atom_text(a as usize);
11664                let (class, message) = match b {
11665                    0 => ("TypeError", format!("'{name}' is read-only")),
11666                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
11667                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
11668                    // `delete super.x` is a syntax-level mistake the reference reports
11669                    // with this wording, not a property-access failure.
11670                    3 => (
11671                        "ReferenceError",
11672                        "unsupported reference to 'super'".to_string(),
11673                    ),
11674                    4 => (
11675                        "TypeError",
11676                        "iterator does not have a throw method".to_string(),
11677                    ),
11678                    5 => (
11679                        "ReferenceError",
11680                        "invalid assignment left-hand side".to_string(),
11681                    ),
11682                    _ => ("TypeError", format!("invalid operation on '{name}'")),
11683                };
11684                return Err(Signal::Throw(self.make_error(class, &message)));
11685            }
11686            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
11687            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
11688            YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
11689            AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
11690            Await => return Ok(Step::Suspend(SuspendKind::Await)),
11691            ReturnAsync => {
11692                // The reference's `return_async` returns `undefined` and lets the resume
11693                // machinery pick the real value off `sp[-1]`, which is how it tells a
11694                // completion from a suspension. Carrying the value explicitly says the
11695                // same thing without the implicit stack slot.
11696                let value = self.pop();
11697                return Ok(Step::Return(value));
11698            }
11699            Return => {
11700                let value = self.pop();
11701                return Ok(Step::Return(value));
11702            }
11703            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
11704
11705            // -- calls ------------------------------------------------------
11706            Call | Call0 | Call1 | Call2 | Call3 => {
11707                let argc = self.argc_operand(op, a);
11708                let args = self.pop_n(argc);
11709                let callee = self.pop();
11710                // A plain call has no receiver; the callee decides what to do with
11711                // `undefined` (a sloppy function substitutes the global object).
11712                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
11713                    self.push(result);
11714                }
11715            }
11716            CallConstructor => {
11717                // `constructor this_obj args… -> object`. The duplicated
11718                // constructor is `new.target`; this milestone does not expose it,
11719                // so the extra copy is simply consumed here.
11720                let argc = a as usize;
11721                let args = self.pop_n(argc);
11722                let new_target = self.pop();
11723                let callee = self.pop();
11724                let result = self.construct(callee, new_target, args)?;
11725                self.push(result);
11726            }
11727            CallMethod => {
11728                let argc = a as usize;
11729                let args = self.pop_n(argc);
11730                let callee = self.pop();
11731                let this = self.pop();
11732                if let Some(result) = self.call_or_push(callee, this, args)? {
11733                    self.push(result);
11734                }
11735            }
11736            Apply => {
11737                // `func this array -> result`, the spread-call form: the compiler
11738                // builds one array of arguments, and all that is left here is to
11739                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
11740                let array = self.pop();
11741                let this = self.pop();
11742                let callee = self.pop();
11743                let args = self.array_like_to_args(&array)?;
11744                if a & 1 != 0 {
11745                    let result = self.construct(callee, this, args)?;
11746                    self.push(result);
11747                } else if let Some(result) = self.call_or_push(callee, this, args)? {
11748                    self.push(result);
11749                }
11750            }
11751            TailCall | TailCallMethod => {
11752                // `tail_call` is `call` whose result is returned immediately — the
11753                // reference jumps straight to `done` instead of storing the value and
11754                // running on. The callee still gets its own frame, so deep tail
11755                // recursion hits the stack limit exactly like plain recursion does;
11756                // marking this frame lets the return path unwind without needing
11757                // instructions after the call.
11758                let argc = if op == TailCallMethod {
11759                    a as usize
11760                } else {
11761                    self.argc_operand(op, a)
11762                };
11763                let args = self.pop_n(argc);
11764                let callee = self.pop();
11765                let this = if op == TailCallMethod {
11766                    self.pop()
11767                } else {
11768                    Value::Undefined
11769                };
11770                if let Value::Object(function) = &callee
11771                    && let Some((code, env)) = bytecode_of(function)
11772                {
11773                    // A generator or async body is not run here at all: calling it only
11774                    // *creates* the generator/coroutine, so it must not inherit this
11775                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
11776                    // onto `f`'s frame, and the first `yield`/`await` then reported
11777                    // "a generator body ran as an ordinary call".
11778                    if code.code.kind.is_generator() || code.code.kind.is_async() {
11779                        let value = self.call_value(callee, this, args)?;
11780                        return Ok(Step::Return(value));
11781                    }
11782                    self.frame_mut().tail = true;
11783                    self.push_frame(code, env, this, args, callee)?;
11784                    return Ok(Step::Continue);
11785                }
11786                // A native callee has no frame to reuse, so its value is simply
11787                // returned.
11788                let value = self.call_value(callee, this, args)?;
11789                return Ok(Step::Return(value));
11790            }
11791
11792            // -- objects ----------------------------------------------------
11793            SpecialObject => {
11794                let value = self.special_object(a)?;
11795                self.push(value);
11796            }
11797            PrivateSymbol => {
11798                // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
11799                // symbol each time it is evaluated, which is why the compiler evaluates it
11800                // once (at class definition) and stores it in a class-scope binding.
11801                let name = self.atom_text(a as usize);
11802                let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
11803                self.push(Value::Symbol(symbol));
11804            }
11805            GetPrivateField => {
11806                // `obj symbol -> value`. A missing private field is a TypeError, which is what
11807                // makes `#x` inaccessible on any object not built by this class.
11808                let symbol = self.pop();
11809                let object = self.pop();
11810                let value = self.read_private_field(&object, &symbol)?;
11811                self.push(value);
11812            }
11813            PutPrivateField => {
11814                // `obj value symbol ->`, and the store is a plain assignment to a property the
11815                // class already created, so there is no setter to consult.
11816                let symbol = self.pop();
11817                let value = self.pop();
11818                let object = self.pop();
11819                self.write_private_field(&object, &symbol, value)?;
11820            }
11821            DefinePrivateField => {
11822                // `obj symbol value -> obj`: a field initialiser creates the property, and
11823                // redefining one is a TypeError ("already exists").
11824                let value = self.pop();
11825                let symbol = self.pop();
11826                let object = self.pop();
11827                self.define_private_field(&object, &symbol, value)?;
11828                self.push(object);
11829            }
11830            PrivateIn => {
11831                // `obj key -> bool`: `#x in o`. The second operand decides which question is
11832                // being asked, which is the reference's `js_operator_private_in`: a *symbol*
11833                // is a field, so this is an own-property test; a *function* is a method or
11834                // accessor, so this is a brand check.
11835                let key = self.pop();
11836                let object = self.pop();
11837                let Some(target) = object.as_object() else {
11838                    return Err(Signal::Throw(
11839                        self.make_error("TypeError", "invalid 'in' operand"),
11840                    ));
11841                };
11842                let present = match &key {
11843                    Value::Object(_) => self.check_brand(target, &key)?,
11844                    _ => target.own_property_key(&self.private_key(&key)?).is_some(),
11845                };
11846                self.push(Value::Bool(present));
11847            }
11848            AddBrand => {
11849                // `obj home ->`: create the class brand on `home` if it has none, then give
11850                // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
11851                // class definition: only the prototype's copy of the symbol is wanted.
11852                let home = self.pop();
11853                let object = self.pop();
11854                self.add_brand(&object, &home)?;
11855            }
11856            CheckBrand => {
11857                // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
11858                // Both stay, because the caller needs them — `nip` halves a read into its
11859                // value and `call_method` uses the pair as receiver and callee.
11860                let function = self.peek(0);
11861                let object = self.peek(1);
11862                let Some(target) = object.as_object() else {
11863                    return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11864                };
11865                if !self.check_brand(target, &function)? {
11866                    return Err(Signal::Throw(
11867                        self.make_error("TypeError", "invalid brand on object"),
11868                    ));
11869                }
11870            }
11871            GetLength => {
11872                // `get_length` is the `.length` read; an array and a string answer
11873                // from their own length, anything else from the property.
11874                let target = self.pop();
11875                let value = match &target {
11876                    Value::Object(object) => match object.array_length() {
11877                        Some(length) => crate::object::length_value(length),
11878                        None => self.read_field(&target, "length")?,
11879                    },
11880                    Value::String(text) => Value::Int(text.utf16_len() as i32),
11881                    _ => self.read_field(&target, "length")?,
11882                };
11883                self.push(value);
11884            }
11885            GetField | GetField2 => {
11886                let object = self.pop();
11887                // Borrowed out of the code object, not cloned: `atom_key` returns an owned
11888                // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
11889                // just below is what lets the borrow outlive the `&mut self` the lookup
11890                // needs — one refcount bump instead of a key clone plus its drop, on the
11891                // hottest property path there is: every `o.x` and every `o.m()` receiver.
11892                let code = self.frame().code.clone();
11893                let key = &code.atom_keys[a as usize];
11894                let value = self.read_field_cached(&object, key, next)?;
11895                if op == GetField2 {
11896                    self.push(object);
11897                }
11898                self.push(value);
11899            }
11900            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
11901                let key = self.pop();
11902                let object = self.pop();
11903                // §7.1.1 `GetValue` step 3 orders these two conversions: `ToObject(V.[[Base]])`
11904                // first, then `ToPropertyKey(V.[[ReferencedName]])`. So a nullish base is a
11905                // `TypeError` and the key is **never coerced** — `null[{toString(){throw}}]`
11906                // throws the TypeError, not the key's exception
11907                // (`S11.3.1_A6_T1`). A write has the opposite order, which is why
11908                // `PutArrayEl` deliberately does not do this.
11909                //
11910                // Only nullish is checked here, and the full boxing is still left to
11911                // `read_field_key`: a string base has an index fast path that turning it
11912                // into a `String` object up front would throw away.
11913                if object.is_nullish() {
11914                    return Err(Signal::Throw(self.make_error(
11915                        "TypeError",
11916                        &format!("cannot read property of {}", object.to_js_string()),
11917                    )));
11918                }
11919                let key = self.propkey(&key)?;
11920                let value = self.read_field_key(&object, &key)?;
11921                if matches!(op, GetArrayEl2 | GetArrayEl3) {
11922                    self.push(object);
11923                }
11924                if op == GetArrayEl3 {
11925                    // The key goes back in its *value* form, which the compiler stores
11926                    // into the target of a destructuring assignment.
11927                    self.push(match &key {
11928                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11929                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
11930                    });
11931                }
11932                self.push(value);
11933            }
11934            PutField => {
11935                let value = self.pop();
11936                let object = self.pop();
11937                // Borrowed, like the `get_field` arm: `atom_key` would return an owned
11938                // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
11939                // only reads. `this.value = …` is the write half of the hottest loop in
11940                // `property:method-call`, and `own_property_key` was 4.8% of the case.
11941                let code = self.frame().code.clone();
11942                let key = &code.atom_keys[a as usize];
11943                self.write_field_key(&object, key, value)?;
11944            }
11945            PutArrayEl => {
11946                let value = self.pop();
11947                let key = self.pop();
11948                let object = self.pop();
11949                let key = self.propkey(&key)?;
11950                self.write_field_key(&object, &key, value)?;
11951            }
11952            DefineField => {
11953                let value = self.pop();
11954                let object = self.pop();
11955                // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
11956                // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
11957                // three U+FFFD — a property under a different name from the one
11958                // `o["\uD800"]` reads.
11959                let code = self.frame().code.clone();
11960                let key = code.atom_keys[a as usize].clone();
11961                // No naming here. `{m: function(){}}` is named by the *compiler*, which
11962                // emits `set_name` — and only where `NamedEvaluation` applies, so
11963                // `{m: (0, function(){})}` stays anonymous. Naming every function that
11964                // reaches a property definition got that case wrong, and the compiler is
11965                // the only place that can tell the two apart.
11966                self.define_field(&object, &key, value)?;
11967                self.push(object);
11968            }
11969            DefineArrayEl => {
11970                // `obj key value -> obj key`. The *value* form of the key is what goes
11971                // back on the stack — the compiler stores it into the pattern's binding —
11972                // so the symbol is not stringified on the way through.
11973                //
11974                // `define_field` and not `write_field_key`: this is `CreateDataProperty`,
11975                // and only the define algorithm gives `{ ['__proto__']: v }` an ordinary
11976                // own property. Going through `[[Set]]` found `Object.prototype`'s
11977                // `__proto__` accessor on the prototype chain and *changed the prototype*
11978                // instead, and it would have called a user setter from a literal
11979                // (`computed-__proto__`, `__proto__-duplicate-computed`).
11980                let value = self.pop();
11981                let key_value = self.pop();
11982                let object = self.peek(0);
11983                let key = self.propkey(&key_value)?;
11984                self.define_field(&object, &key, value)?;
11985                self.push(key_value);
11986            }
11987            SetHomeObject => {
11988                // `obj func -> obj func`: records the object a method was defined on so
11989                // `super` inside it resolves against that object's prototype.
11990                let function = self.peek(0);
11991                let home = self.peek(1);
11992                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
11993                    function.set_home_object(Some(home.clone()));
11994                }
11995            }
11996            Regexp => {
11997                // `pattern flags -> regexp`. A literal compiles here rather than through the
11998                // constructor, which is both what the reference's dedicated opcode is for
11999                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
12000                let flags = self.pop();
12001                let pattern = self.pop();
12002                let pattern = self.checked_to_wtf8(&pattern)?;
12003                let flags = self.to_js_string(&flags)?;
12004                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
12005                self.push(Value::Object(object));
12006            }
12007            UsingDisposeInit => {
12008                // The error state a disposal accumulates into. Uninitialised means "no
12009                // failure yet"; anything else is the exception being propagated.
12010                self.push(Value::Uninitialized);
12011            }
12012            UsingCheck => {
12013                // `value -> value, method`: validate and snapshot the disposer now, so a
12014                // later change to `Symbol.dispose` cannot change what gets called, and so a
12015                // value that is not disposable fails before the body runs.
12016                let value = self.pop();
12017                let method = self.using_method_for(&value, a as u8 == 1)?;
12018                self.push(value);
12019                self.push(method);
12020            }
12021            UsingDispose => {
12022                // `error_state -> error_state'`: dispose the variable at `slot` — its value
12023                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
12024                // the pending error.
12025                let slot = self.slot_operand(op, a);
12026                let error_state = self.pop();
12027                let merged = self.using_dispose_once(slot, error_state)?;
12028                self.push(merged);
12029            }
12030            UsingDisposeMerge => {
12031                let new_error = self.pop();
12032                let error_state = self.pop();
12033                let merged = self.merge_dispose_error(new_error, error_state);
12034                self.push(merged);
12035            }
12036            UsingDisposeEnd => {
12037                // A disposal that failed replaces the block's normal completion, so the
12038                // error state becomes a real throw here rather than at the call site.
12039                let error_state = self.pop();
12040                if !matches!(error_state, Value::Uninitialized) {
12041                    return Err(Signal::Throw(error_state));
12042                }
12043            }
12044            UsingDisposeAsync => {
12045                // `error_state -> error_state, promise`: the disposer is called here and
12046                // its result wrapped, so the `await` the compiler emits next is what
12047                // actually waits. Calling it and dropping the result lost every failure
12048                // from an `async [Symbol.asyncDispose]` — the rejection had no handler and
12049                // no path back into the error state
12050                // (`throws-error-as-is-if-only-one-error-during-disposal`).
12051                let slot = self.slot_operand(op, a);
12052                let error_state = self.pop();
12053                let value = self.get_loc(slot);
12054                let method = self.get_loc(slot + 1);
12055                let promise = if value.is_nullish()
12056                    || matches!(value, Value::Uninitialized)
12057                    || matches!(method, Value::Undefined | Value::Uninitialized)
12058                {
12059                    // Nothing to dispose: `await undefined` is a no-op, as it is in the
12060                    // reference (`sp[0] = JS_UNDEFINED`).
12061                    Value::Undefined
12062                } else {
12063                    let result = self.call_value(method, value, Vec::new())?;
12064                    self.promise_resolve_value(result)?
12065                };
12066                self.push(error_state);
12067                self.push(promise);
12068            }
12069            GetSuper => {
12070                // `obj -> obj's prototype`: the starting point of a `super` lookup.
12071                let object = self.pop();
12072                let proto = match &object {
12073                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
12074                    _ => Value::Null,
12075                };
12076                self.push(proto);
12077            }
12078            GetSuperValue => {
12079                // `receiver proto key -> value`, searching from `proto` but reporting to
12080                // `receiver`, which is what `super.g` must do for a getter to see `this`.
12081                //
12082                // Three values in, one out: the receiver is *consumed*, not left under the
12083                // result. Leaving it there was invisible for `super.x` in `return` or
12084                // statement position (the result is what gets popped) and corrupted the
12085                // frame everywhere else — `print(super.x)` left the class where the call
12086                // opcode looks for the receiver and called the class itself.
12087                let key = self.pop();
12088                let proto = self.pop();
12089                let receiver = self.pop();
12090                let value = self.super_read(&receiver, &proto, &key)?;
12091                self.push(value);
12092            }
12093            PutSuperValue => {
12094                // `receiver proto key value ->`: a store that starts at `proto` but
12095                // assigns to `receiver`.
12096                let value = self.pop();
12097                let key = self.pop();
12098                let proto = self.pop();
12099                let receiver = self.pop();
12100                self.super_write(&receiver, &proto, &key, value)?;
12101            }
12102            DefineClass => {
12103                // `parent ctor -> ctor proto`: the constructor becomes the class and a
12104                // fresh prototype object lands on top for the methods to go on.
12105                let name = self.atom_text(a as usize);
12106                let (ctor, proto) = self.define_class(&name, b)?;
12107                self.push(ctor);
12108                self.push(Value::Object(proto));
12109            }
12110            DefineClassComputed => {
12111                // `parent ctor key -> ctor proto key`: the computed name stays put so
12112                // `define_field`-style consumers can still read it.
12113                let key = self.pop();
12114                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
12115                let (ctor, proto) = self.define_class(&name, b)?;
12116                self.push(ctor);
12117                self.push(Value::Object(proto));
12118                self.push(key);
12119            }
12120            DefineMethod => {
12121                let function = self.pop();
12122                let object = self.pop();
12123                // The exact key, like `define_field`: a quoted method key may hold an
12124                // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
12125                // that `o["\uD800"]` finds.
12126                let code = self.frame().code.clone();
12127                let key = code.atom_keys[a as usize].clone();
12128                // A method's `[[HomeObject]]` is the object it was defined on, which is
12129                // what `super` inside it resolves against.
12130                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12131                    function.set_home_object(Some(object.clone()));
12132                }
12133                let name = match key.as_wtf8() {
12134                    Some(text) => text.clone(),
12135                    // A symbol atom — one of the well-known symbols, which the lexer keeps
12136                    // as an atom rather than a runtime value. Its name is the bracketed
12137                    // description, like any other symbol key.
12138                    None => symbol_key_name(&key),
12139                };
12140                self.set_function_name_wtf8(&function, &accessor_prefixed(&name, b));
12141                if let Some(array) = object.as_object()
12142                    && !define_function_property(array, &key, function, b)
12143                {
12144                    return Err(self.type_error("property is not configurable"));
12145                }
12146                self.push(object);
12147            }
12148            DefineMethodComputed => {
12149                let function = self.pop();
12150                let key = self.pop();
12151                let object = self.pop();
12152                let key = self.propkey(&key)?;
12153                // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
12154                // the name: `super` inside a computed method resolves through it. Without
12155                // this, `class B extends A { [k]() { return super.m() } }` read the
12156                // home object as null and threw.
12157                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12158                    function.set_home_object(Some(object.clone()));
12159                }
12160                // A symbol key names the method `[description]`, or `""` without one —
12161                // §7.3.24, the same rule [`Interp::function_name_from_key`] applies to
12162                // `set_name_computed`. Falling back to `to_string` here named every
12163                // `{ [sym](){} }` method `Symbol()` instead.
12164                match &key {
12165                    PropertyKey::Symbol(_) => {
12166                        // The accessor prefix still applies: `get [Symbol.iterator](){}`
12167                        // is named `"get [Symbol.iterator]"`.
12168                        let name = accessor_prefixed(&symbol_key_name(&key), a);
12169                        self.set_function_name_wtf8(&function, &name);
12170                    }
12171                    PropertyKey::String(text) => {
12172                        let name = accessor_prefixed(text, a);
12173                        self.set_function_name_wtf8(&function, &name);
12174                    }
12175                }
12176                if let Some(array) = object.as_object()
12177                    && !define_function_property(array, &key, function, a)
12178                {
12179                    return Err(self.type_error("property is not configurable"));
12180                }
12181                self.push(object);
12182            }
12183            SetProto => {
12184                // `{ __proto__: v }` — §13.2.5.1 step 6: nothing is defined and nothing is
12185                // changed unless `v` is an object or `null`. A primitive was taken as "no
12186                // prototype" instead, so `{ __proto__: undefined }` came out with `null`
12187                // where the answer is an ordinary object
12188                // (`__proto__-value-non-object`).
12189                let proto = self.pop();
12190                let object = self.pop();
12191                if matches!(proto, Value::Null | Value::Object(_))
12192                    && let Some(target) = object.as_object()
12193                {
12194                    target.set_proto(proto.as_object().cloned());
12195                }
12196                self.push(object);
12197            }
12198            CopyDataProperties => {
12199                let exclusion = self.pop();
12200                let source = self.pop();
12201                let target = self.peek(0);
12202                self.copy_properties(&target, &source, &exclusion)?;
12203                self.push(source);
12204                self.push(exclusion);
12205            }
12206            ToPropkey => {
12207                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
12208                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
12209                // ordinary `"Symbol(b)"` property.
12210                let value = self.pop();
12211                let key = match self.propkey(&value)? {
12212                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
12213                    PropertyKey::String(text) => self.string_wtf8(text),
12214                };
12215                self.push(key);
12216            }
12217            SetName => {
12218                let function = self.peek(0);
12219                let name = self.atom_wtf8(a as usize);
12220                self.set_function_name_wtf8(&function, &name);
12221            }
12222            SetNameComputed => {
12223                let key = self.peek(1);
12224                let function = self.peek(0);
12225                let name = self.function_name_from_key(&key)?;
12226                self.set_function_name_wtf8(&function, &name);
12227            }
12228
12229            // -- arrays -----------------------------------------------------
12230            ArrayFrom => {
12231                let count = a as usize;
12232                let elements = self.pop_n(count);
12233                let array = self.new_array(elements);
12234                self.push(Value::Object(array));
12235            }
12236            Append => {
12237                // `array index iterable -> array new_index`
12238                let iterable = self.pop();
12239                self.pop();
12240                let array = self.peek(0);
12241                let added = self.append_enumerate(&array, &iterable)?;
12242                self.push(Value::Int(added));
12243            }
12244
12245            // -- iteration --------------------------------------------------
12246            ForInStart => {
12247                let value = self.pop();
12248                let record = self.for_in_record(&value)?;
12249                self.push(Value::Object(record));
12250            }
12251            ForInNext => {
12252                // `record -> record key done`. The flag is *done*, not "found":
12253                // the compiler tests it with `if_false` to jump back into the body,
12254                // so reporting `true` while keys remain would end the loop at once.
12255                let record = self.peek(0);
12256                match self.for_in_advance(&record)? {
12257                    Some(key) => {
12258                        let text = self.string(key);
12259                        self.push(text);
12260                        self.push(Value::Bool(false));
12261                    }
12262                    None => {
12263                        self.push(Value::Undefined);
12264                        self.push(Value::Bool(true));
12265                    }
12266                }
12267            }
12268            ForOfStart => {
12269                let value = self.pop();
12270                let iterator = self.get_iterator(&value)?;
12271                self.push(iterator.object);
12272                self.push(iterator.next);
12273                self.push(Value::CatchOffset(0));
12274            }
12275            ForOfNext => {
12276                // `iter next catch_offset -> iter next catch_offset value done`.
12277                //
12278                // The operand is how many values sit *above* the iterator triple: a
12279                // destructuring rest element keeps its target array and running index
12280                // there while draining the iterator, so the triple is not at the top.
12281                let extra = a as usize;
12282                let iterator_slot = 2 + extra;
12283                // An exhausted iterator is replaced by `undefined` (see below), so a
12284                // second step must not call `next` again — `Array.from` and a
12285                // destructuring pattern both keep stepping past the end.
12286                let stepped = if matches!(self.peek(iterator_slot), Value::Undefined) {
12287                    Ok((Value::Undefined, true))
12288                } else {
12289                    let iterator = Iterator {
12290                        object: self.peek(iterator_slot),
12291                        next: self.peek(1 + extra),
12292                    };
12293                    self.iterator_step(&iterator)
12294                };
12295                let (value, done) = match stepped {
12296                    Ok(stepped) => stepped,
12297                    Err(signal) => {
12298                        // An exception from `next()` is not an abrupt completion of the
12299                        // *body*, so §7.4.6 does not apply and the iterator must not be
12300                        // closed: `[ , ] = iterable` with a throwing `next` expects
12301                        // `returnCount === 0`. Clearing the slot is how the reference says
12302                        // so (`js_for_of_next`: `sp[offset] = JS_UNDEFINED` before it
12303                        // returns -1), and it is also what makes the destructor below — the
12304                        // exception path's `catch_offset 0` close — a no-op here.
12305                        self.clear_iterator_slot(iterator_slot);
12306                        return Err(signal);
12307                    }
12308                };
12309                if done {
12310                    // The result's `value` is meaningless once the iterator is done:
12311                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
12312                    // rather than binding the generator's return value.
12313                    let top = self.frame().stack.len() - 1 - iterator_slot;
12314                    self.frame_mut().stack[top] = Value::Undefined;
12315                    self.push(Value::Undefined);
12316                    self.push(Value::Bool(true));
12317                } else {
12318                    self.push(value);
12319                    self.push(Value::Bool(false));
12320                }
12321            }
12322            IteratorNext => {
12323                // `iter next catch val -> iter next catch val'`: replace the argument with
12324                // the result of `next(val)`. The triple below stays put, which is why the
12325                // three instructions of the `yield*` loop all address the stack the same way.
12326                let value = self.pop();
12327                let object = self.peek(2);
12328                let next = self.peek(1);
12329                let result = self.call_value(next, object, vec![value])?;
12330                self.push(result);
12331            }
12332            IteratorCall => {
12333                // `iter next catch val -> iter next catch val' flag`.
12334                //
12335                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
12336                // The flag is `true` when the method was missing, which is how the
12337                // caller learns that the inner iterator cannot take part in the
12338                // unwinding.
12339                let value = self.pop();
12340                let object = self.peek(2);
12341                let key = if a & 1 != 0 { "throw" } else { "return" };
12342                let method = self.read_field(&object, key)?;
12343                if matches!(method, Value::Undefined | Value::Null) {
12344                    self.push(value);
12345                    self.push(Value::Bool(true));
12346                } else {
12347                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
12348                    let result = self.call_value(method, object, argument)?;
12349                    self.push(result);
12350                    self.push(Value::Bool(false));
12351                }
12352            }
12353            IteratorCheckObject => {
12354                if !matches!(self.peek(0), Value::Object(_)) {
12355                    return Err(Signal::Throw(
12356                        self.make_error("TypeError", "iterator must return an object"),
12357                    ));
12358                }
12359            }
12360            IteratorClose => {
12361                // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
12362                // calling the iterator's `return` so it can release whatever it holds.
12363                //
12364                // The catch offset goes first, so an exception from `return` is not caught
12365                // by the loop being abandoned. This used to pop the three operands and call
12366                // nothing at all, which made `break` out of a `for of` invisible to an
12367                // iterator with a `return` method.
12368                self.pop();
12369                self.pop();
12370                let iterator = self.pop();
12371                if !matches!(iterator, Value::Undefined) {
12372                    let method = self.read_field(&iterator, "return")?;
12373                    if !matches!(method, Value::Undefined | Value::Null) {
12374                        let result = self.call_value(method, iterator.clone(), Vec::new())?;
12375                        // §7.4.6: a `return` that answers a non-object is a TypeError.
12376                        if !matches!(result, Value::Object(_)) {
12377                            return Err(Signal::Throw(
12378                                self.make_error("TypeError", "iterator must return an object"),
12379                            ));
12380                        }
12381                    }
12382                }
12383            }
12384            Import => {
12385                // `import(specifier, options)`: the options slot is on top. Both are
12386                // `GetValue`-ed by the compiler, which is why this pops values rather than
12387                // references — and why the validation of `options` (§13.3.10.1 step 10)
12388                // happens inside `dynamic_import`, where its failures can be turned into a
12389                // rejection instead of a throw.
12390                let options = self.pop();
12391                let specifier = self.pop();
12392                let promise = self.dynamic_import(specifier, options)?;
12393                self.push(promise);
12394            }
12395            ForAwaitOfStart => {
12396                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
12397                // `Symbol.iterator` fallback.
12398                let value = self.pop();
12399                let iterator = self.get_async_iterator(&value)?;
12400                self.push(iterator.object);
12401                self.push(iterator.next);
12402                self.push(Value::CatchOffset(0));
12403            }
12404            ForAwaitOfNext => {
12405                // `for await` steps the iterator and leaves the *result* wrapped in a
12406                // promise, so the `await` the compiler emits right after this can suspend
12407                // on it. Unwrapping happens in `iterator_get_value_done`.
12408                let extra = a as usize;
12409                let iterator_slot = 2 + extra;
12410                // The enumerator marker is **disabled for the step**, and
12411                // `iterator_get_value_done` puts it back once the result has survived the
12412                // awaiting. Both halves are load-bearing for the async case:
12413                //
12414                // * a rejection is not "the body threw", so the loop must not close the
12415                //   iterator *again* — the wrapper already did;
12416                // * but until the result arrives the record is live, so a later failure
12417                //   still has to close it.
12418                //
12419                // The reference says the same in one line each
12420                // (`js_for_await_of_next`: `sp[-1] = JS_UNDEFINED; /* disable the catch
12421                // offset so that exceptions do not close the iterator */`).
12422                self.clear_iterator_slot(extra);
12423                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
12424                    Value::Undefined
12425                } else {
12426                    let iterator = Iterator {
12427                        object: self.peek(iterator_slot),
12428                        next: self.peek(1 + extra),
12429                    };
12430                    let next = iterator.next.clone();
12431                    self.call_value(next, iterator.object, Vec::new())?
12432                };
12433                let promise = self.promise_resolve_value(result)?;
12434                self.push(promise);
12435            }
12436            IteratorGetValueDone => {
12437                // `result -> value done`. A missing result object means the iterator was
12438                // already exhausted, which the loop treats as `done`.
12439                let result = self.pop();
12440                // Re-arm the marker `for_await_of_next` disabled; the step got this far, so
12441                // from here on the record is closeable again.
12442                {
12443                    let depth = self.frame().stack.len();
12444                    if depth >= 2 {
12445                        self.frame_mut().stack[depth - 1] = Value::CatchOffset(0);
12446                    }
12447                }
12448                let done = match &result {
12449                    Value::Object(object) => self
12450                        .get_property(object, "done")?
12451                        .is_some_and(|value| value.to_boolean()),
12452                    _ => true,
12453                };
12454                if done {
12455                    // Clear the iterator object so the `iterator_close` the loop emits on
12456                    // its way out has nothing to close: `AsyncIteratorClose` must *not* run
12457                    // on normal completion, and this is where a normal completion is
12458                    // recognised — the same trick `for_of_next` uses, which also replaces
12459                    // the slot with `undefined`.
12460                    //
12461                    // The layout is fixed because only `for await` emits this opcode:
12462                    // `iter next catch [result]`, so the iterator is three below the top.
12463                    let depth = self.frame().stack.len();
12464                    if depth >= 3 {
12465                        self.frame_mut().stack[depth - 3] = Value::Undefined;
12466                    }
12467                    self.push(Value::Undefined);
12468                    self.push(Value::Bool(true));
12469                } else {
12470                    let Value::Object(object) = &result else {
12471                        self.push(Value::Undefined);
12472                        self.push(Value::Bool(true));
12473                        return Ok(Step::Continue);
12474                    };
12475                    let value = self
12476                        .get_property(object, "value")?
12477                        .unwrap_or(Value::Undefined);
12478                    self.push(value);
12479                    self.push(Value::Bool(false));
12480                }
12481            }
12482
12483            Delete => {
12484                // `delete obj[key]`, where the key was just pushed. Deleting an array
12485                // index leaves a *hole* rather than closing the gap, and a
12486                // non-configurable property answers `false` and stays.
12487                let key = self.pop();
12488                let target = self.pop();
12489                let key = self.propkey(&key)?;
12490                let text_label = key.as_str().unwrap_or("").to_string();
12491                let deleted = match &target {
12492                    Value::Object(object) => {
12493                        let object = object.clone();
12494                        self.delete_property_key(&object, &key)?
12495                    }
12496                    // A string's `length` and its index properties are
12497                    // non-configurable, so deleting one answers `false`.
12498                    Value::String(text) => {
12499                        !(text_label == "length"
12500                            || array_index(&text_label)
12501                                .is_some_and(|index| (index as usize) < text.utf16_len()))
12502                    }
12503                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
12504                    // object to delete from, and only a *boxable* primitive has one.
12505                    Value::Undefined | Value::Null => {
12506                        return Err(Signal::Throw(
12507                            self.make_error("TypeError", "cannot convert to object"),
12508                        ));
12509                    }
12510                    // Any other primitive has no own properties; deleting nothing
12511                    // succeeds.
12512                    _ => true,
12513                };
12514                // §13.5.1.2: in strict mode a `delete` that answers `false` is a
12515                // `TypeError` rather than a `false` result. Sloppy mode silently reports
12516                // the refusal, which is why the same statement throws here but not there.
12517                if !deleted && self.current_strict() {
12518                    return Err(Signal::Throw(
12519                        self.make_error("TypeError", "cannot delete property"),
12520                    ));
12521                }
12522                self.push(Value::Bool(deleted));
12523            }
12524
12525            // -- exceptions and bookkeeping ---------------------------------
12526            Fclosure | Fclosure8 => {
12527                let value = self.closure(a as usize)?;
12528                self.push(value);
12529            }
12530
12531            other => {
12532                let name = other.info().name;
12533                return Err(Signal::Throw(self.make_error(
12534                    "InternalError",
12535                    &format!("{name} is not implemented yet"),
12536                )));
12537            }
12538        }
12539        Ok(Step::Continue)
12540    }
12541
12542    // -- operand helpers ----------------------------------------------------
12543
12544    /// The slot index an operand names, taking short forms into account.
12545    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
12546        use Opcode::*;
12547        match op {
12548            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
12549            | SetVarRef0 => 0,
12550            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
12551            | SetVarRef1 => 1,
12552            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
12553            | SetVarRef2 => 2,
12554            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
12555            | SetVarRef3 => 3,
12556            _ => a as usize,
12557        }
12558    }
12559
12560    /// The argument count of a call, taking `call0`…`call3` into account.
12561    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
12562        use Opcode::*;
12563        match op {
12564            Call0 => 0,
12565            Call1 => 1,
12566            Call2 => 2,
12567            Call3 => 3,
12568            _ => a as usize,
12569        }
12570    }
12571
12572    /// The atom's name as a property key.
12573    ///
12574    /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
12575    /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
12576    /// `String::clone` was a heap allocation and a copy — per property access.
12577    /// The atom at `index`, as a property key.
12578    ///
12579    /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
12580    /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
12581    /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
12582    /// 5.3% of `property:monomorphic`.
12583    /// The atom's text, exactly — including an unpaired surrogate.
12584    ///
12585    /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
12586    /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
12587    /// `atom_text` below is for the other kind of use, where the atom is a key in the
12588    /// engine's own tables.
12589    fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
12590        self.frame()
12591            .code
12592            .code
12593            .atoms
12594            .get(index)
12595            .map(|atom| match atom {
12596                Atom::Str(text) => text.clone(),
12597                Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
12598                // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
12599                Atom::Null => crate::value::Wtf8::new(String::new()),
12600            })
12601            .unwrap_or_default()
12602    }
12603
12604    fn atom_text(&self, index: usize) -> String {
12605        self.frame()
12606            .code
12607            .code
12608            .atoms
12609            .get(index)
12610            .map(|atom| match atom {
12611                // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
12612                // compare it to an identifier, and a surrogate-bearing name is reachable
12613                // through `atom_wtf8` where it matters.
12614                Atom::Str(text) => text.to_string_lossy().into_owned(),
12615                Atom::Index(value) => value.to_string(),
12616                // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
12617                // `throw_error`, `delete super.x`) never read it.
12618                Atom::Null => String::new(),
12619            })
12620            .unwrap_or_default()
12621    }
12622
12623    fn constant(&mut self, index: usize) -> JsResult<Value> {
12624        let constant = self.frame().code.code.cpool.get(index).cloned();
12625        Ok(match &constant {
12626            Some(Constant::Number(number)) => Value::Float(*number),
12627            Some(Constant::String(text)) => self.string_wtf8(text.clone()),
12628            Some(Constant::BigInt { digits, radix }) => {
12629                match crate::bigint::BigInt::from_radix(digits, *radix) {
12630                    Some(big) => self.bigint(big),
12631                    // A literal the parser accepted is always parseable; a failure here
12632                    // would be a compiler bug, so it reads as an `InternalError`.
12633                    None => {
12634                        return Err(Signal::Throw(
12635                            self.make_error("InternalError", "unparseable bigint literal"),
12636                        ));
12637                    }
12638                }
12639            }
12640            Some(Constant::Function(_)) => {
12641                return Err(Signal::Throw(
12642                    self.make_error("InternalError", "a bare function constant"),
12643                ));
12644            }
12645            // A tagged template's call site: a frozen array of the cooked chunks with a
12646            // frozen `raw` array beside it, which is what `String.raw` reads back.
12647            //
12648            // §13.2.8.1 caches it on the realm: `runTemplate()` called twice must hand the
12649            // tag the *same* object, and only a registry gives that. The site is
12650            // (code object, constant index) — see [`Realm::template_map`].
12651            Some(Constant::Template { site, cooked, raw }) => {
12652                // Weakly held, and reaped when the map gets crowded: a program that calls
12653                // `eval` with a tagged template in a loop compiles a fresh site each time,
12654                // and keeping a strong handle would grow this map without bound. Losing an
12655                // expired entry costs nothing — nothing is using the object it named.
12656                if let Some(cached) = self
12657                    .realm
12658                    .template_map
12659                    .get(site)
12660                    .and_then(|weak| weak.upgrade())
12661                {
12662                    return Ok(Value::Object(cached));
12663                }
12664                let cooked_values: Vec<Value> = cooked
12665                    .iter()
12666                    .map(|chunk| match chunk {
12667                        Some(text) => self.string_wtf8(text.clone()),
12668                        None => Value::Undefined,
12669                    })
12670                    .collect();
12671                let raw_values: Vec<Value> =
12672                    raw.iter().map(|text| self.string(text.clone())).collect();
12673                let raw_array = self.new_array(raw_values);
12674                let template = self.new_array(cooked_values);
12675                template.define(
12676                    "raw",
12677                    Property::with_attributes(Value::Object(raw_array.clone()), false, false),
12678                );
12679                // `SetIntegrityLevel(…, frozen)`, not just a refusal of new properties: the
12680                // template object's indices have to be non-writable and non-configurable, and
12681                // so does `length`. `set_extensible(false)` alone left every index writable,
12682                // which is what `template-object` checks with `verifyProperty`.
12683                // An array of template strings cannot be a proxy, so neither call can be
12684                // refused — `freeze_object` is `?` rather than best-effort on purpose.
12685                crate::builtins::object::freeze_object(self, &raw_array)?;
12686                crate::builtins::object::freeze_object(self, &template)?;
12687                if self.realm.template_map.len() > 256 {
12688                    self.realm
12689                        .template_map
12690                        .retain(|_, weak| weak.upgrade().is_some());
12691                }
12692                self.realm.template_map.insert(*site, template.downgrade());
12693                Value::Object(template)
12694            }
12695            _ => Value::Undefined,
12696        })
12697    }
12698
12699    /// The reference cell a closure-variable slot names.
12700    ///
12701    /// Two kinds of binding share this addressing: a genuine closure variable
12702    /// (captured from an enclosing function) lives in this frame's environment,
12703    /// while a *declared global* lives in the realm so that a script, a function
12704    /// declaration and their uses all see one binding. A plain `Global` — an
12705    /// undeclared name that may be satisfied by the global object — has no cell at
12706    /// all, which is how `typeof x` still works for a name that does not exist.
12707    /// The reference cell a closure-variable slot names.
12708    ///
12709    /// The environment is resolved once, when the closure is built, and this is
12710    /// just the lookup afterwards. A *declared global* is in there too, pointing at
12711    /// the realm's cell, so a script, a hoisted function declaration and their uses
12712    /// all share one binding. A plain `Global` — a name the script never declared —
12713    /// is read and written through `get_var`/`put_var` by name instead, which is
12714    /// what lets the global object satisfy it.
12715    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
12716        self.frame().env.cells.get(slot).cloned()
12717    }
12718
12719    /// Whether `slot` refers to a global binding through the reference table.
12720    ///
12721    /// A global's cell in the closure environment only exists so the slot has
12722    /// something to point at; the binding itself lives on the global object (a `var`)
12723    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
12724    /// be routed, not performed on the placeholder.
12725    fn is_global_slot(&self, slot: usize) -> bool {
12726        self.frame()
12727            .code
12728            .code
12729            .closure_vars
12730            .get(slot)
12731            .is_some_and(|c| {
12732                // A module's declarations and imports are *not* globals: their cells are
12733                // the module environment's, filled by the host, so the placeholder routing
12734                // must not apply to them.
12735                matches!(
12736                    c.closure_type,
12737                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
12738                )
12739            })
12740    }
12741
12742    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
12743        if self.is_global_slot(slot) {
12744            return self.get_global(slot);
12745        }
12746        Ok(self
12747            .var_ref_cell(slot)
12748            .map(|cell| cell.get())
12749            .unwrap_or(Value::Undefined))
12750    }
12751
12752    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
12753        // A function declaration is hoisted by storing into a global reference before
12754        // the body runs, so this path is also what puts it on the global object.
12755        if self.is_global_slot(slot) {
12756            return self.put_global(slot, value);
12757        }
12758        if let Some(cell) = self.var_ref_cell(slot) {
12759            cell.set(value);
12760        }
12761        Ok(())
12762    }
12763
12764    // -- closures -----------------------------------------------------------
12765
12766    /// Build the closure for the function constant `index`.
12767    ///
12768    /// Every entry in the child's closure table names where its binding lives in
12769    /// *this* frame: a local or argument slot that was marked captured, or a cell
12770    /// this frame is itself holding. That is how a variable three functions deep
12771    /// stays one binding.
12772    fn closure(&mut self, index: usize) -> JsResult<Value> {
12773        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
12774        else {
12775            return Err(Signal::Throw(
12776                self.make_error("InternalError", "fclosure of a non-function"),
12777            ));
12778        };
12779        let mut cells = Vec::with_capacity(function.closure_vars.len());
12780        for closure_var in &function.closure_vars {
12781            let cell = match closure_var.closure_type {
12782                ClosureType::Arg => {
12783                    let slot = closure_var.var_idx as usize;
12784                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
12785                }
12786                ClosureType::Local => {
12787                    let slot = closure_var.var_idx as usize;
12788                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
12789                }
12790                ClosureType::Ref | ClosureType::GlobalRef => {
12791                    // A `Ref` names a cell in this frame's own closure table; a
12792                    // `GlobalRef` also starts there, then resolves by name below.
12793                    let slot = closure_var.var_idx as usize;
12794                    if let Some(cell) = self.frame().env.cells.get(slot) {
12795                        cells.push(cell.clone());
12796                        continue;
12797                    }
12798                    -1
12799                }
12800                _ => -1,
12801            };
12802            if cell >= 0 {
12803                let cell = self.frame().cells[cell as usize].clone();
12804                cells.push(cell);
12805                continue;
12806            }
12807            // A global: the cell is created on demand and shared through the realm,
12808            // so every function sees one binding.
12809            let name = closure_var.name.clone();
12810            let cell = match self.realm.globals.get(&name) {
12811                Some(cell) => cell.clone(),
12812                None => {
12813                    let cell = self.new_cell(Value::Undefined);
12814                    self.realm.globals.insert(name.clone(), cell.clone());
12815                    cell
12816                }
12817            };
12818            cells.push(cell);
12819        }
12820        let name = function.name.clone();
12821        // `.length` is the arity before any default or rest parameter, not the number
12822        // of slots a pattern parameter needs.
12823        let length = function.defined_args;
12824        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
12825        // function and an arrow function do not. A *method* also does not, but that is not
12826        // known here — the method is marked when the `[[HomeObject]]` is attached (see
12827        // `set_home_object`), which is the moment it becomes a method.
12828        let function_kind = function.kind;
12829        let constructible =
12830            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
12831        let code = Gc::new(self.heap, CompiledCode::new(*function));
12832        // A closure built inside an `eval` inherits the eval's view of the enclosing
12833        // bindings, so it can still read them once the eval has returned.
12834        let eval_scope = self
12835            .active_eval_scope
12836            .clone()
12837            .or_else(|| self.frame().env.eval_scope.clone());
12838        // A closure sees the variables a direct `eval` declared in the frame it was
12839        // created in — the ones declared before *and after* it, so the same object is
12840        // shared; only the phase bounds which of them are visible.
12841        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
12842        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
12843        let env = Gc::new(
12844            self.heap,
12845            ClosureEnv {
12846                cells,
12847                eval_scope,
12848                local_vars,
12849                local_phase,
12850            },
12851        );
12852        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
12853        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
12854        // the only thing that carries `Symbol.toStringTag`, so without it
12855        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
12856        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
12857        let proto = match function_kind {
12858            js_compile::bytecode::FunctionKind::AsyncGenerator => self
12859                .realm
12860                .async_generator_function_proto
12861                .clone()
12862                .or_else(|| self.realm.function_proto.clone().into()),
12863            js_compile::bytecode::FunctionKind::Generator => self
12864                .realm
12865                .generator_function_proto
12866                .clone()
12867                .or_else(|| self.realm.function_proto.clone().into()),
12868            js_compile::bytecode::FunctionKind::Async => self
12869                .realm
12870                .async_function_proto
12871                .clone()
12872                .or_else(|| self.realm.function_proto.clone().into()),
12873            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
12874        };
12875        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
12876        object.set_constructible(constructible);
12877        object.define(
12878            "length",
12879            Property::name_or_length(Value::Int(length as i32)),
12880        );
12881        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
12882        // that checks the own-property descriptor fails if the property is missing.
12883        object.define("name", Property::name_or_length(self.string(name)));
12884        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
12885        // when `[[Construct]]` is created, so an async function and an arrow function have
12886        // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
12887        // function) an own `prototype` property, which `builtin.js` checks for absence.
12888        //
12889        // A **generator** function is the exception that is not constructible: it still
12890        // gets a `prototype` field, because that object is what a generator *instance*
12891        // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
12892        // made `function* g(){}; g.prototype` `undefined` and every generator share
12893        // `%GeneratorPrototype%` as its direct prototype.
12894        if constructible {
12895            self.install_function_prototype(&object);
12896        } else if matches!(
12897            function_kind,
12898            js_compile::bytecode::FunctionKind::Generator
12899                | js_compile::bytecode::FunctionKind::AsyncGenerator
12900        ) {
12901            let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
12902                self.realm.generator_proto.clone()
12903            } else {
12904                self.realm
12905                    .async_generator_proto
12906                    .clone()
12907                    .unwrap_or_else(|| self.realm.generator_proto.clone())
12908            };
12909            self.install_generator_prototype(&object, parent);
12910        }
12911        Ok(Value::Object(object))
12912    }
12913
12914    // -- conversions used by the operators ----------------------------------
12915
12916    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
12917        // `+x` is `ToNumber`, which for a string parses it and for an object runs
12918        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
12919        // string, which then behaves differently in every later comparison.
12920        match value {
12921            Value::Int(_) | Value::Float(_) => Ok(value),
12922            other => Ok(Value::Float(self.to_js_number(&other)?)),
12923        }
12924    }
12925
12926    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
12927    ///
12928    /// Returns the *converted* old value and the new one, because the two callers need
12929    /// different halves: `++x` yields the new value, while `x++` yields the old one and
12930    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
12931    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
12932    /// boolean.
12933    ///
12934    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
12935    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
12936    /// a bigint algorithm then ran exactly once.
12937    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
12938        if let Value::BigInt(big) = &value {
12939            let one = crate::bigint::BigInt::from_i64(1);
12940            let next = if up { big.add(&one) } else { big.sub(&one) };
12941            return Ok((value, self.bigint(next)));
12942        }
12943        let old = self.numeric_operand(value)?;
12944        if let Value::BigInt(big) = &old {
12945            let one = crate::bigint::BigInt::from_i64(1);
12946            let next = if up { big.add(&one) } else { big.sub(&one) };
12947            return Ok((old, self.bigint(next)));
12948        }
12949        let new = if up {
12950            increment(old.clone())
12951        } else {
12952            decrement(old.clone())
12953        };
12954        Ok((old, new))
12955    }
12956
12957    /// `ToNumeric` for a unary or update operand: `ToPrimitive(number)`, then either branch.
12958    ///
12959    /// The unary operators are defined on `Numeric`, not on `Number`: `-x` and `~x` are
12960    /// `Numeric::unaryMinus`/`bitwiseNOT`, which a bigint answers exactly. [`Interp::numeric`]
12961    /// is `ToNumber` and collapses a bigint to a float, so an operand that is a *wrapper
12962    /// object* — `-Object(5n)` — lost its bigint-ness before the operator ever saw it and
12963    /// raised "cannot convert bigint to number". A primitive bigint never took that path
12964    /// (`Neg`/`Not` matched `Value::BigInt` first), which is why only the boxed form broke.
12965    fn numeric_operand(&mut self, value: Value) -> JsResult<Value> {
12966        let primitive = match value {
12967            Value::Int(_) | Value::Float(_) | Value::BigInt(_) => value,
12968            other => self.to_primitive(other, Hint::Number)?,
12969        };
12970        match primitive {
12971            Value::BigInt(_) => Ok(primitive),
12972            other => self.numeric(other),
12973        }
12974    }
12975
12976    fn numeric(&mut self, value: Value) -> JsResult<Value> {
12977        // `ToNumber` on an object runs `ToPrimitive` first, which is how
12978        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
12979        // heard at all. Reading the object's own tag instead (`other.to_number()`)
12980        // turned the whole operand into `NaN` and swallowed the exception.
12981        match value {
12982            Value::Int(_) | Value::Float(_) => Ok(value),
12983            other => Ok(Value::Float(self.to_js_number(&other)?)),
12984        }
12985    }
12986
12987    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
12988    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
12989        match value {
12990            Value::BigInt(big) => Ok((**big).clone()),
12991            // The reference words this the same way for every operator, so a failing
12992            // script reads identically; the operator itself adds nothing a caller can use.
12993            _ => Err(Signal::Throw(
12994                self.make_error("TypeError", "cannot convert bigint to number"),
12995            )),
12996        }
12997    }
12998
12999    /// Arithmetic where at least one operand is a `BigInt`.
13000    ///
13001    /// The two numeric types never mix, so a bigint paired with anything else is an error
13002    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
13003    /// that the relational operators handle it separately.
13004    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13005        use Opcode::*;
13006        let a = self.bigint_operand(&left)?;
13007        let b = self.bigint_operand(&right)?;
13008        let result = match op {
13009            Add => a.add(&b),
13010            Sub => a.sub(&b),
13011            Mul => a.mul(&b),
13012            Div | Mod => {
13013                let Some((quotient, remainder)) = a.div_rem(&b) else {
13014                    return Err(Signal::Throw(
13015                        self.make_error("RangeError", "division by zero"),
13016                    ));
13017                };
13018                if op == Div { quotient } else { remainder }
13019            }
13020            Pow => {
13021                let Some(value) = a.pow(&b) else {
13022                    return Err(Signal::Throw(self.make_error(
13023                        "RangeError",
13024                        "BigInt exponent must be non-negative and not absurdly large",
13025                    )));
13026                };
13027                value
13028            }
13029            And => a.bitand(&b),
13030            Or => a.bitor(&b),
13031            Xor => a.bitxor(&b),
13032            Shl | Sar => {
13033                // A shift count is a `BigInt` here, and both directions are exact; a
13034                // negative count would be the other direction, which the spec forbids.
13035                let Some(count) = b.to_i64() else {
13036                    return Err(Signal::Throw(
13037                        self.make_error("RangeError", "BigInt shift count is too large"),
13038                    ));
13039                };
13040                if count < 0 {
13041                    return Err(Signal::Throw(self.make_error(
13042                        "RangeError",
13043                        "BigInt shift count must be non-negative",
13044                    )));
13045                }
13046                if op == Shl {
13047                    a.shl(count as u64)
13048                } else {
13049                    a.shr(count as u64)
13050                }
13051            }
13052            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
13053            _ => {
13054                return Err(Signal::Throw(self.make_error(
13055                    "TypeError",
13056                    "BigInts have no unsigned right shift, use >> instead",
13057                )));
13058            }
13059        };
13060        Ok(self.bigint(result))
13061    }
13062
13063    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
13064    ///
13065    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
13066    /// is on the mathematical values, and nothing is rounded first.
13067    /// `<`, `<=`, `>`, `>=`.
13068    ///
13069    /// Both operands go through `ToPrimitive` **before** the comparison, which is what
13070    /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
13071    /// It is a `?`-returning function for exactly that reason: an object operand can run
13072    /// script, and script can throw. The old version compared `to_number` of the raw
13073    /// values, which answered `false` for every object instead of calling `valueOf` —
13074    /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
13075    /// never ran.
13076    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13077        // The hot arm first: `i < n` with both sides already integers. No conversion, no
13078        // call, nothing that can throw.
13079        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13080            let ordering = Some(left.cmp(right));
13081            return Ok(ordering_answer(op, ordering));
13082        }
13083        // Anything that can run script has to be converted first, in this order.
13084        let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
13085        {
13086            (
13087                self.to_primitive(left, Hint::Number)?,
13088                self.to_primitive(right, Hint::Number)?,
13089            )
13090        } else {
13091            (left, right)
13092        };
13093        let ordering = match (&left, &right) {
13094            // The loop condition `i < n` is integer against integer, and it runs once
13095            // per iteration of every loop in every program. Without this arm it took the
13096            // `to_number` path twice, which is a `match` plus a conversion each.
13097            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
13098            // **Code unit** order, not code point order. They differ exactly where a
13099            // surrogate pair meets a BMP character above U+E000: `"\uDC00" > "\uD800"` is
13100            // true because 0xDC00 > 0xD800, while comparing code points would have turned
13101            // both lone surrogates into U+FFFD and called them equal
13102            // (`greater-than/S11.8.2_A4.12_T1`).
13103            (Value::String(a), Value::String(b)) => Some(compare_code_units(a, b)),
13104            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
13105            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
13106            // is true even though `2.5` has no bigint form.
13107            // §7.2.13 step 3.d-3.e: a bigint against a string goes through
13108            // `StringToBigInt`, **not** `ToNumber` — `"9007199254740993" > 9007199254740992n`
13109            // is true because both sides stay exact integers, which converting the string to
13110            // a double would destroy. A string that is not an integer literal makes the
13111            // whole comparison `undefined`, i.e. `false` for every relational operator.
13112            (Value::BigInt(a), Value::String(text)) => {
13113                string_to_bigint(&text.to_string_lossy()).map(|b| a.cmp(&b))
13114            }
13115            (Value::String(text), Value::BigInt(b)) => {
13116                string_to_bigint(&text.to_string_lossy()).map(|a| b.cmp(&a).reverse())
13117            }
13118            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
13119                let b = self.number_operand(other)?;
13120                if b.is_nan() {
13121                    None
13122                } else {
13123                    compare_bigint_and_f64(a, b)
13124                }
13125            }
13126            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
13127                let a = self.number_operand(other)?;
13128                if a.is_nan() {
13129                    None
13130                } else {
13131                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
13132                }
13133            }
13134            // `ToNumeric` on the pair, which refuses a Symbol rather than answering `NaN`:
13135            // `Object(Symbol()) <= ""` is a `TypeError`, and the total `to_number` made it
13136            // `false` (`Symbol/prototype/Symbol.toPrimitive/…-ordinary-toprimitive`).
13137            _ => self
13138                .to_js_number(&left)?
13139                .partial_cmp(&self.to_js_number(&right)?),
13140        };
13141        Ok(ordering_answer(op, ordering))
13142    }
13143
13144    /// `ToNumber(V)`, refusing a Symbol instead of answering `NaN`.
13145    ///
13146    /// §7.1.4 throws for a Symbol, and the relational operators inherit that: `3n < Symbol()`
13147    /// is a `TypeError`, not `false`. `Value::to_number` is a total function — it has to be,
13148    /// because it is also what `Number(x)` uses — so the check lives here.
13149    fn number_operand(&self, value: &Value) -> JsResult<f64> {
13150        if matches!(value, Value::Symbol(_)) {
13151            return Err(self.type_error("cannot convert symbol to number"));
13152        }
13153        Ok(value.to_number())
13154    }
13155
13156    fn binary_add(&mut self) -> JsResult<()> {
13157        let right = self.pop();
13158        let left = self.pop();
13159        // Two integers add without any of the machinery below: no `ToPrimitive` (an
13160        // `Int` is already primitive), no string check, no bigint check, no allocation.
13161        // `x += 1` in a loop is the single most common instruction sequence in real
13162        // script, and it used to walk every one of those checks before reaching the
13163        // same `checked_add`.
13164        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13165            self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
13166            return Ok(());
13167        }
13168        let left = self.primitive_of(left)?;
13169        let right = self.primitive_of(right)?;
13170        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
13171        // that check comes before the bigint one: `"" + 1n` is a string, not a
13172        // mixed-type error.
13173        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
13174            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
13175            // `TypeError`, the one place a symbol and a string do not mix.
13176            // Keep the operands as strings rather than as bytes: `JsString::concat` decides
13177            // between a copy and a rope from their lengths, and a rope is what turns
13178            // `text += "abc"` in a loop from quadratic into linear.
13179            if let (Value::String(left), Value::String(right)) = (&left, &right) {
13180                // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
13181                // reports as `InternalError: string too long`.
13182                let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
13183                    return Err(Signal::Throw(
13184                        self.make_error("InternalError", "string too long"),
13185                    ));
13186                };
13187                self.push(Value::String(Gc::new(self.heap, joined)));
13188                return Ok(());
13189            }
13190            // At least one operand was not a string, so `ToString` it. This rejects a
13191            // symbol, which is the one place a symbol and a string do not mix.
13192            let left = self.checked_to_wtf8(&left)?;
13193            let right = self.checked_to_wtf8(&right)?;
13194            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
13195            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
13196            let text = left.concat(&right);
13197            self.push(self.string_wtf8(text));
13198            return Ok(());
13199        }
13200        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
13201        // not a conversion.
13202        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
13203            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
13204            self.push(value);
13205            return Ok(());
13206        }
13207        let left = self.numeric(left)?;
13208        let right = self.numeric(right)?;
13209        self.push(add_numbers(left, right));
13210        Ok(())
13211    }
13212
13213    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
13214        self.to_primitive(value, Hint::Default)
13215    }
13216
13217    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
13218    ///
13219    /// The order depends on the hint: the "number" order tries `valueOf` first and
13220    /// `toString` second, the "string" order the other way round, and the default
13221    /// hint uses the number order. A result that is still an object is a `TypeError`,
13222    /// because no built-in `valueOf`/`toString` returns one.
13223    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
13224        let Value::Object(object) = &value else {
13225            return Ok(value);
13226        };
13227        // A Date overrides the default hint to mean "string", which is what
13228        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
13229        // this, `"" + new Date()` would print the milliseconds, not the date.
13230        let hint = if hint == Hint::Default && is_date_object(self, object) {
13231            Hint::String
13232        } else {
13233            hint
13234        };
13235        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
13236        // handed the hint as a string. This is the hook a Date uses for its default hint
13237        // and a script uses to take over conversion entirely.
13238        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
13239        // `GetMethod`, not "is it a callable object": the property has to be read and then
13240        // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
13241        // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
13242        // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
13243        // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
13244        // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
13245        // callable.
13246        match self.get_property_key(object, &key)? {
13247            None | Some(Value::Undefined) | Some(Value::Null) => {}
13248            Some(Value::Object(function)) if function.is_callable() => {
13249                let hint = match hint {
13250                    Hint::String => "string",
13251                    Hint::Number => "number",
13252                    Hint::Default => "default",
13253                };
13254                let hint = self.string(hint);
13255                let result = self.call_value(
13256                    Value::Object(function),
13257                    Value::Object(object.clone()),
13258                    vec![hint],
13259                )?;
13260                if !matches!(result, Value::Object(_)) {
13261                    return Ok(result);
13262                }
13263                return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
13264            }
13265            Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
13266        }
13267        let order: [&str; 2] = match hint {
13268            Hint::String => ["toString", "valueOf"],
13269            Hint::Number | Hint::Default => ["valueOf", "toString"],
13270        };
13271        let receiver = object.clone();
13272        for method in order {
13273            if let Some(function) = self.get_property(&receiver, method)?
13274                && matches!(&function, Value::Object(object) if object.is_callable())
13275            {
13276                let result =
13277                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
13278                if !matches!(result, Value::Object(_)) {
13279                    return Ok(result);
13280                }
13281            }
13282        }
13283        Err(self.type_error("cannot convert object to primitive value"))
13284    }
13285
13286    /// `ToString` with the object case going through `ToPrimitive`.
13287    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
13288        if matches!(value, Value::Object(_)) {
13289            let primitive = self.to_primitive(value.clone(), Hint::String)?;
13290            return Ok(primitive.to_js_string());
13291        }
13292        // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
13293        // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
13294        // callers that want that strictness call [`Interp::to_string_strict`] — putting the
13295        // check here broke `String(Symbol())` and 45 cases that print a symbol.
13296        Ok(value.to_js_string())
13297    }
13298
13299    /// `ToString(value)`, with §7.1.19's symbol refusal.
13300    ///
13301    /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
13302    /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
13303    /// operations and conflating them cost 45 cases in one direction and 6 in the other.
13304    pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
13305        if matches!(value, Value::Symbol(_)) {
13306            return Err(self.type_error("cannot convert a Symbol to a string"));
13307        }
13308        if matches!(value, Value::Object(_)) {
13309            let primitive = self.to_primitive(value.clone(), Hint::String)?;
13310            if matches!(primitive, Value::Symbol(_)) {
13311                return Err(self.type_error("cannot convert a Symbol to a string"));
13312            }
13313            return Ok(primitive.to_js_string());
13314        }
13315        Ok(value.to_js_string())
13316    }
13317
13318    /// `ToString` that keeps the string's code units instead of flattening them.
13319    ///
13320    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
13321    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
13322    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13323        if matches!(value, Value::Symbol(_)) {
13324            return Err(Signal::Throw(
13325                self.make_error("TypeError", "cannot convert symbol to string"),
13326            ));
13327        }
13328        // An object runs `ToPrimitive` first, which may itself produce a symbol.
13329        let value = self.to_primitive(value.clone(), Hint::String)?;
13330        match value {
13331            Value::Symbol(_) => Err(Signal::Throw(
13332                self.make_error("TypeError", "cannot convert symbol to string"),
13333            )),
13334            Value::String(text) => Ok(text.wtf8().clone()),
13335            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
13336        }
13337    }
13338
13339    /// `ToNumber` with the object case going through `ToPrimitive`.
13340    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
13341        let value = if matches!(value, Value::Object(_)) {
13342            self.to_primitive(value.clone(), Hint::Number)?
13343        } else {
13344            value.clone()
13345        };
13346        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
13347        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
13348        // `NaN` to stay total, and the operators check for the bigint themselves — but
13349        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
13350        // refuse, and answering `NaN` made them silently wrong instead.
13351        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
13352        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
13353        match value {
13354            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
13355            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
13356            other => Ok(other.to_number()),
13357        }
13358    }
13359
13360    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
13361    /// [`ElementType::write`].
13362    ///
13363    /// This is separated from the write because both conversions are observable script —
13364    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
13365    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
13366    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
13367    /// setters, and a plain `a[i] = v`.
13368    pub(crate) fn element_value(
13369        &mut self,
13370        element: crate::builtins::typedarray::ElementType,
13371        value: Value,
13372    ) -> JsResult<Value> {
13373        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
13374        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
13375        let primitive = match &value {
13376            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
13377            _ => value,
13378        };
13379        if element.is_bigint() {
13380            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
13381            Ok(Value::BigInt(Gc::new(self.heap, big)))
13382        } else {
13383            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
13384            Ok(Value::Float(self.to_js_number(&primitive)?))
13385        }
13386    }
13387
13388    /// `ToPropertyKey`: what a computed member access uses as its key.
13389    ///
13390    /// A symbol is returned as itself, never stringified — that is what keeps
13391    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
13392    pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
13393        match value {
13394            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
13395            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
13396            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
13397            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
13398            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13399                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
13400                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
13401                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
13402                    other.to_js_string(),
13403                ))),
13404            },
13405            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
13406        }
13407    }
13408
13409    /// `ToPropertyKey` for the callers that can only use a string key.
13410    ///
13411    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
13412    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
13413    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
13414    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
13415    /// program continues with a value nobody asked for.
13416    /// `SetFunctionName`'s name for a computed key, which is not `ToPropertyKey`.
13417    ///
13418    /// §7.3.24 step 1: when the key is a **Symbol**, the name is `"[" + description + "]"`
13419    /// — or the empty string when the symbol has no description. Going through
13420    /// `ToPropertyKey` instead gave `Symbol(test262)` and `Symbol()`, so every
13421    /// `{ [sym](){} }` method had the wrong `name` (`fn-name-fn` and its generated
13422    /// relatives, in both `expressions/object` and `statements/class`).
13423    ///
13424    /// Everything else is an ordinary `ToPropertyKey` — a string key keeps its code units,
13425    /// which is what makes `{ "\uD800": function () {} }.name` the lone surrogate.
13426    fn function_name_from_key(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13427        if let Value::Symbol(symbol) = value {
13428            return Ok(match symbol.description() {
13429                Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
13430                None => crate::value::Wtf8::default(),
13431            });
13432        }
13433        self.propkey_of(value)
13434    }
13435
13436    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13437        use crate::value::Wtf8;
13438        Ok(match value {
13439            // A string key keeps its code units. Going through a lossy `String` would make
13440            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
13441            Value::String(text) => text.wtf8().clone(),
13442            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
13443            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
13444            // falling back to its `ToString` would print `[object Object]`.
13445            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13446                Value::String(text) => text.wtf8().clone(),
13447                other => Wtf8::new(other.to_js_string()),
13448            },
13449            other => Wtf8::new(other.to_js_string()),
13450        })
13451    }
13452
13453    // -- object operations used by instructions -----------------------------
13454
13455    /// Read `object[key]`, returning `undefined` when the property is missing.
13456    ///
13457    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
13458    /// primitive (looking through its prototype) as well as an object — which is what
13459    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
13460    /// argument needs too.
13461    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
13462        self.read_field_key(object, &PropertyKey::from(key))
13463    }
13464
13465    /// [`Interp::read_field`] with a key that may be a symbol.
13466    ///
13467    /// A symbol key never reaches the string shortcuts: a string's `length` and its
13468    /// indices are string properties, and a symbol named `length` is a different
13469    /// property that a string primitive cannot have.
13470    /// [`Interp::read_field_key`], with an inline cache in front of it.
13471    ///
13472    /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
13473    /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
13474    /// without this the engine walked the chain and compared ~40 property names on each
13475    /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
13476    ///
13477    /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
13478    /// missing property. Those answers depend on running code or on state the guard below
13479    /// does not cover, and a wrong answer here is far more expensive than a lookup.
13480    ///
13481    /// A hit is re-validated against the *whole* walked chain, not just the level that
13482    /// answered: the receiver and every prototype down to that level must still be the same
13483    /// object (weakly, so a collected and reallocated object is a miss) with unchanged
13484    /// property-table *lengths* — which is what catches a property appearing on an
13485    /// intermediate prototype and shadowing the cached one.
13486    pub fn read_field_cached(
13487        &mut self,
13488        object: &Value,
13489        key: &PropertyKey,
13490        slot: usize,
13491    ) -> JsResult<Value> {
13492        let index = Self::field_cache_slot(object, key, slot);
13493        let Value::Object(target) = object else {
13494            return self.read_field_key(object, key);
13495        };
13496        if target.proxy_state().is_some() {
13497            return self.read_field_key(object, key);
13498        }
13499        if let Some(cached) = &self.field_cache[index]
13500            && cached.key == *key
13501            && let Some(value) = Self::cached_hit(target, cached)
13502        {
13503            return Ok(value);
13504        }
13505        let value = self.read_field_key(object, key)?;
13506        self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
13507        Ok(value)
13508    }
13509
13510    /// Whether a cache entry still describes this lookup, and if so the value.
13511    ///
13512    /// The guard is the whole point of the entry: identity plus property-table length for
13513    /// every level walked. Re-checked per level rather than once at the receiving end,
13514    /// because a shadowing property can appear anywhere along the chain.
13515    fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
13516        // Level 0 — the receiver itself answered — without the `Gc` clone this loop
13517        // starts with: a clone is a reference-count bump and a drop, and for
13518        // `property:monomorphic` every single hit takes only this arm.
13519        let (weak, len) = cached.chain[0].as_ref()?;
13520        if !target.upgrades_to(weak) {
13521            return None;
13522        }
13523        if cached.level == 0 {
13524            // Length and key and accessor-ness in one borrow: see `cached_property_at`.
13525            return target.cached_property_at(cached.index, &cached.key, *len);
13526        }
13527        if target.props_len() != *len {
13528            return None;
13529        }
13530        let mut level = 1;
13531        let mut current = target.proto()?;
13532        loop {
13533            let (weak, len) = cached.chain[level].as_ref()?;
13534            if !current.upgrades_to(weak) || current.props_len() != *len {
13535                return None;
13536            }
13537            if level == cached.level as usize {
13538                // The level that answered: the value is only reusable while the key is
13539                // still there and still a plain data property.
13540                return current.cached_data_property(cached.index, &cached.key);
13541            }
13542            current = current.proto()?;
13543            level += 1;
13544        }
13545    }
13546
13547    /// Build a cache entry for a lookup that just went through the slow path.
13548    ///
13549    /// Records the chain only when the answer came from a plain data property at a level
13550    /// the fixed-size array can hold; everything else simply leaves the slot empty, which
13551    /// costs the next lookup the walk it would have cost anyway.
13552    fn record_field_lookup(
13553        target: &Gc<JsObject>,
13554        key: &PropertyKey,
13555        _value: Value,
13556    ) -> Option<FieldCache> {
13557        let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
13558            [None, None, None];
13559        let mut current = target.clone();
13560        for level in 0..MAX_CACHED_CHAIN {
13561            chain[level] = Some((current.downgrade(), current.props_len()));
13562            if let Some((found, _)) = current.own_property_index(key) {
13563                // `own_property_index` declines an accessor and a hole, which is exactly
13564                // the set that must not be cached.
13565                return Some(FieldCache {
13566                    key: key.clone(),
13567                    index: found,
13568                    level: level as u8,
13569                    chain,
13570                });
13571            }
13572            current = current.proto()?;
13573        }
13574        None
13575    }
13576
13577    /// Which cache slot a lookup uses.
13578    ///
13579    /// Mixes the object's address, the name and the site, so that two properties of one
13580    /// object, and one property of two objects, land in different slots — which is what lets
13581    /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
13582    /// other iteration.
13583    fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
13584        let mut hash = match object {
13585            Value::Object(object) => object.address(),
13586            _ => 0,
13587        };
13588        hash = hash
13589            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
13590            .rotate_left(17)
13591            .wrapping_add(key.hash_code());
13592        hash = hash.wrapping_add(site.wrapping_mul(31));
13593        // The table is a power of two, so the low bits are the slot.
13594        hash & (FIELD_CACHE_SLOTS - 1)
13595    }
13596
13597    /// Read `key` from `object`, without the inline cache.
13598    ///
13599    /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
13600    /// prototype chain, while the cached form answers an own data property from memory.
13601    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
13602        let text = key.as_str().unwrap_or("");
13603        let Value::Object(object) = object else {
13604            // Reading a property of `undefined`/`null` is the classic TypeError.
13605            if object.is_nullish() {
13606                return Err(Signal::Throw(self.make_error(
13607                    "TypeError",
13608                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
13609                )));
13610            }
13611            // A string has `length` and index access without being boxed.
13612            if let Value::String(value) = object {
13613                if text == "length" {
13614                    return Ok(Value::Int(value.utf16_len() as i32));
13615                }
13616                if let Some(index) = array_index(text) {
13617                    return Ok(match value.wtf8().unit_at(index as usize) {
13618                        Some(unit) => self.string_wtf8(unit),
13619                        None => Value::Undefined,
13620                    });
13621                }
13622            }
13623            // A property of a primitive is looked up on its prototype: this is what
13624            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
13625            let prototype = match object {
13626                Value::String(_) => self.realm.string_proto.clone(),
13627                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13628                Value::Bool(_) => self.realm.boolean_proto.clone(),
13629                // A symbol's methods live on `Symbol.prototype`, reached the same way —
13630                // `sym.description` reads through the prototype, not off the symbol.
13631                Value::Symbol(_) => self.realm.symbol_proto.clone(),
13632                // …and a bigint's on `BigInt.prototype`, which is how
13633                // `(255n).toString(16)` reaches its method.
13634                Value::BigInt(_) => self.realm.bigint_proto.clone(),
13635                _ => None,
13636            };
13637            if let Some(prototype) = prototype
13638                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
13639            {
13640                return Ok(value);
13641            }
13642            return Ok(Value::Undefined);
13643        };
13644        Ok(self
13645            .get_property_key(object, key)?
13646            .unwrap_or(Value::Undefined))
13647    }
13648
13649    /// The `#name` a private symbol stands for, for error messages.
13650    ///
13651    /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
13652    /// was made from.
13653    fn private_name(symbol: &Value) -> Option<String> {
13654        match symbol {
13655            Value::Symbol(symbol) if symbol.is_private() => Some(
13656                symbol
13657                    .description()
13658                    .map(|text| text.to_string())
13659                    .unwrap_or_default(),
13660            ),
13661            _ => None,
13662        }
13663    }
13664
13665    /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
13666    ///
13667    /// Every private-field opcode takes the symbol the class stored in its own scope; a
13668    /// non-symbol here would be a compiler bug, and the reference guards it with
13669    /// `JS_ThrowTypeErrorNotASymbol`.
13670    fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
13671        match symbol {
13672            Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
13673            _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
13674        }
13675    }
13676
13677    /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
13678    ///
13679    /// Three early errors, all from the reference: a non-object receiver, a non-extensible
13680    /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
13681    /// would hit if the parser did not reject it first.
13682    fn define_private_field(
13683        &mut self,
13684        object: &Value,
13685        symbol: &Value,
13686        value: Value,
13687    ) -> JsResult<()> {
13688        let key = self.private_key(symbol)?;
13689        let Some(target) = object.as_object() else {
13690            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13691        };
13692        if !target.is_extensible() {
13693            return Err(Signal::Throw(
13694                self.make_error("TypeError", "object is not extensible"),
13695            ));
13696        }
13697        if target.own_property_key(&key).is_some() {
13698            let name = Self::private_name(symbol).unwrap_or_default();
13699            return Err(Signal::Throw(self.make_error(
13700                "TypeError",
13701                &format!("private class field '{name}' already exists"),
13702            )));
13703        }
13704        target.define_data_key(&key, value);
13705        Ok(())
13706    }
13707
13708    /// `JS_GetPrivateField`: only an own property, never the prototype chain.
13709    fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
13710        let key = self.private_key(symbol)?;
13711        let Some(target) = object.as_object() else {
13712            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13713        };
13714        match target.own_property_key(&key) {
13715            Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
13716            None => {
13717                let name = Self::private_name(symbol).unwrap_or_default();
13718                Err(Signal::Throw(self.make_error(
13719                    "TypeError",
13720                    &format!("private class field '{name}' does not exist"),
13721                )))
13722            }
13723        }
13724    }
13725
13726    /// `JS_SetPrivateField`: the store half of the same rule.
13727    fn write_private_field(
13728        &mut self,
13729        object: &Value,
13730        symbol: &Value,
13731        value: Value,
13732    ) -> JsResult<()> {
13733        let key = self.private_key(symbol)?;
13734        let Some(target) = object.as_object() else {
13735            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13736        };
13737        if target.write_value_key(&key, value) {
13738            return Ok(());
13739        }
13740        let name = Self::private_name(symbol).unwrap_or_default();
13741        Err(Signal::Throw(self.make_error(
13742            "TypeError",
13743            &format!("private class field '{name}' does not exist"),
13744        )))
13745    }
13746
13747    /// The `in` half: does `object` have this private field?
13748    /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
13749    ///
13750    /// The symbol is created once per class — the first `add_brand` on a given home object
13751    /// makes it, every later one reuses it, which is what ties the prototype, the constructor
13752    /// and each instance to one identity. `obj` being `null` is not an error: the class-level
13753    /// emit for the *instance* brand passes null because all it wants is the symbol.
13754    fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
13755        let Some(home_object) = home.as_object() else {
13756            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13757        };
13758        let symbol = match home_object.private_brand() {
13759            Some(symbol) => symbol,
13760            None => {
13761                let symbol = Gc::new(
13762                    self.heap,
13763                    crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
13764                );
13765                home_object.set_private_brand(symbol.clone());
13766                symbol
13767            }
13768        };
13769        let Some(target) = object.as_object() else {
13770            // Not an object: nothing to brand. The reference does the same, and `undefined`
13771            // here would otherwise turn a field initialiser into a TypeError.
13772            return Ok(());
13773        };
13774        if !target.is_extensible() {
13775            return Err(Signal::Throw(
13776                self.make_error("TypeError", "object is not extensible"),
13777            ));
13778        }
13779        if target.carries_brand(&symbol) {
13780            return Err(Signal::Throw(
13781                self.make_error("TypeError", "private method is already present"),
13782            ));
13783        }
13784        target.add_brand(symbol);
13785        Ok(())
13786    }
13787
13788    /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
13789    ///
13790    /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
13791    /// decides whether to throw.
13792    fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
13793        let Some(function) = function.as_object() else {
13794            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13795        };
13796        let Some(home) = function.home_object() else {
13797            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13798        };
13799        let Some(brand) = home.private_brand() else {
13800            return Err(Signal::Throw(
13801                self.make_error("TypeError", "expecting <brand> private field"),
13802            ));
13803        };
13804        Ok(object.carries_brand(&brand))
13805    }
13806
13807    /// `CreateDataPropertyOrThrow(object, key, value)` — §7.3.3.
13808    ///
13809    /// What a property definition does: `[[DefineOwnProperty]]` with all three attributes
13810    /// true. Not `[[Set]]`, which walks the prototype chain and may run a setter there.
13811    fn define_field(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
13812        if let Some(target) = object.as_object() {
13813            // `CreateDataProperty` cannot reshape a non-configurable own property: its
13814            // descriptor asks for `writable` and `configurable`, and a non-configurable
13815            // property may become neither (`class C { static ['prototype'] = 1 }` is a
13816            // `TypeError`, since the constructor's `prototype` is both). The general define
13817            // path only validates *partial* descriptors — see the note there — so this has
13818            // to be said here.
13819            if self
13820                .object_get_own_property(target, key)?
13821                .is_some_and(|existing| {
13822                    !existing.configurable && (existing.is_accessor() || !existing.writable)
13823                })
13824            {
13825                return Err(Signal::Throw(self.make_error(
13826                    "TypeError",
13827                    &format!(
13828                        "cannot define property '{key}' of {}",
13829                        Value::Object(target.clone()).to_js_string()
13830                    ),
13831                )));
13832            }
13833            // Only an *array* stores into the element vector. A numeric key
13834            // on an ordinary object is an ordinary property, which is what
13835            // makes `{1: 'a'}` iterate as a key rather than disappear.
13836            let stored = target.is_array()
13837                && key.as_str().and_then(array_index).is_some_and(|index| {
13838                    target.array_set(self.heap, index as usize, value.clone())
13839                });
13840            if !stored {
13841                // `CreateDataPropertyOrThrow`, not a raw table insert: a class
13842                // field is defined with `[[DefineOwnProperty]]`, so a frozen
13843                // receiver throws (`class Test { f = Object.freeze(this); g = 1 }`
13844                // must fail on `g`) and a **proxy** receiver runs its
13845                // `defineProperty` trap (`class-field-is-observable-by-proxy`
13846                // counts the trap's calls). `define_data_key` writes straight into
13847                // the table, which did neither.
13848                // `?` and not `unwrap_or(false)`: a proxy's `defineProperty` trap
13849                // may *throw*, and that exception is the answer
13850                // (`public-class-field-initialization-is-visible-to-proxy` throws
13851                // a `Test262Error` from the trap and expects it, not a `TypeError`).
13852                let defined =
13853                    self.object_define_own_property(target, key, Property::data(value))?;
13854                if !defined {
13855                    let target = Value::Object(target.clone());
13856                    return Err(Signal::Throw(self.make_error(
13857                        "TypeError",
13858                        &format!(
13859                            "cannot define property '{key}' of {}",
13860                            target.to_js_string()
13861                        ),
13862                    )));
13863                }
13864            }
13865        }
13866        Ok(())
13867    }
13868
13869    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
13870        let Value::Object(object) = object else {
13871            // `PutValue` on a property of a primitive is a silent no-op in sloppy mode and a
13872            // `TypeError` in strict mode: `sym.a = 1` on a Symbol must leave `sym.a`
13873            // `undefined` rather than throwing (`Symbol/auto-boxing-non-strict`). `null` and
13874            // `undefined` still throw, with their own message.
13875            if !self.current_strict() && !matches!(object, Value::Null | Value::Undefined) {
13876                return Ok(());
13877            }
13878            return Err(Signal::Throw(self.make_error(
13879                "TypeError",
13880                &format!("cannot set property '{key}' of {}", object.to_js_string()),
13881            )));
13882        };
13883        // The write half of the property inline cache, in effect: an own, writable,
13884        // non-accessor data property already holds this key, so `[[Set]]` has nothing to
13885        // decide — no prototype walk (an own property shadows the chain before a setter
13886        // there could matter), no extensibility check (the object already has the key),
13887        // and no `[[DefineOwnProperty]]`.
13888        //
13889        // `this.value = …` inside a method is the whole write side of
13890        // `property:method-call`, and it was reaching `set_property_with_key` with its
13891        // proxy test, its typed-array test, its array-index test and finally a linear
13892        // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
13893        //
13894        // Every disqualifier is checked here: a proxy traps the set, an array index and
13895        // `length` live outside the property table, and a typed array's element is stored
13896        // through its view's element type.
13897        if object.proxy_state().is_none()
13898            && !object.is_array()
13899            && object.typed_array_element_type().is_none()
13900            && object.write_value_key(key, value.clone())
13901        {
13902            return Ok(());
13903        }
13904        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
13905        let on_failure = if self.frame().code.code.strict {
13906            DeleteFailure::Throw
13907        } else {
13908            DeleteFailure::Ignore
13909        };
13910        self.set_property_with_key(object, key, value, on_failure)
13911    }
13912
13913    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
13914    ///
13915    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
13916    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
13917    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
13918    /// `Number.parseInt(sym)` — so those callers use this instead.
13919    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
13920        if matches!(value, Value::Symbol(_)) {
13921            return Err(Signal::Throw(
13922                self.make_error("TypeError", "cannot convert symbol to string"),
13923            ));
13924        }
13925        // An object runs `ToPrimitive` first, which may itself produce a symbol —
13926        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
13927        let value = self.to_primitive(value.clone(), Hint::String)?;
13928        if matches!(value, Value::Symbol(_)) {
13929            return Err(Signal::Throw(
13930                self.make_error("TypeError", "cannot convert symbol to string"),
13931            ));
13932        }
13933        Ok(value.to_js_string())
13934    }
13935
13936    /// `ToPropertyKey` for a builtin that takes a key argument.
13937    ///
13938    /// Fallible: a key whose `toString` throws has to propagate that error, both for
13939    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
13940    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
13941    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
13942    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
13943        self.propkey(value)
13944    }
13945
13946    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
13947    ///
13948    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
13949    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
13950    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
13951    /// `RangeError` — and why this cannot be a plain `ToNumber`.
13952    /// `ToNumber(value)` for `ArraySetLength`, which the spec performs **twice**.
13953    ///
13954    /// §10.4.2.4 steps 3–5 are `ToUint32(Desc.[[Value]])`, then `ToNumber(Desc.[[Value]])`,
13955    /// then a `RangeError` when they disagree. Two conversions rather than one is
13956    /// observable: a `valueOf` that runs the first time can make `length` non-writable
13957    /// before the second, which turns the store into a refused write
13958    /// (`length/define-own-prop-length-coercion-order`, `…-set`).
13959    pub fn coerce_array_length_twice(&mut self, value: &Value) -> JsResult<u32> {
13960        let first = self.array_length_of(value)?;
13961        let second = self.array_length_of(value)?;
13962        debug_assert_eq!(first, second);
13963        Ok(first)
13964    }
13965
13966    /// `ArraySetLength`'s `ToNumber(value)`, then the `ToUint32` round-trip check.
13967    ///
13968    /// Separate from [`Interp::coerce_array_length_twice`] so the callers that need one
13969    /// conversion can say so; a caller that needs the spec's two uses that instead.
13970    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
13971        let number = match value {
13972            Value::Int(number) => *number as f64,
13973            Value::Float(number) => *number,
13974            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
13975            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
13976            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
13977            // reference answers 0.
13978            Value::Null | Value::Bool(_) | Value::Undefined => value.to_number(),
13979            // A string goes through the full numeric-literal grammar: `"0x00B"` is 11 and
13980            // `"  5  "` is 5, which is exactly what `string_to_number` implements.
13981            Value::String(text) => crate::value::string_to_number(&text.to_string_lossy()),
13982            _ => {
13983                // The primitive comes back through this same conversion, so a wrapper of a
13984                // boolean (`new Boolean(false)`) is `0` rather than the `NaN` that
13985                // `ToNumber("false")` would give — `S15.4.5.1_A1.3_T1` walks every wrapper.
13986                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
13987                return self.array_length_of(&primitive);
13988            }
13989        };
13990        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
13991        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
13992        // is a `RangeError`, not `0`.
13993        if !number.is_finite()
13994            || number.fract() != 0.0
13995            || !(0.0..=u32::MAX as f64).contains(&number)
13996        {
13997            return Err(self.range_error("invalid array length"));
13998        }
13999        Ok(number as u32)
14000    }
14001
14002    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
14003    /// `Object.getOwnPropertySymbols` put in their result array.
14004    pub fn key_value(&self, key: &PropertyKey) -> Value {
14005        match key {
14006            PropertyKey::String(text) => self.string_wtf8(text.clone()),
14007            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
14008        }
14009    }
14010
14011    /// Fill in a String exotic object: `_value`, `length` and the index properties.
14012    ///
14013    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
14014    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
14015    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
14016    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
14017    /// the two paths had drifted; this is the one both now use.
14018    ///
14019    /// The indices are *code units*, so an astral character occupies two of them — the
14020    /// same rule `s.length` and `s[i]` follow.
14021    /// Give an already-created object the internal slot that makes it a wrapper of
14022    /// `value`, so the primitive's prototype methods work on it.
14023    ///
14024    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
14025    /// which are wrappers of their own type holding the empty value.
14026    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
14027        self.internal_set(object, "_value", value);
14028    }
14029
14030    pub(crate) fn init_string_wrapper(
14031        &mut self,
14032        object: &Gc<JsObject>,
14033        text: &Gc<crate::value::JsString>,
14034    ) {
14035        object.define(
14036            "length",
14037            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
14038        );
14039        for index in 0..text.utf16_len() {
14040            if let Some(unit) = text.wtf8().unit_at(index) {
14041                object.define(
14042                    &index.to_string(),
14043                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
14044                    Property::with_attributes(self.string_wtf8(unit), false, true),
14045                );
14046            }
14047        }
14048        object.define_key(
14049            &self.internal_slot("_value"),
14050            Property::with_attributes(Value::String(text.clone()), false, false),
14051        );
14052    }
14053
14054    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
14055    ///
14056    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
14057    /// throws. The wrapper carries its primitive in `_value` — the same slot
14058    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
14059    /// on a boxed value no constructor ever built.
14060    pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
14061        let (prototype, primitive) = match value {
14062            Value::Object(object) => return Ok(object.clone()),
14063            Value::String(text) => {
14064                let object = self.new_object(self.realm.string_proto.clone());
14065                self.init_string_wrapper(&object, text);
14066                return Ok(object);
14067            }
14068            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
14069            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
14070            // A symbol and a bigint box into wrappers whose methods live on
14071            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
14072            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
14073            // branch below instead produced an object with *no* prototype, so those
14074            // methods were unreachable on a box.
14075            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
14076            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
14077            Value::Undefined | Value::Null => {
14078                return Err(Signal::Throw(self.make_error(
14079                    "TypeError",
14080                    &format!("cannot convert {} to object", value.to_js_string()),
14081                )));
14082            }
14083            _ => (None, value.clone()),
14084        };
14085        let object = self.new_object(prototype);
14086        self.internal_set(&object, "_value", primitive);
14087        Ok(object)
14088    }
14089
14090    /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
14091    ///
14092    /// Split out for a reader that has to create the object *before* it knows what it wraps:
14093    /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
14094    /// written before its primitive, so the placeholder has to exist first and be filled in
14095    /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
14096    /// than a second in the deserialiser.
14097    pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
14098        let prototype = match value {
14099            Value::String(_) => self.realm.string_proto.clone(),
14100            Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
14101            Value::Bool(_) => self.realm.boolean_proto.clone(),
14102            Value::Symbol(_) => self.realm.symbol_proto.clone(),
14103            Value::BigInt(_) => self.realm.bigint_proto.clone(),
14104            _ => {
14105                return Err(Signal::Throw(self.make_error(
14106                    "TypeError",
14107                    &format!("cannot box {}", value.to_js_string()),
14108                )));
14109            }
14110        };
14111        object.set_proto(prototype);
14112        if let Value::String(text) = value {
14113            self.init_string_wrapper(object, text);
14114            return Ok(());
14115        }
14116        self.internal_set(object, "_value", value.clone());
14117        Ok(())
14118    }
14119
14120    /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
14121    ///
14122    /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
14123    /// through the `Symbol` function object, so the registry is reachable as a method rather
14124    /// than only from `builtins::symbol`.
14125    pub fn symbol_for(&mut self, key: &str) -> Value {
14126        if let Some(existing) = self.realm.symbol_registry.get(key) {
14127            return existing.clone();
14128        }
14129        let symbol = crate::builtins::symbol::symbol_value(
14130            self,
14131            crate::value::JsSymbol::registered(key.to_string()),
14132        );
14133        self.realm
14134            .symbol_registry
14135            .insert(key.to_string(), symbol.clone());
14136        symbol
14137    }
14138
14139    /// `a == b`, the coercing comparison.
14140    ///
14141    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
14142    /// which is what makes `[] == ""` true: `[]` becomes `""` via
14143    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
14144    /// because the conversion is allowed to call script code, so the two primitive
14145    /// operands are handed back to it.
14146    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
14147        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
14148            return Ok(left.loose_equals(&right));
14149        }
14150        // `null == undefined` holds even though neither is an object.
14151        if matches!(left, Value::Undefined | Value::Null)
14152            && matches!(right, Value::Undefined | Value::Null)
14153        {
14154            return Ok(true);
14155        }
14156        if matches!(left, Value::Undefined | Value::Null)
14157            || matches!(right, Value::Undefined | Value::Null)
14158        {
14159            return Ok(false);
14160        }
14161        // Two objects compare by identity. Only an object *against a primitive* is
14162        // converted, which is why `{} == {}` is false while `[] == ""` is true.
14163        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
14164            return Ok(a.ptr_eq(b));
14165        }
14166        let left = self.to_primitive(left, Hint::Default)?;
14167        let right = self.to_primitive(right, Hint::Default)?;
14168        Ok(left.loose_equals(&right))
14169    }
14170
14171    /// `HasBinding(N)` for an Object Environment Record whose binding object is `object`.
14172    ///
14173    /// §9.1.1.2.1: `HasProperty` **and then** not listed in the object's
14174    /// `Symbol.unscopables`. The `unscopables` object is read with a plain `Get`, so a
14175    /// getter on it runs exactly once per lookup — `with/with-get-unscopables-once` counts
14176    /// the calls.
14177    fn with_has_binding(&mut self, object: &Value, name: &str) -> JsResult<bool> {
14178        let key = PropertyKey::from(name);
14179        if !self.has_property_value(object, &key)? {
14180            return Ok(false);
14181        }
14182        let unscopables_key = self.realm.well_known_key(WellKnown::Unscopables);
14183        let unscopables = self.read_field_key(object, &unscopables_key)?;
14184        let Value::Object(_) = unscopables else {
14185            // `undefined` (the usual case) or a primitive: nothing is excluded.
14186            return Ok(true);
14187        };
14188        let excluded = self.read_field_key(&unscopables, &key)?;
14189        Ok(!excluded.to_boolean())
14190    }
14191
14192    /// `GetBindingValue(N, S)` for an Object Environment Record: §9.1.1.2.4.
14193    ///
14194    /// `HasProperty` is asked a **second** time — the guard already asked it — because the
14195    /// object may have changed in between: `GetBindingValue` step 2 is a fresh lookup, and
14196    /// a proxy sees two `has` traps plus the `get`. The `unscopables` step is *not*
14197    /// repeated: that belongs to `HasBinding`, not to `GetBindingValue`.
14198    ///
14199    /// When the property has gone, strict code throws and sloppy code reads `undefined`
14200    /// from the environment (step 2's `S` is the strictness of the *running* code, not of
14201    /// the declaration).
14202    fn with_get_binding(&mut self, object: &Value, name: &str) -> JsResult<Value> {
14203        let key = PropertyKey::from(name);
14204        if !self.has_property_value(object, &key)? {
14205            if self.frame().code.code.strict {
14206                return Err(self.throw_reference(name));
14207            }
14208            return Ok(Value::Undefined);
14209        }
14210        self.read_field_key(object, &key)
14211    }
14212
14213    /// `SetMutableBinding(N, V, S)` for an Object Environment Record: §9.1.1.2.5.
14214    ///
14215    /// Same second `HasProperty`, and the same strict-mode `ReferenceError` when the
14216    /// property is gone — before the store, which is what makes
14217    /// `set-mutable-binding-binding-deleted-with-typed-array-in-proto-chain-strict-mode`
14218    /// a `ReferenceError` rather than whatever the failed store would have thrown.
14219    fn with_put_binding(&mut self, object: &Value, name: &str, value: Value) -> JsResult<()> {
14220        let key = PropertyKey::from(name);
14221        if !self.has_property_value(object, &key)? && self.frame().code.code.strict {
14222            return Err(self.throw_reference(name));
14223        }
14224        self.write_field_key(object, &key, value)
14225    }
14226
14227    /// `HasProperty(O, P)` on a `Value`, without the `in`-operator error for a primitive.
14228    fn has_property_value(&mut self, object: &Value, key: &PropertyKey) -> JsResult<bool> {
14229        match object {
14230            Value::Object(target) => self.has_property_key(target, key),
14231            // `with` boxes its object when the statement is entered (`to_object`), so a
14232            // primitive cannot arrive here; `false` is the honest answer rather than a
14233            // panic if it ever does.
14234            _ => Ok(false),
14235        }
14236    }
14237
14238    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
14239        let Value::Object(object) = object else {
14240            return Err(Signal::Throw(
14241                self.make_error("TypeError", "cannot use 'in' on a non-object"),
14242            ));
14243        };
14244        let key = self.propkey(key)?;
14245        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
14246        // trap. One implementation, so an array's derived `length` and its inherited holes
14247        // cannot be right in one caller and wrong in another.
14248        self.has_own_or_inherited(object, &key)
14249    }
14250
14251    /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
14252    ///
14253    /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
14254    /// whole reason the operator is a hook rather than a prototype walk.
14255    ///
14256    /// §13.10.2 `InstanceofOperator(O, C)`, which is stricter than
14257    /// [`Interp::ordinary_instance_of`]: step 1 throws when `C` is not an object at all
14258    /// (`true instanceof true`) and step 4 throws when it is an object but not callable
14259    /// (`1 instanceof Math`). Both used to answer `false`, which is `OrdinaryHasInstance`'s
14260    /// rule (its step 2) and not this operator's — so nine `expressions/instanceof` cases
14261    /// expected a `TypeError` and got a value.
14262    pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14263        // Step 1, before any method lookup.
14264        if constructor.as_object().is_none() {
14265            return Err(Signal::Throw(self.make_error(
14266                "TypeError",
14267                "right-hand side of 'instanceof' is not an object",
14268            )));
14269        }
14270        let Value::Object(function) = constructor else {
14271            unreachable!("just checked");
14272        };
14273        // Step 2. A primitive `C` cannot reach here, so `get_property_key` on the object is
14274        // the whole of it.
14275        let key = self.realm.well_known_key(WellKnown::HasInstance);
14276        let method = self.get_property_key(function, &key)?;
14277        if let Some(method) = method
14278            && !matches!(method, Value::Undefined)
14279        {
14280            let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
14281            return Ok(answer.to_boolean());
14282        }
14283        // Step 4.
14284        if !function.is_callable() {
14285            return Err(Signal::Throw(self.make_error(
14286                "TypeError",
14287                "right-hand side of 'instanceof' is not callable",
14288            )));
14289        }
14290        // Step 5.
14291        self.instance_of(object, constructor)
14292    }
14293
14294    /// `OrdinaryHasInstance`: the prototype walk on its own.
14295    pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14296        self.instance_of(object, constructor)
14297    }
14298
14299    /// `IsArray`: an array, or a proxy whose target is one.
14300    ///
14301    /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
14302    /// makes `Array.isArray(new Proxy([], {}))` true.
14303    pub fn is_array_value(&self, value: &Value) -> bool {
14304        match value {
14305            Value::Object(object) => {
14306                if let Some(state) = object.proxy_state() {
14307                    return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
14308                }
14309                object.is_array()
14310            }
14311            _ => false,
14312        }
14313    }
14314
14315    /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
14316    ///
14317    /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
14318    /// in a Rust closure would hide GC values from the collector. A host-supplied job is
14319    /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
14320    /// see [`Interp::enqueue_job_function`].
14321    pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
14322        // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
14323        // the handler is reported rather than lost — the same reason a `then` reaction needs a
14324        // promise to settle.
14325        let promise = self.new_promise();
14326        self.fulfill_promise(&promise, Value::Undefined);
14327        self.jobs.push_back(Job::Reaction {
14328            handler: Some(function),
14329            argument: Value::Undefined,
14330            rejected: false,
14331            promise,
14332        });
14333        Ok(())
14334    }
14335
14336    /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
14337    ///
14338    /// Four of its steps were missing or wrong, and each one is a test262 case in
14339    /// `Function/prototype/Symbol.hasInstance/`:
14340    ///
14341    /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
14342    /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
14343    ///   `[[BoundThis]]` standing in for the object when that is an object), which is why
14344    ///   `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
14345    ///   `prototype` of its own, so without this step the walk below gives `false`;
14346    /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
14347    /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
14348    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14349        let Value::Object(function) = constructor else {
14350            return Ok(false);
14351        };
14352        if !function.is_callable() {
14353            return Ok(false);
14354        }
14355        // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
14356        // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
14357        // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
14358        if let Some((target, this)) = function.bound_target_and_this() {
14359            let object = if this.as_object().is_some() {
14360                this
14361            } else {
14362                object.clone()
14363            };
14364            return self.instance_of(&object, &target);
14365        }
14366        let Value::Object(target) = object else {
14367            return Ok(false);
14368        };
14369        let prototype = self.get_property(function, "prototype")?;
14370        let Some(Value::Object(prototype)) = prototype else {
14371            return Err(Signal::Throw(self.make_error(
14372                "TypeError",
14373                "function has non-object prototype in instanceof check",
14374            )));
14375        };
14376        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
14377        // which is also what makes `proxyOfInstance instanceof C` work.
14378        let mut current = Some(target.clone());
14379        while let Some(object) = current {
14380            if object.ptr_eq(&prototype) {
14381                return Ok(true);
14382            }
14383            current = self.object_prototype_of(&object)?;
14384        }
14385        Ok(false)
14386    }
14387
14388    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
14389    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
14390        if let Some(proto) = self.proxy_get_prototype_of(object)? {
14391            return Ok(proto);
14392        }
14393        if let Some(exotic) = object.exotic()
14394            && let Some(proto) = exotic.get_prototype(self, object)?
14395        {
14396            return Ok(proto);
14397        }
14398        Ok(object.proto())
14399    }
14400
14401    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
14402    pub fn object_set_prototype_of(
14403        &mut self,
14404        object: &Gc<JsObject>,
14405        proto: Option<Gc<JsObject>>,
14406    ) -> JsResult<bool> {
14407        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
14408            return Ok(answer);
14409        }
14410        if let Some(exotic) = object.exotic()
14411            && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
14412        {
14413            return Ok(answer);
14414        }
14415        // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
14416        // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
14417        // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
14418        // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
14419        if self
14420            .internal_get(object, "_immutable_proto")
14421            .is_some_and(|flag| flag.to_boolean())
14422            && !same_proto(object.proto().as_ref(), proto.as_ref())
14423        {
14424            return Ok(false);
14425        }
14426        // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
14427        // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
14428        // inheriting from itself, which every later prototype walk then had to defend
14429        // against — and `Reflect.setPrototypeOf` reported success for an operation the
14430        // language says is impossible.
14431        if let Some(proto) = &proto {
14432            let mut current = Some(proto.clone());
14433            let mut guard = 0;
14434            while let Some(node) = current {
14435                if node.ptr_eq(object) {
14436                    // §10.1.2.1 step 5.a: a cycle is `return false`, not a throw —
14437                    // `Object.setPrototypeOf` turns that `false` into the `TypeError`,
14438                    // while `Reflect.setPrototypeOf` reports it
14439                    // (`setPrototypeOf/return-false-if-target-is-prototype-of-proto`).
14440                    return Ok(false);
14441                }
14442                guard += 1;
14443                if guard > 1000 {
14444                    break;
14445                }
14446                current = node.proto();
14447            }
14448        }
14449        // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
14450        // re-setting it to the *same* one is a no-op `true`. Missing this made
14451        // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
14452        // actually reparent the object — and it is what
14453        // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
14454        // forwarding path has nothing else left to refuse it.
14455        if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
14456            return Ok(false);
14457        }
14458        object.set_proto(proto);
14459        Ok(true)
14460    }
14461
14462    /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
14463    ///
14464    /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
14465    /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
14466    /// already one.
14467    /// `HasProperty(O, P)`.
14468    ///
14469    /// One implementation, shared with the `in` operator. It used to be a second copy that
14470    /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
14471    /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
14472    /// proxy ran the wrong hook and could even disagree with `in`. The
14473    /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
14474    /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
14475    pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
14476        self.has_own_or_inherited(object, key)
14477    }
14478
14479    /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
14480    ///
14481    /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
14482    /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
14483    /// boolean as well, and it needs the receiver to be the one the caller named.
14484    pub fn set_property_with_key_receiver(
14485        &mut self,
14486        object: &Gc<JsObject>,
14487        key: &PropertyKey,
14488        value: Value,
14489        receiver: Option<&Value>,
14490        on_failure: DeleteFailure,
14491    ) -> JsResult<bool> {
14492        let receiver = receiver
14493            .cloned()
14494            .unwrap_or_else(|| Value::Object(object.clone()));
14495        if object.proxy_state().is_some() {
14496            return match self.proxy_set(object, key, value, &receiver)? {
14497                Some(accepted) => Ok(accepted),
14498                None => Ok(true),
14499            };
14500        }
14501        // §10.4.6.7: a module namespace's `[[Set]]` always answers false, whatever the
14502        // receiver. This has to be answered here as well as in the storing path below,
14503        // because `Reflect.set` reports the refusal as a `bool` instead of raising.
14504        if object.module_namespace_marker() {
14505            return Ok(false);
14506        }
14507        // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
14508        // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
14509        // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
14510        // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
14511        //
14512        // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
14513        //
14514        // * `SameValue(O, Receiver)` stores into the buffer, converting first;
14515        // * an *invalid* index with a different receiver answers `true` and does nothing,
14516        //   not even converting `V` (`valueOfCalls` stays 0);
14517        // * a valid index with a different receiver falls through to
14518        //   `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
14519        //   value lands on the **receiver**, unconverted, and can be refused by a
14520        //   non-extensible receiver, an accessor, or a read-only index there.
14521        //
14522        // The last one used to write into the view itself, which left `target[0]` changed
14523        // and `receiver[0]` untouched — backwards.
14524        if object.typed_array_element_type().is_some()
14525            && let Some(numeric) = canonical_numeric_index(key)
14526        {
14527            let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14528            if same {
14529                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14530                return Ok(true);
14531            }
14532            if !typed_array_index_is_valid(object, numeric) {
14533                return Ok(true);
14534            }
14535            let Some(receiver) = receiver.as_object().cloned() else {
14536                return Ok(false);
14537            };
14538            if let Some(existing) = self.object_get_own_property(&receiver, key)? {
14539                if existing.is_accessor() || !existing.writable {
14540                    return Ok(false);
14541                }
14542                let property = Property {
14543                    value: Some(value),
14544                    ..existing
14545                };
14546                return self.object_define_own_property(&receiver, key, property);
14547            }
14548            return self.object_define_own_property(&receiver, key, Property::data(value));
14549        }
14550        // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
14551        // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
14552        // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
14553        // `Reflect.set` to *report* the refusal instead of raising.
14554        //
14555        // A receiver that is not the object turns the whole operation into
14556        // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
14557        // `[[Set]]` rather than a lookup — that is what makes
14558        // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
14559        // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
14560        // writes to `object`, so it cannot express that and is only used when the two are
14561        // the same.
14562        let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14563        if !same {
14564            return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
14565        }
14566        // Same receiver: the plain path below writes into `object`, which is right, but it
14567        // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
14568        // boolean, so the two step-1 refusals have to be read off the own descriptor here.
14569        if let Some(existing) = self.object_get_own_property(object, key)? {
14570            if existing.is_accessor() {
14571                return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
14572                    Some(setter) => {
14573                        self.call_value(setter, receiver, vec![value])?;
14574                        Ok(true)
14575                    }
14576                    None => Ok(false),
14577                };
14578            }
14579            if !existing.writable {
14580                return Ok(false);
14581            }
14582        }
14583        // Otherwise it is an ordinary create-or-write into `object` itself.
14584        self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14585        Ok(true)
14586    }
14587
14588    /// `[[IsExtensible]]`, with the proxy trap when there is one.
14589    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14590        if let Some(answer) = self.proxy_is_extensible(object)? {
14591            return Ok(answer);
14592        }
14593        if let Some(exotic) = object.exotic()
14594            && let Some(answer) = exotic.is_extensible(self, object)?
14595        {
14596            return Ok(answer);
14597        }
14598        Ok(object.is_extensible())
14599    }
14600
14601    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
14602    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14603        if let Some(answer) = self.proxy_prevent_extensions(object)? {
14604            return Ok(answer);
14605        }
14606        // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
14607        //
14608        // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
14609        //
14610        // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
14611        // created with an explicit length, because the buffer can still move it. That is
14612        // what makes `Object.freeze` refuse every such view, including a zero-length one
14613        // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
14614        // plain buffer is allowed.
14615        if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
14616            && buffer
14617                .array_buffer_storage()
14618                .is_some_and(|storage| storage.borrow().is_resizable())
14619        {
14620            return Err(
14621                self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
14622            );
14623        }
14624        if let Some(exotic) = object.exotic()
14625            && let Some(answer) = exotic.prevent_extensions(self, object)?
14626        {
14627            return Ok(answer);
14628        }
14629        object.set_extensible(false);
14630        Ok(true)
14631    }
14632
14633    fn copy_properties(
14634        &mut self,
14635        target: &Value,
14636        source: &Value,
14637        exclusion: &Value,
14638    ) -> JsResult<()> {
14639        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
14640        // does contribute: its index properties are own, enumerable and writable, which
14641        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
14642        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
14643        // is a no-op.
14644        let Some(target) = target.as_object() else {
14645            return Ok(());
14646        };
14647        let source_object = match source {
14648            Value::Object(object) => object.clone(),
14649            Value::String(text) => {
14650                // Untaken keys are the string's indices, which are code units.
14651                for index in 0..text.utf16_len() {
14652                    if let Some(unit) = text.wtf8().unit_at(index) {
14653                        target.define_data(&index.to_string(), self.string_wtf8(unit));
14654                    }
14655                }
14656                return Ok(());
14657            }
14658            _ => return Ok(()),
14659        };
14660        // An object *rest* element passes the keys already taken by the literal part as
14661        // an array of **key values**; a spread passes `null`, which excludes nothing. The
14662        // array is read by its elements rather than by its own property names, and the
14663        // values stay `PropertyKey`s: a computed key can be a symbol, and
14664        // `{[sym]: a, ...rest}` has to leave `sym` out of `rest`
14665        // (`object-rest-proxy-gopd-not-called-on-excluded-keys`). Flattening them to
14666        // strings made a symbol exclusion a no-op.
14667        let mut excluded: Vec<PropertyKey> = Vec::new();
14668        if let Value::Object(list) = exclusion
14669            && let Some(length) = list.array_length()
14670        {
14671            for index in 0..length {
14672                if let Some(value) = list.array_get(index) {
14673                    excluded.push(self.propkey(&value)?);
14674                }
14675            }
14676        }
14677        let source = &source_object;
14678        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
14679        // Reading the property table directly made every spread of a proxy empty.
14680        let keys = self.object_own_property_keys(source)?;
14681        for as_key in keys {
14682            // §7.3.25 step 4 walks `[[OwnPropertyKeys]]`, so **symbol**-keyed properties
14683            // are copied as well — `{...{[Symbol("s")]: 1}}` has one own symbol key.
14684            // Skipping them silently lost every symbol on every spread and every object
14685            // rest element (`obj-rest-order`).
14686            //
14687            if excluded.contains(&as_key) {
14688                continue;
14689            }
14690            let enumerable = self
14691                .object_get_own_property(source, &as_key)?
14692                .is_some_and(|property| property.enumerable);
14693            if !enumerable {
14694                continue;
14695            }
14696            let value = self
14697                .get_property_key(source, &as_key)?
14698                .unwrap_or(Value::Undefined);
14699            target.define_data_key(&as_key, value);
14700        }
14701        Ok(())
14702    }
14703
14704    // -- iteration ---------------------------------------------------------
14705
14706    /// One object's own keys in enumeration order: array indices ascending, then the
14707    /// rest in insertion order.
14708    ///
14709    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
14710    /// whether the key is enumerable, which the caller resolves per key because an
14711    /// array's elements are not in the same store as its named properties.
14712    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
14713        // An index can arrive twice, once from the array's element store and once from
14714        // its property map, so the numeric keys go through a map that keeps the
14715        // enumerable answer if either source gave one.
14716        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
14717        for (key, enumerable) in &own {
14718            if let Some(index) = key.as_str().and_then(array_index) {
14719                let entry = numeric.entry(index).or_insert(false);
14720                *entry = *entry || *enumerable;
14721            }
14722        }
14723        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
14724            .into_iter()
14725            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
14726            .collect();
14727        ordered.extend(
14728            own.into_iter()
14729                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
14730        );
14731        ordered
14732    }
14733
14734    /// Build the key list a `for-in` loop walks.
14735    ///
14736    /// The order is the specification's: own properties before inherited ones, and
14737    /// within one object the integer-like keys in ascending numeric order ahead of the
14738    /// string keys in insertion order. A shadowed key only appears once, and a key that
14739    /// is a non-enumerable own property anywhere nearer is skipped entirely.
14740    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
14741        let record = self.new_object(None);
14742        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
14743        // A proxy supplies its own key list, and — the reason this is not just another
14744        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
14745        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
14746        // descriptor there.
14747        if let Value::Object(object) = value
14748            && object.proxy_state().is_some()
14749        {
14750            let own = self
14751                .proxy_own_keys(object)?
14752                .unwrap_or_else(|| object.own_property_keys());
14753            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
14754            let mut numeric: Vec<u32> = Vec::new();
14755            let mut rest: Vec<PropertyKey> = Vec::new();
14756            for key in own {
14757                match key.as_str().and_then(array_index) {
14758                    Some(index) => numeric.push(index),
14759                    None => rest.push(key),
14760                }
14761            }
14762            numeric.sort_unstable();
14763            ordered.extend(
14764                numeric
14765                    .into_iter()
14766                    .map(|index| PropertyKey::from(index.to_string())),
14767            );
14768            ordered.extend(rest);
14769            for (index, key) in ordered.into_iter().enumerate() {
14770                record.define_data(&index.to_string(), self.key_value(&key));
14771            }
14772            record.define_data("__index", Value::Int(0));
14773            // The mark that makes `for_in_advance` re-ask the proxy per key.
14774            record.define_data("__proxy", Value::Object(object.clone()));
14775            return Ok(record);
14776        }
14777        if let Value::Object(object) = value {
14778            let mut chain = vec![object.clone()];
14779            chain.extend(object.chain());
14780            // Every own string key the walk has seen, enumerable or not. A
14781            // non-enumerable own property still hides a same-named enumerable one
14782            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
14783            // keeps `x` out of the loop even when the prototype has one.
14784            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
14785            for object in chain {
14786                let mut own: Vec<(crate::value::Wtf8, bool)> = object
14787                    .own_property_keys()
14788                    .iter()
14789                    .filter_map(|key| key.as_wtf8().cloned())
14790                    .map(|key| {
14791                        let enumerable = object
14792                            .own_property(&key.to_string_lossy())
14793                            .map(|property| property.enumerable)
14794                            .unwrap_or(false);
14795                        (key, enumerable)
14796                    })
14797                    .collect();
14798                if let Some(length) = object.array_length() {
14799                    own.retain(|(key, _)| key.as_str() != Some("length"));
14800                    for index in 0..length {
14801                        // A dense element is enumerable; a **hole** is not there at all —
14802                        // and a hole is also what an index with a recorded descriptor
14803                        // leaves behind, in which case the table entry above already
14804                        // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
14805                        // defines index 0 non-enumerable and `for…in` must skip it).
14806                        if let Some(value) = object.array_get(index)
14807                            && !matches!(value, Value::Hole)
14808                        {
14809                            own.push((crate::value::Wtf8::new(index.to_string()), true));
14810                        }
14811                    }
14812                }
14813                // Integer-like keys come first in ascending order, then the rest in
14814                // insertion order — and the ordering is *per object*, not for the chain
14815                // as a whole: one pass over every collected key lifted a prototype's
14816                // `"4"` above the target's own `x`/`y`, which is not the order
14817                // `for…in` reports.
14818                for (key, enumerable) in Self::order_own_keys(own) {
14819                    if visited.contains(&key) {
14820                        continue;
14821                    }
14822                    visited.push(key.clone());
14823                    if enumerable {
14824                        keys.push(key);
14825                    }
14826                }
14827            }
14828        }
14829        for (index, key) in keys.into_iter().enumerate() {
14830            record.define_data(&index.to_string(), self.string_wtf8(key));
14831        }
14832        record.define_data("__index", Value::Int(0));
14833        Ok(record)
14834    }
14835
14836    /// The next key of a `for…in` record, `None` when the loop is done.
14837    ///
14838    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
14839    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
14840    /// the loop reaches it, so a handler that stops reporting a key partway through drops
14841    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
14842    /// key the handler had already withdrawn.
14843    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
14844        let Value::Object(record) = record else {
14845            return Ok(None);
14846        };
14847        let proxy = record
14848            .own_property("__proxy")
14849            .and_then(|property| property.value);
14850        loop {
14851            let index = record
14852                .own_property("__index")
14853                .and_then(|property| property.value)
14854                .map(|value| value.to_int32())
14855                .unwrap_or(0);
14856            let Some(candidate) = record
14857                .own_property(&index.to_string())
14858                .and_then(|property| property.value)
14859            else {
14860                return Ok(None);
14861            };
14862            record.define_data("__index", Value::Int(index + 1));
14863            let text = candidate.to_js_string();
14864            let Some(Value::Object(proxy)) = &proxy else {
14865                return Ok(Some(text));
14866            };
14867            // The candidate is already a key string here, so the lookup does not need a
14868            // second `ToPropertyKey` conversion.
14869            let key = PropertyKey::from(text.as_str());
14870            let live = match self.proxy_get_own_property(proxy, &key)? {
14871                Some(descriptor) => descriptor,
14872                // Not a proxy after all, or it lost its state: fall back to the target.
14873                None => proxy.own_property_key(&key),
14874            };
14875            if live.is_some_and(|property| property.enumerable) {
14876                return Ok(Some(text));
14877            }
14878            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
14879            // next one.
14880        }
14881    }
14882
14883    /// The iterator for `for-of`: the object and its `next` method.
14884    ///
14885    /// An object that already carries a `next` method is used as it is — that is what
14886    /// `arr.values()` returns — and only arrays and strings get the built-in
14887    /// sequence iterator.
14888    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
14889    ///
14890    /// Callers that must choose between the iterable and the array-like protocol — the
14891    /// typed-array constructor is the main one — need to ask *before* committing to one.
14892    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
14893        let key = self.realm.well_known_key(WellKnown::Iterator);
14894        let method = self.read_field_key(value, &key)?;
14895        if matches!(method, Value::Undefined | Value::Null) {
14896            return Ok(false);
14897        }
14898        if !matches!(&method, Value::Object(object) if object.is_callable()) {
14899            return Err(Signal::Throw(
14900                self.make_error("TypeError", "Symbol.iterator is not callable"),
14901            ));
14902        }
14903        Ok(true)
14904    }
14905
14906    /// Collect everything an iterable yields.
14907    ///
14908    /// The cap is a guard against a generator that never ends: an unbounded collect would
14909    /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
14910    /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
14911    /// `MAX_ARRAY_LIKE` in the `Array` builtins.
14912    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
14913        const MAX_ITEMS: usize = 1 << 24;
14914        let iterator = self.get_iterator(value)?;
14915        let mut out = Vec::new();
14916        loop {
14917            let (element, done) = self.iterator_step(&iterator)?;
14918            if done {
14919                return Ok(out);
14920            }
14921            out.push(element);
14922            if out.len() > MAX_ITEMS {
14923                // Close before refusing: the walk is being abandoned, so the iterator's
14924                // `return` has to run (§7.4.6). Leaving it open left a `finally` block
14925                // unrun and a locked resource unreleased.
14926                self.close_iterator_after_throw(&iterator)?;
14927                return Err(self.range_error("iterable is too long to collect"));
14928            }
14929        }
14930    }
14931
14932    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
14933    ///
14934    /// A native constructor calls this once it has validated its arguments, which is the
14935    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
14936    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
14937    /// never reached. The prototype comes from `new.target` when it is an object, and from
14938    /// `default_proto` otherwise.
14939    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14940        let proto = self.ctor_prototype(default_proto)?;
14941        Ok(self.new_object(Some(proto)))
14942    }
14943
14944    /// An **array** whose prototype comes from `new.target`.
14945    ///
14946    /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
14947    /// instance from `new.target.prototype`, and building a plain array instead made every
14948    /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
14949    pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
14950        let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
14951        Ok(JsObject::array(self.heap, Some(proto), 0))
14952    }
14953
14954    /// `new.target.prototype` when this is a construction, or `None` for a plain call.
14955    ///
14956    /// The `Option` form is for the constructors that build their instance in a helper which
14957    /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
14958    /// from `await`'s internal promise, and only the first has a `new.target`.
14959    fn ctor_prototype_opt(
14960        &mut self,
14961        default_proto: Option<Gc<JsObject>>,
14962    ) -> JsResult<Option<Gc<JsObject>>> {
14963        // `active_new_target`: by the time a native constructor runs, `call_value` has
14964        // already consumed the parked value.
14965        let Some(target) = self
14966            .active_new_target
14967            .as_object()
14968            .cloned()
14969            .map(Value::Object)
14970        else {
14971            return Ok(default_proto);
14972        };
14973        let Some(target) = target.as_object().cloned() else {
14974            return Ok(default_proto);
14975        };
14976        match self.get_property(&target, "prototype")? {
14977            Some(Value::Object(proto)) => Ok(Some(proto)),
14978            _ => Ok(default_proto),
14979        }
14980    }
14981
14982    /// `new.target.prototype`, or `default_proto` when this is a plain call.
14983    fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14984        let Some(target) = self.active_new_target.as_object().cloned() else {
14985            return Ok(default_proto);
14986        };
14987        match self.get_property(&target, "prototype")? {
14988            Some(Value::Object(proto)) => Ok(proto),
14989            _ => Ok(default_proto),
14990        }
14991    }
14992
14993    /// `CreateDataPropertyOrThrow(O, key, value)`.
14994    ///
14995    /// A *definition*, not an assignment. The difference is visible the moment the target
14996    /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
14997    /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
14998    /// replaces the descriptor. It is a `TypeError` only when the definition itself is
14999    /// refused (`configurable: false`).
15000    ///
15001    /// The fast path exists because this is called once per element by `map`, `filter`,
15002    /// `slice` and friends: a plain array with no custom element descriptors and a writable
15003    /// `length` can store straight into its element vector.
15004    pub fn create_data_property_or_throw(
15005        &mut self,
15006        object: &Gc<JsObject>,
15007        index: usize,
15008        value: Value,
15009    ) -> JsResult<()> {
15010        // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
15011        // an array (that is what `Array.isArray` must say), so the element fast path would
15012        // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
15013        // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
15014        // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
15015        // records the exact trap sequence.
15016        if object.proxy_state().is_none()
15017            && object.is_array()
15018            && object.elements_writable()
15019            && !object.has_element_descriptors()
15020            && object.is_extensible()
15021            && object.array_set(self.heap, index, value.clone())
15022        {
15023            return Ok(());
15024        }
15025        let key = PropertyKey::from(index.to_string());
15026        let property = Property {
15027            value: Some(value),
15028            writable: true,
15029            enumerable: true,
15030            configurable: true,
15031            ..Property::default()
15032        };
15033        // `CreateDataProperty` always asks for the default attributes, so it can only ever
15034        // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
15035        // the rest. Checking here rather than inside `object_define_own_property` is
15036        // deliberate: that function receives a fully-populated `Property` and cannot tell
15037        // an omitted attribute from an explicit `false`, so the generic check it would need
15038        // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
15039        // writable property (that cost eight `Object/defineProperty` tests).
15040        if object.proxy_state().is_none()
15041            && let Some(existing) = self.object_get_own_property(object, &key)?
15042            && !existing.configurable
15043        {
15044            return Err(self.type_error("cannot create the property"));
15045        }
15046        if self.object_define_own_property(object, &key, property)? {
15047            return Ok(());
15048        }
15049        Err(self.type_error("cannot create the property"))
15050    }
15051
15052    /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
15053    ///
15054    /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
15055    /// its callers have; this is the same operation for the named properties a built-in
15056    /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
15057    /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
15058    /// `Array.prototype` cannot see it — while `Set` would run that accessor.
15059    pub fn create_named_data_property_or_throw(
15060        &mut self,
15061        object: &Gc<JsObject>,
15062        key: &str,
15063        value: Value,
15064    ) -> JsResult<()> {
15065        let key = PropertyKey::from(key);
15066        let property = Property {
15067            value: Some(value),
15068            writable: true,
15069            enumerable: true,
15070            configurable: true,
15071            ..Property::default()
15072        };
15073        if object.proxy_state().is_none()
15074            && let Some(existing) = self.object_get_own_property(object, &key)?
15075            && !existing.configurable
15076        {
15077            return Err(self.type_error("cannot create the property"));
15078        }
15079        if self.object_define_own_property(object, &key, property)? {
15080            return Ok(());
15081        }
15082        Err(self.type_error("cannot create the property"))
15083    }
15084
15085    /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
15086    ///
15087    /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
15088    /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
15089    /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
15090    /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
15091    /// run user code and both can throw.
15092    pub fn species_constructor(
15093        &mut self,
15094        object: &Gc<JsObject>,
15095        default: Value,
15096    ) -> JsResult<Value> {
15097        let Some(constructor) = self.get_property(object, "constructor")? else {
15098            return Ok(default);
15099        };
15100        let constructor = match constructor {
15101            Value::Undefined => return Ok(default),
15102            Value::Object(constructor) => constructor,
15103            _ => return Err(self.type_error("constructor is not an object")),
15104        };
15105        let key = self.realm.well_known_key(WellKnown::Species);
15106        let species = self.get_property_key(&constructor, &key)?;
15107        match species {
15108            None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
15109            Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
15110            Some(_) => Err(self.type_error("species is not a constructor")),
15111        }
15112    }
15113
15114    /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
15115    ///
15116    /// The result is an array of `length` holes whose prototype comes from
15117    /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
15118    /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
15119    /// is why the `IsArray` check is the first step and not an optimisation.
15120    pub fn array_species_create(
15121        &mut self,
15122        original: &Value,
15123        length: usize,
15124    ) -> JsResult<Gc<JsObject>> {
15125        // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
15126        // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
15127        // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
15128        // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
15129        // `new_array_of_length` (`slice/create-non-array-invalid-len`).
15130        // `ArrayCreate(length)` is only reached when the result is a **plain array of this
15131        // realm** — the species may be a user function that ignores the length entirely, and
15132        // then `2**53 - 1` is not its problem
15133        // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
15134        // a short proxy and expects the copy loop to run).
15135        let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
15136            if length > ARRAY_CREATE_LIMIT {
15137                return Err(interp.range_error("invalid array length"));
15138            }
15139            Ok(interp.new_array_of_length(length))
15140        };
15141        let Some(object) = original.as_object().cloned() else {
15142            return default(self);
15143        };
15144        if !object.is_array() {
15145            return default(self);
15146        }
15147        // A `constructor` that *is* this realm's `Array` means "the default", and skipping
15148        // it here is what keeps `Array.prototype.map` from calling `Array` at all.
15149        let Some(constructor) = self.get_property(&object, "constructor")? else {
15150            return default(self);
15151        };
15152        let species = match constructor {
15153            Value::Undefined => return Ok(self.new_array_of_length(length)),
15154            Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
15155                return default(self);
15156            }
15157            Value::Object(constructor) => {
15158                let key = self.realm.well_known_key(WellKnown::Species);
15159                match self.get_property_key(&constructor, &key)? {
15160                    None | Some(Value::Undefined) | Some(Value::Null) => {
15161                        return default(self);
15162                    }
15163                    Some(species) => species,
15164                }
15165            }
15166            // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
15167            // is a `TypeError`, not "the default". Treating it as the default made
15168            // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
15169            // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
15170            // `concat/create-ctor-non-object` are the same rule three times.
15171            _ => return Err(self.type_error("constructor is not an object")),
15172        };
15173        // `IsConstructor(species)` decides whether step 7 may construct at all; a species
15174        // that is merely callable is the `create-species-non-ctor` case.
15175        if !matches!(&species, Value::Object(object) if object.is_constructor()) {
15176            return Err(self.type_error("species is not a constructor"));
15177        }
15178        // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
15179        // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
15180        // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
15181        let created = self.construct(
15182            species.clone(),
15183            species,
15184            vec![crate::object::length_value(length)],
15185        )?;
15186        let Some(created) = created.as_object().cloned() else {
15187            return Err(self.type_error("species constructor did not answer an object"));
15188        };
15189        // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
15190        // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
15191        // object, and `create-species-with-non-writable-property` asserts exactly that.
15192        // The length is set for the array case; the generic case is the caller's
15193        // `Set(A, "length", …)`.
15194        if created.is_array() {
15195            created.array_set_length(self.heap, length);
15196        }
15197        Ok(created)
15198    }
15199
15200    /// Whether `object` is this realm's `%Array%`.
15201    fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
15202        self.realm
15203            .array_constructor
15204            .as_ref()
15205            .is_some_and(|array| array.ptr_eq(object))
15206    }
15207
15208    /// A fresh `length`-hole array with the intrinsic prototype.
15209    pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
15210        let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
15211        array.array_set_length(self.heap, length);
15212        array
15213    }
15214
15215    /// Whether this call is a construction, i.e. `new.target` is defined.
15216    ///
15217    /// A native constructor receives `this = undefined` (it builds its own instance), so it
15218    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
15219    /// The native function currently executing, if any.
15220    pub fn current_native(&self) -> Option<Gc<JsObject>> {
15221        self.current_native.clone()
15222    }
15223
15224    /// Whether this call is a construction, i.e. `new.target` is defined.
15225    pub fn is_constructing(&self) -> bool {
15226        // `active_new_target`, not `pending_new_target`: the parked value is consumed by
15227        // `call_value` before a native runs, so by the time a constructor body asks, the
15228        // answer is only in the active slot.
15229        matches!(self.active_new_target, Value::Object(_))
15230    }
15231
15232    /// The `TypeError` a constructor too primitive to have a wrapper raises.
15233    ///
15234    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
15235    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
15236    /// happens inside the native function, which is why the trace carries an
15237    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
15238    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
15239    /// constructor`, and an unnamed one reports the leading space of `" is not a
15240    /// constructor"` because the reference formats the empty name as it is.
15241    ///
15242    /// It is also the answer for a `new.target` that cannot be named at all — not a
15243    /// function, or a throwing `name` getter — where the reference falls back to the bare
15244    /// `not a constructor`.
15245    pub fn not_a_constructor_error(&mut self) -> Signal {
15246        let target = self.active_new_target.clone();
15247        self.not_a_constructor_error_for(target)
15248    }
15249
15250    /// The same `TypeError` for an explicit target, for the callers that check
15251    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
15252    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
15253        let target = match target {
15254            Value::Object(target) if target.is_callable() => target,
15255            _ => return self.type_error("not a constructor"),
15256        };
15257        let name = match self.get_property(&target, "name") {
15258            Ok(Some(value)) => value.to_js_string(),
15259            _ => return self.type_error("not a constructor"),
15260        };
15261        self.type_error(format!("{name} is not a constructor"))
15262    }
15263
15264    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
15265    ///
15266    /// True whenever `new.target` is not the callee itself, or when it has no usable
15267    /// `prototype` — the cases where reading the property is observable at all.
15268    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
15269        match &self.active_new_target {
15270            Value::Object(target) => !target.ptr_eq(callee),
15271            Value::Undefined => false,
15272            _ => true,
15273        }
15274    }
15275
15276    /// The symbol key for one of the engine's own hidden slots.
15277    ///
15278    /// Cached on the realm, so every object of a kind shares one key and a slot can be
15279    /// read back by name.
15280    /// Whether any object on `object`'s **prototype chain** owns an array index.
15281    ///
15282    /// The one question the array methods' dense fast paths have to ask before touching the
15283    /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
15284    /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
15285    /// vector an unreliable answer. Walking the chain once per call is cheap because a
15286    /// prototype almost never holds an index.
15287    pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
15288        let mut current = object.proto();
15289        // Bounded, like every other prototype walk here: a proxy can answer a cycle.
15290        for _ in 0..10_000 {
15291            let Some(proto) = current else {
15292                return false;
15293            };
15294            if proto.has_indexed_own_property() {
15295                return true;
15296            }
15297            current = proto.proto();
15298        }
15299        false
15300    }
15301
15302    /// The hidden symbol a named internal slot is keyed by, created on first use.
15303    ///
15304    /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
15305    /// either keeping a table of its own.
15306    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
15307        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
15308            return PropertyKey::Symbol(symbol.clone());
15309        }
15310        let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
15311        self.realm
15312            .internal_slots
15313            .borrow_mut()
15314            .insert(name, Value::Symbol(symbol.clone()));
15315        PropertyKey::Symbol(symbol)
15316    }
15317
15318    /// Read a hidden slot, or `None` when the object has none of that name.
15319    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
15320        let slots = self.realm.internal_slots.borrow();
15321        let Value::Symbol(symbol) = slots.get(name)? else {
15322            return None;
15323        };
15324        object
15325            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
15326            .and_then(|property| property.value)
15327    }
15328
15329    /// Define a hidden slot.
15330    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
15331        let key = self.internal_slot(name);
15332        object.define_key(&key, Property::with_attributes(value, false, false));
15333    }
15334
15335    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
15336    ///
15337    /// The method is looked up on the value (through its prototype), called with no
15338    /// arguments, and its result becomes the iterator. A generator gets here through
15339    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
15340    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
15341    ///
15342    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
15343    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
15344    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
15345    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
15346    /// does, and a user-defined iterable works without a special case.
15347    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
15348    /// `Symbol.iterator`.
15349    ///
15350    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
15351    /// iterable is legal there, and each value it produces is simply already settled by
15352    /// the time the `await` around it runs.
15353    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15354        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
15355        let method = self.read_field_key(value, &async_key)?;
15356        // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
15357        // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
15358        // is *present but not callable* is a TypeError — it does not mean "try the other
15359        // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
15360        // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
15361        // guard is there to catch.
15362        let absent = matches!(method, Value::Undefined | Value::Null);
15363        if !absent {
15364            let Value::Object(object) = &method else {
15365                return Err(Signal::Throw(
15366                    self.make_error("TypeError", "value is not iterable"),
15367                ));
15368            };
15369            if !object.is_callable() {
15370                return Err(Signal::Throw(
15371                    self.make_error("TypeError", "value is not iterable"),
15372                ));
15373            }
15374        }
15375        if absent {
15376            // §7.4.2 step 5: the synchronous iterator is **wrapped**. `for await` and an async
15377            // generator's `yield*` both reach here, and the wrapper is what puts
15378            // `PromiseResolve(%Promise%, value)` between the sync iterator's `value` and the
15379            // caller — a poisoned `constructor` on that value rejects instead of being
15380            // yielded, and a rejection closes the synchronous iterator first.
15381            let sync = self.get_iterator(value)?;
15382            return self.async_from_sync_iterator(sync);
15383        }
15384        let iterator = self.call_value(method, value.clone(), Vec::new())?;
15385        if !matches!(iterator, Value::Object(_)) {
15386            return Err(Signal::Throw(
15387                self.make_error("TypeError", "iterator is not an object"),
15388            ));
15389        }
15390        let next = self.read_field(&iterator, "next")?;
15391        Ok(Iterator {
15392            object: iterator,
15393            next,
15394        })
15395    }
15396
15397    /// `CreateAsyncFromSyncIterator(syncIteratorRecord)` (§27.1.4.1).
15398    ///
15399    /// The wrapper itself is script (see [`crate::builtins::async_from_sync`]); this only
15400    /// hands it the record and reads back its `next`. Both are properties of the wrapper, so
15401    /// the returned [`Iterator`] steps through `%AsyncFromSyncIteratorPrototype%.next`.
15402    fn async_from_sync_iterator(&mut self, sync: Iterator) -> JsResult<Iterator> {
15403        let Some(factory) = self.realm.async_from_sync.clone() else {
15404            // No wrapper installed (a realm whose heap refused to hold it): fall back to the
15405            // raw synchronous iterator rather than refusing to iterate at all.
15406            return Ok(sync);
15407        };
15408        let wrapper = self.call_value(factory, Value::Undefined, vec![sync.object, sync.next])?;
15409        let next = self.read_field(&wrapper, "next")?;
15410        Ok(Iterator {
15411            object: wrapper,
15412            next,
15413        })
15414    }
15415
15416    /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
15417    /// read — `@@iterator` is **not** consulted.
15418    ///
15419    /// The distinction is observable and test262 exercises it: a set-like object's `keys`
15420    /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
15421    /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
15422    /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
15423    /// refused it with "[object Object] is not iterable".
15424    pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
15425        if !matches!(value, Value::Object(_)) {
15426            return Err(self.type_error("iterator is not an object"));
15427        }
15428        let next = self.read_field(&value, "next")?;
15429        Ok(Iterator {
15430            object: value,
15431            next,
15432        })
15433    }
15434
15435    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15436        let key = self.realm.well_known_key(WellKnown::Iterator);
15437        let method = self.read_field_key(value, &key)?;
15438        let Value::Object(function) = &method else {
15439            return Err(Signal::Throw(self.make_error(
15440                "TypeError",
15441                &format!("{} is not iterable", value.to_js_string()),
15442            )));
15443        };
15444        if !function.is_callable() {
15445            return Err(Signal::Throw(self.make_error(
15446                "TypeError",
15447                &format!("{} is not iterable", value.to_js_string()),
15448            )));
15449        }
15450        let iterator = self.call_value(method, value.clone(), Vec::new())?;
15451        // The spec requires an object here; a primitive iterator has no `next` to call
15452        // and would fail one step later with a confusing message.
15453        if !matches!(iterator, Value::Object(_)) {
15454            return Err(Signal::Throw(
15455                self.make_error("TypeError", "iterator is not an object"),
15456            ));
15457        }
15458        let next = self.read_field(&iterator, "next")?;
15459        Ok(Iterator {
15460            object: iterator,
15461            next,
15462        })
15463    }
15464
15465    /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
15466    /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
15467    /// exception from `return` propagates normally instead of being swallowed. That is the
15468    /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
15469    /// because confusing them is exactly the bug both exist to avoid.
15470    pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
15471        let method = self.read_field(&iterator.object, "return")?;
15472        if matches!(method, Value::Undefined | Value::Null) {
15473            return Ok(());
15474        }
15475        if !matches!(&method, Value::Object(object) if object.is_callable()) {
15476            return Err(self.type_error("iterator return is not a function"));
15477        }
15478        self.call_value(method, iterator.object.clone(), Vec::new())?;
15479        Ok(())
15480    }
15481
15482    /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
15483    /// cannot replace it.
15484    fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
15485        let method = self.read_field(&iterator.object, "return")?;
15486        if matches!(method, Value::Undefined | Value::Null) {
15487            return Ok(());
15488        }
15489        if !matches!(&method, Value::Object(object) if object.is_callable()) {
15490            return Err(self.type_error("iterator return is not a function"));
15491        }
15492        self.call_value(method, iterator.object.clone(), Vec::new())?;
15493        Ok(())
15494    }
15495
15496    /// One step of an internal iterator: the value and whether it is exhausted.
15497    /// Replace the iterator slot of an iteration record with `undefined`.
15498    ///
15499    /// `slot` counts values above it, the same convention `for_of_next`'s operand uses. An
15500    /// `undefined` record is what every close path already treats as "nothing to close", so
15501    /// one store both records "this iterator must not be closed" and keeps
15502    /// [`Interp::catch_here`] from calling `return` on an iterator whose `next` threw.
15503    fn clear_iterator_slot(&mut self, slot: usize) {
15504        let frame = self.frame_mut();
15505        let depth = frame.stack.len();
15506        if depth > slot {
15507            frame.stack[depth - 1 - slot] = Value::Undefined;
15508        }
15509    }
15510
15511    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
15512        // §7.4.4 `IteratorNext`: `Call(iteratorRecord.[[NextMethod]], …)` is where a
15513        // non-callable `next` is rejected — **not** `GetIteratorDirect`, which only reads
15514        // the property. The difference is observable: `[ …{}[yield] ] = it` suspends
15515        // before the first step, so an iterator with no `next` still gets its `return`
15516        // called by `it.return()` instead of failing up front
15517        // (`array-rest-iter-rtrn-close-err`).
15518        if let Value::Object(object) = &iterator.next
15519            && object.is_callable()
15520        {
15521            let result =
15522                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
15523            let Some(result) = result.as_object().cloned() else {
15524                return Err(self.type_error("iterator result is not an object"));
15525            };
15526            let done = self
15527                .get_property(&result, "done")?
15528                .is_some_and(|value| value.to_boolean());
15529            // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
15530            // `done` is false. Reading it unconditionally ran a throwing `value` getter on
15531            // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
15532            // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
15533            // made an unrelated `value` getter observable after the loop was over.
15534            if done {
15535                return Ok((Value::Undefined, true));
15536            }
15537            let value = self
15538                .get_property(&result, "value")?
15539                .unwrap_or(Value::Undefined);
15540            return Ok((value, false));
15541        }
15542        // §7.4.4: `next` was read by `GetIteratorDirect` but its callability is only
15543        // tested at the call. Treating a non-callable `next` as "exhausted" instead made
15544        // `Object.fromEntries({[Symbol.iterator]: () => ({next: null})})` succeed with an
15545        // empty object, where §21.1.2.2's `? IteratorStepValue` must throw a `TypeError`.
15546        Err(Signal::Throw(self.make_error(
15547            "TypeError",
15548            "iterator's next method is not callable",
15549        )))
15550    }
15551
15552    /// `[...iterable]`: append everything the iterator yields, and answer the next
15553    /// index.
15554    ///
15555    /// This goes through the same iterator machinery `for-of` uses rather than copying
15556    /// an array's elements, because a spread source is any iterable: a string spreads
15557    /// into its characters and an array iterator spreads into its results. Handling
15558    /// only arrays made `[..."ab"]` come out empty with no error at all.
15559    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
15560        let Some(target) = array.as_object().cloned() else {
15561            return Ok(0);
15562        };
15563        let start = target.array_length().unwrap_or(0);
15564        let mut added = 0;
15565        let iterator = self.get_iterator(iterable)?;
15566        loop {
15567            let (value, done) = self.iterator_step(&iterator)?;
15568            if done {
15569                break;
15570            }
15571            target.array_set(self.heap, start + added, value);
15572            added += 1;
15573        }
15574        Ok((start + added) as i32)
15575    }
15576
15577    /// How an uncaught exception is reported.
15578    ///
15579    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
15580    /// with `ToString` — `js_std_dump_error` is three lines that end in
15581    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
15582    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
15583    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
15584    ///
15585    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
15586    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
15587    /// `toString`"; it does call it, but only for objects of a class it does not know how
15588    /// to walk, and never for errors, arrays or plain objects.
15589    ///
15590    /// A printer that fails must not take the reporter down with it, so that case falls
15591    /// back to the `ToString` rendering.
15592    pub fn describe_exception(&mut self, value: &Value) -> String {
15593        match crate::print::sprint(self, value) {
15594            Ok(text) => text,
15595            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
15596        }
15597    }
15598
15599    /// The file name of whatever is running, innermost frame first.
15600    ///
15601    /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
15602    /// innermost frame's file name, without distinguishing a module body from a plain
15603    /// script. `import()` uses it as the base for a relative specifier, which is why
15604    /// `import('./x.js')` inside a script resolves next to the script and not next to the
15605    /// process's working directory.
15606    pub fn script_or_module_name(&self) -> Option<String> {
15607        self.script_or_module_name_at(0)
15608    }
15609
15610    /// [`Interp::script_or_module_name`] `level` frames further out.
15611    ///
15612    /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
15613    /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
15614    /// frame without a file name is skipped rather than counted, because a native call
15615    /// pushes no frame of its own and so cannot be a level.
15616    pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
15617        self.frames
15618            .iter()
15619            .rev()
15620            .filter_map(|frame| frame.code.code.filename.clone())
15621            .nth(level)
15622    }
15623
15624    /// The innermost frame name that could be a *file*, skipping `<eval>`-style pseudo-names.
15625    ///
15626    /// `eval` and `std.evalScript` compile their bodies under `<input>` / `<evalScript>`
15627    /// because that is what a stack trace should print, but §19.2.1.1's
15628    /// `GetActiveScriptOrModule` makes an eval'd body belong to the script that called it —
15629    /// never to something called `<input>`. Resolving `import('./x.js')` against a pseudo-name
15630    /// produced the bare specifier `x.js`, which the loader then looked for in the working
15631    /// directory instead of beside the file that called `eval`.
15632    pub fn script_or_module_file_name(&self) -> Option<String> {
15633        self.frames.iter().rev().find_map(|frame| {
15634            let name = frame.code.code.filename.as_deref()?;
15635            (!name.starts_with('<')).then(|| name.to_string())
15636        })
15637    }
15638
15639    /// The current call stack, formatted the way `qjs` prints `error.stack`.
15640    ///
15641    /// One `    at name (file:line:col)` line per active frame, innermost first. The
15642    /// position is the one recorded for the instruction each frame is stopped on, which
15643    /// is why the compiler builds a pc-to-position table per function: without it a
15644    /// trace could only name the function, not the line inside it.
15645    ///
15646    /// A frame whose code has no positions prints just `(file)`, matching the
15647    /// reference's output for stripped bytecode.
15648    pub fn stack_trace(&self) -> String {
15649        self.stack_trace_skipping(0)
15650    }
15651
15652    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
15653    fn stack_trace_skipping(&self, skip: usize) -> String {
15654        // One ordered list, innermost first, so `skip` counts the same thing whether the
15655        // frames it leaves out are native or bytecode. Indices rather than references: a
15656        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
15657        let depth = self.frames.len();
15658        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
15659        // A native entered while `at` bytecode frames were live was called *from* the
15660        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
15661        // entered at the current depth are therefore innermost of all.
15662        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
15663            for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
15664                if *at == wanted {
15665                    order.push((true, index));
15666                }
15667            }
15668        };
15669        push_natives(&mut order, depth);
15670        for index in (0..depth).rev() {
15671            order.push((false, index));
15672            push_natives(&mut order, index);
15673        }
15674        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
15675        // barrier. Natives entered at exactly the barrier depth are the eval entry point
15676        // itself (`evalScript (native)`), and the reference leaves those out too.
15677        if let Some(barrier) = self.trace_barriers.last().copied() {
15678            order.retain(|(is_native, index)| match is_native {
15679                true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
15680                false => *index >= barrier,
15681            });
15682        }
15683
15684        let mut out = String::new();
15685        for (is_native, index) in order.into_iter().skip(skip) {
15686            match is_native {
15687                true => {
15688                    out.push_str("    at ");
15689                    let (native, _) = &self.native_frames[index];
15690                    let name = native
15691                        .own_property("name")
15692                        .and_then(|property| property.value)
15693                        .map(|value| value.to_js_string())
15694                        .unwrap_or_default();
15695                    out.push_str(&name);
15696                    out.push_str(" (native)\n");
15697                }
15698                false => {
15699                    let frame = &self.frames[index];
15700                    let code = &frame.code.code;
15701                    let file = code.filename.as_deref().unwrap_or("<input>");
15702                    // The name comes from the function *object*, not from the compiled code:
15703                    // an anonymous function expression is named by the property it is stored
15704                    // in (`{valueOf: function(){}}`), which only the object knows.
15705                    let bound_name = match &frame.callee {
15706                        Value::Object(object) => {
15707                            object
15708                                .own_property("name")
15709                                .and_then(|property| match property.value {
15710                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
15711                                        Some(text.to_string_lossy().into_owned())
15712                                    }
15713                                    _ => None,
15714                                })
15715                        }
15716                        _ => None,
15717                    };
15718                    // No callee object means the body was entered by the host, so the
15719                    // name has to come from the compiled code. Two cases differ:
15720                    //
15721                    // * an *unnamed* function of any kind — the reference reads the
15722                    //   `name` property, finds it empty, and prints `<anonymous>`;
15723                    // * a *module* body, which has no `name` property at all: the
15724                    //   reference builds that function object with `js_closure2` and
15725                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
15726                    //   so a trace reaching it also prints `<anonymous>` — while a
15727                    //   *script* body prints `<eval>`, its `name`.
15728                    let unnamed = code.name.is_empty() || code.module.is_some();
15729                    out.push_str("    at ");
15730                    match bound_name.as_deref() {
15731                        Some(name) => out.push_str(name),
15732                        None if unnamed => out.push_str("<anonymous>"),
15733                        None => out.push_str(&code.name),
15734                    }
15735                    match code.position_at(frame.at as u32) {
15736                        Some((line, column)) => {
15737                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
15738                        }
15739                        None => out.push_str(&format!(" ({file})\n")),
15740                    }
15741                }
15742            }
15743        }
15744        out
15745    }
15746
15747    /// Give an anonymous function the name of the property it is stored in.
15748    ///
15749    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
15750    /// enumerable and not configurable, and a function that already has a real name
15751    /// keeps it.
15752    ///
15753    /// "Already named" means a *non-empty* name: every function object is created with
15754    /// a `name` of `""` so the property exists on all of them, and treating that empty
15755    /// string as a name left every anonymous function nameless — which is how a stack
15756    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
15757    /// `SetFunctionName`, for a name that came from source text.
15758    fn set_function_name(&mut self, function: &Value, name: &str) {
15759        self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
15760    }
15761
15762    /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
15763    /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
15764    fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
15765        let Value::Object(object) = function else {
15766            return;
15767        };
15768        // `SetFunctionName` applies to *functions* and classes only, and only when they are
15769        // anonymous. Without the callability guard, `{value: someObject}` renamed
15770        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
15771        // on the right-hand side of a property. That is how a `zipKeyed` result object
15772        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
15773        // has no `NamedEvaluation` at all.
15774        if !object.is_callable() {
15775            return;
15776        }
15777        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
15778            && !existing.wtf8().is_empty()
15779        {
15780            return;
15781        }
15782        let text = self.string_wtf8(name.clone());
15783        object.define("name", Property::name_or_length(text));
15784    }
15785
15786    // -- global declarations -----------------------------------------------
15787
15788    /// Declare a global binding, creating its reference cell.
15789    /// Declare a `var` or function global, whose home is the global object.
15790    ///
15791    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
15792    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
15793    /// such as `print`, or a redeclaration — is left alone.
15794    pub fn declare_var_global(&mut self, name: &str) {
15795        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
15796        // global object is exactly the leak `typeof my_var === "undefined"` after
15797        // `eval("var my_var=2")` rules out.
15798        if let Some(scope) = self.eval_scope.as_mut() {
15799            scope.entry(name.to_string()).or_insert(Value::Undefined);
15800            return;
15801        }
15802        // A sloppy direct eval declares into its *caller's* variable environment. Doing
15803        // this on the global object instead made `eval("var c = 1")` inside a parameter
15804        // list overwrite a global `c`, and made two calls to the same function share one
15805        // binding.
15806        if let Some(cell) = self.declare_eval_local(name) {
15807            cell.set(Value::Undefined);
15808            return;
15809        }
15810        let global = self.realm.global.clone();
15811        if global.own_property(name).is_some() {
15812            return;
15813        }
15814        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
15815        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
15816        // whole point of that trick and what lets `Object.defineProperty` reshape it
15817        // afterwards. `eval_scope` is `Some` while an eval is running.
15818        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
15819        global.define(
15820            name,
15821            Property {
15822                value: Some(Value::Undefined),
15823                writable: true,
15824                enumerable: true,
15825                configurable: from_eval,
15826                ..Property::default()
15827            },
15828        );
15829    }
15830
15831    /// Declare a *lexical* global binding, which starts in its dead zone.
15832    ///
15833    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
15834    /// global object and is created when its initialiser runs.
15835    pub fn declare_global(&mut self, name: &str, is_const: bool) {
15836        if is_const {
15837            self.realm.lexical_consts.insert(name.to_string());
15838        }
15839        if !self.realm.globals.contains_key(name) {
15840            // `Uninitialized` rather than `Undefined`: the binding exists but is not
15841            // readable until its initialiser runs, and that is what `let x` before
15842            // `x = 1` has to observe.
15843            let cell = self.new_cell(Value::Uninitialized);
15844            self.realm.globals.insert(name.to_string(), cell);
15845            self.realm.declared.push(name.to_string());
15846        }
15847    }
15848}
15849
15850/// The bytecode and environment of a function object, if it is a bytecode function.
15851///
15852/// Extracted before a call so no borrow of the object is held across it.
15853fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
15854    function.with(|data| match &data.kind {
15855        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
15856        _ => None,
15857    })
15858}
15859
15860/// A native call target, extracted before the call so no borrow is held.
15861enum NativeCall {
15862    Native(NativeFn),
15863    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
15864    /// not hold that object's `RefCell` borrow.
15865    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
15866    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
15867    Bound {
15868        target: Value,
15869        this: Value,
15870        leading: Vec<Value>,
15871    },
15872    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
15873    Revoker(crate::object::ProxyRef),
15874    /// A promise's `resolve`.
15875    PromiseResolve(Gc<JsObject>),
15876    /// A promise's `reject`.
15877    PromiseReject(Gc<JsObject>),
15878    /// The executor `NewPromiseCapability(C)` hands a user constructor.
15879    CapabilityExecutor {
15880        state: Gc<JsObject>,
15881    },
15882    /// One leg of a `then` that settles through a user capability.
15883    ThenShim {
15884        handler: Option<Value>,
15885        resolve: Value,
15886        reject: Value,
15887        fulfilled: bool,
15888    },
15889    /// One continuation of an `await`.
15890    AwaitResume {
15891        coroutine: Gc<JsObject>,
15892        promise: Gc<JsObject>,
15893        kind: ResumeKind,
15894    },
15895    /// One element of a `Promise` combinator settling.
15896    CombinatorSettle {
15897        state: Gc<JsObject>,
15898        index: usize,
15899        fulfilled: bool,
15900    },
15901    /// One of `Promise.prototype.finally`'s two shims.
15902    FinallyShim {
15903        callback: Option<Value>,
15904        fulfilled: bool,
15905        constructor: Value,
15906    },
15907    /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
15908    ReturnValue(Value),
15909    /// A thunk that throws a fixed value, for `finally`'s `thrower`.
15910    ThrowValue(Value),
15911    /// Settle a promise with a fixed outcome.
15912    SettlePromise {
15913        promise: Gc<JsObject>,
15914        value: Value,
15915        rejected: bool,
15916    },
15917    /// Continue an async generator after its `await` settled.
15918    GeneratorResume {
15919        generator: Gc<JsObject>,
15920        promise: Gc<JsObject>,
15921        kind: ResumeKind,
15922    },
15923    /// Read a module namespace's binding out of its cell.
15924    ModuleBinding(Gc<Cell>),
15925    /// Finish a completed async generator's `return(v)` once `v` has settled.
15926    CompletedReturn {
15927        generator: Gc<JsObject>,
15928        promise: Gc<JsObject>,
15929        rejected: bool,
15930    },
15931    /// Answer a pending async-generator method with `{value, done}`.
15932    YieldResult {
15933        generator: Gc<JsObject>,
15934        promise: Gc<JsObject>,
15935        done: bool,
15936    },
15937    /// One step of `AsyncDisposableStack.disposeAsync`.
15938    DisposeStep {
15939        remaining: Gc<JsObject>,
15940        promise: Gc<JsObject>,
15941        error: Value,
15942        rejected: bool,
15943        awaited: bool,
15944        needs_await: bool,
15945    },
15946}
15947
15948/// What a store does when the object refuses the write.
15949#[derive(Clone, Copy, PartialEq, Eq)]
15950pub enum DeleteFailure {
15951    /// Raise a `TypeError`, which is what strict mode and every built-in does.
15952    Throw,
15953    /// Ignore the write, which is what a sloppy-mode assignment does.
15954    Ignore,
15955}
15956
15957/// Whether `object` is a `Date` instance, by the class tag it carries.
15958///
15959/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
15960/// builtins module depending on the interpreter's conversion order.
15961fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
15962    interp
15963        .internal_get(object, "_class")
15964        .is_some_and(|value| value.to_js_string() == "Date")
15965}
15966
15967/// Which type `ToPrimitive` prefers when it converts an object.
15968#[derive(Clone, Copy, PartialEq, Eq)]
15969pub enum Hint {
15970    /// The default hint, which behaves like [`Hint::Number`].
15971    Default,
15972    /// `Number(obj)` and the arithmetic operators.
15973    Number,
15974    /// `String(obj)` and `ToPropertyKey`.
15975    String,
15976}
15977
15978/// Which table a binding slot indexes, for the messages that name it.
15979#[derive(Clone, Copy)]
15980enum VarSlot {
15981    Loc,
15982    Closure,
15983}
15984
15985/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
15986fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
15987    Ok(this)
15988}
15989
15990/// An internal iterator: the sequence plus a cursor.
15991pub(crate) struct Iterator {
15992    pub(crate) object: Value,
15993    pub(crate) next: Value,
15994}
15995
15996/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
15997/// and plain `a` for a method.
15998///
15999/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
16000/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
16001/// reads `at get a (file:1:2)`.
16002/// The same prefixing, for a name that may hold an unpaired surrogate.
16003fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
16004    let prefix = match flags & 3 {
16005        1 => "get ",
16006        2 => "set ",
16007        _ => return key.clone(),
16008    };
16009    let mut units: Vec<u16> = prefix.encode_utf16().collect();
16010    units.extend_from_slice(&key.to_units());
16011    crate::value::Wtf8::from_units(&units)
16012}
16013
16014/// `SetFunctionName`'s name for a symbol property key: `[description]`, or `""`.
16015///
16016/// §7.3.24 step 1. A symbol without a description names the function the empty string, not
16017/// `Symbol()` — the two are different and test262 checks both.
16018fn symbol_key_name(key: &PropertyKey) -> crate::value::Wtf8 {
16019    let PropertyKey::Symbol(symbol) = key else {
16020        return crate::value::Wtf8::default();
16021    };
16022    match symbol.description() {
16023        Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
16024        None => crate::value::Wtf8::default(),
16025    }
16026}
16027
16028/// Define a method or accessor property, per the `define_method` flag byte.
16029///
16030/// The low two bits pick value/getter/setter and bit 2 marks the property
16031/// enumerable.
16032///
16033/// A getter and a setter arrive as two separate `define_method` instructions, and the
16034/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
16035/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
16036/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
16037/// `JS_DefineProperty`, which leaves the other half alone.
16038fn define_function_property(
16039    object: &Gc<JsObject>,
16040    key: &PropertyKey,
16041    function: Value,
16042    flags: u32,
16043) -> bool {
16044    let enumerable = flags & 4 != 0;
16045    let kind = flags & 3;
16046    let existing = object.own_property_key(key);
16047    let property = match kind {
16048        1 => Property {
16049            getter: Some(function),
16050            // The setter half, if this literal already defined one.
16051            setter: existing
16052                .filter(Property::is_accessor)
16053                .and_then(|p| p.setter),
16054            enumerable,
16055            configurable: true,
16056            ..Property::default()
16057        },
16058        2 => Property {
16059            getter: existing
16060                .filter(Property::is_accessor)
16061                .and_then(|p| p.getter),
16062            setter: Some(function),
16063            enumerable,
16064            configurable: true,
16065            ..Property::default()
16066        },
16067        _ => Property {
16068            value: Some(function),
16069            writable: true,
16070            enumerable,
16071            configurable: true,
16072            ..Property::default()
16073        },
16074    };
16075    object.create_data_property_key(key, property)
16076}
16077
16078// ---------------------------------------------------------------------------
16079// Operand decoding
16080// ---------------------------------------------------------------------------
16081
16082/// How `print` renders a value: the reference's `JS_PrintValue`.
16083///
16084/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
16085/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
16086/// The format is reproduced closely because the test suite compares output text:
16087///
16088/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
16089/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
16090/// * a cycle prints `[circular N]` with `N` the stack index of the object;
16091/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
16092///   end print as `<N empty item(s)>`;
16093/// * a string is quoted inside a container but raw at the top level, which is why
16094///   `print("x")` and `print(["x"])` differ.
16095pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
16096    // A string argument is printed raw: `js_print` converts it with `ToString`
16097    // instead of dumping it, and the quoting only appears inside a container.
16098    if let Value::String(text) = value {
16099        return text.to_string_lossy().into_owned();
16100    }
16101    let mut printer = Printer {
16102        interp,
16103        out: String::new(),
16104        stack: Vec::new(),
16105    };
16106    printer.value(value, 0);
16107    printer.out
16108}
16109
16110/// The internal class name an object carries, when it has one.
16111fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
16112    interp
16113        .internal_get(object, "_class")
16114        .map(|value| value.to_js_string())
16115}
16116
16117/// A string property, looked up the way `GetProperty` does: own first, then the
16118/// prototype chain. Needed because the print formatter holds the interpreter
16119/// immutably and so cannot run getters.
16120fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
16121    let mut current = Some(object.clone());
16122    // Bounded, because a prototype cycle would otherwise loop forever.
16123    for _ in 0..100 {
16124        let node = current?;
16125        if let Some(property) = node.own_property(name)
16126            && let Some(value) = property.value
16127        {
16128            return Some(value.to_js_string());
16129        }
16130        current = node.with(|data| data.proto.clone());
16131    }
16132    None
16133}
16134
16135/// The `JS_PrintValue` state: output, and the objects currently being printed.
16136struct Printer<'a, 'rt> {
16137    /// Kept for the class-name lookups that typed arrays and `Date` will need.
16138    #[allow(dead_code)]
16139    interp: &'a Interp<'rt>,
16140    out: String,
16141    stack: Vec<Gc<JsObject>>,
16142}
16143
16144impl Printer<'_, '_> {
16145    /// Depth past which a container is summarised by its class name.
16146    const MAX_DEPTH: usize = 2;
16147
16148    fn value(&mut self, value: &Value, level: usize) {
16149        match value {
16150            Value::Undefined
16151            | Value::Uninitialized
16152            | Value::Hole
16153            | Value::CatchOffset(_)
16154            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
16155            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
16156            // The printer writes a bigint the way the language spells one, so a dump is
16157            // unambiguous about which kind of number it is showing.
16158            Value::BigInt(big) => {
16159                self.out.push_str(&big.to_decimal_string());
16160                self.out.push('n');
16161            }
16162            Value::Null => self.out.push_str("null"),
16163            Value::Bool(true) => self.out.push_str("true"),
16164            Value::Bool(false) => self.out.push_str("false"),
16165            Value::Int(number) => self.out.push_str(&number.to_string()),
16166            Value::Float(number) => {
16167                self.out
16168                    .push_str(&crate::value::number_to_string_for_print(*number));
16169            }
16170            Value::String(text) => self.print_string(&text.to_string_lossy()),
16171            Value::Object(object) => self.object(object, level),
16172        }
16173    }
16174
16175    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
16176        // A cycle is reported rather than followed; the index is where the object
16177        // already sits in the print stack, which is what the reference shows.
16178        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
16179            self.out.push_str(&format!("[circular {index}]"));
16180            return;
16181        }
16182        if object.is_callable() {
16183            let name = object
16184                .own_property("name")
16185                .and_then(|property| property.value)
16186                .map(|value| value.to_js_string())
16187                .unwrap_or_default();
16188            if name.is_empty() {
16189                self.out.push_str("[Function (anonymous)]");
16190            } else {
16191                self.out.push_str(&format!("[Function {name}]"));
16192            }
16193            return;
16194        }
16195        if level >= Self::MAX_DEPTH {
16196            let class = if object.is_array() { "Array" } else { "Object" };
16197            self.out.push_str(&format!("[{class}]"));
16198            return;
16199        }
16200        // A `RegExp` prints as its own literal, `js_print_regexp`'s `/%s/%s`. Without this
16201        // it fell through to the plain-object form and `print(/x/)` answered `{  }` — no
16202        // properties, so nothing to show, and the value's identity lost.
16203        if let Some(data) = object.regexp() {
16204            let source = crate::builtins::regexp::escaped_source(&data.source);
16205            self.out.push('/');
16206            self.out.push_str(&source.to_string_lossy());
16207            self.out.push('/');
16208            self.out.push_str(&data.flags);
16209            return;
16210        }
16211        // `Date` and `Error` print as themselves rather than as bags of properties:
16212        // the ISO string, and `Name: message` followed by the trace.
16213        if let Some(class) = class_of(self.interp, object) {
16214            if class == "Date" {
16215                self.date(object);
16216                return;
16217            }
16218            if class == "Error" {
16219                self.error(object);
16220                return;
16221            }
16222        }
16223        self.stack.push(object.clone());
16224        if object.is_array() {
16225            self.array(object, level);
16226        } else {
16227            self.plain_object(object, level);
16228        }
16229        self.stack.pop();
16230    }
16231
16232    /// A Date prints as its ISO string; an invalid one falls through to the plain
16233    /// object form, the way the reference falls back when `toISOString` throws.
16234    fn date(&mut self, object: &Gc<JsObject>) {
16235        let value = self
16236            .interp
16237            .internal_get(object, "_date_value")
16238            .map(|value| value.to_number());
16239        match value.and_then(crate::builtins::date::iso_string) {
16240            Some(text) => self.out.push_str(&text),
16241            None => self.plain_object(object, 0),
16242        }
16243    }
16244
16245    /// `Name: message`, then the trace with its trailing newline removed.
16246    fn error(&mut self, object: &Gc<JsObject>) {
16247        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
16248        self.out.push_str(&name);
16249        if let Some(message) = inherited(object, "message")
16250            && !message.is_empty()
16251        {
16252            self.out.push_str(": ");
16253            self.out.push_str(&message);
16254        }
16255        if let Some(stack) = inherited(object, "stack") {
16256            self.out.push('\n');
16257            self.out.push_str(stack.trim_end_matches('\n'));
16258        }
16259    }
16260
16261    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
16262        let elements = object.array_elements().unwrap_or_default();
16263        self.out.push_str("[ ");
16264        // An interior hole means the array is "sparse": the reference prints those
16265        // as `index: value` pairs and says nothing about the holes themselves, while
16266        // a hole run at the end becomes a single `<N empty items>` note.
16267        let last_present = elements
16268            .iter()
16269            .rposition(|value| !matches!(value, Value::Hole));
16270        let has_interior_hole = match last_present {
16271            Some(last) => elements[..last]
16272                .iter()
16273                .any(|value| matches!(value, Value::Hole)),
16274            None => false,
16275        };
16276        let mut first = true;
16277        if has_interior_hole {
16278            let mut index = 0;
16279            while index < elements.len() {
16280                let value = &elements[index];
16281                if matches!(value, Value::Hole) {
16282                    index += 1;
16283                    continue;
16284                }
16285                if !first {
16286                    self.out.push_str(", ");
16287                }
16288                first = false;
16289                self.out.push_str(&format!("{index}: "));
16290                self.value(value, level + 1);
16291                index += 1;
16292            }
16293        } else {
16294            for (index, value) in elements.iter().enumerate() {
16295                if matches!(value, Value::Hole) {
16296                    continue;
16297                }
16298                if !first {
16299                    self.out.push_str(", ");
16300                }
16301                first = false;
16302                let _ = index;
16303                self.value(value, level + 1);
16304            }
16305            if let Some(last) = last_present {
16306                let trailing = elements.len() - last - 1;
16307                if trailing > 0 {
16308                    if !first {
16309                        self.out.push_str(", ");
16310                    }
16311                    self.out.push_str(&format!(
16312                        "<{trailing} empty item{}>",
16313                        if trailing > 1 { "s" } else { "" }
16314                    ));
16315                }
16316            } else if !elements.is_empty() {
16317                let count = elements.len();
16318                self.out.push_str(&format!(
16319                    "<{count} empty item{}>",
16320                    if count > 1 { "s" } else { "" }
16321                ));
16322            }
16323        }
16324        self.out.push_str(" ]");
16325    }
16326
16327    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
16328        self.out.push_str("{ ");
16329        let mut first = true;
16330        for key in object.own_keys() {
16331            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
16332                continue;
16333            };
16334            if !property.enumerable {
16335                continue;
16336            }
16337            if !first {
16338                self.out.push_str(", ");
16339            }
16340            first = false;
16341            self.out
16342                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
16343                    &key.to_string_lossy(),
16344                )));
16345            self.out.push_str(": ");
16346            // An accessor has no value to dump; the reference names the half that
16347            // exists instead of calling it.
16348            if property.is_accessor() {
16349                let text = match (property.getter.is_some(), property.setter.is_some()) {
16350                    (true, true) => "[Getter/Setter]",
16351                    (false, true) => "[Setter]",
16352                    _ => "[Getter]",
16353                };
16354                self.out.push_str(text);
16355            } else {
16356                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
16357            }
16358        }
16359        self.out.push_str(" }");
16360    }
16361
16362    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
16363    fn print_string(&mut self, text: &str) {
16364        self.out.push('"');
16365        for character in text.chars() {
16366            match character {
16367                '"' => self.out.push_str("\\\""),
16368                '\\' => self.out.push_str("\\\\"),
16369                '\n' => self.out.push_str("\\n"),
16370                '\r' => self.out.push_str("\\r"),
16371                '\t' => self.out.push_str("\\t"),
16372                c if (c as u32) < 0x20 => {
16373                    self.out.push_str(&format!("\\u{:04x}", c as u32));
16374                }
16375                c => self.out.push(c),
16376            }
16377        }
16378        self.out.push('"');
16379    }
16380}
16381
16382/// How `print` renders a value.
16383///
16384/// `ToString`, except that negative zero keeps its sign — the reference's host
16385/// printer does that while `String(-0)` is `"0"`.
16386pub fn display(value: &Value) -> String {
16387    match value {
16388        Value::Float(number) => crate::value::number_to_string_for_print(*number),
16389        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
16390            "undefined".to_string()
16391        }
16392        other => other.to_js_string(),
16393    }
16394}
16395
16396// ---------------------------------------------------------------------------
16397// Numeric operators
16398// ---------------------------------------------------------------------------
16399
16400/// `a + b` keeping the `Int` representation when it fits.
16401fn add_numbers(left: Value, right: Value) -> Value {
16402    match (&left, &right) {
16403        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
16404            Some(sum) => Value::Int(sum),
16405            None => Value::Float(*a as f64 + *b as f64),
16406        },
16407        _ => Value::Float(left.to_number() + right.to_number()),
16408    }
16409}
16410
16411/// The arithmetic operators other than `+`, which needs string concatenation.
16412fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16413    use Opcode::*;
16414    // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
16415    // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
16416    // *before* the match, so even the arms that never needed `a` or `b` paid for it.
16417    if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
16418        return Ok(match op {
16419            And => Value::Int(x & y),
16420            Or => Value::Int(x | y),
16421            Xor => Value::Int(x ^ y),
16422            Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
16423            Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
16424            Shr => match (*x as u32) >> ((*y as u32) & 31) {
16425                shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
16426                shifted => Value::Float(shifted as f64),
16427            },
16428            Sub => match x.checked_sub(*y) {
16429                Some(value) => Value::Int(value),
16430                None => Value::Float(*x as f64 - *y as f64),
16431            },
16432            _ => return arithmetic_slow(op, left, right),
16433        });
16434    }
16435    arithmetic_slow(op, left, right)
16436}
16437
16438/// [`arithmetic`] for everything the integer fast path above does not take.
16439fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16440    use Opcode::*;
16441    let (a, b) = (left.to_number(), right.to_number());
16442    Ok(match op {
16443        Sub => match (&left, &right) {
16444            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
16445                Some(value) => Value::Int(value),
16446                None => Value::Float(a - b),
16447            },
16448            _ => Value::Float(a - b),
16449        },
16450        Mul => Value::Float(a * b),
16451        Div => Value::Float(a / b),
16452        Mod => Value::Float(js_mod(a, b)),
16453        Pow => Value::Float(a.powf(b)),
16454        And => Value::Int(left.to_int32() & right.to_int32()),
16455        Or => Value::Int(left.to_int32() | right.to_int32()),
16456        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
16457        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
16458        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
16459        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
16460        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
16461        // fits the small-integer representation stays an `Int`; the rest become a
16462        // float, which is how the reference keeps `n >>> 0` non-negative.
16463        Shr => {
16464            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
16465            match i32::try_from(shifted) {
16466                Ok(value) => Value::Int(value),
16467                Err(_) => Value::Float(shifted as f64),
16468            }
16469        }
16470        _ => Value::Float(a),
16471    })
16472}
16473
16474/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
16475///
16476/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
16477/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
16478/// slow path where the rules live.
16479fn is_number(value: &Value) -> bool {
16480    matches!(value, Value::Int(_) | Value::Float(_))
16481}
16482
16483/// The `Value::Bool` a comparison operator answers for `ordering`.
16484///
16485/// `None` is the unordered case — a `NaN` on either side — and every operator answers
16486/// false for it, including `<=` and `>=`.
16487fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
16488    use Opcode::*;
16489    let answer = match (op, ordering) {
16490        (_, None) => false,
16491        (Lt, Some(ordering)) => ordering.is_lt(),
16492        (Lte, Some(ordering)) => ordering.is_le(),
16493        (Gt, Some(ordering)) => ordering.is_gt(),
16494        (Gte, Some(ordering)) => ordering.is_ge(),
16495        _ => false,
16496    };
16497    Value::Bool(answer)
16498}
16499
16500/// `%`, which follows the sign of the dividend rather than Rust's.
16501fn js_mod(left: f64, right: f64) -> f64 {
16502    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
16503        return f64::NAN;
16504    }
16505    if right.is_infinite() {
16506        return left;
16507    }
16508    let remainder = left % right;
16509    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
16510    // the spec makes the sign match the dividend.
16511    if remainder == 0.0 {
16512        0.0f64.copysign(left)
16513    } else {
16514        remainder
16515    }
16516}
16517
16518fn negate(value: Value) -> Value {
16519    match value {
16520        Value::Int(0) => Value::Float(-0.0),
16521        Value::Int(i) => Value::Int(-i),
16522        other => Value::Float(-other.to_number()),
16523    }
16524}
16525
16526fn increment(value: Value) -> Value {
16527    match value {
16528        Value::Int(i) => match i.checked_add(1) {
16529            Some(next) => Value::Int(next),
16530            None => Value::Float(i as f64 + 1.0),
16531        },
16532        other => Value::Float(other.to_number() + 1.0),
16533    }
16534}
16535
16536fn decrement(value: Value) -> Value {
16537    match value {
16538        Value::Int(i) => match i.checked_sub(1) {
16539            Some(next) => Value::Int(next),
16540            None => Value::Float(i as f64 - 1.0),
16541        },
16542        other => Value::Float(other.to_number() - 1.0),
16543    }
16544}
16545
16546/// Compare a `BigInt` with an `f64` on their mathematical values.
16547///
16548/// Neither side is rounded to the other's precision: the number is split into its integer
16549/// part (compared as an exact bigint) and its fraction, which is what decides the answer
16550/// when the integer parts are equal. An infinite value is larger than every bigint.
16551fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
16552    use std::cmp::Ordering;
16553    if number.is_nan() {
16554        return None;
16555    }
16556    if number.is_infinite() {
16557        return Some(if number > 0.0 {
16558            Ordering::Less
16559        } else {
16560            Ordering::Greater
16561        });
16562    }
16563    // The comparison is **exact**, because rounding it is observable: an f64 is
16564    // `m * 2^e` with `m` a 53-bit integer, so scaling the bigint by the same power of two
16565    // turns this into an integer comparison at any width. Converting the *bigint* to f64
16566    // instead — which is what this used to do once the number was wider than `i128` —
16567    // rounds it to the nearest double, and `0xfffffffffffff7ff…n < Number.MAX_VALUE` is
16568    // decided by a difference of one bit at 2^971, which rounding erases
16569    // (`less-than/bigint-and-number-extremes`).
16570    // Both branches answer `big.cmp(number)`; which side gets scaled depends on the sign of
16571    // the exponent, because scaling the smaller one keeps the shift bounded by the f64's own
16572    // range (at most 1074 bits) instead of by the bigint's width.
16573    let (mantissa, exponent) = decompose_f64(number);
16574    let product = crate::bigint::BigInt::from_i64(mantissa);
16575    Some(if exponent >= 0 {
16576        // `number = mantissa * 2^exponent`, and that product is the exact f64 value.
16577        big.cmp(&product.shl(exponent as u64))
16578    } else {
16579        // `number = mantissa / 2^-exponent`; scale the *bigint* up instead so both sides stay
16580        // integers.
16581        big.shl((-exponent) as u64).cmp(&product)
16582    })
16583}
16584
16585/// `value` as `(mantissa, exponent)` with `value == mantissa * 2^exponent` exactly.
16586///
16587/// `mantissa` carries the sign and is the f64's significand with its implicit bit made
16588/// explicit, so `|mantissa| <= 2^53` and the `i64` conversion is exact. `value` must be
16589/// finite.
16590fn decompose_f64(value: f64) -> (i64, i32) {
16591    let bits = value.abs().to_bits();
16592    let raw_exponent = ((bits >> 52) & 0x7ff) as i32;
16593    let fraction = bits & ((1u64 << 52) - 1);
16594    // A subnormal has no implicit bit and an exponent of `1 - 1023`; a normal one carries a
16595    // leading 1 at bit 52, and the `-1075` folds in the bias and the 52 fraction bits.
16596    let (significand, exponent) = if raw_exponent == 0 {
16597        (fraction, -1074)
16598    } else {
16599        (fraction | (1u64 << 52), raw_exponent - 1075)
16600    };
16601    let significand = significand as i64;
16602    let mantissa = if value < 0.0 {
16603        -significand
16604    } else {
16605        significand
16606    };
16607    (mantissa, exponent)
16608}
16609
16610/// The UTF-16 code unit ordering of two strings, which is what `<` compares.
16611///
16612/// `JsString` caches its code units on first access, so the first `code_unit_at` builds the
16613/// cache and the rest are O(1) — no allocation here, and no decoding in the loop.
16614fn compare_code_units(
16615    a: &crate::value::JsString,
16616    b: &crate::value::JsString,
16617) -> std::cmp::Ordering {
16618    let (left, right) = (a.utf16_len(), b.utf16_len());
16619    for index in 0..left.min(right) {
16620        let (x, y) = (
16621            a.code_unit_at(index).unwrap_or(0),
16622            b.code_unit_at(index).unwrap_or(0),
16623        );
16624        if x != y {
16625            return x.cmp(&y);
16626        }
16627    }
16628    // A proper prefix sorts first, which is what the length comparison gives.
16629    left.cmp(&right)
16630}
16631
16632/// `StringToBigInt(argument)` (§7.1.14): the string read as an **integer** literal.
16633///
16634/// `undefined` — `None` here — for anything that is only a *number* literal: `"0."`,
16635/// `".0"`, `"0e0"` and `"Infinity"` all fail, which is why `1n > "0."` is `false` rather
16636/// than `true` (`greater-than/bigint-and-incomparable-string`). Leading zeros are outside
16637/// the grammar too (`"007"`), and so is whitespace between the sign and the digits.
16638///
16639/// The empty string *is* `0n`: §7.1.14 turns a whitespace-only literal into `0`.
16640fn string_to_bigint(text: &str) -> Option<crate::bigint::BigInt> {
16641    let trimmed = text.trim();
16642    let body = trimmed.strip_prefix(['+', '-']).unwrap_or(trimmed);
16643    let signed = body.len() != trimmed.len();
16644    // A radix prefix admits no sign, and the digits must follow immediately.
16645    let (radix, digits) = if let Some(rest) = body.strip_prefix("0x").or(body.strip_prefix("0X")) {
16646        (16, rest)
16647    } else if let Some(rest) = body.strip_prefix("0o").or(body.strip_prefix("0O")) {
16648        (8, rest)
16649    } else if let Some(rest) = body.strip_prefix("0b").or(body.strip_prefix("0B")) {
16650        (2, rest)
16651    } else {
16652        (10, body)
16653    };
16654    if signed && radix != 10 && signed {
16655        // `StrNonDecimalIntegerLiteral` has no sign.
16656        return None;
16657    }
16658    if radix == 10 && digits.len() > 1 && digits.starts_with('0') {
16659        // `StrUnsignedDecimalLiteral : 0 | NonZeroDigit DecimalDigits?`.
16660        return None;
16661    }
16662    crate::bigint::BigInt::from_string(trimmed)
16663}
16664
16665/// `CanonicalNumericIndexString(argument)` (§7.1.21).
16666///
16667/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
16668/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
16669/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
16670/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
16671/// rather than treating it as `0`.
16672fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
16673    let PropertyKey::String(text) = key else {
16674        // A symbol is never an index.
16675        return None;
16676    };
16677    let text = text.to_string_lossy();
16678    if text == "-0" {
16679        return Some(-0.0);
16680    }
16681    let number: f64 = text.parse().ok()?;
16682    // The round-trip test *is* the definition: only the canonical spelling qualifies.
16683    // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
16684    // `"0.10"` does not.
16685    let rendered = Value::Float(number).to_js_string();
16686    (rendered == text).then_some(number)
16687}
16688
16689/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
16690///
16691/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
16692/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
16693/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
16694/// numeric and invalid, which is why they stop the prototype chain instead of falling
16695/// through it.
16696///
16697/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
16698/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
16699/// `in`, `delete` and `defineProperty` separately to make sure it does not.
16700fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
16701    numeric.is_finite()
16702        && numeric.fract() == 0.0
16703        && !(numeric == 0.0 && numeric.is_sign_negative())
16704        && numeric >= 0.0
16705        && object
16706            .typed_array_length()
16707            .is_some_and(|length| (numeric as usize) < length)
16708}
16709
16710/// `ArrayCreate`'s length bound, `2**32 - 1`.
16711///
16712/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
16713/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
16714/// through — can enforce it without depending on a builtin module.
16715const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;