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, RefTarget, array_index, has_own,
27    lookup_key, 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        /// Which phase `import`/`import.defer`/`import.source` asked for.
598        phase: js_parse::ast::ImportPhase,
599    },
600    /// An async generator resuming after the value it awaited settled.
601    GeneratorResume {
602        /// The async generator to continue.
603        generator: Gc<JsObject>,
604        /// The promise the pending method returned.
605        promise: Gc<JsObject>,
606        /// Whether this delivers the value or raises the reason.
607        kind: ResumeKind,
608        /// The settled value, or the rejection reason.
609        value: Value,
610    },
611    /// An async function resuming after the value it awaited settled.
612    Resume {
613        /// The body, parked in a coroutine.
614        coroutine: Gc<JsObject>,
615        /// The promise the async function handed its caller.
616        promise: Gc<JsObject>,
617        /// Whether this resumption delivers a value or raises one.
618        kind: ResumeKind,
619        /// The settled value, or the rejection reason.
620        value: Value,
621    },
622}
623
624/// One macro-task: work the event loop owes the script but has not run yet.
625///
626/// The microtask queue ([`Job`]) is different: those run before the host regains control.
627/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
628/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
629/// logic: the engine decides *what* is due, the host decides *how to wait*.
630///
631/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
632/// reference counting even though nothing else references it — the same rule the `HostFn`
633/// documentation states from the other side (a host closure must not hold a `Gc`, so the
634/// `Gc` lives here instead).
635pub enum Task {
636    /// A `setTimeout` that is due at `due_at`.
637    ///
638    /// There is no `setInterval` variant because the reference has no `os.setInterval` at
639    /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
640    /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
641    /// would give this engine a timer the reference cannot produce, with nothing to
642    /// compare it against.
643    Timer {
644        /// The id `setTimeout` returned, for `clearTimeout`.
645        id: i32,
646        /// What to call when it fires.
647        callback: Value,
648        /// When it becomes runnable, as a monotonic instant.
649        due_at: std::time::Instant,
650    },
651}
652
653/// A descriptor the host has to poll, and which directions have a handler.
654///
655/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
656/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
657/// blocks on it, and the host reports back through [`Interp::fire_fd`].
658#[derive(Debug, Clone, Copy, PartialEq, Eq)]
659pub struct FdInterest {
660    /// The descriptor to watch.
661    pub fd: i32,
662    /// Whether `os.setReadHandler` registered a callback.
663    pub read: bool,
664    /// Whether `os.setWriteHandler` registered a callback.
665    pub write: bool,
666}
667
668/// The callbacks registered for one descriptor, per direction.
669#[derive(Default)]
670pub(crate) struct FdHandlers {
671    /// `os.setReadHandler`'s callback.
672    pub read: Option<Value>,
673    /// `os.setWriteHandler`'s callback.
674    pub write: Option<Value>,
675}
676
677/// The file name `eval` reports, which the reference does not inherit from the caller.
678///
679/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
680/// reference and the names show up in stack traces.
681/// The description of the private symbol a class brand is made from.
682///
683/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
684/// place no script can reach, since no expression can name a private symbol.
685const BRAND_DESCRIPTION: &str = "brand";
686
687/// One validated property lookup.
688///
689/// Covers both own-property hits and prototype hits. The second kind was deliberately left
690/// uncached at first ("a prototype hit depends on more than the object and the name"), and
691/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
692/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
693/// names on every iteration (measured: 100 ns per call over an empty loop).
694pub struct FieldCache {
695    /// The name, so two different properties of one object do not collide.
696    key: PropertyKey,
697    /// Where the value was found, relative to the chain below.
698    index: usize,
699    /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
700    level: u8,
701    /// The receiver and every prototype down to (and including) the level that answered,
702    /// each with the length of its property table at the time.
703    ///
704    /// That length is the whole guard, and it is sufficient for the ways the answer can
705    /// change without a lookup: adding or deleting any property moves it, and a
706    /// same-length rewrite is caught by `cached_data_property` re-checking the key and
707    /// refusing an accessor. Storing the *whole* chain — not just the object that answered
708    /// — is what catches a property appearing on an *intermediate* prototype and shadowing
709    /// the one that was cached.
710    ///
711    /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
712    /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
713    chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
714}
715
716/// How many links of a prototype chain a [`FieldCache`] remembers.
717///
718/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
719/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
720/// at three.
721const MAX_CACHED_CHAIN: usize = 3;
722
723/// A remembered global-variable lookup.
724///
725/// A `var` global is an ordinary property of the global object, so reading one walks the
726/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
727/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
728/// fixed by the bytecode, and the slot in the object's table only changes if the global
729/// object is mutated, which the index-and-name check below catches.
730pub struct GlobalCache {
731    /// The global object the lookup was resolved on, weakly.
732    object: js_gc::WeakGc<JsObject>,
733    /// Index of the data property in the global object's table.
734    index: usize,
735}
736
737/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
738const GLOBAL_CACHE_SLOTS: usize = 1024;
739
740/// How many property lookups are remembered.
741///
742/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
743/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
744/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
745/// lookup itself. Making it bigger stops helping: the working set of a real program's
746/// property sites is bounded by its code size.
747const FIELD_CACHE_SLOTS: usize = 4096;
748
749/// How much the heap may grow past the last `out of memory` before saying it again.
750///
751/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
752/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
753/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
754/// because it looks like it works. The reference gets this for free: it fails inside
755/// `js_malloc`, and its printing path happens not to allocate.
756///
757/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
758/// allocating is stopped within a rounding error of the limit) and far above what a
759/// handler needs.
760const OOM_HYSTERESIS: usize = 64 * 1024;
761
762/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
763pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
764
765/// How many instructions run between polls of [`Interp::interrupt`].
766///
767/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
768/// order of magnitude on both implementations — which is what lets a C driver compare its
769/// output byte for byte (see `scripts/m15-capi.sh --embed`).
770pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
771
772/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
773///
774/// Chosen so that the byte budget is what actually decides for every ordinary
775/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
776/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
777/// millions of frames.
778pub const MAX_FRAMES: usize = 200_000;
779
780const EVAL_FILE: &str = "<input>";
781
782/// The file name `std.evalScript` reports.
783const EVAL_SCRIPT_FILE: &str = "<evalScript>";
784
785/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
786///
787/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
788/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
789fn clamp_delay(delay_ms: f64) -> std::time::Duration {
790    // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
791    // on a float, which reads as a typo even when it is deliberate. Both NaN and a
792    // non-positive delay mean "due now".
793    if delay_ms.is_nan() || delay_ms <= 0.0 {
794        return std::time::Duration::ZERO;
795    }
796    std::time::Duration::from_secs_f64(delay_ms / 1000.0)
797}
798
799impl js_gc::Trace for Task {
800    fn trace(&self, tracer: &mut js_gc::Tracer) {
801        let Task::Timer { callback, .. } = self;
802        callback.trace(tracer);
803    }
804}
805
806/// What one turn of the event loop did, so the caller cannot spin by accident.
807///
808/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
809/// core until the timer is due. Naming the three cases makes the wait explicit.
810#[derive(Debug, Clone, Copy, PartialEq, Eq)]
811pub enum Turn {
812    /// Something ran. Call again immediately — there may be more ready work.
813    Ran,
814    /// Nothing is runnable, but descriptors are registered: the host must poll
815    /// [`Interp::pending_fds`] for at most this long, then report readiness with
816    /// [`Interp::fire_fd`].
817    ///
818    /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
819    /// the failure this project treats as worst — a handler that silently never fires —
820    /// so the two cannot be confused by accident.
821    Poll(std::time::Duration),
822    /// Nothing is runnable yet, but something is pending. Block at most this long, then
823    /// call again.
824    Wait(std::time::Duration),
825    /// Nothing is pending at all: the loop is done.
826    Done,
827}
828
829impl js_gc::Trace for Job {
830    fn trace(&self, tracer: &mut js_gc::Tracer) {
831        match self {
832            Job::Reaction {
833                handler,
834                argument,
835                promise,
836                ..
837            } => {
838                if let Some(handler) = handler {
839                    handler.trace(tracer);
840                }
841                argument.trace(tracer);
842                tracer.visit(promise);
843            }
844            Job::Thenable {
845                then,
846                value,
847                promise,
848            } => {
849                then.trace(tracer);
850                value.trace(tracer);
851                tracer.visit(promise);
852            }
853            Job::Resume {
854                coroutine,
855                promise,
856                value,
857                ..
858            } => {
859                tracer.visit(coroutine);
860                tracer.visit(promise);
861                value.trace(tracer);
862            }
863            Job::Import { promise, .. } => tracer.visit(promise),
864            Job::GeneratorResume {
865                generator,
866                promise,
867                value,
868                ..
869            } => {
870                tracer.visit(generator);
871                tracer.visit(promise);
872                value.trace(tracer);
873            }
874        }
875    }
876}
877
878/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
879#[derive(Debug, Clone, Copy, PartialEq, Eq)]
880pub enum ResumeKind {
881    /// The generator was just created and is being run to its first suspension.
882    Start,
883    /// `next(v)`.
884    Next,
885    /// `return(v)`.
886    Return,
887    /// `throw(e)`.
888    Throw,
889}
890
891/// A generator object's saved execution.
892///
893/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
894/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
895/// separately allocated buffers.
896pub struct GeneratorState {
897    /// The detached frame, or `None` once the generator has finished or while it runs.
898    frame: Option<Frame>,
899    /// How far it got.
900    phase: GeneratorPhase,
901    /// Whether the last suspension was an `await` rather than a `yield`.
902    ///
903    /// The two resume with *different stack shapes*: a `yield` is re-entered with the
904    /// value and a magic number, because the emitted code branches on which method
905    /// resumed it, while an `await` simply continues with its value. Getting this wrong
906    /// leaves an extra value on the operand stack that the next instruction then
907    /// consumes — a wrong answer rather than a crash.
908    parked_on_await: bool,
909    /// Whether the last suspension was a `yield*` rather than a plain `yield`.
910    ///
911    /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
912    /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
913    /// has to be forwarded into the inner iterator's `throw` method instead — which is the
914    /// `rethrow` branch the compiled delegation emits — because that is the whole point of
915    /// delegating. Tracking it as part of the phase, the way the reference splits
916    /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
917    /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
918    /// exception and never reached `xs.throw`.
919    parked_on_yield_star: bool,
920    /// Pending `next`/`return`/`throw` calls, oldest first.
921    ///
922    /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
923    /// called back to back must answer in that order, with the second call's value
924    /// arriving at the *second* `yield`. Running each call straight into the body — which
925    /// is what this engine did before — delivered the last queued value to whichever
926    /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
927    /// `a === b ===` the final argument.
928    ///
929    /// The front entry is the one being served; it stays there (with `async_busy` set)
930    /// until its promise settles, because an `await` inside the body is a suspension of
931    /// the *driver*, not the end of the request.
932    requests: std::collections::VecDeque<AsyncRequest>,
933    /// Whether the front request is in flight.
934    async_busy: bool,
935    /// Whether this came from an `async function*`.
936    ///
937    /// A sync generator and an async one share `ObjectKind::Generator`, so without this
938    /// flag `%AsyncGeneratorPrototype%.next` happily ran a sync generator's body:
939    /// `AsyncGeneratorValidate` has to tell them apart
940    /// (`AsyncGeneratorPrototype/next/this-val-not-async-generator.js`).
941    pub is_async: bool,
942}
943
944/// How one async-generator request ended.
945enum AsyncOutcome {
946    /// The method answered this `{value, done}`.
947    Value(Value),
948    /// The body threw.
949    Error(Value),
950}
951
952/// One queued `next`/`return`/`throw` on an async generator: the reference's
953/// `JSAsyncGeneratorRequest`.
954pub struct AsyncRequest {
955    /// Which method was called.
956    kind: ResumeKind,
957    /// Its argument.
958    value: Value,
959    /// The promise the method answered.
960    promise: Gc<JsObject>,
961}
962
963/// Which of §27.5.3.3's states a generator is in.
964#[derive(Debug, Clone, Copy, PartialEq, Eq)]
965enum GeneratorPhase {
966    /// Created, `initial_yield` reached, body not entered.
967    SuspendedStart,
968    /// Parked at a `yield`.
969    SuspendedYield,
970    /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
971    Executing,
972    /// Finished; the frame is gone.
973    Completed,
974}
975
976impl js_gc::Trace for GeneratorState {
977    fn trace(&self, tracer: &mut js_gc::Tracer) {
978        if let Some(frame) = &self.frame {
979            frame.trace(tracer);
980        }
981        for request in &self.requests {
982            request.value.trace(tracer);
983            tracer.visit(&request.promise);
984        }
985    }
986}
987
988/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
989/// them in.
990///
991/// Each is a field rather than a map entry because the runtime reads them on hot paths
992/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
993/// failure — reaching a default here means the builtin did not install, and every
994/// accessor panics rather than silently answering `undefined`.
995///
996/// [`builtins::symbol`]: crate::builtins::symbol
997#[derive(Default)]
998pub struct WellKnownSymbols {
999    /// The symbol values, positionally. Empty until `Symbol` installs.
1000    symbols: Vec<Value>,
1001}
1002
1003/// Which well-known symbol a caller wants.
1004///
1005/// A typed accessor beats passing a name around: a typo is a compile error rather than
1006/// an `undefined` key that quietly matches nothing.
1007#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1008pub enum WellKnown {
1009    /// `Symbol.toPrimitive`.
1010    ToPrimitive,
1011    /// `Symbol.iterator`.
1012    Iterator,
1013    /// `Symbol.match`.
1014    Match,
1015    /// `Symbol.matchAll`.
1016    MatchAll,
1017    /// `Symbol.replace`.
1018    Replace,
1019    /// `Symbol.search`.
1020    Search,
1021    /// `Symbol.split`.
1022    Split,
1023    /// `Symbol.toStringTag`.
1024    ToStringTag,
1025    /// `Symbol.isConcatSpreadable`.
1026    IsConcatSpreadable,
1027    /// `Symbol.hasInstance`.
1028    HasInstance,
1029    /// `Symbol.species`.
1030    Species,
1031    /// `Symbol.unscopables`.
1032    Unscopables,
1033    /// `Symbol.asyncIterator`.
1034    AsyncIterator,
1035    /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
1036    Disposable,
1037    /// `Symbol.asyncDispose` — the awaited form.
1038    AsyncDisposable,
1039}
1040
1041impl WellKnown {
1042    /// The index `Symbol`'s installer creates this symbol at.
1043    fn index(self) -> usize {
1044        match self {
1045            WellKnown::ToPrimitive => 0,
1046            WellKnown::Iterator => 1,
1047            WellKnown::Match => 2,
1048            WellKnown::MatchAll => 3,
1049            WellKnown::Replace => 4,
1050            WellKnown::Search => 5,
1051            WellKnown::Split => 6,
1052            WellKnown::ToStringTag => 7,
1053            WellKnown::IsConcatSpreadable => 8,
1054            WellKnown::HasInstance => 9,
1055            WellKnown::Species => 10,
1056            WellKnown::Unscopables => 11,
1057            WellKnown::AsyncIterator => 12,
1058            WellKnown::Disposable => 13,
1059            WellKnown::AsyncDisposable => 14,
1060        }
1061    }
1062}
1063
1064impl Realm {
1065    /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1066    pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1067        self.well_known_symbols.symbols = symbols;
1068    }
1069
1070    /// A well-known symbol.
1071    pub fn well_known(&self, which: WellKnown) -> Value {
1072        self.well_known_symbols
1073            .symbols
1074            .get(which.index())
1075            .cloned()
1076            .unwrap_or(Value::Undefined)
1077    }
1078
1079    /// The well-known symbol as a property key.
1080    pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1081        match self.well_known(which) {
1082            Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1083            // Unreachable once `Symbol` has installed; an empty string key matches
1084            // nothing, which degrades to "the object has no such method".
1085            _ => PropertyKey::from(String::new()),
1086        }
1087    }
1088}
1089
1090/// The interpreter: a realm plus a frame stack.
1091pub struct Interp<'a> {
1092    /// The heap everything is allocated on.
1093    pub heap: &'a Heap,
1094    /// The realm.
1095    pub realm: Realm,
1096    /// Active frames, outermost first.
1097    frames: Vec<Frame>,
1098    /// Value buffers from frames that have finished, reused by the next call.
1099    ///
1100    /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1101    /// the locals and the operand stack — and free all four on return. `call:recursion`
1102    /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1103    /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1104    ///
1105    /// Bounded in both directions: a few buffers per kind, and none larger than
1106    /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1107    /// and keeping its buffer would pin that memory for the rest of the run.
1108    free_values: Vec<Vec<Value>>,
1109    /// A strict-mode `eval`'s own variable scope, while its script runs.
1110    ///
1111    /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1112    /// become a global. Name lookups still fall through to the realm, which is why
1113    /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1114    /// A **stack**, innermost last, because evals nest: the inner eval of
1115    /// `eval("var a; eval('a')")` must still see the outer one's `a`, and each strict eval
1116    /// gets a fresh environment of its own layered over the previous.
1117    eval_scope: Vec<BTreeMap<String, Value>>,
1118    /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1119    /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1120    eval_depth: usize,
1121    /// Whether the program currently being compiled is an `eval` body rather than a
1122    /// global script. See [`Compiler::eval_body`].
1123    compiling_eval_body: bool,
1124    /// The calling frame's own bindings, which the running `eval` can read and write.
1125    ///
1126    /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1127    /// come from the frame, and a write is applied back to the frame (or to the cell
1128    /// the frame captured) when the eval finishes. That is what makes
1129    /// `f("a = 3")` visible to the caller as `a === 3`.
1130    eval_bindings: Vec<EvalBinding>,
1131    /// The calling frame's `arguments`, while an `eval` runs.
1132    ///
1133    /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1134    /// own yet still has to see the caller's `arguments`.
1135    eval_arguments: Option<Value>,
1136    /// The `with` objects live at the moment the running `eval` started, innermost first.
1137    ///
1138    /// `None` outside an eval, which is what keeps a finished block's object from
1139    /// shadowing ordinary bytecode reads.
1140    eval_with: Option<Vec<Gc<JsObject>>>,
1141    /// The bindings the running direct `eval` makes visible, as name → cell.
1142    ///
1143    /// Set for the duration of an eval and then restored, but every closure created
1144    /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1145    /// `eval("f = () => i")` work after the eval has returned.
1146    active_eval_scope: Option<Gc<EvalScope>>,
1147    /// The frame that called the direct `eval` currently running, if any.
1148    ///
1149    /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1150    /// on the global object, which is what keeps
1151    /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1152    /// gives each call its own `x`.
1153    eval_caller: Option<Option<usize>>,
1154    /// The caller's `new.target`, while an `eval` runs.
1155    ///
1156    /// The eval'd code is a script with no constructor of its own, so it inherits the
1157    /// one the enclosing function was called with.
1158    eval_new_target: Option<Value>,
1159    /// `new.target` for the frame about to be pushed.
1160    ///
1161    /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1162    /// value reaches the frame without threading a parameter through every call site.
1163    ///
1164    /// A **native** has no frame, so `call_value` takes it the same way and moves it to
1165    /// [`Interp::active_new_target`] for the duration of the call. Without that, a plain
1166    /// `native()` made from inside a constructor body saw the enclosing `new.target` — the
1167    /// value was parked for the outer call and never consumed.
1168    pending_new_target: Option<Value>,
1169    /// `new.target` of the call currently running, for [`Interp::current_new_target`].
1170    ///
1171    /// `undefined` outside a `new` call.
1172    active_new_target: Value,
1173    /// Names of the native functions currently executing, outermost first.
1174    ///
1175    /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1176    /// trace still names it with `(native)` instead of a position, so the names are
1177    /// tracked separately and stitched into [`Interp::stack_trace`].
1178    ///
1179    /// The third field is how many bytecode frames were live when the native was entered,
1180    /// which is what places it *among* them rather than before all of them. Native
1181    /// functions used to be emitted up front on the grounds that they never re-enter
1182    /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1183    /// The natives currently running, innermost last: the function object and the
1184    /// depth it was entered at.
1185    ///
1186    /// The *name* is deliberately not stored. It used to be, read with
1187    /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1188    /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1189    /// benchmark. A stack trace is built rarely; it can read the name then.
1190    native_frames: Vec<(Gc<JsObject>, usize)>,
1191    /// The native function currently executing, for the ones that have to know *which*
1192    /// function they are — a typed-array constructor reads its element type off itself.
1193    ///
1194    /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1195    /// reports whatever the enclosing bytecode frame was called with.
1196    current_native: Option<Gc<JsObject>>,
1197    /// Text written by `print` and friends, in order.
1198    ///
1199    /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1200    /// once at the end, which is also when upstream's line buffering becomes
1201    /// visible for the cases compared here.
1202    pub output: String,
1203    /// Where `print` also writes, as it goes. `output` keeps the full log for
1204    /// [`crate::Context::output`]; this is the live copy, flushed per line.
1205    ///
1206    /// Both exist on purpose. A host that gives a script a sink sees output *when it
1207    /// happens* — which is what a timer callback's `console.log` has to do, and what the
1208    /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1209    /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1210    /// would show a script's output all at once when it finished.
1211    pub output_sink: Option<Box<dyn std::io::Write>>,
1212    /// Where recent property reads found their value.
1213    ///
1214    /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1215    /// table remembering *which object* and *which entry of its property table* answered a
1216    /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1217    /// can move; the property can become an accessor), which is what makes a stale entry a
1218    /// miss rather than a wrong answer.
1219    ///
1220    /// The object is held weakly: a cache that held it strongly would keep up to
1221    /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1222    /// program cannot see and cannot work around.
1223    pub field_cache: Vec<Option<FieldCache>>,
1224    /// Global lookups, by binding slot. See [`GlobalCache`].
1225    global_cache: Vec<Option<GlobalCache>>,
1226    /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1227    /// under its limit. See [`Interp::check_memory`].
1228    pub oom_reported_at: usize,
1229    /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1230    /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1231    ///
1232    /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1233    /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1234    /// host that wants to stop a runaway script must not have to wait for it to return.
1235    ///
1236    /// Two things this cannot do, both of them differences a host can observe:
1237    ///
1238    /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1239    ///   uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1240    ///   needs a signal that the `catch` machinery does not see, which is a change to
1241    ///   [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1242    ///   a host that stops the script itself.
1243    /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1244    ///   also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1245    ///   both, so the difference is when the counter hits zero, not whether it will.
1246    pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1247    /// Instructions until the next [`Interp::interrupt`] poll.
1248    pub interrupt_counter: u32,
1249    /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1250    ///
1251    /// A separate field from [`Interp::uncatchable`] because the two live for different
1252    /// spans. This one is the host's standing request; it survives the start of an
1253    /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1254    /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1255    /// for both was the first attempt and it did nothing at all: the outermost `execute`
1256    /// cleared it before the script it was set for had a chance to throw.
1257    pub uncatchable_next: bool,
1258    /// Whether the exception now unwinding may be caught by a `catch`.
1259    ///
1260    /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1261    /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1262    /// a host stopping a runaway loop is not fought by the loop.
1263    ///
1264    /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1265    /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1266    /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1267    /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1268    pub uncatchable: bool,
1269    /// The most stack a JavaScript call chain may use, in bytes of frame state.
1270    ///
1271    /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1272    /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1273    /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1274    /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1275    /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1276    /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1277    ///
1278    /// The numbers come out close for the same reason a C frame and a heap frame of this
1279    /// shape cost about the same (both are a few hundred bytes, dominated by the value
1280    /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1281    /// and this engine lands in the same neighbourhood — measured, not fudged, by
1282    /// `crates/quickjs-cli/tests/limits.rs`.
1283    pub stack_limit: usize,
1284    /// The most frames that may be live at once, whatever the byte budget says.
1285    ///
1286    /// A second bound for a reason the reference does not have: our frames cost less than
1287    /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1288    /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1289    /// `--stack-size 1G` from being a memory bomb.
1290    pub max_frames: usize,
1291    /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1292    ///
1293    /// Script execution does not return until this has drained, which is what makes
1294    /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1295    /// than never. Reactions append to it while it drains, so the loop is a `while` and
1296    /// not a `for`.
1297    pub(crate) jobs: std::collections::VecDeque<Job>,
1298    /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1299    ///
1300    /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1301    /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1302    pub(crate) tasks: Vec<Task>,
1303    /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1304    /// barrier'd evaluation started.
1305    ///
1306    /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1307    /// lets a REPL report an error from the line it just evaluated without also reporting
1308    /// its own readline loop.
1309    trace_barriers: Vec<usize>,
1310    /// `os.signal` handlers, keyed by signal number.
1311    ///
1312    /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1313    /// a handler cannot be freed while it is still registered.
1314    pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1315    /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1316    ///
1317    /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1318    /// that is only reachable from a host closure could be freed while still registered.
1319    pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1320    /// The next timer id.
1321    ///
1322    /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1323    /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1324    next_timer_id: i32,
1325    /// Errors thrown by timer callbacks, already rendered.
1326    ///
1327    /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1328    /// that throws has no promise behind it. Both are reported by the host at the end of
1329    /// the loop, but only one is fixed up by a later `.catch`.
1330    timer_errors: Vec<String>,
1331    /// The module registry, keyed by canonical name.
1332    pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1333    /// How the host turns a specifier into bytes.
1334    pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1335    /// The module the host was asked to run, for `import.meta.main`.
1336    pub main_module_name: Option<String>,
1337    /// The name to register the *entry* module under, when the host supplies one.
1338    ///
1339    /// The entry's bytes come from a path on disk; this is the name the module graph should
1340    /// know it by. They differ for a host that evaluates a file it did not write — a test
1341    /// runner that prepends a harness, a bundler, a REPL — and getting it wrong is visible:
1342    /// a module importing *itself* resolves the specifier against the real path, finds no
1343    /// record under that name, and loads a second copy with its own bindings.
1344    pub entry_module_name: Option<String>,
1345    /// Module bodies currently running, innermost last.
1346    ///
1347    /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1348    /// this is the only place that knows which module that is.
1349    pub module_stack: Vec<String>,
1350    /// Rejections that no handler has claimed, with the promise they belong to.
1351    ///
1352    /// A `then` registered later prunes its entry, which is why the promise is kept: the
1353    /// reason alone cannot say whether somebody eventually listened.
1354    unhandled: Vec<(Gc<JsObject>, Value)>,
1355}
1356
1357impl<'a> Interp<'a> {
1358    /// Build an interpreter over `heap`, with a fresh realm.
1359    pub fn new(heap: &'a Heap) -> Interp<'a> {
1360        let object_proto = JsObject::ordinary(heap, None);
1361        let function_proto = JsObject::function(
1362            heap,
1363            Some(object_proto.clone()),
1364            Callable::Native {
1365                func: |_, _, _| Ok(Value::Undefined),
1366                own_instance: false,
1367            },
1368        );
1369        let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1370        let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1371        let mut interp = Interp {
1372            heap,
1373            realm: Realm {
1374                global,
1375                object_proto,
1376                function_proto,
1377                array_proto,
1378                array_constructor: None,
1379                promise_constructor: None,
1380                object_proto_to_string: None,
1381                globals: BTreeMap::new(),
1382                declared: Vec::new(),
1383                lexical_consts: BTreeSet::new(),
1384                errors: BTreeMap::new(),
1385                string_proto: None,
1386                number_proto: None,
1387                boolean_proto: None,
1388                bigint_proto: None,
1389                error_proto: JsObject::ordinary(heap, None),
1390                date_proto: JsObject::ordinary(heap, None),
1391                throw_type_error: None,
1392                generator_proto: JsObject::ordinary(heap, None),
1393                promise_proto: None,
1394                async_generator_proto: None,
1395                async_iterator_proto: None,
1396                symbol_proto: None,
1397                symbol_registry: BTreeMap::new(),
1398                internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1399                regexp_proto: None,
1400                regexp_ctor: None,
1401                suppressed_error_proto: None,
1402                disposable_stack_proto: None,
1403                map_proto: None,
1404                set_proto: None,
1405                finalization_registries: Vec::new(),
1406                array_buffer_proto: None,
1407                typed_array_proto: None,
1408                typed_array_protos: Vec::new(),
1409                data_view_proto: None,
1410                async_disposable_stack_proto: None,
1411                async_from_sync: None,
1412                iterator_proto: None,
1413                iterator_ctor: None,
1414                iterator_helper_proto: None,
1415                iterator_wrap_proto: None,
1416                generator_function_proto: None,
1417                async_function_proto: None,
1418                async_generator_function_proto: None,
1419                iterator_protos: std::collections::BTreeMap::new(),
1420                well_known_symbols: WellKnownSymbols::default(),
1421                host_classes: HostClasses::new(),
1422                template_map: std::collections::HashMap::new(),
1423            },
1424            frames: Vec::new(),
1425            free_values: Vec::new(),
1426            global_cache: {
1427                let mut cache = Vec::new();
1428                cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1429                cache
1430            },
1431            eval_scope: Vec::new(),
1432            eval_depth: 0,
1433            compiling_eval_body: false,
1434            eval_bindings: Vec::new(),
1435            eval_arguments: None,
1436            eval_with: None,
1437            active_eval_scope: None,
1438            eval_caller: None,
1439            pending_new_target: None,
1440            active_new_target: Value::Undefined,
1441            eval_new_target: None,
1442            native_frames: Vec::new(),
1443            current_native: None,
1444            output: String::new(),
1445            output_sink: None,
1446            field_cache: {
1447                let mut cache = Vec::new();
1448                cache.resize_with(FIELD_CACHE_SLOTS, || None);
1449                cache
1450            },
1451            oom_reported_at: 0,
1452            interrupt: None,
1453            interrupt_counter: INTERRUPT_POLL_INTERVAL,
1454            uncatchable_next: false,
1455            uncatchable: false,
1456            // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1457            // absent.
1458            stack_limit: DEFAULT_STACK_SIZE,
1459            max_frames: MAX_FRAMES,
1460            jobs: std::collections::VecDeque::new(),
1461            tasks: Vec::new(),
1462            trace_barriers: Vec::new(),
1463            signal_handlers: std::collections::BTreeMap::new(),
1464            fd_handlers: std::collections::BTreeMap::new(),
1465            next_timer_id: 1,
1466            timer_errors: Vec::new(),
1467            modules: std::collections::BTreeMap::new(),
1468            module_loader: None,
1469            main_module_name: None,
1470            entry_module_name: None,
1471            module_stack: Vec::new(),
1472            unhandled: Vec::new(),
1473        };
1474        crate::builtins::install(&mut interp);
1475        interp
1476    }
1477
1478    // -- allocation helpers -------------------------------------------------
1479
1480    /// A new string value.
1481    /// A `BigInt` value from a computed big integer.
1482    pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1483        Value::BigInt(Gc::new(self.heap, value))
1484    }
1485
1486    /// A string value from bytes that are already WTF-8, which is how a string with an
1487    /// unpaired surrogate reaches a `Value`.
1488    pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1489        Value::string_wtf8(self.heap, text)
1490    }
1491
1492    /// A new string value, from text that is valid UTF-8.
1493    pub fn string(&self, text: impl Into<String>) -> Value {
1494        Value::string(self.heap, text)
1495    }
1496
1497    /// A new ordinary object with the given prototype.
1498    pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1499        JsObject::ordinary(self.heap, proto)
1500    }
1501
1502    // -- host classes -------------------------------------------------------
1503
1504    /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1505    pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1506        self.realm.host_classes.register(def)
1507    }
1508
1509    /// Register `def` under an id the host already holds (`JS_NewClass`).
1510    ///
1511    /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1512    /// `JS_NewClass`.
1513    pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1514        self.realm.host_classes.define(id, def)
1515    }
1516
1517    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1518    pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1519        self.realm.host_classes.set_proto(id, proto);
1520    }
1521
1522    /// The prototype installed for `id`, if any.
1523    pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1524        self.realm.host_classes.proto(id)
1525    }
1526
1527    /// A new instance of `id` (`JS_NewObjectProtoClass`).
1528    ///
1529    /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1530    /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1531    /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1532    /// host installed none.
1533    ///
1534    /// Answers `None` for an id that was never registered: the C API would return an
1535    /// exception, and silently making an ordinary object instead would move the failure to
1536    /// the first `JS_GetOpaque` that no longer matches.
1537    pub fn new_host_object(
1538        &mut self,
1539        proto: Option<Gc<JsObject>>,
1540        class_id: ClassId,
1541    ) -> Option<Gc<JsObject>> {
1542        let class = self.realm.host_classes.def(class_id)?;
1543        let proto = proto
1544            .or_else(|| self.realm.host_classes.proto(class_id))
1545            .or_else(|| Some(self.realm.object_proto.clone()));
1546        Some(JsObject::host_object(self.heap, proto, class_id, class))
1547    }
1548
1549    /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1550    ///
1551    /// `None` covers both answers the C API gives as a null pointer — the value is not an
1552    /// object, it is an object of another class, or the class never got a payload. A host
1553    /// that has to tell them apart uses [`JsObject::host_class_id`].
1554    pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1555        let object = value.as_object()?;
1556        if object.host_class_id()? != class_id {
1557            return None;
1558        }
1559        object.host_opaque()
1560    }
1561
1562    /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1563    pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1564        match value.as_object() {
1565            Some(object) => object.set_host_opaque(opaque),
1566            None => false,
1567        }
1568    }
1569
1570    /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1571    ///
1572    /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1573    /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1574    /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1575    /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1576    /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1577    /// said `[object Object]` instead of `[object Array Iterator]`.
1578    ///
1579    /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1580    /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1581    /// its own.
1582    pub fn new_iterator_prototype(
1583        &mut self,
1584        tag: &str,
1585        next: crate::object::NativeFn,
1586    ) -> Gc<JsObject> {
1587        if let Some(existing) = self.realm.iterator_protos.get(tag) {
1588            return existing.clone();
1589        }
1590        let parent = self.realm.iterator_proto.clone();
1591        let proto = self.new_object(parent);
1592        let next = self.new_native("next", 0, next);
1593        proto.define(
1594            "next",
1595            Property::with_attributes(Value::Object(next), true, false),
1596        );
1597        let key = self.realm.well_known_key(WellKnown::Iterator);
1598        let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1599        proto.define_key(
1600            &key,
1601            Property::with_attributes(Value::Object(identity), true, false),
1602        );
1603        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1604        let tag_value = self.string(tag);
1605        // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1606        // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1607        // checks it.
1608        proto.define_key(&tag_key, Property::configurable_only(tag_value));
1609        self.realm
1610            .iterator_protos
1611            .insert(tag.to_string(), proto.clone());
1612        proto
1613    }
1614
1615    /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1616    ///
1617    /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1618    /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1619    /// produced. That is why the two branches are not merged.
1620    pub fn object_own_property_keys(
1621        &mut self,
1622        object: &Gc<JsObject>,
1623    ) -> JsResult<Vec<PropertyKey>> {
1624        if let Some(keys) = self.proxy_own_keys(object)? {
1625            return Ok(keys);
1626        }
1627        // §10.4.6.10 `[[OwnPropertyKeys]]`: the list of a namespace's exports is only
1628        // available once the module is evaluated, so a deferred namespace evaluates here —
1629        // with no symbol-like exemption, because this operation has no key to exempt.
1630        if object.module_namespace_marker() {
1631            self.trigger_deferred_namespace(object)?;
1632        }
1633        // Integer-like keys ascending, then the string keys in insertion order, then the
1634        // symbols — the order every schema that walks an object expects.
1635        let entries = object.property_entries();
1636        let mut numeric: Vec<u32> = Vec::new();
1637        // An integer-indexed exotic object reports its indices as own keys even though they
1638        // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1639        // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1640        // order). The length is asked per call, so a resizable buffer's view reports the
1641        // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1642        if object.typed_array_parts().is_some() {
1643            for index in 0..object.typed_array_length().unwrap_or(0) {
1644                // `u32::try_from` cannot fail for a real length, but the length is a
1645                // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1646                // as an array index and one element beyond is not.
1647                match u32::try_from(index) {
1648                    Ok(index) => numeric.push(index),
1649                    Err(_) => break,
1650                }
1651            }
1652        }
1653        let mut strings: Vec<PropertyKey> = Vec::new();
1654        let mut symbols: Vec<PropertyKey> = Vec::new();
1655        for (key, _) in entries {
1656            match &key {
1657                // A class-private name is never reported by any enumeration: that is the
1658                // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1659                // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1660                // symbol skip, `Object.assign`) therefore cannot see it.
1661                PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1662                PropertyKey::Symbol(_) => symbols.push(key),
1663                PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1664                    Some(index) => {
1665                        if !numeric.contains(&index) {
1666                            numeric.push(index);
1667                        }
1668                    }
1669                    None => strings.push(key),
1670                },
1671            }
1672        }
1673        // An array's `length` is an own property from the moment the array exists, so it
1674        // sits **before** every string key added afterwards — `arr.a = 1; arr.length` lists
1675        // as `["length", "a"]`, not `["a", "length"]`
1676        // (`getOwnPropertyNames/order-after-define-property`). It is synthesised rather
1677        // than stored in the property table, which is why it has to be placed here.
1678        if object.is_array() && object.proxy_state().is_none() {
1679            // Unconditionally: `Object.defineProperty(arr, "length", …)` files `length` in
1680            // the property table, at whatever position the *define* happened, but the key
1681            // lists it as the array's oldest string property because that is what it is.
1682            if let Some(position) = strings
1683                .iter()
1684                .position(|key| key.as_str() == Some("length"))
1685            {
1686                strings.remove(position);
1687            }
1688            strings.insert(0, PropertyKey::from("length"));
1689        }
1690        numeric.sort_unstable();
1691        let mut keys: Vec<PropertyKey> = numeric
1692            .into_iter()
1693            .map(|index| PropertyKey::from(index.to_string()))
1694            .collect();
1695        keys.extend(strings);
1696        keys.extend(symbols);
1697        Ok(keys)
1698    }
1699
1700    /// The state behind a promise object, or `None` when `object` is not one.
1701    pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1702        object.with(|data| match &data.kind {
1703            ObjectKind::Promise(state) => Some(state.clone()),
1704            _ => None,
1705        })
1706    }
1707
1708    /// A new pending promise.
1709    pub fn new_promise(&mut self) -> Gc<JsObject> {
1710        // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1711        // the one place every promise is built, and a subclass that builds its instances
1712        // somewhere else would be invisible to `instanceof`.
1713        let default = self.realm.promise_proto.clone();
1714        // A throwing `new.target.prototype` getter cannot be reported from here — this is
1715        // the raw promise constructor and its result is not `JsResult` — so the rejection is
1716        // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1717        // `prototype` getter therefore still gets a working promise; the alternative is a
1718        // panic, and the throwing path is covered by `Promise`'s own argument validation.
1719        let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1720        Self::make_promise_object(self.heap, proto)
1721    }
1722
1723    /// A promise object with an explicit prototype, and nothing else.
1724    ///
1725    /// Separate from [`Interp::new_promise`] for the callers that have to *report* an abrupt
1726    /// `Get(newTarget, "prototype")` — `new Promise(executor)` is specified as
1727    /// `OrdinaryCreateFromConstructor`, so a throwing `prototype` getter on `new.target` is an
1728    /// exception rather than a reason to fall back (`Promise/get-prototype-abrupt`).
1729    pub fn make_promise_object(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1730        let promise = JsObject::ordinary(heap, proto);
1731        promise.with_mut(|data| {
1732            data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1733                crate::object::PromiseState::default(),
1734            )));
1735        });
1736        promise
1737    }
1738
1739    /// Fulfil `promise`, unless it has already settled.
1740    ///
1741    /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1742    /// after `reject`, changes nothing.
1743    pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1744        let Some(state) = self.promise_state(promise) else {
1745            return;
1746        };
1747        let reactions = {
1748            let mut state = state.borrow_mut();
1749            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1750                return;
1751            }
1752            state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1753            std::mem::take(&mut state.reactions)
1754        };
1755        self.queue_reactions(reactions, value, false);
1756    }
1757
1758    /// Reject `promise`, unless it has already settled.
1759    pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1760        let Some(state) = self.promise_state(promise) else {
1761            return;
1762        };
1763        let reactions = {
1764            let mut state = state.borrow_mut();
1765            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1766                return;
1767            }
1768            state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1769            std::mem::take(&mut state.reactions)
1770        };
1771        // Remember it only when nothing is listening *now*; a `then` registered later
1772        // prunes the entry in `perform_then`.
1773        if reactions.is_empty() {
1774            self.unhandled.push((promise.clone(), reason.clone()));
1775        }
1776        self.queue_reactions(reactions, reason, true);
1777    }
1778
1779    /// Queue one job per reaction.
1780    ///
1781    /// This is what makes `then` asynchronous even on an already-settled promise:
1782    /// `p.then(f); g()` calls `g` first.
1783    fn queue_reactions(
1784        &mut self,
1785        reactions: Vec<crate::object::PromiseReaction>,
1786        argument: Value,
1787        rejected: bool,
1788    ) {
1789        for reaction in reactions {
1790            let handler = if rejected {
1791                reaction.on_rejected.clone()
1792            } else {
1793                reaction.on_fulfilled.clone()
1794            };
1795            self.jobs.push_back(Job::Reaction {
1796                handler,
1797                argument: argument.clone(),
1798                rejected,
1799                promise: reaction.promise,
1800            });
1801        }
1802    }
1803
1804    /// `NewPromiseCapability` as the executor receives it: the promise plus its
1805    /// resolve/reject pair.
1806    ///
1807    /// The pair are callable objects rather than Rust closures, because the script gets
1808    /// them and may stash them for later.
1809    pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1810        let promise = self.new_promise();
1811        // Both handlers are built-ins with an empty name and length 1, in
1812        // `length`-then-`name` order — `reject-function-property-order` reads the order back
1813        // off `Object.getOwnPropertyNames`.
1814        let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1815        let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1816        (promise, Value::Object(resolve), Value::Object(reject))
1817    }
1818
1819    /// §27.2.1.5 `NewPromiseCapability(C)`.
1820    ///
1821    /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1822    /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1823    /// decide what capability it hands back. That is the whole mechanism behind subclassing
1824    /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1825    /// silently ignored argument.
1826    ///
1827    /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1828    /// the engine's own executor is exactly what `new_promise_capability` builds.
1829    pub fn new_promise_capability_for(
1830        &mut self,
1831        constructor: &Value,
1832    ) -> JsResult<(Value, Value, Value)> {
1833        let Some(object) = constructor.as_object().cloned() else {
1834            return Err(self.type_error("promise constructor is not a constructor"));
1835        };
1836        if !object.is_constructor() {
1837            return Err(self.type_error("promise constructor is not a constructor"));
1838        }
1839        if self
1840            .realm
1841            .promise_constructor
1842            .as_ref()
1843            .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1844        {
1845            let (promise, resolve, reject) = self.new_promise_capability();
1846            return Ok((Value::Object(promise), resolve, reject));
1847        }
1848        let state = self.new_object(Some(self.realm.object_proto.clone()));
1849        // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1850        // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1851        // which only a *custom* constructor can observe, and none of the combinator tests
1852        // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1853        let executor = self.builtin_function(
1854            "",
1855            2,
1856            Callable::CapabilityExecutor {
1857                state: state.clone(),
1858            },
1859        );
1860        let promise = self.construct(
1861            Value::Object(object.clone()),
1862            Value::Object(object),
1863            vec![Value::Object(executor)],
1864        )?;
1865        // The pair is read *after* the constructor returns, so a constructor that never
1866        // called its executor, or called it with non-callables, is the spec's step 11
1867        // `TypeError` — not something the engine can paper over.
1868        let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1869            return Err(self.type_error("promise executor never ran"));
1870        };
1871        let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1872            return Err(self.type_error("promise executor never ran"));
1873        };
1874        for handler in [&resolve, &reject] {
1875            if !matches!(handler, Value::Object(object) if object.is_callable()) {
1876                return Err(self.type_error("promise capability handler is not callable"));
1877            }
1878        }
1879        Ok((promise, resolve, reject))
1880    }
1881
1882    /// §27.2.3.1 `PromiseResolve(C, x)`.
1883    ///
1884    /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1885    /// an `x` that is already a promise of exactly this constructor is handed back
1886    /// unchanged, and anything else gets a fresh capability from `C`.
1887    pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1888        if let Value::Object(object) = &value
1889            && self.promise_state(object).is_some()
1890        {
1891            // `x.constructor === C` means "already the right kind", so no capability is
1892            // built — which is observable through a `resolve` that counts its calls.
1893            let x_constructor = self.get_property(object, "constructor")?;
1894            let same = match (
1895                x_constructor.as_ref().and_then(Value::as_object),
1896                constructor.as_object(),
1897            ) {
1898                (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1899                _ => false,
1900            };
1901            if same {
1902                return Ok(value);
1903            }
1904        }
1905        let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1906        // §27.2.4.6 step 5: `? Call(resolve, undefined, «x»)` — an exception from a
1907        // *user* resolve function propagates (`resolve/capability-invocation-error`), while
1908        // the intrinsic one swallows its own self-resolution error.
1909        self.call_value(resolve, Value::Undefined, vec![value])?;
1910        Ok(promise)
1911    }
1912
1913    /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1914    /// promise, as `{ value: completion }`.
1915    ///
1916    /// The three cases are the reference's, and they differ on purpose:
1917    ///
1918    /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1919    ///   exception before any promise exists;
1920    /// * a **runtime** error rejects the returned promise;
1921    /// * success resolves it with `{ value }`, where the value is the script's completion
1922    ///   value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1923    ///   {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1924    ///   `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1925    ///   `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1926    ///
1927    /// # What this does not do
1928    ///
1929    /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1930    /// is evaluated in an async context, so `await` outside a function is legal. That needs
1931    /// the parser and the suspension machinery to accept a suspended top-level script, and
1932    /// is not implemented — such source is a syntax error here. Everything else about the
1933    /// flag is reproduced.
1934    pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1935        // The barrier goes up before compiling: a *parse* failure is reported with a trace
1936        // too, and the reference truncates that one at the same place as a runtime failure.
1937        if barrier {
1938            let depth = self.frames.len();
1939            self.trace_barriers.push(depth);
1940        }
1941        // Compiled before the promise exists, so a parse failure propagates as a throw
1942        // instead of being folded into a rejection.
1943        let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1944            Ok(compiled) => compiled,
1945            Err(error) => {
1946                if barrier {
1947                    self.trace_barriers.pop();
1948                }
1949                return Err(error);
1950            }
1951        };
1952        // An async body answers its own promise, and that promise is what the reference
1953        // hands back — the same object, not a wrapper around it. Its resolution value is
1954        // the `{value}` object the compiled epilogue built.
1955        if compiled.kind.is_async() {
1956            let strict = compiled.strict;
1957            let promise = self.run_eval_script(compiled, strict)?;
1958            if barrier {
1959                self.trace_barriers.pop();
1960            }
1961            return Ok(promise);
1962        }
1963        let (promise, resolve, reject) = self.new_promise_capability();
1964        let strict = compiled.strict;
1965        match self.run_eval_script(compiled, strict) {
1966            Ok(value) => {
1967                // `{ value }` is a plain object, so resolving with it adopts nothing even
1968                // when the completion value is itself a promise.
1969                let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1970                self.set_property(&wrapped, "value", value)?;
1971                self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1972            }
1973            Err(Signal::Throw(error)) => {
1974                self.call_value(reject, Value::Undefined, vec![error])?;
1975            }
1976            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1977        }
1978        if barrier {
1979            self.trace_barriers.pop();
1980        }
1981        Ok(Value::Object(promise))
1982    }
1983
1984    /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1985    ///
1986    /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1987    /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1988    /// timer table, where the collector already scans it.
1989    pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1990        let (promise, resolve, _reject) = self.new_promise_capability();
1991        let resolve = self.new_host_function(
1992            "resolve",
1993            1,
1994            Box::new(
1995                move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1996                    let value = args.first().cloned().unwrap_or(Value::Undefined);
1997                    interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1998                },
1999            ),
2000        );
2001        // The timer keeps the resolver alive: it is a property of the timer entry, and the
2002        // timer table is part of what the collector walks.
2003        self.schedule_timer(Value::Object(resolve), delay_ms);
2004        Ok(Value::Object(promise))
2005    }
2006
2007    /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
2008    /// new promise resolved with it.
2009    pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
2010        if let Value::Object(object) = &value
2011            && self.promise_state(object).is_some()
2012        {
2013            return Ok(value);
2014        }
2015        let promise = self.new_promise();
2016        self.resolve_promise_with(&promise, value)?;
2017        Ok(Value::Object(promise))
2018    }
2019
2020    /// §27.2.4.7 `PromiseResolve(%Promise%, value)`.
2021    ///
2022    /// The difference from [`Interp::promise_resolve_value`] is step 1.a: when `value` is
2023    /// already a promise, its **`constructor` is read**, and only if that is the intrinsic
2024    /// `%Promise%` is `value` returned unchanged. A getter placed on `constructor` is
2025    /// therefore observable — which is exactly what
2026    /// `AsyncGeneratorPrototype/return/return-*-broken-promise*.js` use to check that the
2027    /// `AsyncGeneratorAwaitReturn` path goes through `PromiseResolve` rather than a private
2028    /// shortcut.
2029    pub fn promise_resolve_intrinsic(&mut self, value: Value) -> JsResult<Value> {
2030        if let Value::Object(object) = &value
2031            && self.promise_state(object).is_some()
2032        {
2033            let constructor = self.get_property(object, "constructor")?;
2034            let same = match (&constructor, &self.realm.promise_constructor) {
2035                (Some(Value::Object(found)), Some(intrinsic)) => found.ptr_eq(intrinsic),
2036                _ => false,
2037            };
2038            if same {
2039                return Ok(value);
2040            }
2041        }
2042        let promise = self.new_promise();
2043        self.resolve_promise_with(&promise, value)?;
2044        Ok(Value::Object(promise))
2045    }
2046
2047    /// Claim `[[AlreadyResolved]]` for `promise`: `true` for the first caller, `false` after.
2048    ///
2049    /// The pair of resolving functions a promise hands to its executor shares this record, so
2050    /// whichever runs first wins and the other is a silent no-op. Promise *status* is not a
2051    /// substitute: resolving with a thenable leaves the promise `Pending` for a whole job.
2052    pub fn claim_resolution(&mut self, promise: &Gc<JsObject>) -> bool {
2053        let Some(state) = self.promise_state(promise) else {
2054            return true;
2055        };
2056        let mut state = state.borrow_mut();
2057        if state.resolved {
2058            return false;
2059        }
2060        state.resolved = true;
2061        true
2062    }
2063
2064    /// Clear `[[AlreadyResolved]]`, for the job that hands out a fresh pair.
2065    fn forget_resolution(&mut self, promise: &Gc<JsObject>) {
2066        let Some(state) = self.promise_state(promise) else {
2067            return;
2068        };
2069        state.borrow_mut().resolved = false;
2070    }
2071
2072    /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
2073    pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
2074        // Resolving a promise with itself is a `TypeError`. The check exists because the
2075        // alternative is a chain of self-reactions that never settles.
2076        if let Value::Object(object) = &value
2077            && object.ptr_eq(promise)
2078        {
2079            // The spec rejects *and* throws, so both the promise and the caller see it.
2080            let thrown = self.type_error("cannot resolve a promise with itself");
2081            let Signal::Throw(error) = thrown.clone() else {
2082                unreachable!("type_error always throws")
2083            };
2084            self.reject_promise(promise, error);
2085            return Err(thrown);
2086        }
2087        // §27.2.1.3.1 `NewPromiseResolveThenableJob` step 3: `Get(resolution, "then")` is a
2088        // `Completion`, and an abrupt one **rejects** the promise rather than throwing to
2089        // whoever resolved it — a poisoned `then` getter is the case every
2090        // `*-poisoned-then` test is written against.
2091        let then = match &value {
2092            Value::Object(object) => match self.get_property(object, "then") {
2093                Ok(then) => then,
2094                Err(signal) => {
2095                    if let Signal::Throw(reason) = signal {
2096                        self.reject_promise(promise, reason);
2097                        return Ok(());
2098                    }
2099                    return Err(signal);
2100                }
2101            },
2102            _ => None,
2103        };
2104        let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
2105        if !callable_then {
2106            // Not a thenable: a non-callable `then` makes the value fulfil as it is.
2107            self.fulfill_promise(promise, value);
2108            return Ok(());
2109        }
2110        // Adopting a thenable is asynchronous — `then` is called from a job, never from
2111        // inside `resolve`, so a script cannot make a promise settle synchronously.
2112        self.jobs.push_back(Job::Thenable {
2113            then: then.expect("checked callable"),
2114            value,
2115            promise: promise.clone(),
2116        });
2117        Ok(())
2118    }
2119
2120    /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
2121    ///
2122    /// `C.resolve` is user code and may answer a plain thenable rather than one of this
2123    /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
2124    ///
2125    /// The property read is **not** short-circuitable even for a real promise: the spec says
2126    /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
2127    /// expects it to run. Skipping the read for promises not only lost the throw, it made
2128    /// the combinator's loop infinite — the test's iterator never sets `done`.
2129    pub fn invoke_then(
2130        &mut self,
2131        thenable: Value,
2132        on_fulfilled: Value,
2133        on_rejected: Value,
2134    ) -> JsResult<()> {
2135        let then = match &thenable {
2136            Value::Object(object) => self.get_property(object, "then")?,
2137            primitive => {
2138                let boxed = self.object_from(primitive)?;
2139                self.get_property(&boxed, "then")?
2140            }
2141        };
2142        let Some(then) = then else {
2143            return Err(self.type_error("thenable has no then method"));
2144        };
2145        if !matches!(&then, Value::Object(object) if object.is_callable()) {
2146            return Err(self.type_error("then is not a function"));
2147        }
2148        self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
2149        Ok(())
2150    }
2151
2152    /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
2153    ///
2154    /// `Promise.prototype.then` in one step: register a reaction and answer the derived
2155    /// promise.
2156    pub fn perform_then(
2157        &mut self,
2158        promise: &Gc<JsObject>,
2159        on_fulfilled: Option<Value>,
2160        on_rejected: Option<Value>,
2161    ) -> JsResult<Value> {
2162        let Some(state) = self.promise_state(promise) else {
2163            return Err(self.type_error("not a promise"));
2164        };
2165        // Whether a rejection handler is being attached decides whether a recorded
2166        // rejection stops being unhandled, so it is read before the values are moved.
2167        let has_rejection_handler = on_rejected.is_some();
2168        let derived = self.new_promise();
2169        let reaction = crate::object::PromiseReaction {
2170            on_fulfilled,
2171            on_rejected,
2172            promise: derived.clone(),
2173        };
2174        let settled = {
2175            let mut state = state.borrow_mut();
2176            // A rejection somebody reacts to is no longer unhandled.
2177            state.handled = true;
2178            match &state.status {
2179                crate::object::PromiseStatus::Pending => {
2180                    state.reactions.push(reaction.clone());
2181                    None
2182                }
2183                crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2184                crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2185            }
2186        };
2187        // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2188        // later, means somebody is listening after all.
2189        if has_rejection_handler {
2190            self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2191        }
2192        if let Some((argument, rejected)) = settled {
2193            let handler = if rejected {
2194                reaction.on_rejected
2195            } else {
2196                reaction.on_fulfilled
2197            };
2198            self.jobs.push_back(Job::Reaction {
2199                handler,
2200                argument,
2201                rejected,
2202                promise: reaction.promise,
2203            });
2204        }
2205        Ok(Value::Object(derived))
2206    }
2207
2208    /// The rejections nobody listened to, formatted the way the reference reports them.
2209    ///
2210    /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2211    /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2212    /// unhandled at the point the queue drains, because a `then` may still be attached
2213    /// before the host acts on it.
2214    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2215        let entries = std::mem::take(&mut self.unhandled);
2216        // Somebody may have attached a handler after the rejection was recorded, so the
2217        // promise is the authority rather than the list.
2218        let still_unhandled: Vec<Value> = entries
2219            .into_iter()
2220            .filter_map(|(promise, reason)| {
2221                let handled = self
2222                    .promise_state(&promise)
2223                    .map(|state| state.borrow().handled)
2224                    .unwrap_or(true);
2225                (!handled).then_some(reason)
2226            })
2227            .collect();
2228        still_unhandled
2229            .into_iter()
2230            .map(|reason| {
2231                let text = self.describe_exception(&reason);
2232                let stack = match &reason {
2233                    Value::Object(object) => self
2234                        .get_property(object, "stack")
2235                        .ok()
2236                        .flatten()
2237                        .map(|value| value.to_js_string())
2238                        // `stack` carries a trailing newline of its own, which would leave
2239                        // a blank line between two reported rejections.
2240                        .map(|text| text.trim_end().to_string())
2241                        .unwrap_or_default(),
2242                    _ => String::new(),
2243                };
2244                if stack.is_empty() {
2245                    format!("Possibly unhandled promise rejection: {text}")
2246                } else {
2247                    format!("Possibly unhandled promise rejection: {text}\n{stack}")
2248                }
2249            })
2250            .collect()
2251    }
2252
2253    /// Run the microtask queue to exhaustion.
2254    ///
2255    /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2256    /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2257    /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2258    ///
2259    /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2260    /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2261    /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2262    pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2263        crate::builtins::json::parse_text(self, text, true)
2264    }
2265
2266    /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2267    ///
2268    /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2269    /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2270    /// immediately, and `setTimeout(f, -1)` is ordinary code.
2271    ///
2272    /// The callback is called with **no arguments**. The reference stores only the function
2273    /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2274    /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2275    /// extra arguments arrive as `undefined`.
2276    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2277        let id = self.next_timer_id;
2278        // Wrap rather than grow: the id reaches the script as an `Int32`.
2279        self.next_timer_id = if self.next_timer_id == i32::MAX {
2280            1
2281        } else {
2282            self.next_timer_id + 1
2283        };
2284        let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2285        self.tasks.push(Task::Timer {
2286            id,
2287            callback,
2288            due_at,
2289        });
2290        id
2291    }
2292
2293    /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2294    /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2295    pub fn cancel_timer(&mut self, id: i32) -> bool {
2296        let before = self.tasks.len();
2297        self.tasks.retain(|task| match task {
2298            Task::Timer { id: task_id, .. } => *task_id != id,
2299        });
2300        self.tasks.len() != before
2301    }
2302
2303    /// How long until the earliest pending timer, or `None` when none is pending.
2304    pub fn next_timeout(&self) -> Option<std::time::Duration> {
2305        let now = std::time::Instant::now();
2306        self.tasks
2307            .iter()
2308            .map(|task| match task {
2309                Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2310            })
2311            .min()
2312    }
2313
2314    /// Run one turn of the event loop.
2315    ///
2316    /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2317    /// run at most one due timer, then drain again. The blocking belongs to the caller
2318    /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2319    /// is how it asks.
2320    ///
2321    /// One timer per turn rather than all of them: a timer callback may schedule another
2322    /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2323    /// starve the microtask queue.
2324    pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2325        self.drain_jobs()?;
2326        let now = std::time::Instant::now();
2327        // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2328        // followed by `setTimeout(g, 1)` must run `g` first.
2329        let due = self
2330            .tasks
2331            .iter()
2332            .enumerate()
2333            .filter(|(_, task)| match task {
2334                Task::Timer { due_at, .. } => *due_at <= now,
2335            })
2336            .min_by_key(|(_, task)| match task {
2337                Task::Timer { due_at, .. } => *due_at,
2338            })
2339            .map(|(index, _)| index);
2340        let Some(index) = due else {
2341            // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2342            // descriptor is registered but no timer is closer, so a script that never
2343            // touches the descriptor still gets control back. Without a cap a handler on a
2344            // descriptor that is never ready would block for as long as the host allows.
2345            let timeout = self
2346                .next_timeout()
2347                .unwrap_or(std::time::Duration::from_secs(10))
2348                .min(std::time::Duration::from_secs(10));
2349            if !self.fd_handlers.is_empty() {
2350                // Blocking on a timer while descriptors are registered would starve them,
2351                // and blocking on the descriptors while a timer is due would delay it; the
2352                // host polls with the earlier of the two deadlines, which this timeout is.
2353                return Ok(Turn::Poll(timeout));
2354            }
2355            return Ok(match self.next_timeout() {
2356                Some(wait) => Turn::Wait(wait),
2357                None => Turn::Done,
2358            });
2359        };
2360        let Task::Timer { callback, .. } = self.tasks.remove(index);
2361        let this = Value::Undefined;
2362        // A throwing timer callback must not stop the loop: the reference reports it and
2363        // keeps going, because the alternative is that one bad timer silently stops every
2364        // later one.
2365        // No arguments: see `schedule_timer` — the reference calls the callback bare.
2366        match self.call_value(callback, this, Vec::new()) {
2367            Ok(_) => {}
2368            Err(Signal::Throw(value)) => {
2369                let text = self.describe_exception(&value);
2370                self.timer_errors.push(text);
2371            }
2372            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2373        }
2374        self.drain_jobs()?;
2375        Ok(Turn::Ran)
2376    }
2377
2378    /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2379    ///
2380    /// `callback` of `None` unregisters that direction, and an entry with neither direction
2381    /// left is removed — the reference does the same, so a script can rely on
2382    /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2383    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2384        let entry = self.fd_handlers.entry(fd).or_default();
2385        if readable {
2386            entry.read = callback;
2387        } else {
2388            entry.write = callback;
2389        }
2390        if entry.read.is_none() && entry.write.is_none() {
2391            self.fd_handlers.remove(&fd);
2392        }
2393    }
2394
2395    /// Register or clear an `os.signal` handler.
2396    ///
2397    /// `None` removes it; the host separately restores the default disposition or sets
2398    /// ignore, because which of those happened is the script's choice (`null` versus
2399    /// `undefined`) and not something this table can express.
2400    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2401        match handler {
2402            Some(handler) => {
2403                self.signal_handlers.insert(signal, handler);
2404            }
2405            None => {
2406                self.signal_handlers.remove(&signal);
2407            }
2408        }
2409    }
2410
2411    /// Run the handler for `signal`, reporting whether one ran.
2412    ///
2413    /// A throwing handler is reported and the loop continues, like a timer's.
2414    pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2415        let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2416            return Ok(false);
2417        };
2418        match self.call_value(handler, Value::Undefined, Vec::new()) {
2419            Ok(_) => {}
2420            Err(Signal::Throw(value)) => {
2421                let text = self.describe_exception(&value);
2422                self.timer_errors.push(text);
2423            }
2424            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2425        }
2426        self.drain_jobs()?;
2427        Ok(true)
2428    }
2429
2430    /// The descriptors the host has to poll, and in which direction.
2431    ///
2432    /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2433    /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2434    /// `os_poll` asks for.
2435    pub fn pending_fds(&self) -> Vec<FdInterest> {
2436        self.fd_handlers
2437            .iter()
2438            .map(|(fd, entry)| FdInterest {
2439                fd: *fd,
2440                read: entry.read.is_some(),
2441                write: entry.write.is_some(),
2442            })
2443            .collect()
2444    }
2445
2446    /// Call the handler registered for `fd`, reporting whether one ran.
2447    ///
2448    /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2449    /// poll iteration and then restarts the loop, because the handler may have changed the
2450    /// registration list underneath it; doing the same here keeps a handler that
2451    /// unregisters itself from being called with stale state.
2452    ///
2453    /// A throwing handler is reported and the loop continues — a bad handler must not stop
2454    /// every later one, exactly as with timers.
2455    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2456        let Some(entry) = self.fd_handlers.get(&fd) else {
2457            return Ok(false);
2458        };
2459        let callback = if readable {
2460            entry.read.clone()
2461        } else if writable {
2462            entry.write.clone()
2463        } else {
2464            None
2465        };
2466        let Some(callback) = callback else {
2467            return Ok(false);
2468        };
2469        self.drain_jobs()?;
2470        match self.call_value(callback, Value::Undefined, Vec::new()) {
2471            Ok(_) => {}
2472            Err(Signal::Throw(value)) => {
2473                let text = self.describe_exception(&value);
2474                self.timer_errors.push(text);
2475            }
2476            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2477        }
2478        self.drain_jobs()?;
2479        Ok(true)
2480    }
2481
2482    /// Take the errors timer callbacks threw, leaving the list empty.
2483    pub fn take_timer_errors(&mut self) -> Vec<String> {
2484        std::mem::take(&mut self.timer_errors)
2485    }
2486
2487    /// Whether anything is still pending: a microtask or a timer.
2488    pub fn has_pending_work(&self) -> bool {
2489        !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2490    }
2491
2492    /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2493    pub fn has_pending_timers_or_jobs(&self) -> bool {
2494        !self.jobs.is_empty() || !self.tasks.is_empty()
2495    }
2496
2497    /// Run every queued microtask, including ones queued while draining.
2498    pub fn drain_jobs(&mut self) -> JsResult<()> {
2499        // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2500        // would spin forever, so the drain is bounded the way the call stack is.
2501        let mut budget = 1_000_000usize;
2502        while let Some(job) = self.jobs.pop_front() {
2503            if budget == 0 {
2504                return Err(Signal::Throw(
2505                    self.make_error("InternalError", "promise job queue did not drain"),
2506                ));
2507            }
2508            budget -= 1;
2509            self.run_job(job)?;
2510            // `FinalizationRegistry` at the job boundary: this is the safe point where the
2511            // engine may run script that the script itself did not ask for. Doing it here
2512            // rather than from a drop hook is what keeps the callback out of arbitrary
2513            // engine bookkeeping — see `builtins::weak`'s header.
2514            crate::builtins::weak::drain_finalizers(self)?;
2515        }
2516        // A script that queued no jobs may still have dropped targets, so the checkpoint
2517        // runs once more after the queue empties.
2518        crate::builtins::weak::drain_finalizers(self)?;
2519        Ok(())
2520    }
2521
2522    /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2523    ///
2524    /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2525    /// `None` and is swept out here. This is also where the realm learns that a registry
2526    /// died, which is why it is a mutation rather than a read.
2527    pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2528        let handles = std::mem::take(&mut self.realm.finalization_registries);
2529        let mut live = Vec::with_capacity(handles.len());
2530        for handle in handles {
2531            let Some(object) = handle.upgrade() else {
2532                continue;
2533            };
2534            let Some(state) = object.finalization_state() else {
2535                continue;
2536            };
2537            live.push((object.clone(), *state));
2538            self.realm.finalization_registries.push(object.downgrade());
2539        }
2540        live
2541    }
2542
2543    /// Run one microtask.
2544    fn run_job(&mut self, job: Job) -> JsResult<()> {
2545        match job {
2546            Job::Reaction {
2547                handler: None,
2548                argument,
2549                rejected,
2550                promise,
2551            } => {
2552                // No handler: the settlement passes straight through to the derived
2553                // promise, which is why `p.catch(f)` ignores fulfilments.
2554                if rejected {
2555                    self.reject_promise(&promise, argument);
2556                } else {
2557                    self.fulfill_promise(&promise, argument);
2558                }
2559                Ok(())
2560            }
2561            Job::Reaction {
2562                handler: Some(handler),
2563                argument,
2564                promise,
2565                ..
2566            } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2567                Ok(answer) => {
2568                    if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2569                        self.reject_promise(&promise, error);
2570                    }
2571                    Ok(())
2572                }
2573                Err(Signal::Throw(reason)) => {
2574                    self.reject_promise(&promise, reason);
2575                    Ok(())
2576                }
2577                Err(other) => Err(other),
2578            },
2579            Job::Thenable {
2580                then,
2581                value,
2582                promise,
2583            } => {
2584                // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2585                // the value it produces settles `promise`.
2586                // The thenable's `then` gets this promise's own pair, so whatever it
2587                // produces settles `promise`.
2588                // `length: 1`, `name: ""` — a resolve/reject function is a
2589                // `%Promise.prototype.then%`-style pair, not a bare native. Building them
2590                // with `JsObject::function` left `length` at 0, which a test reads straight
2591                // off the function (`finally/resolved-observable-then-calls-argument`
2592                // requires `resolve.length === 1` for the pair handed to a thenable).
2593                let resolve =
2594                    self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
2595                let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
2596                // §27.2.2.2 step 1: the job builds a **fresh** pair of resolving functions,
2597                // so the one-shot record starts over. Without the reset the pair above was
2598                // already spent by the `resolve` that queued this job, and a thenable that
2599                // calls `reject` left the promise pending forever
2600                // (`Promise/all/reject-immed`).
2601                self.forget_resolution(&promise);
2602                let reject = Value::Object(reject);
2603                match self.call_value(then, value, vec![Value::Object(resolve), reject.clone()]) {
2604                    Ok(_) => Ok(()),
2605                    // Step 3.a is `Call(resolvingFunctions.[[Reject]], …)` — **through** the
2606                    // reject function, whose one-shot record makes this a no-op once `then`
2607                    // has already resolved the promise
2608                    // (`exception-after-resolve-in-thenable-job`).
2609                    Err(Signal::Throw(reason)) => {
2610                        self.call_value(reject, Value::Undefined, vec![reason])?;
2611                        Ok(())
2612                    }
2613                    Err(other) => Err(other),
2614                }
2615            }
2616            Job::Resume {
2617                coroutine,
2618                promise,
2619                kind,
2620                value,
2621            } => self.drive_async(&coroutine, &promise, kind, value),
2622            Job::GeneratorResume {
2623                generator,
2624                promise,
2625                kind,
2626                value,
2627            } => self.step_async_generator(&generator, &promise, kind, value),
2628            Job::Import {
2629                specifier,
2630                referrer,
2631                promise,
2632                phase,
2633            } => {
2634                self.run_dynamic_import(&specifier, &referrer, &promise, phase);
2635                Ok(())
2636            }
2637        }
2638    }
2639
2640    /// One element of a `Promise` combinator settled.
2641    ///
2642    /// The shared state object holds the result array, the number still outstanding, and
2643    /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2644    /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2645    /// to settle, only whatever `Sub` said a capability is.
2646    ///
2647    /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2648    /// and `any` must ignore every later settlement, and `all` must not report a second
2649    /// rejection after the first.
2650    fn settle_combinator(
2651        &mut self,
2652        state: &Gc<JsObject>,
2653        index: usize,
2654        fulfilled: bool,
2655        value: Value,
2656    ) -> JsResult<()> {
2657        let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2658        // Each element settles at most once: a thenable may call `onFulfilled` twice
2659        // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2660        // call a no-op. Without it the second call decremented `remaining` again and settled
2661        // `all` with a short values array (`call-resolve-element-items`).
2662        let done = field("done");
2663        let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2664        let settled = field("settled").is_some_and(|value| value.to_boolean());
2665        if settled {
2666            return Ok(());
2667        }
2668        if let Some(Value::Object(done)) = &done {
2669            if done
2670                .array_get(index)
2671                .is_some_and(|value| value.to_boolean())
2672            {
2673                return Ok(());
2674            }
2675            done.array_set(self.heap, index, Value::Bool(true));
2676        }
2677        let resolve = field("resolve");
2678        let reject = field("reject");
2679        let keys = field("keys");
2680        let results = field("results").and_then(|value| value.as_object().cloned());
2681        // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2682        // promise: the handler is a plain function the constructor chose.
2683        let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2684            if let Some(handler) = handler {
2685                interp.call_value(handler, Value::Undefined, vec![value])?;
2686            }
2687            Ok(())
2688        };
2689        match kind {
2690            // `race`: the first settlement wins and stops the rest.
2691            3 => {
2692                state.define_data("settled", Value::Bool(true));
2693                let handler = if fulfilled { resolve } else { reject };
2694                settle_with(self, handler, value)?;
2695                return Ok(());
2696            }
2697            // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2698            // the first rejection wins outright.
2699            0 | 4 if !fulfilled => {
2700                state.define_data("settled", Value::Bool(true));
2701                settle_with(self, reject, value)?;
2702                return Ok(());
2703            }
2704            // `any`: the first fulfilment wins.
2705            2 if fulfilled => {
2706                state.define_data("settled", Value::Bool(true));
2707                settle_with(self, resolve, value)?;
2708                return Ok(());
2709            }
2710            _ => {}
2711        }
2712        let Some(results) = &results else {
2713            return Ok(());
2714        };
2715        match kind {
2716            4 => {
2717                results.array_set(self.heap, index, value);
2718            }
2719            0 => {
2720                results.array_set(self.heap, index, value);
2721            }
2722            // `allSettled` (and its keyed twin) never rejects; each slot records what
2723            // happened.
2724            1 | 5 => {
2725                let record = self.new_object(Some(self.realm.object_proto.clone()));
2726                if fulfilled {
2727                    record.define_data("status", self.string("fulfilled"));
2728                    record.define_data("value", value);
2729                } else {
2730                    record.define_data("status", self.string("rejected"));
2731                    record.define_data("reason", value);
2732                }
2733                results.array_set(self.heap, index, Value::Object(record));
2734            }
2735            // `any`: a rejection is parked in the errors array and the sweep continues.
2736            2 => {
2737                results.array_set(self.heap, index, value);
2738            }
2739            _ => {}
2740        }
2741        let remaining = field("remaining")
2742            .map(|value| value.to_int32())
2743            .unwrap_or(0);
2744        let left = remaining - 1;
2745        state.define_data("remaining", Value::Int(left));
2746        if left != 0 {
2747            return Ok(());
2748        }
2749        state.define_data("settled", Value::Bool(true));
2750        match kind {
2751            0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2752            // The keyed result: an ordinary object with a **null** prototype, holding the
2753            // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2754            4 | 5 => {
2755                let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2756                settle_with(self, resolve, keyed)?;
2757            }
2758            2 => {
2759                // The rejection is an `AggregateError` whose `errors` is the results array
2760                // itself — the slots are the reasons, in input order.
2761                let errors = results.array_elements().unwrap_or_default();
2762                let error = self.aggregate_error(errors, "all promises were rejected");
2763                settle_with(self, reject, error)?;
2764            }
2765            _ => {}
2766        }
2767        Ok(())
2768    }
2769
2770    /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2771    ///
2772    /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2773    /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2774    /// prototype is load-bearing in both directions: a key called `toString` must not
2775    /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2776    /// (`resolves-empty-object.js`).
2777    pub(crate) fn keyed_result_object(
2778        &mut self,
2779        keys: Option<&Value>,
2780        values: &Gc<JsObject>,
2781    ) -> JsResult<Value> {
2782        let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2783            return Ok(Value::Object(self.new_object(None)));
2784        };
2785        let result = self.new_object(None);
2786        let count = values.array_length().unwrap_or(0);
2787        for index in 0..count {
2788            let Some(key) = keys.array_get(index) else {
2789                continue;
2790            };
2791            let Some(value) = values.array_get(index) else {
2792                continue;
2793            };
2794            let property = Property::with_attributes(value, true, true);
2795            match &key {
2796                Value::Symbol(symbol) => {
2797                    result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2798                }
2799                other => {
2800                    let text = self.to_js_string(other)?;
2801                    result.define_key(&PropertyKey::from(text.as_str()), property);
2802                }
2803            }
2804        }
2805        Ok(Value::Object(result))
2806    }
2807
2808    /// Build an async function's result: a promise whose body runs as a coroutine.
2809    pub fn new_async_function(
2810        &mut self,
2811        function: Value,
2812        this: Value,
2813        args: Vec<Value>,
2814    ) -> JsResult<Value> {
2815        let promise = self.new_promise();
2816        let coroutine = self.new_coroutine(function, this, args)?;
2817        if let Err(Signal::Throw(reason)) =
2818            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2819        {
2820            self.reject_promise(&promise, reason);
2821        }
2822        Ok(Value::Object(promise))
2823    }
2824
2825    /// The coroutine an async body runs in.
2826    ///
2827    /// Generator-shaped and never exposed to the script: what makes `await` work is the
2828    /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2829    /// than growing a second state machine. The difference is only in the ending — a
2830    /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2831    /// Run `code` as an async function body, answering the promise it settles.
2832    ///
2833    /// Used for a module with top-level `await`: its body is an async function whose
2834    /// caller is the host, so there is no function object to pass through
2835    /// [`Interp::new_async_function`].
2836    pub fn run_async_body(
2837        &mut self,
2838        code: Gc<CompiledCode>,
2839        env: Gc<ClosureEnv>,
2840        this: Value,
2841    ) -> JsResult<Value> {
2842        let promise = self.new_promise();
2843        let coroutine = self.new_coroutine_from(code, env, this, Vec::new(), Value::Undefined)?;
2844        if let Err(Signal::Throw(reason)) =
2845            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2846        {
2847            self.reject_promise(&promise, reason);
2848        }
2849        Ok(Value::Object(promise))
2850    }
2851
2852    fn new_coroutine(
2853        &mut self,
2854        function: Value,
2855        this: Value,
2856        args: Vec<Value>,
2857    ) -> JsResult<Gc<JsObject>> {
2858        let Some(object) = function.as_object().cloned() else {
2859            return Err(self.type_error("not a function"));
2860        };
2861        let Some((code, env)) = bytecode_of(&object) else {
2862            return Err(self.type_error("not a function"));
2863        };
2864        self.new_coroutine_from(code, env, this, args, function)
2865    }
2866
2867    /// Build a coroutine over an already-resolved body.
2868    ///
2869    /// `callee` is the function object the body belongs to, or `undefined` when there is
2870    /// none — a module with top-level `await`. It has to be handed over rather than
2871    /// defaulted: the frame's callee is what `special_object 2` answers, and an async
2872    /// function's body uses that to initialise its own-name binding. Passing `undefined`
2873    /// made `var f = async function Binding(){ return typeof Binding }` answer
2874    /// `"undefined"`, so a named async function expression could not see its own name and
2875    /// `Binding = 1` inside it silently succeeded (`named-reassign-fn-name-in-body`).
2876    fn new_coroutine_from(
2877        &mut self,
2878        code: Gc<CompiledCode>,
2879        env: Gc<ClosureEnv>,
2880        this: Value,
2881        args: Vec<Value>,
2882        callee: Value,
2883    ) -> JsResult<Gc<JsObject>> {
2884        self.push_frame(code, env, this, args, callee)?;
2885        let frame = self.frames.pop().expect("push_frame just pushed it");
2886        let state = GeneratorState {
2887            frame: Some(frame),
2888            phase: GeneratorPhase::SuspendedStart,
2889            parked_on_await: false,
2890            parked_on_yield_star: false,
2891            requests: std::collections::VecDeque::new(),
2892            async_busy: false,
2893            // An `async function` body is driven by `drive_async`, never by the generator
2894            // protocol, and the object is not reachable from script.
2895            is_async: false,
2896        };
2897        let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2898        coroutine.with_mut(|data| {
2899            data.kind = ObjectKind::Generator(Box::new(state));
2900        });
2901        Ok(coroutine)
2902    }
2903
2904    /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2905    /// `await` and `value` is what it awaited.
2906    fn resume_coroutine(
2907        &mut self,
2908        coroutine: &Gc<JsObject>,
2909        kind: ResumeKind,
2910        value: Value,
2911    ) -> JsResult<(Value, bool)> {
2912        let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2913            ObjectKind::Generator(state) => {
2914                let is_async = state.is_async;
2915                Some(std::mem::replace(
2916                    state.as_mut(),
2917                    GeneratorState {
2918                        frame: None,
2919                        phase: GeneratorPhase::Executing,
2920                        parked_on_await: false,
2921                        parked_on_yield_star: false,
2922                        requests: std::collections::VecDeque::new(),
2923                        async_busy: false,
2924                        is_async,
2925                    },
2926                ))
2927            }
2928            _ => None,
2929        }) else {
2930            return Err(self.type_error("not a coroutine"));
2931        };
2932        let result = self.step_generator(&mut state, kind, value);
2933        coroutine.with_mut(|data| {
2934            data.kind = ObjectKind::Generator(Box::new(state));
2935        });
2936        let (value, done, _ready, _reason) = result?;
2937        Ok((value, done))
2938    }
2939
2940    /// Advance an async body and settle its promise with the outcome.
2941    fn drive_async(
2942        &mut self,
2943        coroutine: &Gc<JsObject>,
2944        promise: &Gc<JsObject>,
2945        kind: ResumeKind,
2946        value: Value,
2947    ) -> JsResult<()> {
2948        match self.resume_coroutine(coroutine, kind, value) {
2949            Ok((value, true)) => {
2950                // `Ok` with `done` means the body finished *normally*, even when it was
2951                // resumed by a `throw` — `try { await p } catch {}` completes by
2952                // returning. Only the `Err` arm below is a rejection.
2953                //
2954                // Resolving rather than fulfilling matters: `return promise` in an async
2955                // body adopts the inner promise, so `async function f(){ return
2956                // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2957                // promise.
2958                if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2959                    self.reject_promise(promise, reason);
2960                }
2961                Ok(())
2962            }
2963            Ok((value, false)) => {
2964                // Parked on `await`: follow what it awaited and resume with the outcome.
2965                let awaited = match self.promise_resolve_value(value) {
2966                    Ok(awaited) => awaited,
2967                    Err(Signal::Throw(error)) => {
2968                        self.reject_promise(promise, error);
2969                        return Ok(());
2970                    }
2971                    Err(other) => return Err(other),
2972                };
2973                self.hook_await(awaited, coroutine, promise)
2974            }
2975            Err(Signal::Throw(reason)) => {
2976                self.reject_promise(promise, reason);
2977                Ok(())
2978            }
2979            Err(other) => Err(other),
2980        }
2981    }
2982
2983    /// Arrange for `coroutine` to resume when `awaited` settles.
2984    fn hook_await(
2985        &mut self,
2986        awaited: Value,
2987        coroutine: &Gc<JsObject>,
2988        promise: &Gc<JsObject>,
2989    ) -> JsResult<()> {
2990        let resumed = JsObject::function(
2991            self.heap,
2992            Some(self.realm.function_proto.clone()),
2993            Callable::AwaitResume {
2994                coroutine: coroutine.clone(),
2995                promise: promise.clone(),
2996                kind: ResumeKind::Next,
2997            },
2998        );
2999        let raised = JsObject::function(
3000            self.heap,
3001            Some(self.realm.function_proto.clone()),
3002            Callable::AwaitResume {
3003                coroutine: coroutine.clone(),
3004                promise: promise.clone(),
3005                kind: ResumeKind::Throw,
3006            },
3007        );
3008        // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
3009        // guarantees one; the fallback keeps a mis-shaped value from panicking.
3010        let Value::Object(awaited) = &awaited else {
3011            self.jobs.push_back(Job::Resume {
3012                coroutine: coroutine.clone(),
3013                promise: promise.clone(),
3014                kind: ResumeKind::Next,
3015                value: awaited,
3016            });
3017            return Ok(());
3018        };
3019        self.perform_then(
3020            awaited,
3021            Some(Value::Object(resumed)),
3022            Some(Value::Object(raised)),
3023        )?;
3024        Ok(())
3025    }
3026
3027    /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
3028    /// things an engine keeps outside it — array elements and an array's `length`.
3029    fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
3030        if let Some(property) = object.own_property_key(key) {
3031            return Some(property);
3032        }
3033        // A typed array's indices are bytes in its buffer, so a descriptor for one has to
3034        // be synthesized too — and every one of them is a plain writable, enumerable,
3035        // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
3036        // `undefined` before this, which made `key-is-numericindex` fail on its own
3037        // side effect check.
3038        //
3039        // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
3040        // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
3041        // likewise not elements however numeric they look.
3042        if object.typed_array_element_type().is_some()
3043            && let Some(numeric) = canonical_numeric_index(key)
3044            && numeric.is_finite()
3045            && numeric.fract() == 0.0
3046            && !(numeric == 0.0 && numeric.is_sign_negative())
3047            && numeric >= 0.0
3048            && (numeric as usize) < object.typed_array_length().unwrap_or(0)
3049        {
3050            let value = object.typed_array_element(numeric as usize)?;
3051            return Some(Property::data(value));
3052        }
3053        // An array's elements live in their own vector rather than the property table, so
3054        // a descriptor for one has to be synthesized — with the attributes an element has.
3055        if let Some(index) = key.as_str().and_then(array_index)
3056            && let Some(value) = object.array_get(index as usize)
3057            && !matches!(value, Value::Hole)
3058        {
3059            return Some(Property::data(value));
3060        }
3061        // `length` is an own property of an array that is not in its property table
3062        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
3063        // and non-enumerable.
3064        if key.as_str() == Some("length")
3065            && let Some(length) = object.array_length()
3066        {
3067            return Some(Property {
3068                value: Some(crate::object::length_value(length)),
3069                writable: object.length_writable(),
3070                enumerable: false,
3071                configurable: false,
3072                getter: None,
3073                setter: None,
3074                descriptor_fields: None,
3075            });
3076        }
3077        None
3078    }
3079
3080    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
3081    pub fn object_get_own_property(
3082        &mut self,
3083        object: &Gc<JsObject>,
3084        key: &PropertyKey,
3085    ) -> JsResult<Option<Property>> {
3086        if let Some(answer) = self.proxy_get_own_property(object, key)? {
3087            return Ok(answer);
3088        }
3089        if let Some(exotic) = object.exotic()
3090            && let Some(answer) = exotic.get_own_property(self, object, key)?
3091        {
3092            return Ok(answer);
3093        }
3094        // A module namespace's bindings are accessors internally and data properties to
3095        // script; see `namespace_own_property`.
3096        //
3097        // This is also where a *deferred* namespace evaluates its module, and it is the one
3098        // place that has to be: §10.4.6 answers `[[Get]]`, `[[GetOwnProperty]]` and
3099        // `[[HasProperty]]` all through `GetModuleExportsList`, and in this engine all three
3100        // arrive here. `@@…` keys and `"then"` are exempt — see `is_symbol_like_namespace_key`.
3101        if object.module_namespace_marker() {
3102            self.trigger_deferred_namespace_for_key(object, key)?;
3103            return self.namespace_own_property(object, key);
3104        }
3105        // A mapped `arguments` index is a data property as far as script can see: the
3106        // accessor pair that aliases the parameter is plumbing, and exposing it would
3107        // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
3108        // report a `get` where the spec has a `[[Value]]`.
3109        if let Some(index) = key.as_str().and_then(crate::object::array_index)
3110            && let Some(cell) = object.mapped_argument_cell(index as usize)
3111        {
3112            // Non-configurable is *not* the default: an ordinary mapped index is
3113            // configurable, and only becomes non-configurable once something
3114            // redefines it. Preserve whatever the property table currently says.
3115            // The attributes come from whatever the property table holds, because they
3116            // can be changed independently of the mapping; only the *value* and the
3117            // data-property *kind* are the accessor's secret.
3118            let flags = Self::ordinary_own_property(object, key);
3119            if let Some(existing) = &flags
3120                && !existing.is_accessor()
3121            {
3122                // Already demapped: the table entry is the answer, not the cell.
3123                return Ok(flags);
3124            }
3125            return Ok(Some(Property {
3126                value: Some(cell.get()),
3127                writable: true,
3128                enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
3129                configurable: flags.as_ref().is_some_and(|p| p.configurable),
3130                ..Property::default()
3131            }));
3132        }
3133        Ok(Self::ordinary_own_property(object, key))
3134    }
3135
3136    /// Whether `object` is a module namespace exotic object (§10.4.6).
3137    ///
3138    /// Recognised by shape rather than by a flag: a namespace is the only object whose
3139    /// properties are all accessors over a `ModuleBinding` cell. That is the same
3140    /// identification `Set`/`Add` membership tests use on function objects, and it keeps the
3141    /// distinction in one place instead of adding a boolean every constructor has to
3142    /// remember to set.
3143    pub fn is_module_namespace(&self, object: &Gc<JsObject>) -> bool {
3144        object.module_namespace_marker()
3145    }
3146
3147    /// `IsSymbolLikeNamespaceKey` — the keys a deferred namespace never evaluates for.
3148    ///
3149    /// A symbol never triggers, because the namespace machinery itself walks symbols:
3150    /// `Object.prototype.toString.call(ns)` reads `@@toStringTag` through this very
3151    /// function, and triggering there would make a mere type inspection run a module.
3152    ///
3153    /// `"then"` never triggers when the object is deferred, and that is the subtle half:
3154    /// the namespace is about to be handed to a promise as a resolution value, and the
3155    /// promise machinery reads `then` to decide whether it is a thenable. Evaluating a
3156    /// module as a side effect of *ignoring* a `then` that is not exported would evaluate
3157    /// it in the middle of `await import.defer(…)`.
3158    pub(crate) fn is_symbol_like_namespace_key(object: &Gc<JsObject>, key: &PropertyKey) -> bool {
3159        if key.is_symbol() {
3160            return true;
3161        }
3162        match key.as_str() {
3163            Some("then") => object.deferred_namespace_module().is_some(),
3164            _ => false,
3165        }
3166    }
3167
3168    /// Evaluate a deferred namespace before the operation that asked for its exports.
3169    ///
3170    /// Every MOP entry point that §10.4.6 sends through `GetModuleExportsList` calls this
3171    /// with the key it was given, so the symbol-like exemption is applied once rather than
3172    /// at each site. An ordinary object — a namespace that is not deferred included — costs
3173    /// one marker test.
3174    pub(crate) fn trigger_deferred_namespace_for_key(
3175        &mut self,
3176        object: &Gc<JsObject>,
3177        key: &PropertyKey,
3178    ) -> JsResult<()> {
3179        if object.module_namespace_marker() && !Self::is_symbol_like_namespace_key(object, key) {
3180            self.trigger_deferred_namespace(object)?;
3181        }
3182        Ok(())
3183    }
3184
3185    /// `[[GetOwnProperty]]` for a module namespace exotic object.
3186    ///
3187    /// The bindings are stored as getters — that is the only way a live binding can be read
3188    /// through the namespace — but §10.4.6.5 says the *observable* descriptor is a data
3189    /// descriptor:
3190    ///
3191    /// ```text
3192    /// { [[Value]]: current value, [[Writable]]: true,
3193    ///   [[Enumerable]]: true, [[Configurable]]: false }
3194    /// ```
3195    ///
3196    /// So `Object.getOwnPropertyDescriptor(ns, "x").writable` is `true`, and `.get` is
3197    /// `undefined`. Reporting the accessor instead — which is what the property table holds
3198    /// — made every one of test262's namespace descriptor assertions fail, in both the
3199    /// `await-ns-*` and `promise-then-ns-*` families.
3200    ///
3201    /// `[[Configurable]]: false` is why `Reflect.defineProperty(ns, "x", {value: 1})` answers
3202    /// `true` only when the new value is `SameValue` the current one (`await-ns-define-own-
3203    /// property`); the ordinary descriptor machinery derives that from these attributes.
3204    pub fn namespace_own_property(
3205        &mut self,
3206        object: &Gc<JsObject>,
3207        key: &PropertyKey,
3208    ) -> JsResult<Option<Property>> {
3209        let Some(stored) = Self::ordinary_own_property(object, key) else {
3210            return Ok(None);
3211        };
3212        let Some(Property {
3213            getter: Some(getter),
3214            ..
3215        }) = Some(&stored)
3216        else {
3217            return Ok(Some(stored));
3218        };
3219        // Reading the binding is what a namespace `[[Get]]` does, and it can run script
3220        // (`export let x` assigned by a getter elsewhere), so the value is materialised here
3221        // rather than stored.
3222        let value = self.call_value(getter.clone(), Value::Object(object.clone()), Vec::new())?;
3223        Ok(Some(Property {
3224            value: Some(value),
3225            writable: true,
3226            enumerable: true,
3227            configurable: false,
3228            ..Property::default()
3229        }))
3230    }
3231
3232    /// `[[DefineOwnProperty]]` for a module namespace exotic object (§10.4.6.6).
3233    ///
3234    /// Modelled as "does this descriptor describe the property that is already there?",
3235    /// because a namespace property's attributes are fixed and its value cannot be changed
3236    /// through the namespace. The three ways to succeed:
3237    ///
3238    /// * a descriptor that names no field at all (`Reflect.defineProperty(ns, k, {})`);
3239    /// * one whose `[[Value]]` is `SameValue` the current binding value;
3240    /// * one whose attribute fields all restate `{writable: true, enumerable: true,
3241    ///   configurable: false}`.
3242    ///
3243    /// `@@toStringTag` is a real own property of the namespace (a data property, writable
3244    /// false), so it goes through the same check against its stored value — which is what
3245    /// makes `{value: "Module", writable: false, enumerable: false, configurable: false}`
3246    /// answer `true` while `{value: "Other"}` answers `false`.
3247    fn namespace_define_own_property(
3248        &mut self,
3249        object: &Gc<JsObject>,
3250        key: &PropertyKey,
3251        property: &Property,
3252    ) -> JsResult<bool> {
3253        let Some(current) = self.namespace_own_property(object, key)? else {
3254            // A name the namespace does not export cannot be added to it.
3255            return Ok(false);
3256        };
3257        if let Some(value) = &property.value {
3258            let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3259            if !self.same_value(value, current_value)? {
3260                return Ok(false);
3261            }
3262        }
3263        Ok(true)
3264    }
3265
3266    /// `[[DefineOwnProperty]]` for a namespace, driven by the *descriptor object*.
3267    ///
3268    /// §10.4.6.6 is worded entirely in terms of which fields the descriptor **has**: "If
3269    /// Desc has [[Value]] and SameValue(Desc.[[Value]], current) is false, return false",
3270    /// then the same for [[Writable]], [[Enumerable]] and [[Configurable]], then true. A
3271    /// descriptor with no fields at all therefore succeeds, which is what
3272    /// `Reflect.defineProperty(ns, k, {})` checks.
3273    ///
3274    /// Taking the *merged* `Property` instead cannot work: the merge inherits from the
3275    /// stored property, and a namespace stores its bindings as accessors, so every
3276    /// definition looked like "accessor → data kind changed" or carried `writable: false`
3277    /// from the accessor's own entry. Presence is only available here, before the merge.
3278    pub fn namespace_define_from_descriptor(
3279        &mut self,
3280        object: &Gc<JsObject>,
3281        key: &PropertyKey,
3282        descriptor: &Gc<JsObject>,
3283    ) -> JsResult<bool> {
3284        let Some(current) = self.namespace_own_property(object, key)? else {
3285            return Ok(false);
3286        };
3287        // An accessor descriptor can never describe a namespace binding.
3288        if self.get_property(descriptor, "get")?.is_some()
3289            || self.get_property(descriptor, "set")?.is_some()
3290        {
3291            return Ok(false);
3292        }
3293        if let Some(value) = self.get_property(descriptor, "value")? {
3294            let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3295            if !self.same_value(&value, current_value)? {
3296                return Ok(false);
3297            }
3298        }
3299        // The three attribute fields, when named, must restate what the property already
3300        // has. Not a fixed shape: an exported binding reports
3301        // `{writable: true, enumerable: true, configurable: false}` while `@@toStringTag`
3302        // is a real own data property with `{false, false, false}`, and both are namespace
3303        // properties. Comparing against `current` is what makes one rule cover both.
3304        for (name, have) in [
3305            ("writable", current.writable),
3306            ("enumerable", current.enumerable),
3307            ("configurable", current.configurable),
3308        ] {
3309            if let Some(named) = self.get_property(descriptor, name)?
3310                && named.to_boolean() != have
3311            {
3312                return Ok(false);
3313            }
3314        }
3315        Ok(true)
3316    }
3317
3318    /// `SameValue` (§7.2.9), exposed because the namespace's `[[DefineOwnProperty]]` needs to
3319    /// compare a requested value against a live binding.
3320    pub fn same_value(&mut self, a: &Value, b: &Value) -> JsResult<bool> {
3321        Ok(a.same_value(b))
3322    }
3323
3324    ///
3325    /// Written for `Error.prototype.stack`'s setter and the exact mechanism
3326    /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
3327    /// abstract operation here rather than a private helper in `error.rs`.
3328    ///
3329    /// The name is the whole point: the setter must behave as if the prototype were not
3330    /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3331    /// the accessor for every error object in the realm. Everything below follows from that:
3332    ///
3333    /// 1. `thisValue` must be an object — otherwise `TypeError`.
3334    /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3335    ///    accessor's own home an error rather than a self-shadow.
3336    /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3337    ///    either has a string or has made a mistake.
3338    /// 4. An existing *own* property decides the path — an own setter is called, an own
3339    ///    non-writable data property is a `TypeError` — and only a missing own property
3340    ///    falls through to defining one.
3341    /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3342    ///    traps and a non-extensible receiver is a `TypeError`.
3343    ///
3344    /// The installed shape is writable + configurable, not enumerable.
3345    pub fn setter_that_ignores_prototype_properties(
3346        &mut self,
3347        this_value: Value,
3348        home: &Gc<JsObject>,
3349        property_key: &str,
3350        args: &[Value],
3351    ) -> JsResult<Value> {
3352        self.setter_that_ignores_prototype_properties_key(
3353            this_value,
3354            home,
3355            &PropertyKey::from(property_key),
3356            args,
3357        )
3358    }
3359
3360    /// [`Interp::setter_that_ignores_prototype_properties`] for a key that may be a symbol.
3361    ///
3362    /// `Iterator.prototype[@@toStringTag]`'s setter is the symbol-keyed caller.
3363    pub fn setter_that_ignores_prototype_properties_key(
3364        &mut self,
3365        this_value: Value,
3366        home: &Gc<JsObject>,
3367        key: &PropertyKey,
3368        args: &[Value],
3369    ) -> JsResult<Value> {
3370        let Some(receiver) = this_value.as_object().cloned() else {
3371            return Err(self.type_error("setter called on a non-object"));
3372        };
3373        if Gc::ptr_eq(&receiver, home) {
3374            return Err(self.type_error("cannot assign to the accessor's own home object"));
3375        }
3376        // No type check here: §7.3.40 takes an arbitrary `v`, and
3377        // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3378        // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3379        // before calling this.
3380        let value = args.first().cloned().unwrap_or(Value::Undefined);
3381        // Step 4: an own property on the receiver changes what happens, and there are three
3382        // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3383        // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3384        // `Set` with `throw = true`, and a test exists for each.
3385        if let Some(existing) = self.object_get_own_property(&receiver, key)? {
3386            if existing.is_accessor() && existing.setter.is_none() {
3387                // A getter-only own accessor cannot be written through.
3388                return Err(self.type_error("no setter for the own property"));
3389            }
3390            // Everything else — an own data property, or an own accessor *with* a setter —
3391            // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3392            // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3393            // an own user setter receives the value (`setter-own-accessor`), because
3394            // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3395            // setter directly is the difference between one code path and two that can
3396            // disagree.
3397            self.set_property_with_key(
3398                &receiver,
3399                key,
3400                value.clone(),
3401                crate::interp::DeleteFailure::Throw,
3402            )?;
3403            return Ok(Value::Undefined);
3404        }
3405        let property = Property {
3406            value: Some(value.clone()),
3407            writable: true,
3408            // Enumerable, despite the accessor it shadows not being. The reference installs
3409            // it that way and six cases check it (`setter-creates-own-property` and friends).
3410            enumerable: true,
3411            configurable: true,
3412            ..Property::default()
3413        };
3414        if !self.object_define_own_property(&receiver, key, property)? {
3415            return Err(self.type_error("the receiver refused the definition"));
3416        }
3417        Ok(Value::Undefined)
3418    }
3419
3420    /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3421    ///
3422    /// The indices of a typed array are not properties at all — they are bytes in the
3423    /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3424    /// fly. That makes their descriptor shape fixed: every valid index is writable,
3425    /// enumerable and configurable, so a definition can only ever change the *value*, and
3426    /// every other descriptor is refused rather than applied.
3427    ///
3428    /// The order of the checks is the spec's, and two of them are load-bearing:
3429    ///
3430    /// * the index is validated **before** the value is converted, because the conversion
3431    ///   itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3432    ///   detaches from a `valueOf` and still expects `true` with no store, which only
3433    ///   happens when the index was valid on the way in;
3434    /// * the store is attempted even when the index has gone out of bounds by the time the
3435    ///   conversion finishes, because the store is a silent no-op rather than a failure —
3436    ///   the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3437    ///   the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3438    ///
3439    /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3440    /// the existing element, which is harmless here: every valid index is already
3441    /// writable, enumerable and configurable, so a `false` in the merged property can only
3442    /// have come from the descriptor having named `false`.
3443    fn integer_indexed_define_own_property(
3444        &mut self,
3445        object: &Gc<JsObject>,
3446        numeric: f64,
3447        property: &Property,
3448    ) -> JsResult<bool> {
3449        // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3450        // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3451        if !typed_array_index_is_valid(object, numeric) {
3452            return Ok(false);
3453        }
3454        // Step 6: the indices are data properties, so an accessor descriptor is refused
3455        // rather than converted. `Object.defineProperty` turns the `false` into a
3456        // `TypeError`; `Reflect.defineProperty` reports it.
3457        if property.is_accessor() {
3458            return Ok(false);
3459        }
3460        // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3461        // definition that asks for anything else cannot be honoured.
3462        if !property.writable || !property.enumerable || !property.configurable {
3463            return Ok(false);
3464        }
3465        // Step 10: only a descriptor that names a value stores anything.
3466        let Some(value) = property.value.clone() else {
3467            return Ok(true);
3468        };
3469        let Some(element) = object.typed_array_element_type() else {
3470            return Ok(false);
3471        };
3472        let stored = self.element_value(element, value)?;
3473        if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3474            return Err(self.type_error(reason));
3475        }
3476        Ok(true)
3477    }
3478
3479    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3480    pub fn object_define_own_property(
3481        &mut self,
3482        object: &Gc<JsObject>,
3483        key: &PropertyKey,
3484        property: Property,
3485    ) -> JsResult<bool> {
3486        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3487            return Ok(accepted);
3488        }
3489        // §10.4.6.6 `[[DefineOwnProperty]]` for a module namespace.
3490        //
3491        // The only definitions that can succeed are ones describing the property the
3492        // namespace *already* has: `Reflect.defineProperty(ns, "x", {})` asks for no change
3493        // and answers `true`; so does `{value: <SameValue current>}` or the exact attribute
3494        // set `{writable: true, enumerable: true, configurable: false}`. A different value,
3495        // `writable: false`, `configurable: true`, or any name the namespace does not
3496        // export is `false`.
3497        //
3498        // The ordinary path gets the no-change case right by accident — it compares against
3499        // `[[GetOwnProperty]]` — but cannot describe a namespace binding, because the binding
3500        // is an accessor internally while the definition script writes is a data descriptor.
3501        // Answering here is what makes that attribute-only definition a no-op rather than a
3502        // refusal (`namespace/await-ns-define-own-property`).
3503        if object.module_namespace_marker() {
3504            self.trigger_deferred_namespace_for_key(object, key)?;
3505            return self.namespace_define_own_property(object, key, &property);
3506        }
3507        // A proxy always answers above — with `Some` from its trap, or with `None` when
3508        // the trap is absent, and then the definition belongs to the **target**
3509        // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3510        // when there is no trap). Falling through to the ordinary path here defined the
3511        // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3512        // property the target never saw.
3513        if object.proxy_state().is_some() {
3514            let Some((target, _handler)) = self.proxy_parts(object)? else {
3515                return Err(self.type_error("cannot use a proxy that has been revoked"));
3516            };
3517            return self.object_define_own_property(&target, key, property);
3518        }
3519        // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3520        // they accept exactly one descriptor shape. This has to happen before the
3521        // ordinary path, which would happily store a data property next to the buffer —
3522        // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3523        // and `TypedArray/prototype/set` are about this section.
3524        if object.typed_array_element_type().is_some()
3525            && let Some(index) = canonical_numeric_index(key)
3526        {
3527            return self.integer_indexed_define_own_property(object, index, &property);
3528        }
3529        // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3530        // non-extensible object. The check lives here rather than in the callers because
3531        // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3532        // `Array.prototype.filter` uses to store its result, and a species object made
3533        // non-extensible by its own constructor must make that a `TypeError`
3534        // (`target-array-non-extensible`).
3535        // Note the `is_none()`: an already-present property may still be **redefined** on a
3536        // non-extensible object, and only *adding* one is refused (as Distinct from
3537        // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3538        // properties — testing extensibility before looking for the property made every
3539        // `Object.freeze` of an ordinary object refuse its own second step).
3540        if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3541            return Ok(false);
3542        }
3543        // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3544        // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3545        // an omitted field is left alone). Merging here rather than at each call site is
3546        // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3547        // the value and `enumerable` in place.
3548        //
3549        // The merge is a no-op when the property is absent: there is nothing to keep.
3550        let was_partial = property.descriptor_fields.is_some();
3551        let property = match property.descriptor_fields {
3552            None => property,
3553            Some(fields) => {
3554                let base = self.object_get_own_property(object, key)?;
3555                let mut merged = base.clone().unwrap_or_default();
3556                // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3557                // descriptor names, and switching kind discards the other half —
3558                // `{set: f}` on a data property is an accessor with no getter, not a data
3559                // property whose `get` happens to be absent.
3560                let wants_accessor = fields.get || fields.set;
3561                let wants_data = fields.value || fields.writable;
3562                if wants_accessor {
3563                    merged.value = None;
3564                    merged.writable = false;
3565                    merged.getter = property.getter.clone();
3566                    merged.setter = property.setter.clone();
3567                } else if wants_data {
3568                    merged.getter = None;
3569                    merged.setter = None;
3570                    if fields.value {
3571                        merged.value = property.value.clone();
3572                    }
3573                    if fields.writable {
3574                        merged.writable = property.writable;
3575                    }
3576                }
3577                if fields.enumerable {
3578                    merged.enumerable = property.enumerable;
3579                }
3580                if fields.configurable {
3581                    merged.configurable = property.configurable;
3582                }
3583                merged.descriptor_fields = None;
3584                merged
3585            }
3586        };
3587        // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3588        // descriptor. `define_property_on` runs the same check before it calls here, so an
3589        // ordinary object is already covered; what is *not* is the forwarding a proxy does
3590        // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3591        // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3592        // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3593        // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3594        // own define would have refused.
3595        //
3596        // Only partial descriptors are validated here. A whole `Property` passed by an
3597        // internal caller (`Property::data(…)`) carries attributes that say nothing about
3598        // what the descriptor "named", and those callers rely on the write landing.
3599        if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3600            // Every branch below is gated on `!existing.configurable`: a *configurable*
3601            // property may be reshaped however the descriptor likes, which is why an
3602            // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3603            // must succeed. Testing only `writable` refused that and broke
3604            // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3605            let same_kind = existing.is_accessor() == property.is_accessor();
3606            if !same_kind {
3607                // Step 4: a non-configurable property may not change kind.
3608                if !existing.configurable {
3609                    return Ok(false);
3610                }
3611            } else if existing.is_accessor() {
3612                // Step 6: an accessor's halves are its value.
3613                if !existing.configurable
3614                    && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3615                        || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3616                {
3617                    return Ok(false);
3618                }
3619            } else if !existing.configurable && !existing.writable {
3620                // Step 7: a non-configurable *and* non-writable data property's value is
3621                // fixed, and it may not become writable again.
3622                if property.writable {
3623                    return Ok(false);
3624                }
3625                let current = existing.value.clone().unwrap_or(Value::Undefined);
3626                let requested = property.value.clone().unwrap_or(Value::Undefined);
3627                if !current.same_value(&requested) {
3628                    return Ok(false);
3629                }
3630            }
3631            // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3632            // is frozen with it.
3633            if !existing.configurable
3634                && (property.configurable || property.enumerable != existing.enumerable)
3635            {
3636                return Ok(false);
3637            }
3638        }
3639        // A host class that intercepts definitions owns the attributes of the properties it
3640        // defines: `_class`-style storage on the native side is the usual reason.
3641        if let Some(exotic) = object.exotic()
3642            && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3643        {
3644            return Ok(accepted);
3645        }
3646        // An array index is stored in the element vector, which can hold a plain value and
3647        // nothing else. An accessor — or a data property with non-default attributes —
3648        // therefore has to live in the property table, and the element slot is blanked so
3649        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3650        // {get})` stored the accessor where no read ever looked, and the array kept
3651        // answering its old value.
3652        // An array's `length` is not stored in the property table, so defining it has to
3653        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3654        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3655        // {value: 1})` reported success and changed nothing.
3656        if key.as_str() == Some("length") && object.is_array() {
3657            // `{writable: false}` on `length` does not change the length, but it does make
3658            // it read-only — after which neither a later `{writable: true}` nor a store
3659            // past the end may succeed.
3660            if property.value.is_none() {
3661                if !object.length_writable() && property.writable {
3662                    return Ok(false);
3663                }
3664                object.set_length_writable(property.writable);
3665                return Ok(true);
3666            }
3667            if !object.length_writable() {
3668                return Ok(false);
3669            }
3670        }
3671        if key.as_str() == Some("length")
3672            && object.is_array()
3673            && let Some(value) = property.value.clone()
3674        {
3675            let requested = value.to_number();
3676            let valid = requested.is_finite()
3677                && requested >= 0.0
3678                && requested.fract() == 0.0
3679                && requested <= u32::MAX as f64;
3680            if !valid {
3681                return Err(self.range_error("invalid array length"));
3682            }
3683            // Truncating deletes the elements above the new length, and a non-configurable
3684            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3685            // makes `a.length = 2` fail rather than quietly drop it.
3686            let current = object.array_length().unwrap_or(0);
3687            let requested = requested as usize;
3688            if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3689                // §10.4.2.4 `ArraySetLength` step 3.i.2: the refusal still applies
3690                // `[[Writable]]: false` when the descriptor asked for it — the length is
3691                // left at its old value but locked. Returning `false` alone left it
3692                // writable, which `verifyProperty` catches
3693                // (`defineProperties/15.2.3.7-6-a-164`).
3694                if property
3695                    .descriptor_fields
3696                    .is_some_and(|fields| fields.writable)
3697                    && !property.writable
3698                    && object.length_writable()
3699                {
3700                    object.set_length_writable(false);
3701                }
3702                return Ok(false);
3703            }
3704            object.array_set_length(self.heap, requested);
3705            return Ok(true);
3706        }
3707        let plain = property.writable
3708            && property.enumerable
3709            && property.configurable
3710            && !property.is_accessor();
3711        if let Some(index) = key.as_str().and_then(array_index)
3712            && object.is_array()
3713        {
3714            // Growing the array needs a writable `length`: after
3715            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3716            // be added.
3717            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3718                return Ok(false);
3719            }
3720            if plain && property.value.is_some() {
3721                // An ordinary element: the vector is where a read looks first, so it has
3722                // to be the vector that changes — unless the index is too far out to be
3723                // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3724                // one property, because past its own limit it stores the index as an
3725                // ordinary key. Falling through to `define_key` below is the same choice,
3726                // and the alternative was worse: the store used to be *dropped* and the
3727                // length left at 0, which is a silent wrong answer.
3728                let value = property.value.clone().unwrap_or(Value::Undefined);
3729                object.delete_key(key);
3730                if object.array_set(self.heap, index as usize, value) {
3731                    return Ok(true);
3732                }
3733                // Past the dense limit the element lives in the table like any property.
3734                object.note_element_descriptor();
3735                object.define_key(key, property);
3736                // A sparse store past the dense limit still extends `length`, which is what
3737                // `a[a.length] = v` relies on — but only extends: shortening would delete
3738                // the sparse properties above the index, including this one.
3739                if index as usize + 1 > object.array_length().unwrap_or(0) {
3740                    object.array_set_length(self.heap, index as usize + 1);
3741                }
3742                return Ok(true);
3743            }
3744            // A non-plain element — an accessor, or an attribute that is not the default —
3745            // lives in the table while the slot becomes a hole. Recording it keeps every
3746            // later `a[i] = v` off the dense path, where the write would have shadowed the
3747            // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3748            // replace the accessor with a plain data property.
3749            object.note_element_descriptor();
3750            object.define_key(key, property);
3751            // The slot stays, so `length` does not shrink; a hole is not an element, so
3752            // the table entry is now what a read finds.
3753            object.array_set(self.heap, index as usize, Value::Hole);
3754            // `ArraySetLength` step 2 of `OrdinaryDefineOwnProperty`'s index branch —
3755            // `length = index + 1` — applies whatever the descriptor's *attributes* are,
3756            // not just to a plain one: `Object.defineProperty(a, 4294967294, {value: 100})`
3757            // makes `a.length` 4294967295 (`defineProperty/15.2.3.6-4-183`).
3758            if index as usize + 1 > object.array_length().unwrap_or(0) {
3759                object.array_set_length(self.heap, index as usize + 1);
3760            }
3761            return Ok(true);
3762        }
3763        object.define_key(key, property);
3764        Ok(true)
3765    }
3766
3767    /// Build a proxy object over `target`, with its traps read from `handler`.
3768    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3769        JsObject::proxy(self.heap, target, handler)
3770    }
3771
3772    /// The `revoke` function for a proxy's slots.
3773    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3774        let revoke = JsObject::function(
3775            self.heap,
3776            Some(self.realm.function_proto.clone()),
3777            Callable::Revoker(slots),
3778        );
3779        // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3780        // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3781        // inherited from `Function.prototype` reads the same but fails the three cases that
3782        // check the own-property list (`revocation-function-{length,name,property-order}`).
3783        revoke.define("length", Property::name_or_length(Value::Int(0)));
3784        revoke.define("name", Property::name_or_length(self.string("")));
3785        revoke
3786    }
3787
3788    /// A new array.
3789    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3790        let array = JsObject::array(
3791            self.heap,
3792            Some(self.realm.array_proto.clone()),
3793            elements.len(),
3794        );
3795        for (index, element) in elements.into_iter().enumerate() {
3796            array.array_set(self.heap, index, element);
3797        }
3798        array
3799    }
3800
3801    /// A new native function object.
3802    ///
3803    /// The observable `name` and `length` are installed as properties here, which is
3804    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3805    /// so `f.name = "x"` behaves like the writable property it is.
3806    /// A native constructor that builds its own instance after validating its arguments.
3807    ///
3808    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3809    /// check runs before `new.target.prototype` is read.
3810    pub fn new_native_ctor(
3811        &self,
3812        name: impl Into<String>,
3813        length: u32,
3814        func: NativeFn,
3815    ) -> Gc<JsObject> {
3816        let function = JsObject::function(
3817            self.heap,
3818            Some(self.realm.function_proto.clone()),
3819            Callable::Native {
3820                func,
3821                own_instance: true,
3822            },
3823        );
3824        function.set_constructible(true);
3825        function.define(
3826            "length",
3827            Property::name_or_length(Value::Int(length as i32)),
3828        );
3829        function.define("name", Property::name_or_length(self.string(name)));
3830        function
3831    }
3832
3833    /// A native constructor that lets `new` build the instance first.
3834    ///
3835    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3836    /// validation that must precede reading `new.target.prototype`, so the object can be
3837    /// created before the implementation runs. Distinct from [`Interp::new_native`],
3838    /// which makes a *method* and therefore not a constructor at all.
3839    pub fn new_native_constructor(
3840        &self,
3841        name: impl Into<String>,
3842        length: u32,
3843        func: NativeFn,
3844    ) -> Gc<JsObject> {
3845        let function = self.new_native(name, length, func);
3846        function.set_constructible(true);
3847        function
3848    }
3849
3850    /// A new host function object: a native closure that carries its own state.
3851    ///
3852    /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3853    /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3854    /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3855    /// this safe: the closure must not capture a `Gc`.
3856    pub fn new_host_function(
3857        &self,
3858        name: impl Into<String>,
3859        length: u32,
3860        func: crate::object::HostFn,
3861    ) -> Gc<JsObject> {
3862        self.new_host_inner(name.into(), length, func, false)
3863    }
3864
3865    /// A host constructor: `new` hands it `this = undefined`, so it validates its
3866    /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3867    pub fn new_host_ctor(
3868        &self,
3869        name: impl Into<String>,
3870        length: u32,
3871        func: crate::object::HostFn,
3872    ) -> Gc<JsObject> {
3873        let function = self.new_host_inner(name.into(), length, func, true);
3874        function.set_constructible(true);
3875        // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3876        // installs its own methods on it, so it starts as a plain object.
3877        let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3878        function.define(
3879            "prototype",
3880            Property {
3881                value: Some(Value::Object(proto)),
3882                writable: true,
3883                enumerable: false,
3884                configurable: false,
3885                ..Property::default()
3886            },
3887        );
3888        function
3889    }
3890
3891    fn new_host_inner(
3892        &self,
3893        name: String,
3894        length: u32,
3895        func: crate::object::HostFn,
3896        own_instance: bool,
3897    ) -> Gc<JsObject> {
3898        let function = JsObject::function(
3899            self.heap,
3900            Some(self.realm.function_proto.clone()),
3901            Callable::Host {
3902                func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3903                own_instance,
3904            },
3905        );
3906        function.define(
3907            "length",
3908            Property::name_or_length(Value::Int(length as i32)),
3909        );
3910        function.define("name", Property::name_or_length(self.string(name)));
3911        function
3912    }
3913
3914    /// A callable object with the `length`/`name` a built-in function has, in that order.
3915    ///
3916    /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3917    /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3918    /// [`JsObject::function`] defines neither, which is why every capability helper built
3919    /// with it reported no own `length` and no own `name` at all.
3920    ///
3921    /// The attributes are the spec's for a built-in: not writable, not enumerable,
3922    /// configurable.
3923    pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3924        let function =
3925            JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3926        function.define(
3927            "length",
3928            Property::name_or_length(Value::Int(length as i32)),
3929        );
3930        function.define("name", Property::name_or_length(self.string(name)));
3931        function
3932    }
3933
3934    /// A new native function object.
3935    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3936        let function = JsObject::function(
3937            self.heap,
3938            Some(self.realm.function_proto.clone()),
3939            Callable::Native {
3940                func,
3941                own_instance: false,
3942            },
3943        );
3944        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3945        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3946        // `length,name` and this listed `name,length`. A bytecode function already gets it
3947        // the right way round; only native ones were built backwards.
3948        function.define(
3949            "length",
3950            Property::name_or_length(Value::Int(length as i32)),
3951        );
3952        function.define("name", Property::name_or_length(self.string(name)));
3953        function
3954    }
3955
3956    /// A new bound function.
3957    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3958        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3959        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3960        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3961        let constructible = target
3962            .as_object()
3963            .is_some_and(|target| target.is_constructor());
3964        let bound = JsObject::function(
3965            self.heap,
3966            Some(self.realm.function_proto.clone()),
3967            Callable::Bound { target, this, args },
3968        );
3969        bound.set_constructible(constructible);
3970        bound
3971    }
3972
3973    /// A new reference cell.
3974    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3975        Gc::new(self.heap, Cell::new(value))
3976    }
3977
3978    // -- running ------------------------------------------------------------
3979
3980    /// Evaluate `code` as a script body and return its completion value.
3981    /// Compile and run `source` for the engine's own use, returning its completion value.
3982    ///
3983    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3984    /// needs to be a real async function, and the engine already runs those as coroutines,
3985    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3986    ///
3987    /// Differences from [`Self::eval_in_global`], both deliberate:
3988    ///
3989    /// * It does **not** drain the microtask queue. Install runs while the realm is still
3990    ///   being built, and the source is an IIFE that only constructs a closure, so there
3991    ///   is nothing to drain — and draining here would run script-queued jobs in the
3992    ///   middle of `install`.
3993    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3994    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3995    ///   and it should not look like the user wrote something wrong.
3996    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3997        let program = match js_parse::parse_script(source) {
3998            Ok(program) => program,
3999            Err(error) => {
4000                let message = format!("builtin source does not parse: {error}");
4001                return Err(Signal::Throw(self.make_error("InternalError", &message)));
4002            }
4003        };
4004        let mut code = match js_compile::compile_script_with_source(&program, source) {
4005            Ok(code) => code,
4006            Err(error) => {
4007                let message = format!("builtin source does not compile: {}", error.message);
4008                return Err(Signal::Throw(self.make_error("InternalError", &message)));
4009            }
4010        };
4011        // The frame has to name something, and `<builtin>` is what a stack trace through
4012        // this code should say.
4013        code.set_filename("<builtin>");
4014        let compiled = Gc::new(self.heap, CompiledCode::new(code));
4015        let closure_vars = compiled.code.closure_vars.clone();
4016        let env = self.global_env(&closure_vars);
4017        let this = Value::Object(self.realm.global.clone());
4018        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
4019    }
4020
4021    /// Run an already-parsed script and drain the microtasks it queued.
4022    ///
4023    /// The drain is what lets an `async` function's body advance past its first `await`
4024    /// before the host sees the result: nothing else pumps the job queue.
4025    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
4026        let this = Value::Object(self.realm.global.clone());
4027        self.run_script_with_this(code, this)
4028    }
4029
4030    /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
4031    ///
4032    /// The reference evaluates a global script with whatever `this_obj` the host passed, and
4033    /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
4034    /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
4035    /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
4036    /// state the next script evaluation tripped over.
4037    pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
4038        let compiled = Gc::new(self.heap, CompiledCode::new(code));
4039        let closure_vars = compiled.code.closure_vars.clone();
4040        let env = self.global_env(&closure_vars);
4041        let callee = Value::Undefined;
4042        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
4043        // The script is done, so the microtasks it queued run before the host sees the
4044        // result. Without this an `async` function's body would never advance past its
4045        // first `await`, because nothing else drains the queue.
4046        self.drain_jobs()?;
4047        Ok(result)
4048    }
4049
4050    /// Compile and run `source` in global scope, returning its completion value.
4051    ///
4052    /// This is what `eval` and `new Function` use. Running it as a script means it
4053    /// sees the global object and nothing else, which is right for `eval("1+1")` and
4054    /// for a `Function` body; a *direct* eval that reads a local variable would need
4055    /// the compiler to hand its variable environment over, which is not implemented.
4056    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
4057        self.eval_in_global_named(source, EVAL_FILE, false, true)
4058    }
4059
4060    /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
4061    ///
4062    /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
4063    /// shows `<evalScript>` — and the name is visible in every stack trace that passes
4064    /// through the code, so they cannot share one constant.
4065    pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
4066        // *Not* an eval body: `evalScript` evaluates a global script, so its top-level
4067        // `let`/`const`/`class` are global lexical bindings that outlive the call — which
4068        // is exactly what `global-code/script-decl-lex*` assert.
4069        self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier, false)
4070    }
4071
4072    /// Evaluate `source` as a global script, reported under `file`.
4073    ///
4074    /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
4075    /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
4076    /// from inside a C callback, where the interpreter is the running one rather than a
4077    /// context's own.
4078    pub fn eval_in_global_named(
4079        &mut self,
4080        source: &str,
4081        file: &str,
4082        barrier: bool,
4083        is_eval: bool,
4084    ) -> JsResult<Value> {
4085        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
4086        // eval-created global binding — configurable, unlike a script's own `var`.
4087        self.eval_depth += 1;
4088        if barrier {
4089            let depth = self.frames.len();
4090            self.trace_barriers.push(depth);
4091        }
4092        let result = self.eval_in_global_inner(source, file, is_eval);
4093        if barrier {
4094            self.trace_barriers.pop();
4095        }
4096        self.eval_depth -= 1;
4097        result
4098    }
4099
4100    fn eval_in_global_inner(&mut self, source: &str, file: &str, is_eval: bool) -> JsResult<Value> {
4101        self.compiling_eval_body = is_eval;
4102        let compiled = self.compile_global_script(source, file, false);
4103        self.compiling_eval_body = false;
4104        let compiled = compiled?;
4105        let strict = compiled.strict;
4106        self.run_eval_script(compiled, strict)
4107    }
4108
4109    /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
4110    ///
4111    /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
4112    /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
4113    /// is script-scoped, `var` becomes a global, and the body is not confined the way a
4114    /// direct eval's is.
4115    pub fn eval_script_with_this(
4116        &mut self,
4117        source: &str,
4118        file: &str,
4119        this: Value,
4120    ) -> JsResult<Value> {
4121        let program = match js_parse::parse_script(source) {
4122            Ok(program) => program,
4123            Err(error) => {
4124                return Err(Signal::Throw(self.syntax_error_at(
4125                    file,
4126                    error.span.start.line,
4127                    error.span.start.column,
4128                    &error.message,
4129                )));
4130            }
4131        };
4132        let mut compiled = match js_compile::compile_script(&program) {
4133            Ok(compiled) => compiled,
4134            Err(error) => {
4135                return Err(Signal::Throw(self.syntax_error_at(
4136                    file,
4137                    error.span.start.line,
4138                    error.span.start.column,
4139                    &error.message,
4140                )));
4141            }
4142        };
4143        compiled.set_filename(file);
4144        self.run_script_with_this(compiled, this)
4145    }
4146
4147    /// Parse and compile `source` as a global script, without running it.
4148    ///
4149    /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
4150    /// before a promise exists to reject — while still evaluating in the same eval context
4151    /// (direct-eval strictness, `new.target`, `super`).
4152    fn compile_global_script(
4153        &mut self,
4154        source: &str,
4155        file: &str,
4156        async_body: bool,
4157    ) -> JsResult<CompiledFunction> {
4158        // Nothing of the caller's is inherited by an *indirect* eval: `(0, eval)('super.x')`
4159        // and `(0, eval)('arguments')` are both `SyntaxError`s because there is no caller
4160        // context at all. The site is what tells the two apart — an indirect call leaves no
4161        // site behind, since only a bare `eval(...)` is recorded.
4162        let site = self.eval_site_at_cursor();
4163        // Strictness follows the same rule, and it is *not* a detail: §19.2.1.1 step 4
4164        // makes the eval code strict when the caller is strict **and the call is direct**.
4165        // So `var s = eval; s("var eval;")` called from strict code is sloppy — legal —
4166        // while `eval("var eval;")` there is a `SyntaxError`
4167        // (`statements/variable/12.2.1-*-s`). Inheriting unconditionally rejected the
4168        // indirect form. A `"use strict"` prologue in the source still works either way:
4169        // the parser reads the directive itself, which is how a script becomes strict.
4170        let strict = site.is_some() && self.current_strict();
4171        // `eval` runs in the caller's function context, so `new.target` is legal here
4172        // even though the source is a bare script — and so is `super.x` when the caller
4173        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
4174        // caller's, which is what `special_object 4` already does.
4175        let private = site
4176            .map(|site| site.private_names.clone())
4177            .unwrap_or_default();
4178        let context = js_parse::EvalContext {
4179            in_method: site.is_some() && self.enclosing_home_object().is_some(),
4180            // `super()` belongs to a derived constructor, and an eval'd body is not a
4181            // constructor at all: the caller frame's `this` is already built.
4182            in_derived_constructor: false,
4183            // Private names are lexically scoped, so a direct `eval` inside a class body
4184            // can see them; see `Interp::eval_private_names`.
4185            private_names: private.iter().map(|entry| entry.name.clone()).collect(),
4186            arguments_allowed: site.is_none_or(|site| site.arguments_allowed),
4187            // §19.2.1.1 asks the *caller's* function for `new.target`, and a script or
4188            // module body is not one: at the top level `eval('new.target')` is a
4189            // `SyntaxError`, not `undefined` (`eval-code/direct/new.target`).
4190            // The *nearest non-arrow* frame, because an arrow has no `new.target` of its
4191            // own and `() => eval("new.target")` at the top level is still a
4192            // `SyntaxError` (`new.target-arrow`).
4193            new_target_allowed: site.is_some()
4194                && !self
4195                    .frames
4196                    .iter()
4197                    .rposition(|frame| !frame.code.code.is_arrow)
4198                    .map(|index| self.frames[index].code.code.is_script_body)
4199                    .unwrap_or(true),
4200        };
4201        // A *global* eval is not a function body: `new.target` and `super` are out of
4202        // reach there. Its `{async: true}` form differs in the other direction — the body
4203        // may `await` — so the two flags are independent and the reference sets both from
4204        // the eval type rather than from the caller.
4205        let parsed = if async_body {
4206            js_parse::parse_suspensible_global_eval(source, strict)
4207        } else {
4208            js_parse::parse_eval_script_in(source, strict, context)
4209        };
4210        let program = match parsed {
4211            Ok(program) => program,
4212            Err(error) => {
4213                // The message is bare: the position lives in `fileName`,
4214                // `lineNumber`, `columnNumber` and the stack frame above, which is where
4215                // the reference puts it. An `invalid source: L:C: ` prefix made
4216                // `e.message` differ from the reference while the stack already agreed.
4217                return Err(Signal::Throw(self.syntax_error_at(
4218                    file,
4219                    error.span.start.line,
4220                    error.span.start.column,
4221                    &error.message,
4222                )));
4223            }
4224        };
4225        let is_eval_body = self.compiling_eval_body;
4226        let mut compiled = match if async_body {
4227            js_compile::compile_eval_with_private(&program, &private, true, is_eval_body)
4228        } else {
4229            js_compile::compile_eval_with_private(&program, &private, false, is_eval_body)
4230        } {
4231            Ok(compiled) => compiled,
4232            // A construct the compiler does not handle yet is reported the same way a
4233            // parse error is: it happens before anything runs, so the trace is the
4234            // position in the source followed by the caller.
4235            Err(error) => {
4236                return Err(Signal::Throw(self.syntax_error_at(
4237                    file,
4238                    error.span.start.line,
4239                    error.span.start.column,
4240                    &error.message,
4241                )));
4242            }
4243        };
4244        compiled.set_filename(file);
4245        Ok(compiled)
4246    }
4247
4248    /// The private names the code at the current position can see, innermost first.
4249    ///
4250    /// Private names are lexically scoped (§15.10.2 `AllPrivateIdentifiersValid`), and a
4251    /// direct `eval` runs inside its caller's scope, so
4252    /// `class C { #m = 44; f() { return eval("this.#m") } }` is legal. The names belong to the
4253    /// *call site's* compilation unit, so they are recorded on the `EvalSite` and read back
4254    /// here rather than being derivable from the eval'd source.
4255    ///
4256    /// An indirect `eval` gets nothing: `(0, eval)("this.#m")` outside a class is a
4257    /// `SyntaxError`, and an indirect call leaves no site behind, which is exactly the test
4258    /// [`Interp::run_eval_script`] uses for "direct".
4259    fn eval_site_at_cursor(&self) -> Option<&js_compile::bytecode::EvalSite> {
4260        let frame = self.frames.last()?;
4261        let (line, column) = frame
4262            .code
4263            .code
4264            .position_at(frame.at as u32)
4265            .unwrap_or_default();
4266        // The nearest site at or before the current position: the recorded position of the
4267        // `call` instruction is the callee's, which sits a few columns inside the call
4268        // expression the compiler recorded, so an exact match would never be found.
4269        frame
4270            .code
4271            .code
4272            .eval_sites
4273            .iter()
4274            .filter(|site| (site.line, site.column) <= (line, column))
4275            .max_by_key(|site| (site.line, site.column))
4276    }
4277
4278    /// Run an `eval`'d script in the caller's scope.
4279    ///
4280    /// Three things have to come from the calling frame, because the eval'd code is a
4281    /// script and would otherwise see only the global object:
4282    ///
4283    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
4284    /// * `arguments`, exposed as a binding of the eval's own scope, so
4285    ///   `f("arguments.length", 1)` sees the caller's arguments;
4286    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
4287    ///   `eval("var v = 1")` into the global object.
4288    ///
4289    /// Locals of the calling function are *not* reachable: that needs the compiler to
4290    /// hand its variable environment over, which this milestone does not do.
4291    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
4292        // `this` and `arguments` come from the innermost frame only — those are not
4293        // lexical — while the name bindings come from the whole chain of frames, part
4294        // of it being ordinary scope resolution.
4295        // An arrow has no `this` of its own, so an `eval` inside one inherits the
4296        // enclosing function's receiver — the lexical `this` the arrow was compiled to
4297        // read from its closure.
4298        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
4299        // variable environment is the innermost frame of all: an arrow's own body is where
4300        // `var`s declared by an `eval` inside it belong.
4301        let caller_index = self
4302            .frames
4303            .iter()
4304            .rposition(|frame| !frame.code.code.is_arrow)
4305            .or_else(|| self.frames.len().checked_sub(1));
4306        let env_index = self.frames.len().checked_sub(1);
4307        let caller = caller_index.and_then(|index| self.frames.get(index));
4308        let (this, passed) = match caller {
4309            Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
4310            // No frame at all: the eval is running at the top level, so there is
4311            // nothing to inherit and the global receiver is right.
4312            None => (Value::Object(self.realm.global.clone()), Vec::new()),
4313        };
4314        // Innermost frame first, so the first binding found for a name is the one that
4315        // shadows the rest. A script frame (`<eval>`) contributes nothing.
4316        let mut bindings: Vec<EvalBinding> = Vec::new();
4317        // The calling function's own bindings, resolved by the compiler at the call
4318        // site. That table is the only reliable answer when a name is declared twice in
4319        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
4320        // body means, and guessing by declaration order picks the wrong one as soon as
4321        // two loops in a row use the same name.
4322        // Only a *direct* eval sees the caller's scope. The compiler records a site for
4323        // every direct call — a bare `eval(...)` callee — so finding one at the current
4324        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
4325        // callee to a value first and leave no site behind.
4326        let mut direct = false;
4327        let mut resolved_here = false;
4328        if let Some(frame) = self.frames.last() {
4329            let (line, column) = frame
4330                .code
4331                .code
4332                .position_at(frame.at as u32)
4333                .unwrap_or_default();
4334            // The nearest site at or before the current position, not an exact match:
4335            // the recorded position of the `call` instruction is the callee's, which
4336            // sits a few columns inside the call expression the compiler recorded. A
4337            // site is unique per call, so "the closest one behind us" identifies it.
4338            if let Some(site) = frame
4339                .code
4340                .code
4341                .eval_sites
4342                .iter()
4343                .filter(|site| (site.line, site.column) <= (line, column))
4344                .max_by_key(|site| (site.line, site.column))
4345            {
4346                direct = true;
4347                resolved_here = true;
4348                for binding in &site.bindings {
4349                    // An enclosing function's frame sits `owner` levels below the one
4350                    // running the call.
4351                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
4352                    else {
4353                        continue;
4354                    };
4355                    bindings.push(EvalBinding {
4356                        name: binding.name.clone(),
4357                        frame,
4358                        slot: if binding.is_arg {
4359                            EvalSlot::Arg
4360                        } else {
4361                            EvalSlot::Local
4362                        },
4363                        index: binding.index as usize,
4364                    });
4365                }
4366            }
4367        }
4368        for frame_index in (0..self.frames.len()).rev() {
4369            // Skip the innermost frame's flat scan when the compiler already answered
4370            // for it; an enclosing frame still needs one, because the eval resolves
4371            // those names dynamically.
4372            if resolved_here && frame_index == self.frames.len() - 1 {
4373                continue;
4374            }
4375            let frame = &self.frames[frame_index];
4376            for (index, arg) in frame.code.code.args.iter().enumerate() {
4377                bindings.push(EvalBinding {
4378                    name: arg.name.clone(),
4379                    frame: frame_index,
4380                    slot: EvalSlot::Arg,
4381                    index,
4382                });
4383            }
4384            for (index, local) in frame.code.code.vars.iter().enumerate() {
4385                bindings.push(EvalBinding {
4386                    name: local.name.clone(),
4387                    frame: frame_index,
4388                    slot: EvalSlot::Local,
4389                    index,
4390                });
4391            }
4392        }
4393        let mut seen = BTreeSet::new();
4394        bindings.retain(|binding| seen.insert(binding.name.clone()));
4395
4396        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4397        // elements is all the spec's ordinary uses need.
4398        //
4399        // Known divergence: this is bound for a *global* eval too, where there is no
4400        // caller and the reference throws `'arguments' is not defined`. Deciding properly
4401        // needs "does the calling frame have an `arguments` of its own", which is not
4402        // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4403        // script or eval body does not, and `eval(b)` passes the callee as a value so even
4404        // the call-site detection does not answer it. Modelled as a binding in the caller's
4405        // variable environment, this would fall out; that is a larger change than the one
4406        // this comment is attached to.
4407        let arguments = Value::Object(self.new_array(passed));
4408
4409        // Only a *strict* eval gets a variable environment of its own. A sloppy one
4410        // declares its `var`s in the caller's — which for a top-level eval is the global
4411        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4412        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4413        // vanish into a scope nobody reads back from.
4414        if code_strict {
4415            self.eval_scope.push(BTreeMap::new());
4416        }
4417        // Only a *direct* eval inherits the caller's arguments object. An indirect one runs
4418        // in global scope, where `arguments` means whatever the global object says — which
4419        // is why `var arguments = 1; class C { x = (0, eval)('arguments;') }` answers `1`
4420        // (`indirect-eval-contains-arguments`). Binding the caller's array there made it
4421        // answer the array instead.
4422        let previous_arguments = if direct {
4423            self.eval_arguments.replace(arguments)
4424        } else {
4425            None
4426        };
4427        let previous_with = self.eval_with.replace(self.with_objects());
4428        let inherited_new_target = self
4429            .frames
4430            .iter()
4431            .rev()
4432            .find(|frame| !frame.code.code.is_arrow)
4433            .map(|frame| frame.new_target.clone());
4434        let previous_new_target = self
4435            .eval_new_target
4436            .replace(inherited_new_target.unwrap_or(Value::Undefined));
4437        let eval_cells = self.eval_cells_for(&bindings);
4438        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4439        // A sloppy direct eval declares its `var`s in the caller's variable environment;
4440        // `declare_eval_local` needs to know which frame that is.
4441        // An indirect eval gets the global environment, so nothing of the caller's is
4442        // recorded as the place its `var`s belong.
4443        let previous_caller = self
4444            .eval_caller
4445            .replace(if direct { env_index } else { None });
4446        // The cell-based view of the same bindings, which is what a closure created
4447        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4448        // whose compiler did not put a binding in a cell simply does not appear here —
4449        // reads and writes still work through `eval_bindings`, they just cannot outlive
4450        // the eval.
4451        let previous_eval_scope = self
4452            .active_eval_scope
4453            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4454        let compiled = Gc::new(self.heap, CompiledCode::new(code));
4455        let closure_vars = compiled.code.closure_vars.clone();
4456        // Declaration instantiation is where this belongs: the check needs the caller frame
4457        // (recorded just above) and the eval's own var names, and it raises before any of
4458        // the eval's code runs.
4459        self.check_eval_var_named_arguments(&closure_vars, code_strict)?;
4460        let env = self.global_env(&closure_vars);
4461        let callee = Value::Undefined;
4462        // An async body does not run here: it becomes a coroutine and answers a promise,
4463        // which is what makes `await` legal in it. `this` still has to be the caller's
4464        // (for a global eval, the global object), because `this` is not part of `await`.
4465        let result = if compiled.code.kind.is_async() {
4466            self.run_async_body(compiled, env, this)
4467        } else {
4468            self.execute(compiled, env, this, Vec::new(), callee)
4469        };
4470        if code_strict {
4471            self.eval_scope.pop();
4472        }
4473        self.eval_arguments = previous_arguments;
4474        self.eval_with = previous_with;
4475        self.eval_new_target = previous_new_target;
4476        self.eval_bindings = previous_bindings;
4477        self.eval_caller = previous_caller;
4478        self.active_eval_scope = previous_eval_scope;
4479        result
4480    }
4481
4482    /// The declarations an eval cannot instantiate: they are `SyntaxError`/`TypeError`
4483    /// rather than bindings.
4484    ///
4485    /// Two rules, both from `EvalDeclarationInstantiation` (§19.2.1.3) and both about a
4486    /// declaration that cannot exist:
4487    ///
4488    /// * **`var arguments` in a function's parameter scope.** §10.2.1.3 gives a function with
4489    ///   parameter expressions a separate parameter environment, and `arguments` is bound
4490    ///   implicitly there, so a `var` of that name collides. An arrow that binds no
4491    ///   `arguments` of its own has nothing to collide with and is allowed — see the table in
4492    ///   [`Interp::check_eval_var_named_arguments`].
4493    /// * **A global `var` on a non-extensible global object**, where `CanDeclareGlobalVar` is
4494    ///   false; the operation is a `TypeError`, and `eval("var x")` with
4495    ///   `Object.preventExtensions(this)` must raise rather than quietly do nothing
4496    ///   (`non-definable-global-var` and its four siblings).
4497    fn check_eval_var_named_arguments(
4498        &self,
4499        closure_vars: &[js_compile::bytecode::ClosureVar],
4500        strict: bool,
4501    ) -> JsResult<()> {
4502        if strict {
4503            // A strict eval declares nothing outside itself, so none of the checks below
4504            // apply — they are all about the environment the declarations land in.
4505            return Ok(());
4506        }
4507        // §19.2.1.3 step 5.a: a `var` name that the *caller's* lexical environment already
4508        // binds is a `SyntaxError`, because the declaration would have to go into a
4509        // variable environment that sits inside that binding. `{ let x; eval("var x") }`
4510        // and a top-level `let x; eval("var x")` are both refused
4511        // (`var-env-lower-lex-non-strict`, `var-env-global-lex-non-strict`).
4512        //
4513        // The realm's `let`/`const`/`class` table is the global case; a caller frame's
4514        // lexical local is the nested one. `EvalSlot::Local` covers both, so the check has
4515        // to ask each binding whether it is lexical — which the *compiled code* knows.
4516        // A **declaration**, not a mention: the closure table carries an entry for every
4517        // global name the body touches, and only `GlobalDecl` means the eval itself would
4518        // create the binding. Without this, `for (let a …) eval("() => a")` looked like an
4519        // eval declaring `a` and was refused.
4520        let var_names = closure_vars.iter().filter(|var| {
4521            !var.is_lexical
4522                // `arguments` is not a lexical declaration wherever it appears: the
4523                // implicit one is var-like, and a *parameter* named `arguments` is handled
4524                // by the parameter-scope rule further down. Treating it as lexical made
4525                // every `eval("var arguments")` inside a nested arrow a `SyntaxError`.
4526                && var.name != "*default*"
4527                && var.name != "arguments"
4528                && matches!(
4529                    var.closure_type,
4530                    js_compile::bytecode::ClosureType::GlobalDecl
4531                )
4532        });
4533        for var in var_names {
4534            if self.realm.globals.contains_key(&var.name) {
4535                return Err(Signal::Throw(self.make_error(
4536                    "SyntaxError",
4537                    &format!(
4538                        "eval declares '{}', which an enclosing lexical binding also names",
4539                        var.name
4540                    ),
4541                )));
4542            }
4543            // Only a *direct* eval has a caller environment to collide with. An indirect
4544            // one declares into the global environment, whose `thisLex` is already
4545            // `varEnv`, so the walk in §19.2.1.3 step 5.d has nothing to traverse —
4546            // `{ let x; (0, eval)("var x") }` is legal
4547            // (`eval-code/indirect/var-env-lower-lex-non-strict`).
4548            let lexical = self.eval_caller.flatten().is_some()
4549                && self.eval_bindings.iter().any(|binding| {
4550                    binding.name == var.name
4551                        && matches!(binding.slot, EvalSlot::Local)
4552                        && self
4553                            .frames
4554                            .get(binding.frame)
4555                            .and_then(|frame| frame.code.code.vars.get(binding.index))
4556                            .is_some_and(|local| local.is_lexical)
4557                });
4558            if lexical {
4559                return Err(Signal::Throw(self.make_error(
4560                    "SyntaxError",
4561                    &format!(
4562                        "eval declares '{}', which an enclosing lexical binding also names",
4563                        var.name
4564                    ),
4565                )));
4566            }
4567        }
4568        // A `var` this eval would declare on the global object, where there is no room for it.
4569        //
4570        // Two different rules, and the difference is the whole reason `ClosureVar` carries
4571        // `is_function_decl`:
4572        //
4573        // * `CanDeclareGlobalVar` — `var` — only asks that the global object be extensible
4574        //   when the property does not exist at all, so `eval("var NaN")` is fine.
4575        // * `CanDeclareGlobalFunction` also refuses an existing property that is
4576        //   non-configurable unless it is a writable, enumerable data property, so
4577        //   `eval("function NaN(){}")` is a `TypeError`
4578        //   (`non-definable-global-function`).
4579        let global = &self.realm.global;
4580        for var in closure_vars {
4581            if var.is_lexical || var.name == "*default*" {
4582                continue;
4583            }
4584            if !matches!(
4585                var.closure_type,
4586                js_compile::bytecode::ClosureType::GlobalDecl
4587            ) {
4588                continue;
4589            }
4590            match global.own_property(&var.name) {
4591                None => {
4592                    if !global.is_extensible() {
4593                        return Err(Signal::Throw(self.make_error(
4594                            "TypeError",
4595                            "cannot declare a global in a non-extensible global object",
4596                        )));
4597                    }
4598                }
4599                Some(existing) => {
4600                    if var.is_function_decl
4601                        && !existing.configurable
4602                        && !(!existing.is_accessor() && existing.writable && existing.enumerable)
4603                    {
4604                        return Err(Signal::Throw(self.make_error(
4605                            "TypeError",
4606                            &format!("cannot declare global function '{}'", var.name),
4607                        )));
4608                    }
4609                }
4610            }
4611        }
4612        // Only a *direct* eval declares into a caller's environment; an indirect one gets the
4613        // global environment, where `var arguments` is an ordinary global.
4614        let Some(caller) = self.eval_caller.flatten() else {
4615            return Ok(());
4616        };
4617        // §19.2.1.1 step 8: in a sloppy eval, a `var` name that the *running lexical
4618        // environment* already binds is a `SyntaxError`. While a default expression is being
4619        // evaluated that environment is the **parameter** scope, so
4620        // `function(a = eval("var a = 42")){}` throws rather than writing to the parameter —
4621        // the eval would otherwise declare into an environment that is about to be copied
4622        // into the body. A *different* name is fine, and so is the same name in a function
4623        // with a simple parameter list, where there is no separate parameter environment and
4624        // the `var` belongs to the function's own.
4625        //
4626        // The names come from `args`, which is exactly the plain-identifier parameters. A
4627        // pattern parameter's bindings are also in that scope but are not recoverable from
4628        // the bytecode, so `function([a] = eval("var a")){}` is still accepted; that gap is
4629        // narrower than the one this closes and needs the parameter scope published in the
4630        // compiled function to fix.
4631        if self.in_parameter_list_at(caller) {
4632            let parameter_names: Vec<String> = self
4633                .frames
4634                .get(caller)
4635                .map(|frame| {
4636                    frame
4637                        .code
4638                        .code
4639                        .args
4640                        .iter()
4641                        .map(|arg| arg.name.clone())
4642                        .collect()
4643                })
4644                .unwrap_or_default();
4645            let collides = closure_vars.iter().any(|var| {
4646                !var.is_lexical && var.name != "*default*" && parameter_names.contains(&var.name)
4647            });
4648            if collides {
4649                return Err(Signal::Throw(self.make_error(
4650                    "SyntaxError",
4651                    "eval declares a var that the parameter scope already binds",
4652                )));
4653            }
4654        }
4655        if !closure_vars
4656            .iter()
4657            .any(|var| var.name == "arguments" && !var.is_lexical)
4658        {
4659            return Ok(());
4660        }
4661        // The body of a function is a different environment from its parameter list, and only
4662        // the parameter list is separate from `arguments`.
4663        if !self.in_parameter_list_at(caller) {
4664            return Ok(());
4665        }
4666        let caller_is_arrow = self
4667            .frames
4668            .get(caller)
4669            .is_some_and(|frame| frame.code.code.is_arrow);
4670        // A *parameter* named `arguments`, not merely a binding of that name: a body
4671        // `let arguments` is in the body's environment, which is the one that is separate and
4672        // therefore cannot collide. The slot tells them apart — an argument lives in
4673        // `EvalSlot::Arg`, a lexical in `EvalSlot::Local`.
4674        let parameter_scope_binds_arguments = self.eval_bindings.iter().any(|binding| {
4675            binding.frame == caller
4676                && binding.name == "arguments"
4677                && matches!(binding.slot, EvalSlot::Arg)
4678        });
4679        if caller_is_arrow && !parameter_scope_binds_arguments {
4680            return Ok(());
4681        }
4682        Err(Signal::Throw(self.make_error(
4683            "SyntaxError",
4684            "eval declares 'arguments' in a function's parameter scope",
4685        )))
4686    }
4687
4688    /// The cell-backed subset of `bindings`, in the same priority order.
4689    ///
4690    /// Both lookup routes have to agree — the eval's own reads go through
4691    /// [`Interp::eval_binding_value`] and the closures it builds go through
4692    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4693    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4694    /// is not in a cell simply does not appear: reads and writes still work, they just
4695    /// cannot be handed to a closure that outlives the eval.
4696    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4697        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4698        for binding in bindings {
4699            let Some(frame) = self.frames.get(binding.frame) else {
4700                continue;
4701            };
4702            let cell = match binding.slot {
4703                EvalSlot::Arg => frame
4704                    .code
4705                    .arg_cell
4706                    .get(binding.index)
4707                    .copied()
4708                    .unwrap_or(-1),
4709                EvalSlot::Local => frame
4710                    .code
4711                    .loc_cell
4712                    .get(binding.index)
4713                    .copied()
4714                    .unwrap_or(-1),
4715            };
4716            if cell < 0 {
4717                continue;
4718            }
4719            if let Some(cell) = frame.cells.get(cell as usize) {
4720                names.push((binding.name.clone(), cell.clone()));
4721            }
4722        }
4723        names
4724    }
4725
4726    /// A `SyntaxError` that reports where in the source it happened.
4727    ///
4728    /// Compile-time failures never run, so they have no frame of their own; the
4729    /// reference still puts the position first in the trace, with no function name and
4730    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4731    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4732    /// reference borrows), which is how a script reads the position without parsing
4733    /// the trace.
4734    /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4735    ///
4736    /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4737    /// `columnNumber`, which is how the reference prints one. A positionless error
4738    /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4739    /// the reference raises it from `js_resolve_module`, where there is no position.
4740    pub(crate) fn syntax_error_plain(
4741        &mut self,
4742        error: &js_parse::SyntaxError,
4743        file: &str,
4744    ) -> Value {
4745        if error.positionless {
4746            return self.make_error("SyntaxError", &error.message);
4747        }
4748        self.syntax_error_at(
4749            file,
4750            error.span.start.line,
4751            error.span.start.column,
4752            &error.message,
4753        )
4754    }
4755
4756    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4757        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
4758        let value = self.make_error("SyntaxError", message);
4759        if let Value::Object(object) = &value {
4760            let text = self.string(blamed);
4761            // `stack` is an own data property, and the reference keeps it
4762            // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4763            object.define("stack", Property::with_attributes(text, true, false));
4764            let name = self.string(file);
4765            object.define("fileName", Property::with_attributes(name, true, true));
4766            object.define(
4767                "lineNumber",
4768                Property::with_attributes(Value::Int(line as i32), true, true),
4769            );
4770            object.define(
4771                "columnNumber",
4772                Property::with_attributes(Value::Int(column as i32), true, true),
4773            );
4774        }
4775        value
4776    }
4777
4778    /// Run a compiled script whose completion value is a function, returning it.
4779    ///
4780    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4781    /// get the closure out, which keeps the constant-pool plumbing in one place.
4782    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4783        self.run_script(code)
4784    }
4785
4786    /// The environment of a script or of any function compiled at global scope:
4787    /// every entry is a global binding, so each one resolves to the realm's cell.
4788    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4789        let mut cells = Vec::with_capacity(closure_vars.len());
4790        for closure_var in closure_vars {
4791            let cell = match closure_var.closure_type {
4792                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4793                    if closure_var.is_lexical =>
4794                {
4795                    // A lexical declaration: the cell is created here holding the
4796                    // dead-zone marker, which is what makes the binding exist and
4797                    // unreadable before its initialiser runs.
4798                    self.declare_global(&closure_var.name, closure_var.is_const);
4799                    self.realm.globals[&closure_var.name].clone()
4800                }
4801                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4802                    // A `var` or function declaration becomes a property of the global
4803                    // object, and it exists from here on — which is why
4804                    // `print(v); var v = 1` prints `undefined` instead of raising.
4805                    // Declaring it at instantiation time (rather than at the
4806                    // initialiser) is also what makes it non-configurable: the store
4807                    // then lands on an existing property instead of creating one.
4808                    self.declare_var_global(&closure_var.name);
4809                    // The cell is a placeholder that nothing indexes; it cannot be
4810                    // omitted because the slot has to hold something.
4811                    self.new_cell(Value::Undefined)
4812                }
4813                _ => {
4814                    // An undeclared global is read by name; the cell is a
4815                    // placeholder that nothing indexes.
4816                    self.new_cell(Value::Undefined)
4817                }
4818            };
4819            cells.push(cell);
4820        }
4821        Gc::new(
4822            self.heap,
4823            ClosureEnv {
4824                cells,
4825                eval_scope: None,
4826                local_vars: None,
4827                local_phase: 1,
4828            },
4829        )
4830    }
4831
4832    /// Push a frame and run until it returns.
4833    pub(crate) fn execute(
4834        &mut self,
4835        code: Gc<CompiledCode>,
4836        env: Gc<ClosureEnv>,
4837        this: Value,
4838        args: Vec<Value>,
4839        callee: Value,
4840    ) -> JsResult<Value> {
4841        let depth = self.frames.len();
4842        if depth == 0 {
4843            // A throw that reached the host ends the *active* mode: the next one is catchable
4844            // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4845            // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4846            // for the throw that evaluation will raise.
4847            self.uncatchable = false;
4848        }
4849        self.push_frame(code, env, this, args, callee)?;
4850        loop {
4851            // The fast loop first: it runs whole runs of records with `pc` in a register.
4852            //
4853            // `step`'s `pc` lives in the frame, so every instruction writes it back and
4854            // reads it again — a store, a load and two bounds checks that a loop body does
4855            // not need, because nothing outside the loop can run in between. This is the
4856            // classic split: advance a register, and only spill it when leaving.
4857            //
4858            // `Some(value)` means the function ended by running off the end of its
4859            // instruction array, which is a normal return.
4860            let step = match self.run_fast() {
4861                Ok(Some(value)) => Ok(Step::Return(value)),
4862                Ok(None) => self.step(),
4863                Err(signal) => Err(signal),
4864            };
4865            match step {
4866                Ok(Step::Continue) => {}
4867                Ok(Step::Return(value)) => {
4868                    self.pop_frame();
4869                    // A frame that ended in a `tail_call` hands its value straight to
4870                    // its caller: nothing after the call can run, so every frame above
4871                    // the callee unwinds with the same value. See [`Frame::tail`] —
4872                    // the reference does not reuse frames either, so recursion depth
4873                    // and the stack-overflow limit behave the same way.
4874                    while self.frames.len() > depth && self.frame().tail {
4875                        self.pop_frame();
4876                    }
4877                    if self.frames.len() == depth {
4878                        return Ok(value);
4879                    }
4880                    // The caller resumes with the value on its stack.
4881                    self.frames
4882                        .last_mut()
4883                        .expect("a caller is live")
4884                        .stack
4885                        .push(value);
4886                }
4887                Err(Signal::Throw(value)) => {
4888                    // The host's standing request becomes the active mode for this unwind,
4889                    // and is consumed here so it does not leak into the next throw.
4890                    if self.uncatchable_next {
4891                        self.uncatchable_next = false;
4892                        self.uncatchable = true;
4893                    }
4894                    // An uncatchable throw walks past every `catch` on the way out. The
4895                    // frames are still popped, because the values they hold have to be
4896                    // dropped — only the search for a handler is skipped.
4897                    if self.uncatchable {
4898                        while self.frames.len() > depth {
4899                            self.frames.pop();
4900                        }
4901                        return Err(Signal::Throw(value));
4902                    }
4903                    // A handler lives on the stack of the frame that is throwing —
4904                    // `catch` pushed it there — so this frame gets the first chance
4905                    // to catch before it is popped.
4906                    let mut value = value;
4907                    loop {
4908                        if self.frames.len() <= depth {
4909                            return Err(Signal::Throw(value));
4910                        }
4911                        if self.catch_here(&mut value).is_some() {
4912                            break;
4913                        }
4914                        self.frames.pop();
4915                    }
4916                }
4917                // A `yield` in a frame that `execute` is running directly means a
4918                // generator body was entered as an ordinary call, which only happens if
4919                // the generator check in `call_or_push` was bypassed.
4920                Ok(Step::Suspend(_)) => {
4921                    return Err(Signal::Throw(self.make_error(
4922                        "InternalError",
4923                        "a generator body ran as an ordinary call",
4924                    )));
4925                }
4926                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4927            }
4928        }
4929    }
4930
4931    /// Install a handler for `value` if this frame has one, resuming at it.
4932    ///
4933    /// The scan is the reference's: walk the frame's stack downwards looking for the
4934    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset `0` is an
4935    /// enumerator marker rather than a handler — `for of` keeps one under its record so
4936    /// that `break` and `return` can find the iterator — and an exception reaching one
4937    /// **closes that iterator** before the unwinding continues.
4938    ///
4939    /// Skipping the marker instead leaked the iterator of every `for of` whose body threw:
4940    /// `for (const x of xs) { throw new Error }` never called `return`. It was also the
4941    /// whole of a nineteen-case `dstr` cluster, where `[ {}[thrower()] ] = iterable` has to
4942    /// close the iterator while the reference to store into is being worked out.
4943    ///
4944    /// `value` is `&mut` because closing the iterator may replace it: see
4945    /// [`Interp::close_iterator_on_throw`] for which of the two exceptions wins.
4946    fn catch_here(&mut self, value: &mut Value) -> Option<()> {
4947        loop {
4948            // Popped one at a time so no frame borrow is held across the close below.
4949            let top = self.frames.last_mut()?.stack.pop()?;
4950            let Value::CatchOffset(offset) = top else {
4951                continue;
4952            };
4953            if offset != 0 {
4954                let frame = self.frames.last_mut().expect("the frame was just read");
4955                frame.stack.push(value.clone());
4956                frame.pc = offset as usize;
4957                return Some(());
4958            }
4959            // The record's `iter` and `next` sit directly below the marker.
4960            let close = {
4961                let frame = self.frames.last_mut().expect("the frame was just read");
4962                let next = frame.stack.pop();
4963                let iterator = frame.stack.pop();
4964                match (iterator, next) {
4965                    (Some(iterator), Some(_next)) => Some(iterator),
4966                    // A malformed record cannot be closed, but unwinding still has to go
4967                    // on: this is not a handler, so there is nothing to resume at.
4968                    _ => None,
4969                }
4970            };
4971            if let Some(iterator) = close {
4972                self.close_iterator_on_throw(iterator);
4973            }
4974        }
4975    }
4976
4977    /// `IteratorClose` on the exception path — §7.4.6 reached with a *throw* completion.
4978    ///
4979    /// Two things differ from the ordinary close, both from the spec's step ordering:
4980    ///
4981    /// * the original exception **wins**. Step 4 (`If completion is a throw completion,
4982    ///   return ? completion`) comes before step 5, so an exception raised by `return()`
4983    ///   itself — or by reading it — is discarded;
4984    /// * a non-object result is **not** a `TypeError`, because step 6 is never reached.
4985    ///
4986    /// The reference does exactly this in `JS_IteratorClose(…, is_exception_pending=TRUE)`:
4987    /// it saves the pending exception, clears the slot, and re-throws the saved one from
4988    /// `done:` no matter what happened in between.
4989    fn close_iterator_on_throw(&mut self, iterator: Value) {
4990        if matches!(iterator, Value::Undefined) {
4991            return;
4992        }
4993        let Ok(method) = self.read_field(&iterator, "return") else {
4994            return;
4995        };
4996        if matches!(method, Value::Undefined | Value::Null) {
4997            return;
4998        }
4999        // A throw from `return()` replaces nothing: the exception already being unwound is
5000        // the one that propagates.
5001        let _ = self.call_value(method, iterator, Vec::new());
5002    }
5003
5004    fn push_frame(
5005        &mut self,
5006        code: Gc<CompiledCode>,
5007        env: Gc<ClosureEnv>,
5008        this: Value,
5009        mut args: Vec<Value>,
5010        callee: Value,
5011    ) -> JsResult<()> {
5012        // Two bounds, and the byte budget is the one that decides in practice. The
5013        // reference's message is `stack overflow` on an `InternalError`, not V8's
5014        // `Maximum call stack size exceeded` on a *string* — the difference is visible:
5015        // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
5016        let frame_cost = Self::frame_cost(&code);
5017        let stack_base = self.stack_used();
5018        if self.frames.len() >= self.max_frames
5019            || stack_base.saturating_add(frame_cost) > self.stack_limit
5020        {
5021            return Err(Signal::Throw(
5022                self.make_error("InternalError", "stack overflow"),
5023            ));
5024        }
5025        let arg_count = code.code.args.len();
5026        // How many were actually passed, which `arguments.length` reports and
5027        // `assert(x)` depends on: a call with one argument must not look like a call
5028        // with one argument and an explicit `undefined`.
5029        let passed = args.len();
5030        // Missing arguments are `undefined` in their slots; extra ones are dropped
5031        // from the slots but still reachable through `arguments`.
5032        //
5033        // A call that passes no more than the declared parameters needs **no** copy:
5034        // after the resize below, `args[..passed]` *is* the passed values. Only the
5035        // extra ones — which `truncate` is about to drop — have to be kept, and they are
5036        // the rare case. This used to copy every call: one `Value` clone per argument
5037        // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
5038        let passed_overflow = (passed > arg_count).then(|| {
5039            let mut values = self.take_values(passed, Value::Undefined);
5040            values[..passed].clone_from_slice(&args[..passed]);
5041            values
5042        });
5043        // Only when the counts differ, which for the overwhelmingly common call — as many
5044        // arguments as parameters — is never. `resize` followed by `truncate` on equal
5045        // lengths is two length compares and nothing else, but this is the hottest few
5046        // instructions in the engine: `call:recursion` executes it twice per `fib` step.
5047        if passed != arg_count {
5048            args.resize(arg_count, Value::Undefined);
5049            args.truncate(arg_count);
5050        }
5051        let cell_count = code.code.var_ref_count as usize;
5052        let mut cells = Vec::with_capacity(cell_count);
5053        for _ in 0..cell_count {
5054            cells.push(self.new_cell(Value::Undefined));
5055        }
5056        let locals = self.take_values(code.code.vars.len(), Value::Undefined);
5057        // A captured argument lives in its cell, not in the argument slot, so the
5058        // incoming value has to be moved there before the body runs.
5059        for (slot, cell) in code.arg_cell.iter().enumerate() {
5060            if *cell >= 0
5061                && let Some(value) = args.get(slot).cloned()
5062            {
5063                cells[*cell as usize].set(value);
5064            }
5065        }
5066        // Sloppy mode substitutes the global object for a missing receiver and boxes a
5067        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
5068        // reports `object`. Strict mode passes the value through untouched.
5069        let this = if code.code.strict {
5070            this
5071        } else if this.is_nullish() {
5072            Value::Object(self.realm.global.clone())
5073        } else if matches!(this, Value::Object(_)) {
5074            this
5075        } else {
5076            match crate::builtins::this_object(self, &this) {
5077                Ok(boxed) => Value::Object(boxed),
5078                Err(_) => this,
5079            }
5080        };
5081        let stack_depth = code.code.stack_size as usize + 1;
5082        // Taken before the `push` borrows `self.frames`, because the operand stack comes
5083        // out of the same recycle pool the locals did.
5084        let stack = self.take_values(stack_depth, Value::Undefined);
5085        self.frames.push(Frame {
5086            code,
5087            env,
5088            this,
5089            args,
5090            passed_count: passed,
5091            passed_overflow: passed_overflow.map(Box::new),
5092            locals,
5093            cells,
5094            local_vars: None,
5095            // Exactly the depth the compiler computed, so the operand stack never
5096            // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
5097            // that reallocated on its way in — a malloc per call.) The recycle pool keeps
5098            // the buffer between calls, so "exactly" costs nothing after the first one.
5099            stack,
5100            pc: 0,
5101            at: 0,
5102            callee,
5103            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
5104            cost: frame_cost,
5105            stack_base,
5106            tail: false,
5107        });
5108        Ok(())
5109    }
5110
5111    /// A value buffer of `len` slots, from the recycle pool when there is one.
5112    ///
5113    /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
5114    fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
5115        // A frame with no locals asks for nothing, and that is most frames: taking a
5116        // buffer out of the pool, clearing it and resizing it to zero is four operations
5117        // and a pool pop for an empty `Vec`, which is free to construct.
5118        if len == 0 {
5119            return Vec::new();
5120        }
5121        let mut buffer = self.free_values.pop().unwrap_or_default();
5122        buffer.clear();
5123        buffer.resize(len, fill);
5124        buffer
5125    }
5126
5127    /// Return a finished frame's value buffers for the next call to reuse.
5128    fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
5129        for mut buffer in [
5130            std::mem::take(&mut frame.locals),
5131            frame
5132                .passed_overflow
5133                .take()
5134                .map(|buffer| *buffer)
5135                .unwrap_or_default(),
5136            std::mem::take(&mut frame.stack),
5137        ] {
5138            // **Empty it here, not when it is reused.** A holding buffer in the pool is a
5139            // GC root: it kept every value the frame held reachable, which is invisible
5140            // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
5141            // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
5142            // exactly that within one run — the target `{}` of a finished IIFE was still
5143            // in its operand stack, in the pool.
5144            buffer.clear();
5145            // A buffer with no capacity is what `Vec::new` is; putting it back would just
5146            // fill the pool with nothing to offer.
5147            if free_values.len() < RECYCLE_SLOTS
5148                && buffer.capacity() > 0
5149                && buffer.capacity() <= RECYCLE_MAX_CAPACITY
5150            {
5151                free_values.push(buffer);
5152            }
5153        }
5154    }
5155
5156    /// Pop a finished frame and keep its buffers.
5157    ///
5158    /// Every place that drops a frame goes through here: a recycled buffer is also where
5159    /// the values it held are dropped (`clear` runs the drops), so skipping this loses
5160    /// nothing but the reuse.
5161    fn pop_frame(&mut self) -> Option<()> {
5162        // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
5163        // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
5164        let last = self.frames.len().checked_sub(1)?;
5165        Self::recycle(&mut self.free_values, &mut self.frames[last]);
5166        self.frames.truncate(last);
5167        Some(())
5168    }
5169
5170    /// Poll the host's interrupt handler, if one is installed.
5171    ///
5172    /// The counter is what keeps this off the hot path when nobody asked: the early return is
5173    /// one `Option` test, and with no handler installed the whole function is that test —
5174    /// `check_memory` next door already costs more, so this cannot be what shows up in a
5175    /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
5176    #[inline]
5177    fn check_interrupt(&mut self) -> JsResult<()> {
5178        if self.interrupt.is_none() {
5179            return Ok(());
5180        }
5181        if self.interrupt_counter > 0 {
5182            self.interrupt_counter -= 1;
5183            return Ok(());
5184        }
5185        self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
5186        // The closure is taken out for the duration so that a handler which re-enters the
5187        // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
5188        let mut handler = self.interrupt.take().expect("checked above");
5189        let abort = handler();
5190        self.interrupt = Some(handler);
5191        if abort {
5192            // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
5193            // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
5194            // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
5195            // documentation says.
5196            self.uncatchable = true;
5197            return Err(Signal::Throw(
5198                self.make_error("InternalError", "interrupted"),
5199            ));
5200        }
5201        Ok(())
5202    }
5203
5204    /// A memory checkpoint: does the heap still fit under its limit?
5205    ///
5206    /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
5207    /// a `Cell` read and a predictable branch, and the point of asking that often is that
5208    /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
5209    /// only at calls would let it run until the machine died, which is the exact failure
5210    /// `--memory-limit` exists to prevent.
5211    ///
5212    /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
5213    /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
5214    /// script that catches it, drops the reference and carries on is legitimate: measured
5215    /// on `qjs --memory-limit 1M`, the engine recovers.
5216    fn check_memory(&mut self) -> JsResult<()> {
5217        // One `Cell` read and a predictable branch when no limit is set, and an integer
5218        // compare when one is. Containers report their own growth as it happens
5219        // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
5220        // walking it here was the first version and it was O(live) per 256 instructions,
5221        // which turned a 100k-element push loop into a five-minute one.
5222        let Some(limit) = self.heap.memory_limit() else {
5223            return Ok(());
5224        };
5225        let used = self.heap.used_bytes();
5226        if used <= limit {
5227            // Back under the limit — a collection or a dropped reference did it. The next
5228            // time it goes over is a new failure, not a repeat of this one.
5229            self.oom_reported_at = 0;
5230            return Ok(());
5231        }
5232        // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
5233        // block runs normally after `out of memory` — it allocates nothing, so nothing
5234        // fails. A check that re-fired on every instruction made the handler itself throw,
5235        // which is a dead end: the error became unobservable from script.
5236        //
5237        // Comparing against the total at the last report gives the same behaviour: the
5238        // handler runs while the total is unchanged, and the very next allocation over the
5239        // limit fails.
5240        if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
5241        {
5242            return Ok(());
5243        }
5244        self.oom_reported_at = used;
5245        Err(Signal::Throw(
5246            self.make_error("InternalError", "out of memory"),
5247        ))
5248    }
5249
5250    /// Fail before allocating `payload` bytes, if they would not fit.
5251    ///
5252    /// For the allocations whose size comes from script data — `new Array(n)`,
5253    /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
5254    /// is what takes the machine down. The reference has the same shape, with `js_malloc`
5255    /// answering NULL for the one big request.
5256    pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
5257        if self.heap.fits(payload) {
5258            return Ok(());
5259        }
5260        Err(Signal::Throw(
5261            self.make_error("InternalError", "out of memory"),
5262        ))
5263    }
5264
5265    /// Bytes of frame state the live call chain accounts for.
5266    pub fn stack_used(&self) -> usize {
5267        match self.frames.last() {
5268            Some(frame) => frame.stack_base + frame.cost,
5269            None => 0,
5270        }
5271    }
5272
5273    /// What one frame of `code` costs: the frame itself plus the slots it allocates.
5274    ///
5275    /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
5276    /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
5277    /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
5278    /// instead. That is the whole difference between the two models: it rations C stack, we
5279    /// ration frame state, and both quantities are dominated by the value slots — which is
5280    /// why the two depths come out comparable rather than merely proportional.
5281    fn frame_cost(code: &CompiledCode) -> usize {
5282        let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
5283        std::mem::size_of::<Frame>()
5284            + std::mem::size_of::<Value>() * slots
5285            + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
5286    }
5287
5288    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
5289    ///
5290    /// Only names the eval created are here: a name the frame already declared statically
5291    /// is written through to its own slot instead, so this cannot shadow a real local.
5292    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
5293        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
5294        let (local_vars, phase) = self.visible_local_vars()?;
5295        if !local_vars.contains(name) {
5296            return None;
5297        }
5298        local_vars.get(name, phase)
5299    }
5300
5301    /// The variables a direct `eval` declared, as the code currently running sees them.
5302    ///
5303    /// Inside an eval that is the *caller's* set — the eval's own variable environment
5304    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
5305    /// else it is the current frame's, falling back to the frame the closure was created
5306    /// in.
5307    /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
5308    ///
5309    /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
5310    /// which runs on every global read — and the `Option` it was handed cost two `Gc`
5311    /// refcount operations (the clone out of the frame, the drop at the end of the match)
5312    /// just to be asked `is_none`.
5313    fn has_visible_local_vars(&self) -> bool {
5314        let index = match self.eval_caller.flatten() {
5315            Some(caller) => caller,
5316            None => match self.frames.len().checked_sub(1) {
5317                Some(top) => top,
5318                None => return false,
5319            },
5320        };
5321        match self.frames.get(index) {
5322            Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
5323            None => false,
5324        }
5325    }
5326
5327    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
5328        // While an `eval` runs, its own frame is on top but its variable environment is
5329        // the *caller's* — so the caller is what the lookup has to start from.
5330        let (index, phase) = match self.eval_caller.flatten() {
5331            Some(caller) => (
5332                caller,
5333                if self.in_parameter_list_at(caller) {
5334                    0
5335                } else {
5336                    1
5337                },
5338            ),
5339            None => (
5340                self.frames.len().checked_sub(1)?,
5341                if self.in_parameter_list() { 0 } else { 1 },
5342            ),
5343        };
5344        let frame = self.frames.get(index)?;
5345        // The frame's own variables, or — for an arrow, which has no variable environment
5346        // of its own — the one it was created in, which `ClosureEnv` carries.
5347        if let Some(local_vars) = frame.local_vars.clone() {
5348            return Some((local_vars, phase));
5349        }
5350        frame
5351            .env
5352            .local_vars
5353            .clone()
5354            .map(|local_vars| (local_vars, frame.env.local_phase))
5355    }
5356
5357    /// Whether the innermost frame is still evaluating its parameter list.
5358    ///
5359    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
5360    /// and a closure created there may only see that much of [`LocalVars`].
5361    fn in_parameter_list(&self) -> bool {
5362        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
5363    }
5364
5365    /// [`Interp::in_parameter_list`] for a specific frame.
5366    fn in_parameter_list_at(&self, frame: usize) -> bool {
5367        let Some(frame) = self.frames.get(frame) else {
5368            return false;
5369        };
5370        let code = &frame.code.code;
5371        if !code.has_parameter_expressions {
5372            return false;
5373        }
5374        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
5375        // function as its body and let a direct `eval` act accordingly.
5376        if code.body_start == (0, 0) {
5377            return false;
5378        }
5379        match code.position_at(frame.at as u32) {
5380            Some(position) => position < code.body_start,
5381            None => false,
5382        }
5383    }
5384
5385    fn frame(&self) -> &Frame {
5386        self.frames.last().expect("a frame is live")
5387    }
5388
5389    fn frame_mut(&mut self) -> &mut Frame {
5390        self.frames.last_mut().expect("a frame is live")
5391    }
5392
5393    // -- slot access --------------------------------------------------------
5394
5395    /// Move a local's value out, leaving `undefined` in the slot.
5396    ///
5397    /// `None` for a captured slot: its value lives in a cell shared with every closure
5398    /// that closed over it, so it can never be exclusively ours and must not be taken.
5399    ///
5400    /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
5401    /// for every read and fatal for this one — a clone is exactly the second handle that
5402    /// rules out growing the string in place.
5403    fn take_loc(&mut self, slot: usize) -> Option<Value> {
5404        let frame = self.frames.last_mut()?;
5405        if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
5406            return None;
5407        }
5408        frame
5409            .locals
5410            .get_mut(slot)
5411            .map(|value| std::mem::replace(value, Value::Undefined))
5412    }
5413
5414    /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
5415    /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
5416    ///
5417    /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
5418    /// it** — the value is put back before the general path runs — so a `valueOf` that
5419    /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
5420    /// error as it would have without the fusion. This is why the in-place attempt is a
5421    /// `take` and not a `get`: an optimisation that changes what an exception observes is
5422    /// a wrong answer with a good excuse.
5423    fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
5424        // The take is `matches!`-guarded on the *right* operand only, and the taken value
5425        // is put back on every path that does not append. An earlier version wrote the two
5426        // conditions as one `if let` chain — `if right is a string && let Some(Value::String
5427        // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
5428        // through with its value already taken and dropped: the general path below then
5429        // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
5430        // A wrong answer, from an optimisation, with every test green.
5431        if matches!(right, Value::String(_))
5432            && let Some(taken) = self.take_loc(slot)
5433        {
5434            if let Value::String(mut left) = taken {
5435                let appended = match left.get_mut() {
5436                    Some(string) => string.append_in_place(
5437                        // The pattern is the one `matches!` just checked.
5438                        match &right {
5439                            Value::String(text) => text,
5440                            _ => unreachable!("guarded above"),
5441                        },
5442                    ),
5443                    None => None,
5444                };
5445                self.put_loc(slot, Value::String(left));
5446                if let Some(added) = appended {
5447                    // The buffer grew where it stood, so the heap's running total has to
5448                    // be told: `measure_used` would report the new length, and the two must
5449                    // agree or the subtraction at free time leaves the counter wrong.
5450                    self.heap.adjust_payload(added as isize);
5451                    return Ok(());
5452                }
5453            } else {
5454                self.put_loc(slot, taken);
5455            }
5456        }
5457        // The two-number case, without an operand stack round trip. Everything below
5458        // this point is the *general* path: push both, call `binary_add`, pop the answer,
5459        // store it — five operations and two `Value` clones for what is one integer add.
5460        // `AddImmLoc` already answers this shape that way; the fusion above it was written
5461        // for string append and never got the numeric half, so `t += i` — a counting loop
5462        // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
5463        let left = self.get_loc(slot);
5464        if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
5465            self.put_loc(
5466                slot,
5467                match a.checked_add(*b) {
5468                    Some(sum) => Value::Int(sum),
5469                    None => Value::Float(*a as f64 + *b as f64),
5470                },
5471            );
5472            return Ok(());
5473        }
5474        self.push(left);
5475        self.push(right);
5476        self.binary_add()?;
5477        let value = self.pop();
5478        self.put_loc(slot, value);
5479        Ok(())
5480    }
5481
5482    fn get_arg(&self, slot: usize) -> Value {
5483        self.frame().read_arg(slot)
5484    }
5485
5486    fn put_arg(&mut self, slot: usize, value: Value) {
5487        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
5488        if cell == -1 {
5489            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
5490                *slot = value;
5491            }
5492        } else {
5493            self.frame().cells[cell as usize].set(value);
5494        }
5495    }
5496
5497    fn get_loc(&self, slot: usize) -> Value {
5498        // The cell mapping is `-1` for every slot that was not captured — which is all of
5499        // them in a function that creates no closure. `Frame::read_loc` tests that first,
5500        // so the common case is one array read and a clone: 20% of every loop iteration
5501        // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
5502        // sample of `dispatch:arith`).
5503        self.frame().read_loc(slot)
5504    }
5505
5506    fn put_loc(&mut self, slot: usize, value: Value) {
5507        // One borrow instead of three, and the cell check on the frame we already hold.
5508        let frame = self.frames.last_mut().expect("a frame is live");
5509        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
5510        if cell < 0 {
5511            if let Some(slot) = frame.locals.get_mut(slot) {
5512                *slot = value;
5513            }
5514        } else if let Some(cell) = frame.cells.get(cell as usize) {
5515            cell.set(value);
5516        }
5517    }
5518
5519    // -- globals ------------------------------------------------------------
5520
5521    /// The name a global-slot operand refers to.
5522    fn global_name(&self, slot: usize) -> String {
5523        self.frame()
5524            .code
5525            .code
5526            .closure_vars
5527            .get(slot)
5528            .map(|c| c.name.clone())
5529            .unwrap_or_default()
5530    }
5531
5532    /// The facts about a global binding that decide where it lives.
5533    ///
5534    /// A script's globals split in two, and the split is observable: `var` and
5535    /// function declarations become properties of the global object (`globalThis.v`
5536    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
5537    /// declarations live in the global *lexical* environment and are invisible there
5538    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
5539    /// `is_lexical` flag means the answer is already in the bytecode.
5540    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
5541        let name = self.global_name(slot);
5542        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
5543        // while forwarding a reference through a nested function is built with the
5544        // flags cleared, so `const c` would look like an ordinary `var` from inside a
5545        // closure. Presence in the realm's lexical table is the same fact, recorded
5546        // once, and every slot sees it.
5547        let lexical = self.realm.globals.contains_key(&name);
5548        let is_const = self.realm.lexical_consts.contains(&name);
5549        (name, lexical, is_const)
5550    }
5551
5552    /// The value of `name` in the innermost active `with` object, if any.
5553    ///
5554    /// The active objects are the [`VarKind::With`] locals of every frame still running,
5555    /// innermost frame first and innermost block first within one. Walking frames rather
5556    /// than keeping a separate stack is what makes a closure called from inside a `with`
5557    /// see it, and what keeps the object alive only as long as the block is.
5558    /// The innermost active `with` object that has `name`, if any.
5559    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
5560        let objects = self.eval_with.clone().unwrap_or_default();
5561        for object in objects {
5562            let key = self.string(name.to_string());
5563            if self
5564                .has_property(&key, &Value::Object(object.clone()))
5565                .ok()?
5566            {
5567                return Some(object);
5568            }
5569        }
5570        None
5571    }
5572
5573    /// Every active `with` object, innermost first.
5574    fn with_objects(&self) -> Vec<Gc<JsObject>> {
5575        let mut objects = Vec::new();
5576        for frame in self.frames.iter().rev() {
5577            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
5578                if var.kind != js_compile::VarKind::With {
5579                    continue;
5580                }
5581                // A captured binding lives in its cell and not in the slot list, so the
5582                // cell is consulted first — a closure created inside the block is exactly
5583                // what makes the object captured. Before the store runs the slot still
5584                // holds `undefined`, and a `with` object is always boxed, so a non-object
5585                // entry is simply not in scope yet.
5586                let value = frame
5587                    .code
5588                    .loc_cell
5589                    .get(index)
5590                    .copied()
5591                    .filter(|cell| *cell >= 0)
5592                    .and_then(|cell| frame.cells.get(cell as usize))
5593                    .map(|cell| cell.get())
5594                    .or_else(|| frame.locals.get(index).cloned());
5595                if let Some(Value::Object(object)) = value {
5596                    objects.push(object);
5597                }
5598            }
5599        }
5600        objects
5601    }
5602
5603    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
5604        for object in self.eval_with.clone().unwrap_or_default() {
5605            let key = self.string(name.to_string());
5606            if self.has_property(&key, &Value::Object(object.clone()))? {
5607                return Ok(Some(self.read_field(&Value::Object(object), name)?));
5608            }
5609        }
5610        Ok(None)
5611    }
5612
5613    /// Whether every scope between here and the global object is an ordinary one.
5614    ///
5615    /// `eval` and `with` install extra scopes, and each of them may shadow the name the
5616    /// bytecode resolved; when any is live the general path has to run in full order. When
5617    /// none is — every ordinary program — a global read is a property read and nothing
5618    /// else, and that is worth caching.
5619    fn scopes_are_plain(&self) -> bool {
5620        self.eval_caller.is_none()
5621            && self.eval_with.is_none()
5622            && self.eval_arguments.is_none()
5623            && self.eval_bindings.is_empty()
5624            && self.eval_scope.is_empty()
5625            // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
5626            // that ran a direct `eval("var z = 1")` inherits the eval's variables through
5627            // its `ClosureEnv`, so the test has to be the same one the general path makes.
5628            // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
5629            // upstream corpus caught and no unit test did.
5630            && !self.has_visible_local_vars()
5631            && self.frame().env.eval_scope.is_none()
5632    }
5633
5634    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
5635        // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
5636        // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
5637        // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
5638        // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
5639        // borrow outlive the `&mut self` the lookup needs.
5640        //
5641        // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
5642        // forwarded through a nested function has its flags cleared, so the flag cannot
5643        // be believed.
5644        let code = self.frame().code.clone();
5645        let name = code
5646            .code
5647            .closure_vars
5648            .get(slot)
5649            .map(|c| c.name.as_str())
5650            .unwrap_or_default();
5651        let lexical = self.realm.globals.contains_key(name);
5652        // The common case, first: an ordinary global `var`, with a cache in front of the
5653        // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
5654        // cannot apply when `scopes_are_plain` — and when it does not apply we take the
5655        // cache hit and return without touching any of it.
5656        if !lexical && self.scopes_are_plain() {
5657            return self.get_plain_global(name, slot);
5658        }
5659        if name == "arguments"
5660            && let Some(arguments) = &self.eval_arguments
5661        {
5662            return Ok(arguments.clone());
5663        }
5664        // A `with` block around the *call site* is part of the scope an `eval` sees, so
5665        // the objects live when the eval started are consulted before anything else. The
5666        // snapshot is taken at entry rather than scanning the frames on every read: a
5667        // block that has already finished still leaves its object in the slot, and a
5668        // bytecode read outside the block must not see it.
5669        if let Some(value) = self.with_lookup(name)? {
5670            return Ok(value);
5671        }
5672        // A name a **running** eval declared itself outranks the caller's bindings — that
5673        // is what makes a strict eval's `var` private to it. It has to come first here, and
5674        // first in `put_global`, or a nested eval would read the caller's variable while
5675        // writing its own: `eval("var o = 'str2'; eval('o')")` inside a function that also
5676        // has an `o`.
5677        for scope in self.eval_scope.iter().rev() {
5678            if let Some(value) = scope.get(name) {
5679                return Ok(value.clone());
5680            }
5681        }
5682        // A closure created by an `eval` resolves its free names against the bindings
5683        // that eval saw, even after the eval (and its frames) are gone.
5684        if let Some(cell) = self
5685            .frame()
5686            .env
5687            .eval_scope
5688            .as_ref()
5689            .and_then(|scope| scope.get(name))
5690        {
5691            let value = cell.get();
5692            if matches!(value, Value::Uninitialized) {
5693                return Err(self.throw_reference(name));
5694            }
5695            return Ok(value);
5696        }
5697        // A variable a direct `eval` declared shadows everything the compiler resolved,
5698        // including an enclosing function's binding: the eval put it in the caller's own
5699        // variable environment, which is nearer than any captured scope.
5700        if let Some((local_vars, phase)) = self.visible_local_vars()
5701            && let Some(cell) = local_vars.get(name, phase)
5702        {
5703            return Ok(cell.get());
5704        }
5705        // The frame that called `eval` is the innermost scope the eval'd code sees, so
5706        // its local `a` wins over a global `a`.
5707        if let Some(value) = self.eval_binding_value(name) {
5708            return Ok(value);
5709        }
5710        // A binding declared by the strict `eval` currently running shadows anything
5711        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5712        if lexical {
5713            // A lexical global is a binding in a side table, so the dead zone is
5714            // visible and it is nowhere on the global object.
5715            if let Some(cell) = self.realm.globals.get(name) {
5716                let value = cell.get();
5717                if matches!(value, Value::Uninitialized) {
5718                    return Err(self.throw_reference(name));
5719                }
5720                return Ok(value);
5721            }
5722            return Err(self.throw_reference(name));
5723        }
5724        // A `var` global is an ordinary property, so the prototype chain and the
5725        // global object's own builtins are all reachable through it.
5726        match self.get_property(&self.realm.global.clone(), name)? {
5727            Some(value) => Ok(value),
5728            None => Err(self.throw_reference(name)),
5729        }
5730    }
5731
5732    /// Read a plain global `var`: a cached own data property, or the full lookup.
5733    ///
5734    /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5735    /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5736    fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5737        let object = self.realm.global.clone();
5738        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5739        if let Some(cached) = &self.global_cache[site]
5740            && object.upgrades_to(&cached.object)
5741            && let Some(value) = object.data_property_at(cached.index, name)
5742        {
5743            return Ok(value);
5744        }
5745        // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5746        // chain exactly as before, then remember the answer if it is worth remembering.
5747        let Some(value) = self.get_property(&object, name)? else {
5748            return Err(self.throw_reference(name));
5749        };
5750        if let Some(index) = object.own_data_index(name) {
5751            self.global_cache[site] = Some(GlobalCache {
5752                object: object.downgrade(),
5753                index,
5754            });
5755        }
5756        Ok(value)
5757    }
5758
5759    /// Store to a global binding.
5760    ///
5761    /// Returns a signal when the store is refused: a `const` global may only be
5762    /// written by its initialiser, and a non-configurable `var` global may not be
5763    /// deleted but is always writable.
5764    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5765        let (name, lexical, is_const) = self.global_binding(slot);
5766
5767        // An assignment inside a `with` writes through to the object that supplies the
5768        // name, which for an `eval` means consulting the same chain `get_global` does.
5769        if let Some(owner) = self.with_owner(&name) {
5770            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5771            return Ok(());
5772        }
5773        // A *strict* eval has a variable environment of its own, so a name it declared
5774        // there shadows the caller's binding of the same name: in
5775        // `function f(){ "use strict"; var v = 0; eval("var v = 1") }` the outer `v` must
5776        // stay 0 (`eval-code/direct/var-env-var-strict-caller`). `eval_scope` is `Some`
5777        // only while such an eval runs, and holds only the names it declared, so this is
5778        // narrower than it looks.
5779        //
5780        // It sits ahead of the caller's bindings below on purpose: the *reads* take the
5781        // same order (`get_global`), and a store that disagreed with its own read would
5782        // write somewhere the eval cannot see.
5783        let closure_scope = self
5784            .frame()
5785            .env
5786            .eval_scope
5787            .as_ref()
5788            .and_then(|scope| scope.get(&name))
5789            .cloned();
5790        if let Some(cell) = closure_scope {
5791            cell.set(value);
5792            return Ok(());
5793        }
5794        for scope in self.eval_scope.iter_mut().rev() {
5795            if let Some(slot) = scope.get_mut(&name) {
5796                *slot = value;
5797                return Ok(());
5798            }
5799        }
5800        // A variable the running eval *declared* takes the write before any caller
5801        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5802        // environment even when an enclosing function has a `var c` of its own.
5803        if self.eval_caller.flatten().is_some()
5804            && let Some((local_vars, phase)) = self.visible_local_vars()
5805            && local_vars.contains(&name)
5806            && let Some(cell) = local_vars.get(&name, phase)
5807        {
5808            cell.set(value);
5809            return Ok(());
5810        }
5811        // A binding of the frame that called `eval` takes the write, which is what
5812        // makes `f("a = 3")` change the caller's `a`.
5813        if self.set_eval_binding(&name, &value)? {
5814            return Ok(());
5815        }
5816        // An *assignment* to a name nobody declared is not a declaration, so it falls
5817        // through to the global: strict mode raises `ReferenceError` for it, which is what
5818        // `eval("1 + (@not_def = 1)")` has to do.
5819        if lexical {
5820            if let Some(cell) = self.realm.globals.get(&name).cloned() {
5821                // A lexical global starts out `Uninitialized` and only `init_global` ends
5822                // that, so a store reaching here is either a plain assignment to a slot
5823                // still in its dead zone — `x = 1; let x` at the top level, a
5824                // `ReferenceError` — or a write to a `const` whose initialiser already ran.
5825                if matches!(cell.get(), Value::Uninitialized) {
5826                    return Err(self.dead_zone_global(&name));
5827                }
5828                if is_const {
5829                    return Err(self.read_only_global(&name));
5830                }
5831                cell.set(value);
5832                return Ok(());
5833            }
5834            // Writing an undeclared lexical global is a `ReferenceError` in strict
5835            // mode and a silent global creation otherwise; creating the cell here
5836            // keeps both paths from losing the value.
5837            let cell = self.new_cell(value);
5838            self.realm.globals.insert(name, cell);
5839            return Ok(());
5840        }
5841        // A variable a direct `eval` declared in this call shadows the global object, even
5842        // when the global already has a property of that name — `var c = "global"` at the
5843        // top level must not capture `eval("var c = 1")` inside a function.
5844        if let Some((local_vars, phase)) = self.visible_local_vars()
5845            && local_vars.contains(&name)
5846            && let Some(cell) = local_vars.get(&name, phase)
5847        {
5848            cell.set(value);
5849            return Ok(());
5850        }
5851        // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5852        // remembered a global's slot index since M12b, but the *store* side never did: it
5853        // converted the name to a `PropertyKey` (two allocations) and then scanned the
5854        // global object's whole table — which holds every builtin — on every assignment to
5855        // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5856        // full global lookup per iteration; measured with a counter, `s` as a global made
5857        // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5858        //
5859        // Re-validated exactly like the read: same object, same index, still the name, and
5860        // — the one extra check a store needs — still writable. A global that is an
5861        // accessor, non-writable, or inherited fails here and falls through to the full
5862        // path below, which reports the failure the way it always did.
5863        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5864        let global = self.realm.global.clone();
5865        if let Some(cached) = &self.global_cache[site]
5866            && global.upgrades_to(&cached.object)
5867            && global.write_data_at(cached.index, &name, value.clone())
5868        {
5869            return Ok(());
5870        }
5871        match global.own_property(&name) {
5872            // A `var` global is writable, so the store goes straight through — but
5873            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5874            // store (a non-writable or accessor-without-setter global) is a silent
5875            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5876            // split every other assignment has.
5877            Some(_) => {
5878                let on_failure = if self.current_strict() {
5879                    DeleteFailure::Throw
5880                } else {
5881                    DeleteFailure::Ignore
5882                };
5883                let result = self.set_property_with(&global, &name, value, on_failure);
5884                // Teach the cache the slot for a plain writable own data property, which is
5885                // what a declared `var` is. Without this the fast path above could never
5886                // fire for a global that is only ever *written* — its entry would have to
5887                // be put there by a read of the same slot, and a write-only loop has none.
5888                if result.is_ok()
5889                    && let Some(index) = global.own_data_index(&name)
5890                {
5891                    self.global_cache[site] = Some(GlobalCache {
5892                        object: global.downgrade(),
5893                        index,
5894                    });
5895                }
5896                result
5897            }
5898            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5899            // declaration creates a *configurable* property, which is what makes it
5900            // deletable and is the one way a global differs from a declared `var`.
5901            // In strict mode the same store is a `ReferenceError` instead: that is the
5902            // whole point of strict mode, and creating the global silently meant
5903            // `"use strict"; x = 1` looked like it worked.
5904            None => {
5905                if self.current_strict() {
5906                    return Err(self.throw_reference(&name));
5907                }
5908                // A direct eval declares here rather than on the global object: its
5909                // `var`s belong to the caller's variable environment. `declare_eval_local`
5910                // also covers a plain assignment to a variable an earlier eval made.
5911                if let Some(cell) = self.declare_eval_local(&name) {
5912                    cell.set(value);
5913                    return Ok(());
5914                }
5915                global.define_data(&name, value);
5916                Ok(())
5917            }
5918        }
5919    }
5920
5921    /// The value of a binding of the frame that called `eval`, if there is one.
5922    fn eval_binding_value(&self, name: &str) -> Option<Value> {
5923        let binding = self
5924            .eval_bindings
5925            .iter()
5926            .find(|binding| binding.name == name)?;
5927        let owner = self.frames.get(binding.frame)?;
5928        let (slot, index) = (binding.slot, binding.index);
5929        Some(match slot {
5930            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5931                cell if cell >= 0 => owner
5932                    .cells
5933                    .get(cell as usize)
5934                    .map(|cell| cell.get())
5935                    .unwrap_or(Value::Undefined),
5936                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5937            },
5938            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5939                cell if cell >= 0 => owner
5940                    .cells
5941                    .get(cell as usize)
5942                    .map(|cell| cell.get())
5943                    .unwrap_or(Value::Undefined),
5944                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5945            },
5946        })
5947    }
5948
5949    /// Write to a binding of the frame that called `eval`.
5950    ///
5951    /// `Ok(false)` means no binding matched and the caller should keep looking. A
5952    /// matched binding can still refuse the store, which is why this is fallible: a
5953    /// `const` is read-only everywhere, and a named function expression's own name is
5954    /// read-only in strict mode.
5955    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5956        let Some(binding) = self
5957            .eval_bindings
5958            .iter()
5959            .find(|binding| binding.name == name)
5960        else {
5961            return Ok(false);
5962        };
5963        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5964        let strict = self.current_strict();
5965        let Some(owner) = self.frames.get_mut(frame) else {
5966            return Ok(false);
5967        };
5968        match slot {
5969            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5970                cell if cell >= 0 => {
5971                    if let Some(cell) = owner.cells.get(cell as usize) {
5972                        cell.set(value.clone());
5973                    }
5974                }
5975                _ => {
5976                    if let Some(slot) = owner.args.get_mut(index) {
5977                        *slot = value.clone();
5978                    }
5979                }
5980            },
5981            EvalSlot::Local => {
5982                let declared = owner.code.code.vars.get(index);
5983                // A `const` is read-only even through `eval`. The realm records this for
5984                // globals (see `lexical_consts`), but a local's `const`-ness is only in
5985                // the bytecode, so this is where it has to be enforced.
5986                if declared.is_some_and(|var| var.is_const) {
5987                    return Err(self.read_only_local(name));
5988                }
5989                // The name of a named function expression is read-only too, but only
5990                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5991                // such a name is ignored, the same as a direct store would be.
5992                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5993                    return if strict {
5994                        Err(self.read_only_local(name))
5995                    } else {
5996                        Ok(true)
5997                    };
5998                }
5999                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
6000                    cell if cell >= 0 => {
6001                        if let Some(cell) = owner.cells.get(cell as usize) {
6002                            cell.set(value.clone());
6003                        }
6004                    }
6005                    _ => {
6006                        if let Some(slot) = owner.locals.get_mut(index) {
6007                            *slot = value.clone();
6008                        }
6009                    }
6010                }
6011            }
6012        }
6013        Ok(true)
6014    }
6015
6016    /// The `TypeError` an assignment to a read-only binding raises.
6017    fn read_only_local(&self, name: &str) -> Signal {
6018        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
6019    }
6020
6021    /// Declare `name` as a variable of the frame that called the running `eval`.
6022    ///
6023    /// `None` when there is no direct eval in progress, or it was called from the top
6024    /// level — then the caller's variable environment *is* the global one and the
6025    /// existing path is right.
6026    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
6027        let caller = self.eval_caller.flatten()?;
6028        // The bottom frame is the top-level script, whose variable environment *is* the
6029        // global one — so `eval("var x = 1")` at the top level still creates a global.
6030        if caller == 0 {
6031            return None;
6032        }
6033        // A name the eval's *own* variable environment already binds is not a new
6034        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
6035        // `arguments`, and creating a second binding would leave the first — the one
6036        // closures read — untouched. A binding of an *outer* frame does not count: a
6037        // declaration shadows it rather than writing through.
6038        if self
6039            .eval_bindings
6040            .iter()
6041            .any(|binding| binding.name == name && binding.frame == caller)
6042        {
6043            return None;
6044        }
6045        let phase = if self.in_parameter_list_at(caller) {
6046            0
6047        } else {
6048            1
6049        };
6050        self.frame_local_vars(caller)?;
6051        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
6052        if let Some(cell) = local_vars.get(name, 1) {
6053            return Some(cell);
6054        }
6055        let cell = self.new_cell(Value::Undefined);
6056        Some(local_vars.declare(name, phase, cell))
6057    }
6058
6059    /// Make sure `frame` has a `LocalVars`, creating it on demand.
6060    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
6061        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
6062            return Some(local_vars.clone());
6063        }
6064        let local_vars = Gc::new(self.heap, LocalVars::new());
6065        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
6066        Some(local_vars)
6067    }
6068
6069    /// Whether the realm already has a binding for `name`, lexically or as an *own*
6070    /// property of the global object. Used to decide whether a store inside an
6071    /// `eval` writes through to the realm or declares a binding of its own.
6072    ///
6073    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
6074    /// write to `Object.prototype.toString`, and must not shadow it either.
6075    fn global_knows(&mut self, name: &str) -> bool {
6076        if self.realm.globals.contains_key(name) {
6077            return true;
6078        }
6079        self.realm.global.own_property(name).is_some()
6080    }
6081
6082    /// Whether the code currently running is strict.
6083    ///
6084    /// Read off the frame's function, which is where the parser's answer ended up; a
6085    /// native function never runs strict-only checks, and there is no frame at all
6086    /// before the first script.
6087    pub fn current_strict(&self) -> bool {
6088        self.frames
6089            .last()
6090            .is_some_and(|frame| frame.code.code.strict)
6091    }
6092
6093    /// Initialise a declared global, which is what ends its dead zone.
6094    ///
6095    /// A `var` global becomes a property of the global object: writable, so a later
6096    /// assignment goes through, and non-configurable, so `delete` refuses.
6097    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
6098        let (name, lexical, _) = self.global_binding(slot);
6099        // A `var` declared by the strict `eval` currently running belongs to the
6100        // eval's scope, not to the global object: `eval("var v = 1")` must not make
6101        // `typeof v` answer `"number"` afterwards. A name the realm already has is
6102        // initialised in place, which is what a re-declaration inside eval does.
6103        if !self.eval_scope.is_empty() && !lexical && !self.global_knows(&name) {
6104            self.eval_scope
6105                .last_mut()
6106                .expect("checked above")
6107                .insert(name, value);
6108            return Ok(());
6109        }
6110        for scope in self.eval_scope.iter_mut().rev() {
6111            if let Some(slot) = scope.get_mut(&name) {
6112                *slot = value;
6113                return Ok(());
6114            }
6115        }
6116        if lexical {
6117            // The cell exists (created at declaration time) holding the dead-zone
6118            // marker; storing the value is what makes the binding readable.
6119            if let Some(cell) = self.realm.globals.get(&name).cloned() {
6120                cell.set(value);
6121                return Ok(());
6122            }
6123            let cell = self.new_cell(value);
6124            self.realm.globals.insert(name, cell);
6125            return Ok(());
6126        }
6127        let global = self.realm.global.clone();
6128        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
6129        // to answer `false` and leave the binding in place. `with_attributes` ties
6130        // `configurable` to `writable`, so the property is built field by field.
6131        global.define(
6132            &name,
6133            Property {
6134                value: Some(value),
6135                writable: true,
6136                enumerable: true,
6137                configurable: false,
6138                ..Property::default()
6139            },
6140        );
6141        Ok(())
6142    }
6143
6144    /// The `TypeError` a store to a `const` global raises.
6145    fn read_only_global(&self, name: &str) -> Signal {
6146        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
6147    }
6148
6149    /// The `ReferenceError` a store to a not-yet-initialised lexical global raises.
6150    fn dead_zone_global(&self, name: &str) -> Signal {
6151        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not initialized")))
6152    }
6153
6154    // -- properties ---------------------------------------------------------
6155
6156    /// Read `object[key]`, following the prototype chain.
6157    ///
6158    /// An inherited accessor runs with the *receiver* as `this`, which is why the
6159    /// lookup returns the owner rather than just the value.
6160    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
6161        self.get_property_key(object, &PropertyKey::from(key))
6162    }
6163
6164    /// [`Interp::get_property`] with a key that may be a symbol.
6165    pub fn get_property_key(
6166        &mut self,
6167        object: &Gc<JsObject>,
6168        key: &PropertyKey,
6169    ) -> JsResult<Option<Value>> {
6170        self.get_property_key_for(object, None, key)
6171    }
6172
6173    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
6174    ///
6175    /// The receiver matters when the property is found on a *prototype*: a getter has to
6176    /// see the object the read started from. For a primitive that is the primitive
6177    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
6178    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
6179    /// the owner.
6180    pub fn get_property_key_for(
6181        &mut self,
6182        object: &Gc<JsObject>,
6183        receiver: Option<&Value>,
6184        key: &PropertyKey,
6185    ) -> JsResult<Option<Value>> {
6186        // A proxy answers for itself, before any of the shortcuts below: `new
6187        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
6188        // have.
6189        if object.proxy_state().is_some() {
6190            let receiver = receiver
6191                .cloned()
6192                .unwrap_or_else(|| Value::Object(object.clone()));
6193            return self.proxy_get(object, &receiver, key);
6194        }
6195        // A host class's `get_property` trap replaces the whole read, prototype walk
6196        // included — that is what makes a native accessor free rather than a JavaScript
6197        // getter call.
6198        if let Some(exotic) = object.exotic() {
6199            let receiver_value = receiver
6200                .cloned()
6201                .unwrap_or_else(|| Value::Object(object.clone()));
6202            if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
6203                return Ok(Some(value));
6204            }
6205            // With no `get_property` trap, a `get_own_property` trap still answers for the
6206            // object itself: `[[Get]]` asks each object in the chain for its own descriptor
6207            // and the hook lives exactly there. A key the trap reports as absent is still
6208            // looked for on the prototype, which is why the search resumes *above*.
6209            if let Some(property) = exotic.get_own_property(self, object, key)? {
6210                return match property {
6211                    Some(property) => self.read_property(property, object, receiver),
6212                    None => match lookup_key_above(object, key) {
6213                        Some((_, property)) => self.read_property(property, object, receiver),
6214                        None => Ok(None),
6215                    },
6216                };
6217            }
6218        }
6219        // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
6220        // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
6221        // The `[[Get]]` short-circuit therefore belongs to this one arm.
6222        //
6223        // Constructibility is exactly the split the reference makes: `function f(){}` and
6224        // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
6225        // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
6226        // function" — it *is* the predicate, which is why no extra marker is needed.
6227        if let Some(text) = key.as_str()
6228            && (text == "caller" || text == "arguments")
6229            && object.is_constructor()
6230            && object.is_callable()
6231            && !object.is_bound_function()
6232            // …and only when the body is **sloppy**. A strict body reaches the
6233            // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
6234            // whole `Function/15.3.5.4_2-*gs` family is written against
6235            // (`onlyStrict`, so every function in them is strict).
6236            && !object.function_is_strict()
6237            && object.own_property(text).is_none()
6238        {
6239            return Ok(Some(Value::Undefined));
6240        }
6241        // The element-vector and `length` shortcuts are string-only: an array index
6242        // has no symbol spelling.
6243        if let Some(text) = key.as_str() {
6244            if let Some(value) = self.own_element(object, text) {
6245                return Ok(Some(value));
6246            }
6247            // `length` is not stored as a property: an array's length is its element
6248            // count, and keeping one copy of it is what makes `push`/`pop` and
6249            // `a.length = n` agree.
6250            if let Some(length) = object.array_length()
6251                && text == "length"
6252            {
6253                // Not `Value::Int(length as i32)`: see [`length_value`].
6254                return Ok(Some(crate::object::length_value(length)));
6255            }
6256        }
6257        // A proxy or a hooked exotic object anywhere above `object` makes the static
6258        // table walk below wrong: a proxy's own table is *empty by design* (the properties
6259        // live on its target), so the walk skipped that link entirely and everything behind
6260        // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
6261        // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
6262        // -target-is-proxy.js` are the four.
6263        if Self::chain_needs_dispatch(object) {
6264            return self.walk_get(object, receiver, key);
6265        }
6266        match lookup_key(object, key) {
6267            Some((_, property)) => self.read_property(property, object, receiver),
6268            None => Ok(None),
6269        }
6270    }
6271
6272    /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
6273    /// answer for itself.
6274    ///
6275    /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
6276    /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
6277    /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
6278    /// an inherited getter the object the read started from.
6279    fn walk_get(
6280        &mut self,
6281        start: &Gc<JsObject>,
6282        receiver: Option<&Value>,
6283        key: &PropertyKey,
6284    ) -> JsResult<Option<Value>> {
6285        let receiver = receiver
6286            .cloned()
6287            .unwrap_or_else(|| Value::Object(start.clone()));
6288        let mut current = Some(start.clone());
6289        while let Some(holder) = current {
6290            // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
6291            // has to ask it, not read its (empty) own-property table. `Object.create(new
6292            // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
6293            // instead found nothing.
6294            if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
6295                return Ok(Some(value));
6296            }
6297            // A host class's `get_property` trap replaces the whole read for that holder,
6298            // prototype walk included — the same rule `get_property_key_for` applies to the
6299            // first object.
6300            if let Some(exotic) = holder.exotic()
6301                && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
6302            {
6303                return Ok(Some(value));
6304            }
6305            if let Some(property) = self.object_get_own_property(&holder, key)? {
6306                return self.read_property(property, &holder, Some(&receiver));
6307            }
6308            current = self.object_prototype_of(&holder)?;
6309        }
6310        Ok(None)
6311    }
6312
6313    /// Whether `object` or anything above it has properties that cannot be read out of a
6314    /// property table — a proxy, or an exotic object with a `get_own_property` hook.
6315    ///
6316    /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
6317    /// is the hot path for every property read; this is the check that decides whether it
6318    /// is safe to take it.
6319    fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
6320        // A module namespace answers through `[[GetOwnProperty]]` (§10.4.6), and a
6321        // *deferred* one evaluates its module there — so the static property-table walk is
6322        // the wrong shortcut for it. This is the receiver's own marker, checked first: a
6323        // namespace's `[[Prototype]]` is null, so `chain()` below is empty for it and the
6324        // loop would never see it. Non-deferred namespaces pay a walk instead of a table
6325        // lookup; there are never many of them and they are read by importers.
6326        if object.module_namespace_marker() {
6327            return true;
6328        }
6329        object.chain().iter().any(|ancestor| {
6330            ancestor.proxy_state().is_some()
6331                || ancestor.exotic().is_some()
6332                || ancestor.module_namespace_marker()
6333        })
6334    }
6335
6336    /// The value a property read answers.
6337    ///
6338    /// One place rather than three, because an accessor has to run with the *receiver* as
6339    /// `this` whether the descriptor came from the property table, an exotic
6340    /// `get_own_property` trap, or a prototype above one.
6341    fn read_property(
6342        &mut self,
6343        property: Property,
6344        object: &Gc<JsObject>,
6345        receiver: Option<&Value>,
6346    ) -> JsResult<Option<Value>> {
6347        if property.is_accessor() {
6348            match &property.getter {
6349                Some(getter) if !matches!(getter, Value::Undefined) => {
6350                    let receiver = receiver
6351                        .cloned()
6352                        .unwrap_or_else(|| Value::Object(object.clone()));
6353                    self.call_value(getter.clone(), receiver, Vec::new())
6354                        .map(Some)
6355                }
6356                // An accessor with no getter reads as `undefined`.
6357                _ => Ok(Some(Value::Undefined)),
6358            }
6359        } else {
6360            Ok(property.value)
6361        }
6362    }
6363
6364    /// `super.key` — start the search at `proto`, but report to `receiver`.
6365    ///
6366    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
6367    /// found on the prototype of a class has to see the *instance* as `this`, and a
6368    /// plain property read off `proto` would lose that.
6369    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
6370        let start = self.require_object(proto)?;
6371        let key = self.propkey(key)?;
6372        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
6373        if matches!(proto, Value::Null) {
6374            return Ok(Value::Undefined);
6375        }
6376        // `super.x` is `OrdinaryGet` with `startObject` as the base, so a namespace on the
6377        // way is asked for its exports list — and a deferred one evaluates there, for a
6378        // name the base does *not* have as much as for one it does.
6379        self.trigger_deferred_namespace_for_key(&start, &key)?;
6380        match lookup_key(&start, &key) {
6381            Some((_, property)) if property.is_accessor() => match &property.getter {
6382                Some(getter) if !matches!(getter, Value::Undefined) => {
6383                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
6384                }
6385                _ => Ok(Value::Undefined),
6386            },
6387            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
6388            None => Ok(Value::Undefined),
6389        }
6390    }
6391
6392    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
6393    ///
6394    /// A setter found on the prototype runs with `receiver` as `this`; a data property
6395    /// is shadowed by a new own property on the receiver, the same rule an ordinary
6396    /// assignment follows.
6397    fn super_write(
6398        &mut self,
6399        receiver: &Value,
6400        proto: &Value,
6401        key: &Value,
6402        value: Value,
6403    ) -> JsResult<()> {
6404        let target = self.require_object(receiver)?;
6405        let key = self.propkey(key)?;
6406        if !matches!(proto, Value::Null)
6407            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
6408        {
6409            // §10.4.6.6 / `OrdinarySetWithOwnDescriptor`: the descriptor is fetched from the
6410            // prototype before the store, which is where a deferred namespace evaluates.
6411            self.trigger_deferred_namespace_for_key(&owner, &key)?;
6412            if property.is_accessor() {
6413                if let Some(setter) = &property.setter
6414                    && !matches!(setter, Value::Undefined)
6415                {
6416                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
6417                }
6418                return Ok(());
6419            }
6420            // A data property on the prototype is writable or not; reading `owner` at
6421            // all is only for the attribute check.
6422            if !property.writable {
6423                return Err(self.type_error(format!("'{key}' is read-only")));
6424            }
6425            let _ = owner;
6426        }
6427        // `OrdinarySetWithOwnDescriptor` reaches the store only after asking the *receiver*
6428        // for its own descriptor — which is where a deferred namespace evaluates, and the
6429        // only reason `super[key] = v` runs a module whose `[[Set]]` refuses everything.
6430        self.trigger_deferred_namespace_for_key(&target, &key)?;
6431        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
6432    }
6433
6434    /// The object a `super` operation needs, or the `TypeError` the spec raises.
6435    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
6436        match value.as_object() {
6437            Some(object) => Ok(object.clone()),
6438            None => Err(Signal::Throw(
6439                self.make_error("TypeError", "value is not an object"),
6440            )),
6441        }
6442    }
6443
6444    /// Build the class object `define_class` produces.
6445    ///
6446    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
6447    /// whose prototype property is a fresh object inheriting from the parent's
6448    /// prototype, and whose own prototype is the parent constructor — which is what makes
6449    /// a static method inherited too.
6450    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
6451        let ctor = self.pop();
6452        let parent = self.pop();
6453        let Value::Object(function) = &ctor else {
6454            return Err(Signal::Throw(
6455                self.make_error("TypeError", "class constructor must be a function"),
6456            ));
6457        };
6458        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
6459        // but gives the instances no prototype at all.
6460        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
6461            match &parent {
6462                Value::Null => (Some(self.realm.function_proto.clone()), None),
6463                Value::Object(parent_class) => {
6464                    // `IsConstructor`, not `IsCallable`: §15.7.14 ClassDefinitionEvaluation
6465                    // step 9 rejects a heritage without `[[Construct]]` *before* reading
6466                    // `superclass.prototype`, so an arrow function and a generator — both
6467                    // callable, neither constructible — are a `TypeError` and their
6468                    // `prototype` getter must never run
6469                    // (`subclass/superclass-arrow-function`, `…-generator-function`).
6470                    if !parent_class.is_constructor() {
6471                        return Err(Signal::Throw(
6472                            self.make_error("TypeError", "parent class must be constructor"),
6473                        ));
6474                    }
6475                    let proto = self.get_property(parent_class, "prototype")?;
6476                    match proto {
6477                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
6478                        Some(Value::Null) => (Some(parent_class.clone()), None),
6479                        _ => {
6480                            return Err(Signal::Throw(self.make_error(
6481                                "TypeError",
6482                                "parent prototype must be an object or null",
6483                            )));
6484                        }
6485                    }
6486                }
6487                _ => {
6488                    return Err(Signal::Throw(
6489                        self.make_error("TypeError", "parent class must be constructor"),
6490                    ));
6491                }
6492            }
6493        } else {
6494            (
6495                Some(self.realm.function_proto.clone()),
6496                Some(self.realm.object_proto.clone()),
6497            )
6498        };
6499        let proto = self.new_object(parent_proto);
6500        function.set_proto(parent_ctor);
6501        // A class is not callable without `new`, and its `prototype` is not writable —
6502        // both follow from being a class and are what `class A {}; A()` throws on.
6503        function.set_class_constructor(true);
6504        function.set_home_object(None);
6505        self.set_function_name(&ctor, name);
6506        self.define_class_properties(function, &ctor, &proto)?;
6507        Ok((ctor, proto))
6508    }
6509
6510    /// Give the constructor its `prototype` and `length`, and the prototype its
6511    /// `constructor` back-pointer.
6512    fn define_class_properties(
6513        &mut self,
6514        function: &Gc<JsObject>,
6515        ctor: &Value,
6516        proto: &Gc<JsObject>,
6517    ) -> JsResult<()> {
6518        proto.define(
6519            "constructor",
6520            Property::with_attributes(ctor.clone(), true, false),
6521        );
6522        function.define(
6523            "prototype",
6524            Property::prototype_of(Value::Object(proto.clone()), false),
6525        );
6526        if let Some((code, _)) = bytecode_of(function) {
6527            let length = code.code.defined_args;
6528            function.define(
6529                "length",
6530                Property::name_or_length(Value::Int(length as i32)),
6531            );
6532        }
6533        Ok(())
6534    }
6535
6536    /// The own array element `key` names, if this object has one.
6537    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
6538        // A typed array's elements live in its buffer, not in a property list: reading one
6539        // goes through the view's element type so a bounds check and a detached buffer are
6540        // both handled there.
6541        //
6542        // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
6543        // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
6544        // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
6545        // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
6546        // consulted. Testing with `array_index` rejected all three, which let a throwing
6547        // getter installed on `TypedArray.prototype["-1"]` run.
6548        if object.typed_array_parts().is_some() {
6549            let property_key = PropertyKey::from(key);
6550            let numeric = canonical_numeric_index(&property_key)?;
6551            if typed_array_index_is_valid(object, numeric) {
6552                return object.typed_array_element(numeric as usize);
6553            }
6554            // Canonical, but not a valid index: `undefined`, and *final*.
6555            return Some(Value::Undefined);
6556        }
6557        let index = array_index(key)?;
6558        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
6559        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
6560        // search early, which is why `Array.prototype[1] = 9` could not be seen through
6561        // `[1,,3][1]`.
6562        match object.array_get(index as usize) {
6563            Some(Value::Hole) | None => None,
6564            other => other,
6565        }
6566    }
6567
6568    /// Store `object[key] = value`, honouring setters and inherited properties.
6569    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
6570        self.set_property_with(object, key, value, DeleteFailure::Throw)
6571    }
6572
6573    /// Store a property, choosing what to do when the object refuses.
6574    ///
6575    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
6576    /// mode, which is the one place assignment differs by mode. Native code (the array
6577    /// methods, `JSON`) always asks for the throw.
6578    pub fn set_property_with(
6579        &mut self,
6580        object: &Gc<JsObject>,
6581        key: &str,
6582        value: Value,
6583        on_failure: DeleteFailure,
6584    ) -> JsResult<()> {
6585        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
6586    }
6587
6588    /// [`Interp::set_property_with`] with a key that may be a symbol.
6589    pub fn set_property_with_key(
6590        &mut self,
6591        object: &Gc<JsObject>,
6592        key: &PropertyKey,
6593        value: Value,
6594        on_failure: DeleteFailure,
6595    ) -> JsResult<()> {
6596        self.set_property_with_key_receiver_aware(object, key, value, on_failure)
6597    }
6598
6599    /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
6600    ///
6601    /// The receiver split lives one level up, in
6602    /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
6603    /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
6604    /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
6605    /// stores into `object` itself, which is why the element branch below converts `V`
6606    /// before asking whether the index is valid: `V` may put it back in bounds
6607    /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
6608    fn set_property_with_key_receiver_aware(
6609        &mut self,
6610        object: &Gc<JsObject>,
6611        key: &PropertyKey,
6612        value: Value,
6613        on_failure: DeleteFailure,
6614    ) -> JsResult<()> {
6615        // §10.4.6.7: a module namespace's `[[Set]]` **always** returns false — for an
6616        // exported name, for a name that is not exported, and for `@@toStringTag` alike.
6617        // Nothing about the receiver or the value changes that, so the whole operation is
6618        // one answer.
6619        //
6620        // Not implementing it explicitly left the ordinary algorithm in charge, and that
6621        // says "true" for names the namespace does not own as soon as the value matches or
6622        // the key is writable, so `Reflect.set(ns, 'local1', …)` answered `true` and strict
6623        // assignment stopped throwing (`await-ns-set-strict`).
6624        if object.module_namespace_marker() {
6625            return match on_failure {
6626                DeleteFailure::Ignore => Ok(()),
6627                DeleteFailure::Throw => Err(self.type_error(format!(
6628                    "cannot assign to property '{key}' of a module namespace object"
6629                ))),
6630            };
6631        }
6632        // A proxy's `set` trap decides, and its `false` means the same thing an
6633        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
6634        if object.proxy_state().is_some() {
6635            let receiver = Value::Object(object.clone());
6636            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
6637                return match (accepted, on_failure) {
6638                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6639                    (false, DeleteFailure::Throw) => {
6640                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
6641                    }
6642                };
6643            }
6644        }
6645        // A host class's `set_property` trap decides for itself. `Some(false)` is a
6646        // refusal and means exactly what a proxy's `false` means.
6647        if let Some(exotic) = object.exotic() {
6648            let receiver = Value::Object(object.clone());
6649            if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
6650                return match (accepted, on_failure) {
6651                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6652                    (false, DeleteFailure::Throw) => {
6653                        Err(self.type_error(format!("property '{key}' is read-only")))
6654                    }
6655                };
6656            }
6657        }
6658        // The element and `length` shortcuts only exist for string keys: an array
6659        // index has no symbol spelling, and a symbol named `length` is an ordinary
6660        // property.
6661        let text = key.as_str();
6662        // A typed array's elements are a window onto its buffer: the store has to go
6663        // through the view's element type so the value is wrapped (or clamped) and so an
6664        // out-of-range or detached write is a silent no-op, as the spec says.
6665        //
6666        // The key test is `CanonicalNumericIndexString`, like every other index operation
6667        // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
6668        // does not exist, so they do nothing and leave no own property behind
6669        // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
6670        // path, which created a property named `"-0"`.
6671        //
6672        // The conversion comes **first**, before the index is checked at all, and that
6673        // order is observable twice over:
6674        //
6675        // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
6676        //   has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
6677        //   then store the converted value;
6678        // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
6679        //   `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
6680        //   run and its exception to escape.
6681        //
6682        // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
6683        // validity check, not a validity check that skips the conversion. The store itself
6684        // is a no-op when the index is invalid by then, which is why no extra guard is
6685        // needed around `typed_array_set`.
6686        if let Some(element) = object.typed_array_element_type()
6687            && let Some(numeric) = canonical_numeric_index(key)
6688        {
6689            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
6690            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
6691            // in `Interp`, because it is script-observable and the storage borrow inside
6692            // `typed_array_set` must not be held across it.
6693            let stored = self.element_value(element, value)?;
6694            if typed_array_index_is_valid(object, numeric)
6695                && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
6696            {
6697                return Err(self.type_error(reason));
6698            }
6699            return Ok(());
6700        }
6701        if let Some(text) = text
6702            && let Some(index) = array_index(text)
6703            && object.is_array()
6704        {
6705            // An accessor defined on an index lives in the property table while the
6706            // element slot is a hole, so the store has to go through the property first.
6707            // Writing the vector directly skipped the setter entirely.
6708            if let Some(existing) = object.own_property_key(key) {
6709                if existing.is_accessor() {
6710                    return match existing.setter.clone() {
6711                        Some(setter) if !matches!(setter, Value::Undefined) => {
6712                            let receiver = Value::Object(object.clone());
6713                            self.call_value(setter, receiver, vec![value]).map(|_| ())
6714                        }
6715                        _ => match on_failure {
6716                            DeleteFailure::Throw => Err(self.type_error(format!(
6717                                "cannot set property '{text}', it has only a getter"
6718                            ))),
6719                            DeleteFailure::Ignore => Ok(()),
6720                        },
6721                    };
6722                }
6723                if !existing.writable {
6724                    return match on_failure {
6725                        DeleteFailure::Throw => {
6726                            Err(self.type_error(format!("'{text}' is read-only")))
6727                        }
6728                        DeleteFailure::Ignore => Ok(()),
6729                    };
6730                }
6731            }
6732            {
6733                // Growing the array needs a writable `length`.
6734                if (index as usize) >= object.array_length().unwrap_or(0)
6735                    && !object.length_writable()
6736                {
6737                    return match on_failure {
6738                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6739                        DeleteFailure::Ignore => Ok(()),
6740                    };
6741                }
6742                // Adding an index past the end makes the array longer, which a
6743                // non-extensible array refuses.
6744                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6745                    return match on_failure {
6746                        DeleteFailure::Throw => Err(self.type_error(format!(
6747                            "cannot add property '{key}', object is not extensible"
6748                        ))),
6749                        DeleteFailure::Ignore => Ok(()),
6750                    };
6751                }
6752                if object.element_is_locked(index) {
6753                    return match on_failure {
6754                        DeleteFailure::Throw => {
6755                            Err(self.type_error(format!("'{key}' is read-only")))
6756                        }
6757                        DeleteFailure::Ignore => Ok(()),
6758                    };
6759                }
6760                // The element vector is only half of `[[Set]]` for an index: the
6761                // prototype chain is consulted first, and a setter there answers instead
6762                // of the element store. This branch used to write the element directly, so
6763                // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6764                // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6765                // the reference calls the setter and the array keeps no own index.
6766                //
6767                // An *exotic* prototype has no entry to find, because its indices live
6768                // outside the property table — `Object.setPrototypeOf([], typedArray)`
6769                // then looked like "nothing on the chain" and the store created the
6770                // element, where the view's `[[Set]]` answers `true` and does nothing for
6771                // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6772                // checks the array's `length` stays 0). So the dispatch comes first.
6773                if !object.has_own_key(key)
6774                    && let Some(proto) = object.proto()
6775                    && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6776                {
6777                    let receiver = Value::Object(object.clone());
6778                    let accepted =
6779                        self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6780                    return if accepted {
6781                        Ok(())
6782                    } else {
6783                        match on_failure {
6784                            DeleteFailure::Throw => {
6785                                Err(self.type_error(format!("'{key}' is read-only")))
6786                            }
6787                            DeleteFailure::Ignore => Ok(()),
6788                        }
6789                    };
6790                }
6791                if let Some((owner, property)) = lookup_key(object, key)
6792                    && !owner.ptr_eq(object)
6793                {
6794                    match &property {
6795                        property if property.is_accessor() => {
6796                            match &property.setter {
6797                                Some(setter) if !matches!(setter, Value::Undefined) => {
6798                                    let receiver = Value::Object(object.clone());
6799                                    self.call_value(setter.clone(), receiver, vec![value])?;
6800                                }
6801                                _ => {
6802                                    return match on_failure {
6803                                        DeleteFailure::Throw => Err(self.type_error(format!(
6804                                            "cannot set property '{text}', it has only a getter"
6805                                        ))),
6806                                        DeleteFailure::Ignore => Ok(()),
6807                                    };
6808                                }
6809                            }
6810                            return Ok(());
6811                        }
6812                        property if !property.writable => {
6813                            return match on_failure {
6814                                DeleteFailure::Throw => {
6815                                    Err(self.type_error(format!("'{text}' is read-only")))
6816                                }
6817                                DeleteFailure::Ignore => Ok(()),
6818                            };
6819                        }
6820                        _ => {}
6821                    }
6822                }
6823                if object.array_set(self.heap, index as usize, value.clone()) {
6824                    return Ok(());
6825                }
6826                // Past the dense limit the slot is too far out to be worth one `Value`
6827                // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6828                // constant time by keeping the index as an ordinary property. The store
6829                // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6830                // to a legal program.
6831                object.define_key(key, Property::with_attributes(value, true, true));
6832                // Extend, never shorten: the index may be *inside* the current length (a
6833                // huge `length` with a sparse store), and shortening would delete the
6834                // sparse properties above it — including the one just stored.
6835                if index as usize + 1 > object.array_length().unwrap_or(0) {
6836                    object.array_set_length(self.heap, index as usize + 1);
6837                }
6838                return Ok(());
6839            }
6840        }
6841        if text == Some("length") && object.is_array() {
6842            // §10.4.2.4 steps 3–5: **two** `ToNumber` conversions, then the writability
6843            // test. A `valueOf` that locks `length` on its second call therefore turns the
6844            // store into a refused write rather than a silent success
6845            // (`length/define-own-prop-length-coercion-order-set`).
6846            let rounded = self.coerce_array_length_twice(&value)?;
6847            if !object.length_writable() {
6848                return match on_failure {
6849                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6850                    DeleteFailure::Ignore => Ok(()),
6851                };
6852            }
6853            // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6854            // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6855            // answered `NaN`, which left the assignment silently ignored
6856            // (`S15.4.5.2_A3_T2`).
6857            let _ = rounded;
6858            let length = self.to_js_number(&value)?;
6859            // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6860            // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6861            // `RangeError`s; the old code only tested "finite and non-negative" and then
6862            // truncated, so `[].length = 4294967297` quietly produced a length no array can
6863            // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6864            let valid = length.is_finite()
6865                && length >= 0.0
6866                && length.fract() == 0.0
6867                && length <= u32::MAX as f64;
6868            if !valid {
6869                return Err(self.range_error("invalid array length"));
6870            }
6871            {
6872                let length = length as usize;
6873                // `a.length = n` with `n` below a non-configurable element cannot
6874                // drop that element, so the whole assignment fails. The spec makes
6875                // this a `TypeError` rather than a silent no-op, in any mode.
6876                if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6877                    // Sloppy mode stops the truncation at the blocking element
6878                    // instead of failing; strict mode raises.
6879                    // Both modes stop at the blocking element; they differ in
6880                    // whether that is reported. The reference truncates *then*
6881                    // throws, so the array is left in the shortened state.
6882                    object.array_truncate(self.heap, blocked + 1);
6883                    return match on_failure {
6884                        DeleteFailure::Throw => {
6885                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
6886                        }
6887                        DeleteFailure::Ignore => Ok(()),
6888                    };
6889                }
6890                object.array_set_length(self.heap, length);
6891                return Ok(());
6892            }
6893        }
6894        // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6895        // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6896        // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6897        //
6898        // The prototype step is a dispatch, not a lookup. Walking the chain here and
6899        // applying whatever came back is the same thing for an ordinary prototype and
6900        // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6901        // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6902        // answers "not mine, the receiver is not me" without touching the buffer. This
6903        // code used to find nothing owned by `o`, find no property on the view either,
6904        // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6905        // object and never converted (`key-is-valid-index-prototype-chain-set`,
6906        // `key-is-canonical-invalid-index-prototype-chain-set`).
6907        //
6908        // The read-only and accessor rules of step 1 are what make
6909        // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6910        // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6911        let own = match self.lookup_for_write(object, key)? {
6912            Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6913            _ => None,
6914        };
6915        if let Some(property) = own {
6916            if property.is_accessor() {
6917                return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6918                    Some(setter) => {
6919                        let receiver = Value::Object(object.clone());
6920                        self.call_value(setter, receiver, vec![value])?;
6921                        Ok(())
6922                    }
6923                    // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6924                    // Sloppy code swallows that refusal, strict code raises — the same
6925                    // rule the read-only *data* property below follows, and skipping it
6926                    // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6927                    // return silently. The reference answers `TypeError: 'x' is
6928                    // read-only`.
6929                    None => match on_failure {
6930                        DeleteFailure::Throw => {
6931                            Err(self.type_error(format!("'{key}' is read-only")))
6932                        }
6933                        DeleteFailure::Ignore => Ok(()),
6934                    },
6935                };
6936            }
6937            // An own non-writable data property stops here: nothing may change it.
6938            if !property.writable {
6939                return match on_failure {
6940                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6941                    DeleteFailure::Ignore => Ok(()),
6942                };
6943            }
6944            // An existing writable own property keeps its attributes: only the value
6945            // moves. Redefining instead would reset them, which is how a
6946            // non-configurable global `var` used to become deletable.
6947            if object.write_value_key(key, value.clone()) {
6948                return Ok(());
6949            }
6950        }
6951        // Step 2: hand the store to the prototype, with `object` as the receiver.
6952        if let Some(proto) = object.proto() {
6953            let receiver = Value::Object(object.clone());
6954            let accepted =
6955                self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6956            return if accepted {
6957                Ok(())
6958            } else {
6959                match on_failure {
6960                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6961                    DeleteFailure::Ignore => Ok(()),
6962                }
6963            };
6964        }
6965        // Step 3: create one, and a non-extensible object cannot.
6966        if !object.is_extensible() {
6967            return match on_failure {
6968                DeleteFailure::Throw => Err(self.type_error(format!(
6969                    "cannot add property {key}, object is not extensible"
6970                ))),
6971                DeleteFailure::Ignore => Ok(()),
6972            };
6973        }
6974        object.define_data_key(key, value);
6975        Ok(())
6976    }
6977
6978    /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6979    ///
6980    /// The distinction the fast path above does not need: it is called with the store's
6981    /// receiver already being the object it writes to. Here `object` is the one whose
6982    /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6983    /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6984    /// and not a write to `object`.
6985    ///
6986    /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6987    /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6988    /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6989    /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6990    /// descriptor on the prototype refuses instead, which is the same rule that keeps
6991    /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6992    ///
6993    /// Answers `false` where the spec says `false`; the caller turns that into the
6994    /// strict-mode `TypeError` or the sloppy-mode silence.
6995    fn ordinary_set_with_receiver(
6996        &mut self,
6997        object: &Gc<JsObject>,
6998        receiver: &Value,
6999        key: &PropertyKey,
7000        value: Value,
7001        on_failure: DeleteFailure,
7002    ) -> JsResult<bool> {
7003        // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
7004        if object.proxy_state().is_some() {
7005            return Ok(self
7006                .proxy_set(object, key, value, receiver)?
7007                .unwrap_or(true));
7008        }
7009        // A host class decides for itself, with the receiver the caller named.
7010        if let Some(exotic) = object.exotic()
7011            && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
7012        {
7013            return Ok(accepted);
7014        }
7015        // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
7016        // rather than the receiver, but the receiver may still *be* the view:
7017        // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
7018        // itself as receiver, and then the first half applies — convert `V` once, store
7019        // if the index is valid, answer `true` either way. The conversion is the observable
7020        // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
7021        //
7022        // Only the second half, a view that is *not* the receiver, skips the conversion
7023        // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
7024        // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
7025        // below with the value still unconverted.
7026        if object.typed_array_element_type().is_some()
7027            && let Some(numeric) = canonical_numeric_index(key)
7028        {
7029            if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
7030                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
7031                return Ok(true);
7032            }
7033            if !typed_array_index_is_valid(object, numeric) {
7034                return Ok(true);
7035            }
7036        }
7037        let own = self.object_get_own_property(object, key)?;
7038        if let Some(own) = own {
7039            if own.is_accessor() {
7040                return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
7041                    Some(setter) => {
7042                        self.call_value(setter, receiver.clone(), vec![value])?;
7043                        Ok(true)
7044                    }
7045                    None => Ok(false),
7046                };
7047            }
7048            // A non-writable data descriptor refuses, own or inherited. Either way the
7049            // receiver must not gain a shadowing property.
7050            if !own.writable {
7051                return Ok(false);
7052            }
7053            // Step 1.d: the *receiver's* own descriptor decides whether it can be
7054            // created or written, and it is created as an ordinary data property.
7055            let Some(receiver_object) = receiver.as_object().cloned() else {
7056                return Ok(false);
7057            };
7058            return match self.object_get_own_property(&receiver_object, key)? {
7059                Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
7060                Some(existing) => self.object_define_own_property(
7061                    &receiver_object,
7062                    key,
7063                    Property {
7064                        value: Some(value),
7065                        ..existing
7066                    },
7067                ),
7068                None => {
7069                    self.object_define_own_property(&receiver_object, key, Property::data(value))
7070                }
7071            };
7072        }
7073        // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
7074        if let Some(proto) = object.proto() {
7075            return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
7076        }
7077        // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
7078        // *default* data descriptor here, so control falls into step 2 exactly as if the
7079        // target had owned a writable property — which means the **receiver's** own
7080        // descriptor is asked for before the write. Skipping that question went straight to
7081        // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
7082        // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
7083        // exactly those calls).
7084        let Some(receiver_object) = receiver.as_object().cloned() else {
7085            return Ok(false);
7086        };
7087        match self.object_get_own_property(&receiver_object, key)? {
7088            Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
7089            Some(existing) => self.object_define_own_property(
7090                &receiver_object,
7091                key,
7092                Property {
7093                    value: Some(value),
7094                    ..existing
7095                },
7096            ),
7097            None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
7098        }
7099    }
7100
7101    /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
7102    ///
7103    /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
7104    /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
7105    /// a virtual accessor gets its setter run without implementing `set_property` at all.
7106    /// Answering `Some(None)` from the hook does not end the search: the key may still be on
7107    /// the prototype, so the walk resumes above the object.
7108    fn lookup_for_write(
7109        &mut self,
7110        object: &Gc<JsObject>,
7111        key: &PropertyKey,
7112    ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
7113        let Some(exotic) = object.exotic() else {
7114            return Ok(lookup_key(object, key));
7115        };
7116        Ok(match exotic.get_own_property(self, object, key)? {
7117            Some(Some(property)) => Some((object.clone(), property)),
7118            Some(None) => lookup_key_above(object, key),
7119            None => lookup_key(object, key),
7120        })
7121    }
7122
7123    /// Delete `object[key]`.
7124    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
7125        self.delete_property_key(object, &PropertyKey::from(key))
7126    }
7127
7128    /// [`Interp::delete_property`] with a key that may be a symbol.
7129    pub fn delete_property_key(
7130        &mut self,
7131        object: &Gc<JsObject>,
7132        key: &PropertyKey,
7133    ) -> JsResult<bool> {
7134        // A proxy decides for itself, and may even throw; the invariant checks live in
7135        // `proxy_delete`.
7136        if let Some(answer) = self.proxy_delete(object, key)? {
7137            return Ok(answer);
7138        }
7139        // A host class's `delete_property` trap decides; `false` is a refusal, which the
7140        // caller reports as a failed delete.
7141        if let Some(exotic) = object.exotic()
7142            && let Some(answer) = exotic.delete_property(self, object, key)?
7143        {
7144            return Ok(answer);
7145        }
7146        // §10.4.6.9 `[[Delete]]` also asks for the exports list — every export is
7147        // non-configurable, so the answer is always `false`, but a deferred namespace
7148        // evaluates first and symbol-like keys are exempt.
7149        self.trigger_deferred_namespace_for_key(object, key)?;
7150        // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
7151        // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
7152        // detached buffer — answers `true` (there is nothing to delete), and a *valid*
7153        // one answers `false` because the elements are non-configurable. The prototype
7154        // chain is not consulted either, which is what makes a throwing getter on
7155        // `TypedArray.prototype["-1"]` stay unrun.
7156        if object.typed_array_parts().is_some()
7157            && object.proxy_state().is_none()
7158            && let Some(numeric) = canonical_numeric_index(key)
7159        {
7160            return Ok(!typed_array_index_is_valid(object, numeric));
7161        }
7162        let mapped_index = key.as_str().and_then(array_index);
7163        if let Some(index) = mapped_index
7164            && let Some(length) = object.array_length()
7165            && (index as usize) < length
7166        {
7167            // An accessor defined on an index lives in the property table rather than the
7168            // element vector, so both have to be cleared: `delete` after
7169            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
7170            object.delete_key(key);
7171            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
7172            // index stops answering `in`.
7173            if object.element_is_undeletable(index) {
7174                return Ok(false);
7175            }
7176            // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
7177            // so a later `defineProperty(arguments, "0", {value})` writes to the object
7178            // and no longer through to the parameter. A refused delete leaves the
7179            // mapping alone.
7180            object.drop_mapped_argument(index as usize);
7181            object.array_set(self.heap, index as usize, Value::Hole);
7182            return Ok(true);
7183        }
7184        // An array's `length` is a non-configurable own property that lives outside the
7185        // property table, so `delete_key` finds nothing and reports success — `Reflect
7186        // .deleteProperty([1], "length")` answered `true` and left `length` in place.
7187        // §10.4.4.1 step 3 refuses it.
7188        if key.as_str() == Some("length") && object.array_length().is_some() {
7189            return Ok(false);
7190        }
7191        // The same for an object that is not an array: only a delete that actually
7192        // removed the property ends the alias.
7193        let deleted = object.delete_key(key);
7194        if deleted && let Some(index) = mapped_index {
7195            object.drop_mapped_argument(index as usize);
7196        }
7197        Ok(deleted)
7198    }
7199
7200    // -- proxy traps --------------------------------------------------------
7201    //
7202    // A proxy's internal methods all look the same: ask the handler for the trap, call it
7203    // with the target and the operation's own arguments, then check the answer against
7204    // the target. The checks are not decoration — they are what stops a proxy from
7205    // reporting a `non-configurable` property as missing, which would let a frozen object
7206    // be rewritten by standing in front of it.
7207
7208    /// The target and handler of `object`, or `None` when it is not a proxy.
7209    ///
7210    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
7211    /// one has to fail: the slots the traps would have been read from are gone.
7212    pub(crate) fn proxy_parts(
7213        &mut self,
7214        object: &Gc<JsObject>,
7215    ) -> JsResult<Option<(Gc<JsObject>, Value)>> {
7216        let Some(state) = object.proxy_state() else {
7217            return Ok(None);
7218        };
7219        let state = state.borrow();
7220        match (&state.target, &state.handler) {
7221            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
7222            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
7223        }
7224    }
7225
7226    /// Call `handler[name]`, or answer `None` when the trap is absent.
7227    ///
7228    /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
7229    /// and only a value that is neither is `IsCallable`-checked and refused. Treating
7230    /// `null` as "present but not callable" made every `{ get: null }` proxy throw
7231    /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
7232    /// one per trap plus the `target-is-proxy` variants.
7233    ///
7234    /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
7235    /// this cannot simply be "any non-callable means no trap".
7236    fn proxy_trap(
7237        &mut self,
7238        handler: &Value,
7239        name: &str,
7240        args: Vec<Value>,
7241    ) -> JsResult<Option<Value>> {
7242        let Value::Object(table) = handler else {
7243            return Err(self.type_error("proxy handler is not an object"));
7244        };
7245        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
7246        match trap {
7247            Value::Undefined | Value::Null => Ok(None),
7248            Value::Object(function) if function.is_callable() => {
7249                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
7250                Ok(Some(answer))
7251            }
7252            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
7253        }
7254    }
7255
7256    /// Whether the target's own property `key` is one it refuses to lose.
7257    ///
7258    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
7259    /// its value behind the target's back.
7260    ///
7261    /// A **method**, not a free function, because §10.5.1's invariants say
7262    /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
7263    /// property table directly finds nothing (a proxy's table is empty by design), so every
7264    /// invariant check silently passed for a proxy target. That is what
7265    /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
7266    /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
7267    /// where an array's elements and its `length` — both fixed, both outside the table —
7268    /// are covered.
7269    fn fixed_property(
7270        &mut self,
7271        target: &Gc<JsObject>,
7272        key: &PropertyKey,
7273    ) -> JsResult<Option<Property>> {
7274        Ok(self
7275            .object_get_own_property(target, key)?
7276            .filter(|property| !property.configurable))
7277    }
7278
7279    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
7280    fn proxy_get(
7281        &mut self,
7282        object: &Gc<JsObject>,
7283        receiver: &Value,
7284        key: &PropertyKey,
7285    ) -> JsResult<Option<Value>> {
7286        let Some((target, handler)) = self.proxy_parts(object)? else {
7287            return Ok(None);
7288        };
7289        let key_value = self.key_value(key);
7290        let Some(result) = self.proxy_trap(
7291            &handler,
7292            "get",
7293            vec![Value::Object(target.clone()), key_value, receiver.clone()],
7294        )?
7295        else {
7296            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
7297            // inherited getter still sees the proxy.
7298            return Ok(Some(
7299                self.get_property_key_for(&target, Some(receiver), key)?
7300                    .unwrap_or(Value::Undefined),
7301            ));
7302        };
7303        if let Some(fixed) = self.fixed_property(&target, key)? {
7304            if fixed.is_accessor() {
7305                // A fixed accessor with no getter must read as `undefined`.
7306                let has_getter = fixed
7307                    .getter
7308                    .as_ref()
7309                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
7310                if !has_getter && !matches!(result, Value::Undefined) {
7311                    return Err(self.type_error(format!(
7312                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
7313                    )));
7314                }
7315            } else if !fixed.writable {
7316                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7317                if !fixed_value.same_value(&result) {
7318                    return Err(self.type_error(format!(
7319                        "proxy 'get' disagrees with the non-configurable property '{key}'"
7320                    )));
7321                }
7322            }
7323        }
7324        Ok(Some(result))
7325    }
7326
7327    /// `[[Set]]` on a proxy.
7328    ///
7329    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
7330    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
7331    /// read-only store has.
7332    fn proxy_set(
7333        &mut self,
7334        object: &Gc<JsObject>,
7335        key: &PropertyKey,
7336        value: Value,
7337        receiver: &Value,
7338    ) -> JsResult<Option<bool>> {
7339        let Some((target, handler)) = self.proxy_parts(object)? else {
7340            return Ok(None);
7341        };
7342        let key_value = self.key_value(key);
7343        let Some(result) = self.proxy_trap(
7344            &handler,
7345            "set",
7346            vec![
7347                Value::Object(target.clone()),
7348                key_value,
7349                value.clone(),
7350                receiver.clone(),
7351            ],
7352        )?
7353        else {
7354            // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
7355            // given — not the target. `OrdinarySet` step 3 is
7356            // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
7357            // object whose prototype is a typed array has to reach the proxy's own
7358            // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
7359            // calls and expects exactly one. Storing on the target instead put the value
7360            // in the target and never consulted the trap.
7361            let accepted = self.ordinary_set_with_receiver(
7362                &target,
7363                receiver,
7364                key,
7365                value,
7366                DeleteFailure::Ignore,
7367            )?;
7368            return Ok(Some(accepted));
7369        };
7370        if !result.to_boolean() {
7371            return Ok(Some(false));
7372        }
7373        if let Some(fixed) = self.fixed_property(&target, key)? {
7374            if fixed.is_accessor() {
7375                let has_setter = fixed
7376                    .setter
7377                    .as_ref()
7378                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
7379                if !has_setter {
7380                    return Err(self.type_error(format!(
7381                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
7382                    )));
7383                }
7384            } else if !fixed.writable {
7385                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7386                if !fixed_value.same_value(&value) {
7387                    return Err(self.type_error(format!(
7388                        "proxy 'set' changed the non-configurable property '{key}'"
7389                    )));
7390                }
7391            }
7392        }
7393        // A new property cannot appear on a target that refuses new properties.
7394        if self.object_get_own_property(&target, key)?.is_none()
7395            && !self.object_is_extensible(&target)?
7396        {
7397            return Err(self.type_error(format!(
7398                "proxy 'set' added '{key}' to a non-extensible target"
7399            )));
7400        }
7401        Ok(Some(true))
7402    }
7403
7404    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
7405    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7406        let Some((target, handler)) = self.proxy_parts(object)? else {
7407            return Ok(None);
7408        };
7409        let key_value = self.key_value(key);
7410        let Some(result) = self.proxy_trap(
7411            &handler,
7412            "has",
7413            vec![Value::Object(target.clone()), key_value],
7414        )?
7415        else {
7416            return Ok(Some(self.has_own_or_inherited(&target, key)?));
7417        };
7418        if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7419            return Err(self.type_error(format!(
7420                "proxy 'has' denied the non-configurable property '{key}'"
7421            )));
7422        }
7423        // A non-extensible target cannot grow, so every own property it *has* is fixed.
7424        if !result.to_boolean()
7425            && !self.object_is_extensible(&target)?
7426            && self.object_get_own_property(&target, key)?.is_some()
7427        {
7428            return Err(self.type_error(format!(
7429                "proxy 'has' denied the own property '{key}' of a non-extensible target"
7430            )));
7431        }
7432        Ok(Some(result.to_boolean()))
7433    }
7434
7435    /// `[[Delete]]` on a proxy.
7436    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7437        let Some((target, handler)) = self.proxy_parts(object)? else {
7438            return Ok(None);
7439        };
7440        let key_value = self.key_value(key);
7441        let Some(result) = self.proxy_trap(
7442            &handler,
7443            "deleteProperty",
7444            vec![Value::Object(target.clone()), key_value],
7445        )?
7446        else {
7447            return Ok(Some(self.delete_property_key(&target, key)?));
7448        };
7449        if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7450            return Err(self.type_error(format!(
7451                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
7452            )));
7453        }
7454        if result.to_boolean()
7455            && !self.object_is_extensible(&target)?
7456            && self.object_get_own_property(&target, key)?.is_some()
7457        {
7458            return Err(self.type_error(format!(
7459                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
7460            )));
7461        }
7462        Ok(Some(result.to_boolean()))
7463    }
7464
7465    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
7466    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
7467        let Some((target, handler)) = self.proxy_parts(object)? else {
7468            return Ok(None);
7469        };
7470        let Some(result) =
7471            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
7472        else {
7473            // No trap: the target's own keys, already in the order an object reports.
7474            return Ok(Some(self.object_own_property_keys(&target)?));
7475        };
7476        // `CreateListFromArrayLike` with the string-or-symbol restriction.
7477        let list = self.list_from_array_like(&result, true)?;
7478        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
7479        for value in list {
7480            let key = self.propkey(&value)?;
7481            if keys.contains(&key) {
7482                return Err(self.type_error(format!(
7483                    "proxy 'ownKeys' returned the duplicate key '{key}'"
7484                )));
7485            }
7486            keys.push(key);
7487        }
7488        // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
7489        // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
7490        // table is empty, which made every check below vacuous.
7491        let target_keys = self.object_own_property_keys(&target)?;
7492        let extensible = self.object_is_extensible(&target)?;
7493        for key in &target_keys {
7494            if keys.contains(key) {
7495                continue;
7496            }
7497            if self.fixed_property(&target, key)?.is_some() {
7498                return Err(self.type_error(format!(
7499                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
7500                )));
7501            }
7502            if !extensible {
7503                return Err(self.type_error(format!(
7504                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
7505                )));
7506            }
7507        }
7508        if !extensible {
7509            // §10.5.11 step 12: the lists must match one for one, in any order.
7510            if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
7511            {
7512                return Err(
7513                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
7514                );
7515            }
7516        }
7517        Ok(Some(keys))
7518    }
7519
7520    /// `[[GetOwnProperty]]` on a proxy.
7521    fn proxy_get_own_property(
7522        &mut self,
7523        object: &Gc<JsObject>,
7524        key: &PropertyKey,
7525    ) -> JsResult<Option<Option<Property>>> {
7526        let Some((target, handler)) = self.proxy_parts(object)? else {
7527            return Ok(None);
7528        };
7529        let key_value = self.key_value(key);
7530        let Some(result) = self.proxy_trap(
7531            &handler,
7532            "getOwnPropertyDescriptor",
7533            vec![Value::Object(target.clone()), key_value],
7534        )?
7535        else {
7536            // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
7537            // property table. Two things ride on that choice: a target that is itself a
7538            // proxy has to re-dispatch (its own table is empty, so reading it reported
7539            // `undefined` for every key, `Object.keys` then dropped them all), and an array's
7540            // indices and `length` live outside the table and need the ordinary synthesis.
7541            // `object_get_own_property` does both.
7542            return Ok(Some(self.object_get_own_property(&target, key)?));
7543        };
7544        // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
7545        // `ToPropertyDescriptor` runs, because that operation would box the primitive
7546        // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
7547        // empty descriptor instead of refusing.
7548        if !matches!(result, Value::Undefined | Value::Object(_)) {
7549            return Err(self.type_error(
7550                "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
7551            ));
7552        }
7553        let target_desc = self.object_get_own_property(&target, key)?;
7554        let extensible = self.object_is_extensible(&target)?;
7555        let Some(descriptor) = (match result {
7556            Value::Undefined => None,
7557            _ => Some(self.property_from_descriptor(&result)?),
7558        }) else {
7559            // Steps 12.a–12.d: reporting absent is allowed only when the target's own
7560            // descriptor is configurable *and* the target can still grow back.
7561            if let Some(target_desc) = &target_desc {
7562                if !target_desc.configurable {
7563                    return Err(self.type_error(format!(
7564                        "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
7565                    )));
7566                }
7567                if !extensible {
7568                    return Err(self.type_error(format!(
7569                        "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
7570                    )));
7571                }
7572            }
7573            return Ok(Some(None));
7574        };
7575        // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
7576        // which is a stronger requirement than "the target is not contradicting it" — the
7577        // four branches below are each one test262 case.
7578        if !descriptor.configurable {
7579            let Some(target_desc) = &target_desc else {
7580                return Err(self.type_error(format!(
7581                    "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
7582                )));
7583            };
7584            if target_desc.configurable {
7585                return Err(self.type_error(format!(
7586                    "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
7587                )));
7588            }
7589            let target_is_data = !target_desc.is_accessor();
7590            let result_is_data = !descriptor.is_accessor();
7591            if result_is_data && !target_is_data {
7592                return Err(self.type_error(format!(
7593                    "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7594                )));
7595            }
7596            if target_is_data && !target_desc.writable {
7597                if !result_is_data {
7598                    return Err(self.type_error(format!(
7599                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7600                    )));
7601                }
7602                if descriptor.writable {
7603                    return Err(self.type_error(format!(
7604                        "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7605                    )));
7606                }
7607                let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7608                let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
7609                if !fixed_value.same_value(&reported) {
7610                    return Err(self.type_error(format!(
7611                        "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
7612                    )));
7613                }
7614            }
7615            // Step 16.d: a reported *read-only* data property needs a real read-only data
7616            // property behind it. Missing this let a trap bolt a frozen property onto a
7617            // writable target intent (`resultdesc-is-not-configurable-not-writable-
7618            // targetdesc-is-writable`).
7619            if result_is_data && !descriptor.writable {
7620                if !target_is_data {
7621                    return Err(self.type_error(format!(
7622                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7623                    )));
7624                }
7625                if target_desc.writable {
7626                    return Err(self.type_error(format!(
7627                        "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
7628                    )));
7629                }
7630            }
7631            if descriptor.is_accessor() {
7632                // Step 16.e: a getter the target does not have may not be invented, and
7633                // vice versa.
7634                let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7635                    (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7636                    (Some(a), Some(b)) => a.same_value(b),
7637                    _ => false,
7638                };
7639                if !same(&target_desc.getter, &descriptor.getter)
7640                    || !same(&target_desc.setter, &descriptor.setter)
7641                {
7642                    return Err(self.type_error(format!(
7643                        "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7644                    )));
7645                }
7646            }
7647        }
7648        // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
7649        // where the target's own is locked. Without it a handler could advertise
7650        // `{value: 1, configurable: true}` for a non-configurable property, and a caller
7651        // that believed it would try to redefine something it cannot.
7652        if descriptor.configurable
7653            && let Some(target_desc) = &target_desc
7654            && !target_desc.configurable
7655        {
7656            return Err(self.type_error(format!(
7657                "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
7658            )));
7659        }
7660        // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
7661        // through the trap either, however well-formed the descriptor is. This is the
7662        // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
7663        // the frozen target does not own.
7664        if !extensible {
7665            let Some(target_desc) = &target_desc else {
7666                return Err(self.type_error(format!(
7667                    "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
7668                )));
7669            };
7670            if target_desc.is_accessor() == descriptor.is_accessor() {
7671                let target_is_data = !target_desc.is_accessor();
7672                let result_is_data = !descriptor.is_accessor();
7673                if target_is_data && !target_desc.writable && descriptor.writable {
7674                    return Err(self.type_error(format!(
7675                        "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7676                    )));
7677                }
7678                if !result_is_data && !target_is_data {
7679                    let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7680                        (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7681                        (Some(a), Some(b)) => a.same_value(b),
7682                        _ => false,
7683                    };
7684                    if !same(&target_desc.getter, &descriptor.getter)
7685                        || !same(&target_desc.setter, &descriptor.setter)
7686                    {
7687                        return Err(self.type_error(format!(
7688                            "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7689                        )));
7690                    }
7691                }
7692            }
7693        }
7694        Ok(Some(Some(descriptor)))
7695    }
7696
7697    /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
7698    ///
7699    /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
7700    /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
7701    /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
7702    /// for a data property. `Property` cannot express "this field is absent", so the whole
7703    /// property path is skipped and the descriptor is assembled here field by field.
7704    ///
7705    /// `current` is the property the trap reported, used only to tell a data property from
7706    /// an accessor.
7707    pub fn proxy_seal_property(
7708        &mut self,
7709        object: &Gc<JsObject>,
7710        key: &PropertyKey,
7711        frozen: bool,
7712        current: &Property,
7713    ) -> JsResult<bool> {
7714        let Some((_target, handler)) = self.proxy_parts(object)? else {
7715            return Err(self.type_error("not a proxy"));
7716        };
7717        let descriptor = self.new_object(None);
7718        descriptor.define_data("configurable", Value::Bool(false));
7719        if frozen && !current.is_accessor() {
7720            descriptor.define_data("writable", Value::Bool(false));
7721        }
7722        let key_value = self.key_value(key);
7723        let target = object
7724            .proxy_state()
7725            .and_then(|state| state.borrow().target.clone());
7726        let Some(target) = target else {
7727            return Err(self.type_error("cannot use a proxy that has been revoked"));
7728        };
7729        let Some(result) = self.proxy_trap(
7730            &handler,
7731            "defineProperty",
7732            vec![Value::Object(target), key_value, Value::Object(descriptor)],
7733        )?
7734        else {
7735            // No trap means the definition belongs to the target; `false` is its answer.
7736            return Ok(false);
7737        };
7738        Ok(result.to_boolean())
7739    }
7740
7741    /// `[[DefineOwnProperty]]` on a proxy.
7742    fn proxy_define_property(
7743        &mut self,
7744        object: &Gc<JsObject>,
7745        key: &PropertyKey,
7746        property: Property,
7747    ) -> JsResult<Option<bool>> {
7748        let Some((target, handler)) = self.proxy_parts(object)? else {
7749            return Ok(None);
7750        };
7751        let key_value = self.key_value(key);
7752        let descriptor = self.descriptor_from_property(&property);
7753        let Some(result) = self.proxy_trap(
7754            &handler,
7755            "defineProperty",
7756            vec![Value::Object(target.clone()), key_value, descriptor],
7757        )?
7758        else {
7759            // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7760            // going" answer and `object_define_own_property` turns it into exactly that
7761            // forwarding — see the note there. (Reading it as "not a proxy" would define
7762            // the property on the proxy object itself, whose table is empty and which no
7763            // read ever consults.)
7764            return Ok(None);
7765        };
7766        if !result.to_boolean() {
7767            return Ok(Some(false));
7768        }
7769        // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7770        // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7771        // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7772        // and treating them alike made four cases pass a descriptor the target contradicts.
7773        let target_desc = self.object_get_own_property(&target, key)?;
7774        let extensible = self.object_is_extensible(&target)?;
7775        let named = property
7776            .descriptor_fields
7777            .unwrap_or(crate::object::DescriptorFields {
7778                value: false,
7779                writable: false,
7780                enumerable: false,
7781                configurable: false,
7782                get: false,
7783                set: false,
7784            });
7785        if named.configurable && !property.configurable {
7786            let Some(target_desc) = &target_desc else {
7787                return Err(self.type_error(format!(
7788                    "proxy 'defineProperty' invented the non-configurable '{key}'"
7789                )));
7790            };
7791            if target_desc.configurable {
7792                return Err(self.type_error(format!(
7793                    "proxy 'defineProperty' made '{key}' non-configurable"
7794                )));
7795            }
7796        }
7797        // Step 11's other half: reporting that a property was made *configurable* needs a
7798        // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7799        // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7800        // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7801        // target`).
7802        if named.configurable
7803            && property.configurable
7804            && let Some(target_desc) = &target_desc
7805            && !target_desc.configurable
7806        {
7807            return Err(
7808                self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7809            );
7810        }
7811        // Step 12: a property cannot be reported *made writable* when the target's copy is
7812        // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7813        // the trap is allowed to claim a definition it did not perform, as long as the
7814        // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7815        // legal, and refusing it broke the commonest way to seed a proxy).
7816        if named.writable
7817            && property.writable
7818            && let Some(target_desc) = &target_desc
7819            && !target_desc.writable
7820        {
7821            return Err(self.type_error(format!(
7822                "proxy 'defineProperty' made the read-only '{key}' writable"
7823            )));
7824        }
7825        // Step 13: making a property read-only needs an existing read-only property.
7826        if named.writable
7827            && !property.writable
7828            && let Some(target_desc) = &target_desc
7829            && !target_desc.is_accessor()
7830            && target_desc.writable
7831        {
7832            return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7833        }
7834        // Step 14: a non-writable, non-configurable property's value is fixed.
7835        if named.value
7836            && let Some(target_desc) = &target_desc
7837            && !target_desc.is_accessor()
7838            && !target_desc.writable
7839            && !target_desc.configurable
7840        {
7841            let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7842            let reported = property.value.clone().unwrap_or(Value::Undefined);
7843            if !fixed_value.same_value(&reported) {
7844                return Err(self.type_error(format!(
7845                    "proxy 'defineProperty' changed the value of '{key}'"
7846                )));
7847            }
7848        }
7849        // Step 15: a non-extensible target cannot grow.
7850        if target_desc.is_none() && !extensible {
7851            return Err(self.type_error(format!(
7852                "proxy 'defineProperty' added '{key}' to a non-extensible target"
7853            )));
7854        }
7855        Ok(Some(true))
7856    }
7857
7858    /// `[[GetPrototypeOf]]` on a proxy.
7859    fn proxy_get_prototype_of(
7860        &mut self,
7861        object: &Gc<JsObject>,
7862    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7863        let Some((target, handler)) = self.proxy_parts(object)? else {
7864            return Ok(None);
7865        };
7866        let Some(result) = self.proxy_trap(
7867            &handler,
7868            "getPrototypeOf",
7869            vec![Value::Object(target.clone())],
7870        )?
7871        else {
7872            // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7873            // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7874            // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7875            // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7876            // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7877            return Ok(Some(self.object_prototype_of(&target)?));
7878        };
7879        let proto = match &result {
7880            Value::Null => None,
7881            Value::Object(proto) => Some(proto.clone()),
7882            _ => {
7883                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7884            }
7885        };
7886        if !self.object_is_extensible(&target)? {
7887            let actual = self.object_prototype_of(&target)?;
7888            if !same_proto(proto.as_ref(), actual.as_ref()) {
7889                return Err(self.type_error(
7890                    "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7891                ));
7892            }
7893        }
7894        Ok(Some(proto))
7895    }
7896
7897    /// `[[SetPrototypeOf]]` on a proxy.
7898    fn proxy_set_prototype_of(
7899        &mut self,
7900        object: &Gc<JsObject>,
7901        proto: Option<Gc<JsObject>>,
7902    ) -> JsResult<Option<bool>> {
7903        let Some((target, handler)) = self.proxy_parts(object)? else {
7904            return Ok(None);
7905        };
7906        let proto_value = match &proto {
7907            Some(proto) => Value::Object(proto.clone()),
7908            None => Value::Null,
7909        };
7910        let Some(result) = self.proxy_trap(
7911            &handler,
7912            "setPrototypeOf",
7913            vec![Value::Object(target.clone()), proto_value],
7914        )?
7915        else {
7916            // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7917            // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7918            // its stored prototype overwritten behind its back.
7919            return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7920        };
7921        if result.to_boolean()
7922            && !self.object_is_extensible(&target)?
7923            && !same_proto(
7924                Some(&proto).and_then(|p| p.clone()).as_ref(),
7925                self.object_prototype_of(&target)?.as_ref(),
7926            )
7927        {
7928            return Err(self.type_error(
7929                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7930            ));
7931        }
7932        Ok(Some(result.to_boolean()))
7933    }
7934
7935    /// `[[IsExtensible]]` on a proxy.
7936    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7937        let Some((target, handler)) = self.proxy_parts(object)? else {
7938            return Ok(None);
7939        };
7940        let Some(result) = self.proxy_trap(
7941            &handler,
7942            "isExtensible",
7943            vec![Value::Object(target.clone())],
7944        )?
7945        else {
7946            return Ok(Some(self.object_is_extensible(&target)?));
7947        };
7948        // The answer is not the proxy's to invent: it must agree with the target, or a
7949        // script could learn `false` while the target keeps accepting new properties.
7950        if result.to_boolean() != self.object_is_extensible(&target)? {
7951            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7952        }
7953        Ok(Some(result.to_boolean()))
7954    }
7955
7956    /// `[[PreventExtensions]]` on a proxy.
7957    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7958        let Some((target, handler)) = self.proxy_parts(object)? else {
7959            return Ok(None);
7960        };
7961        let Some(result) = self.proxy_trap(
7962            &handler,
7963            "preventExtensions",
7964            vec![Value::Object(target.clone())],
7965        )?
7966        else {
7967            // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7968            // its answer can be `false`.
7969            return Ok(Some(self.object_prevent_extensions(&target)?));
7970        };
7971        if result.to_boolean() && self.object_is_extensible(&target)? {
7972            return Err(self.type_error(
7973                "proxy 'preventExtensions' reported success but the target is still extensible",
7974            ));
7975        }
7976        Ok(Some(result.to_boolean()))
7977    }
7978
7979    /// `[[Call]]` on a proxy, through the `apply` trap.
7980    fn proxy_apply(
7981        &mut self,
7982        object: &Gc<JsObject>,
7983        this: Value,
7984        args: Vec<Value>,
7985    ) -> JsResult<Option<Value>> {
7986        let Some((target, handler)) = self.proxy_parts(object)? else {
7987            return Ok(None);
7988        };
7989        // The trap gets the arguments as one array, which is the shape the spec passes
7990        // and the shape `apply` traps are written against (`args[0]` is the first one).
7991        let arguments = self.new_array(args.clone());
7992        let this_for_trap = this.clone();
7993        let Some(result) = self.proxy_trap(
7994            &handler,
7995            "apply",
7996            vec![
7997                Value::Object(target.clone()),
7998                this_for_trap,
7999                Value::Object(arguments),
8000            ],
8001        )?
8002        else {
8003            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
8004        };
8005        Ok(Some(result))
8006    }
8007
8008    /// `[[Construct]]` on a proxy, through the `construct` trap.
8009    fn proxy_construct(
8010        &mut self,
8011        object: &Gc<JsObject>,
8012        args: Vec<Value>,
8013        new_target: &Value,
8014    ) -> JsResult<Option<Value>> {
8015        let Some((target, handler)) = self.proxy_parts(object)? else {
8016            return Ok(None);
8017        };
8018        if !target.is_callable() {
8019            return Err(self.type_error("proxy target is not a constructor"));
8020        }
8021        let arguments = self.new_array(args.clone());
8022        let Some(result) = self.proxy_trap(
8023            &handler,
8024            "construct",
8025            vec![
8026                Value::Object(target.clone()),
8027                Value::Object(arguments),
8028                new_target.clone(),
8029            ],
8030        )?
8031        else {
8032            return Ok(Some(self.construct(
8033                Value::Object(target),
8034                new_target.clone(),
8035                args,
8036            )?));
8037        };
8038        if !matches!(result, Value::Object(_)) {
8039            return Err(self.type_error("proxy 'construct' must return an object"));
8040        }
8041        Ok(Some(result))
8042    }
8043
8044    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
8045    pub(crate) fn has_own_or_inherited(
8046        &mut self,
8047        object: &Gc<JsObject>,
8048        key: &PropertyKey,
8049    ) -> JsResult<bool> {
8050        // The object itself first: it may be a proxy, and then the answer is its trap's.
8051        if let Some(answer) = self.proxy_has(object, key)? {
8052            return Ok(answer);
8053        }
8054        // An integer-indexed exotic object answers a canonical numeric index from
8055        // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
8056        // prototype chain. That is observable twice: a view the buffer has been resized
8057        // away from has no indices, so `2 in view` is `false` even when
8058        // `Object.getPrototypeOf(view)[2]` exists (what
8059        // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
8060        // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
8061        // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
8062        // goes through here, which is why the same rule is repeated in `has_property_key`
8063        // rather than living only there.
8064        if object.typed_array_parts().is_some()
8065            && let Some(numeric) = canonical_numeric_index(key)
8066        {
8067            return Ok(typed_array_index_is_valid(object, numeric));
8068        }
8069        // §10.4.6.4 `[[HasProperty]]` asks for the exports list, so a deferred namespace
8070        // evaluates its module here — before the own-key test, because the list is what
8071        // decides the answer. Symbol-like keys are exempt, as everywhere else.
8072        if object.module_namespace_marker() && !Self::is_symbol_like_namespace_key(object, key) {
8073            self.trigger_deferred_namespace(object)?;
8074        }
8075        // A host class answers `in` for its own keys, which may live nowhere in a property
8076        // table — `"x" in point` is true because the class says so, not because a property
8077        // exists.
8078        if let Some(exotic) = object.exotic()
8079            && let Some(answer) = exotic.has_property(self, object, key)?
8080        {
8081            return Ok(answer);
8082        }
8083        // `has_own` rather than `own_property_key`: an array's elements and its derived
8084        // `length` are invisible to the property table, and `Array.prototype` is an array.
8085        // A host class's `get_own_property` counts too, because the reference's
8086        // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
8087        // lives — a class with only `get_own_property` answers `in` through it.
8088        if self.exotic_has_own(object, key)? {
8089            return Ok(true);
8090        }
8091        // A hole is *not* the end of the search: the chain may still have the key, which
8092        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
8093        for ancestor in object.chain() {
8094            // A namespace further up the chain is still asked for its exports list, so a
8095            // deferred one evaluates here — `Object.create(ns); key in obj` is the case.
8096            self.trigger_deferred_namespace_for_key(&ancestor, key)?;
8097            // A proxy further up the chain answers for itself.
8098            if let Some(answer) = self.proxy_has(&ancestor, key)? {
8099                return Ok(answer);
8100            }
8101            // Same for a host class: a prototype may be one, and `in` reaches it.
8102            if let Some(exotic) = ancestor.exotic()
8103                && let Some(answer) = exotic.has_property(self, &ancestor, key)?
8104            {
8105                return Ok(answer);
8106            }
8107            if self.exotic_has_own(&ancestor, key)? {
8108                return Ok(true);
8109            }
8110        }
8111        Ok(false)
8112    }
8113
8114    /// Whether `object` reports `key` as an own property, its class's `get_own_property`
8115    /// trap included.
8116    ///
8117    /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
8118    /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
8119    fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
8120        if let Some(exotic) = object.exotic()
8121            && let Some(answer) = exotic.get_own_property(self, object, key)?
8122        {
8123            return Ok(answer.is_some());
8124        }
8125        Ok(has_own(object, key))
8126    }
8127
8128    /// `CreateListFromArrayLike`, optionally restricted to property keys.
8129    ///
8130    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
8131    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
8132    /// `TypeError` instead of a property named `"1.5"`.
8133    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
8134        let object = self.object_from(value)?;
8135        let length = self
8136            .get_property(&object, "length")?
8137            .map(|value| value.to_number())
8138            .unwrap_or(0.0);
8139        if !length.is_finite() || length < 0.0 {
8140            return Err(self.type_error("invalid array-like length"));
8141        }
8142        let length = length as usize;
8143        let mut items = Vec::with_capacity(length.min(1024));
8144        for index in 0..length {
8145            let item = self
8146                .get_property(&object, &index.to_string())?
8147                .unwrap_or(Value::Undefined);
8148            if keys_only && matches!(&item, Value::Symbol(_)) {
8149                items.push(item);
8150                continue;
8151            }
8152            if keys_only && !matches!(&item, Value::String(_)) {
8153                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
8154            }
8155            items.push(item);
8156        }
8157        Ok(items)
8158    }
8159
8160    /// A `Property` from the descriptor object a trap returned.
8161    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
8162        let object = self.object_from(value)?;
8163        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
8164            interp.get_property(&object, name)
8165        };
8166        let getter = field(self, "get")?;
8167        let setter = field(self, "set")?;
8168        let accessor = getter.is_some() || setter.is_some();
8169        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
8170            Ok(interp
8171                .get_property(&object, name)?
8172                .is_some_and(|value| value.to_boolean()))
8173        };
8174        let enumerable = boolean(self, "enumerable")?;
8175        let configurable = boolean(self, "configurable")?;
8176        if accessor {
8177            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
8178                return Err(
8179                    self.type_error("a descriptor cannot be both a data property and an accessor")
8180                );
8181            }
8182            Ok(Property {
8183                getter: getter.or(Some(Value::Undefined)),
8184                setter: setter.or(Some(Value::Undefined)),
8185                enumerable,
8186                configurable,
8187                writable: false,
8188                value: None,
8189                descriptor_fields: None,
8190            })
8191        } else {
8192            Ok(Property {
8193                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
8194                writable: boolean(self, "writable")?,
8195                enumerable,
8196                configurable,
8197                getter: None,
8198                setter: None,
8199                descriptor_fields: None,
8200            })
8201        }
8202    }
8203
8204    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
8205    fn descriptor_from_property(&mut self, property: &Property) -> Value {
8206        let object = self.new_object(None);
8207        // A partial descriptor names only some fields, and the trap must see exactly those:
8208        // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
8209        // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
8210        // case, where every field is present.
8211        let fields = property.descriptor_fields;
8212        let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
8213            fields.is_none_or(|fields| field(&fields))
8214        };
8215        if property.is_accessor() {
8216            let getter = property.getter.clone().unwrap_or(Value::Undefined);
8217            let setter = property.setter.clone().unwrap_or(Value::Undefined);
8218            object.define_data("get", getter);
8219            object.define_data("set", setter);
8220        } else {
8221            if names(|fields| fields.value) {
8222                let value = property.value.clone().unwrap_or(Value::Undefined);
8223                object.define_data("value", value);
8224            }
8225            if names(|fields| fields.writable) {
8226                object.define_data("writable", Value::Bool(property.writable));
8227            }
8228        }
8229        if names(|fields| fields.enumerable) {
8230            object.define_data("enumerable", Value::Bool(property.enumerable));
8231        }
8232        if names(|fields| fields.configurable) {
8233            object.define_data("configurable", Value::Bool(property.configurable));
8234        }
8235        Value::Object(object)
8236    }
8237
8238    // -- calling ------------------------------------------------------------
8239
8240    /// Call `callee` with `this` and `args`.
8241    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
8242        let Value::Object(function) = &callee else {
8243            // `typeof x === "function"` is not enough to make `x()` legal: only a
8244            // callable object is. `null` and `undefined` need no special wording
8245            // here — their `ToString` already reads the way the reference's does.
8246            let what = format!("{} is not a function", callee.to_js_string());
8247            return Err(Signal::Throw(self.make_error("TypeError", &what)));
8248        };
8249        // A proxy of a function is called through its `apply` trap. It has no
8250        // `ObjectKind::Function` of its own, so this has to come before the dispatch
8251        // below, and a proxy of a non-function has nothing to forward to.
8252        if function.proxy_state().is_some() {
8253            return match self.proxy_apply(function, this, args)? {
8254                Some(result) => Ok(result),
8255                None => Err(Signal::Throw(
8256                    self.make_error("TypeError", "proxy target is not callable"),
8257                )),
8258            };
8259        }
8260        let callable = function.with(|data| match &data.kind {
8261            ObjectKind::Function(callable) => match callable {
8262                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
8263                // The `Rc` is cloned out so the borrow of this object's data is released
8264                // before the closure runs: the closure may touch the same object.
8265                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
8266                Callable::Bound {
8267                    target,
8268                    this,
8269                    args: leading,
8270                } => Some(NativeCall::Bound {
8271                    target: target.clone(),
8272                    this: this.clone(),
8273                    leading: leading.clone(),
8274                }),
8275                Callable::Bytecode { code, env } => {
8276                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
8277                }
8278                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
8279                Callable::PromiseResolve(promise) => {
8280                    Some(NativeCall::PromiseResolve(promise.clone()))
8281                }
8282                Callable::PromiseReject(promise) => {
8283                    Some(NativeCall::PromiseReject(promise.clone()))
8284                }
8285                Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
8286                    state: state.clone(),
8287                }),
8288                Callable::ThenShim {
8289                    handler,
8290                    resolve,
8291                    reject,
8292                    fulfilled,
8293                } => Some(NativeCall::ThenShim {
8294                    handler: handler.clone(),
8295                    resolve: resolve.clone(),
8296                    reject: reject.clone(),
8297                    fulfilled: *fulfilled,
8298                }),
8299                Callable::AwaitResume {
8300                    coroutine,
8301                    promise,
8302                    kind,
8303                } => Some(NativeCall::AwaitResume {
8304                    coroutine: coroutine.clone(),
8305                    promise: promise.clone(),
8306                    kind: *kind,
8307                }),
8308                Callable::CombinatorSettle {
8309                    state,
8310                    index,
8311                    fulfilled,
8312                } => Some(NativeCall::CombinatorSettle {
8313                    state: state.clone(),
8314                    index: *index,
8315                    fulfilled: *fulfilled,
8316                }),
8317                Callable::FinallyShim {
8318                    callback,
8319                    fulfilled,
8320                    constructor,
8321                } => Some(NativeCall::FinallyShim {
8322                    callback: callback.clone(),
8323                    fulfilled: *fulfilled,
8324                    constructor: constructor.clone(),
8325                }),
8326                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
8327                Callable::CompletedReturn {
8328                    generator,
8329                    promise,
8330                    rejected,
8331                } => Some(NativeCall::CompletedReturn {
8332                    generator: generator.clone(),
8333                    promise: promise.clone(),
8334                    rejected: *rejected,
8335                }),
8336                Callable::YieldResult {
8337                    generator,
8338                    promise,
8339                    done,
8340                } => Some(NativeCall::YieldResult {
8341                    generator: generator.clone(),
8342                    promise: promise.clone(),
8343                    done: *done,
8344                }),
8345                Callable::DisposeStep {
8346                    remaining,
8347                    promise,
8348                    error,
8349                    rejected,
8350                    awaited,
8351                    needs_await,
8352                } => Some(NativeCall::DisposeStep {
8353                    remaining: remaining.clone(),
8354                    promise: promise.clone(),
8355                    error: error.clone(),
8356                    rejected: *rejected,
8357                    awaited: *awaited,
8358                    needs_await: *needs_await,
8359                }),
8360                Callable::GeneratorResume {
8361                    generator,
8362                    promise,
8363                    kind,
8364                } => Some(NativeCall::GeneratorResume {
8365                    generator: generator.clone(),
8366                    promise: promise.clone(),
8367                    kind: *kind,
8368                }),
8369                Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
8370                Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
8371                Callable::SettlePromise {
8372                    promise,
8373                    value,
8374                    rejected,
8375                } => Some(NativeCall::SettlePromise {
8376                    promise: promise.clone(),
8377                    value: value.clone(),
8378                    rejected: *rejected,
8379                }),
8380            },
8381            _ => None,
8382        });
8383        match callable {
8384            Some(NativeCall::Host(func)) => {
8385                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
8386                // function by name rather than stopping at the caller.
8387                let frame_less = function
8388                    .own_property("_frame_less")
8389                    .and_then(|property| property.value)
8390                    .is_some_and(|value| value.to_boolean());
8391                let outer = if frame_less {
8392                    None
8393                } else {
8394                    self.native_frames
8395                        .push((function.clone(), self.frames.len()));
8396                    Some(self.current_native.replace(function.clone()))
8397                };
8398                // Same frame bookkeeping as a `Native`, plus `new.target`: a host
8399                // constructor reads it through `current_new_target` because it is handed
8400                // `undefined` for `this`. Taking the parked value here is what stops a
8401                // *plain* call made from inside a constructor body from seeing the
8402                // enclosing `new.target`.
8403                let parked = self.pending_new_target.take();
8404                let result = {
8405                    let outer_new_target = std::mem::replace(
8406                        &mut self.active_new_target,
8407                        parked.unwrap_or(Value::Undefined),
8408                    );
8409                    let result = {
8410                        let mut body = func.borrow_mut();
8411                        body(self, this, &args)
8412                    };
8413                    self.active_new_target = outer_new_target;
8414                    result
8415                };
8416                if !frame_less {
8417                    self.native_frames.pop();
8418                    self.current_native = outer.flatten();
8419                }
8420                result
8421            }
8422            Some(NativeCall::Native(func)) => {
8423                // A function marked `_frame_less` is one the reference implements
8424                // without a call frame — `eval` is the only one so far.
8425                let frame_less = function
8426                    .own_property("_frame_less")
8427                    .and_then(|property| property.value)
8428                    .is_some_and(|value| value.to_boolean());
8429                let outer = if frame_less {
8430                    None
8431                } else {
8432                    self.native_frames
8433                        .push((function.clone(), self.frames.len()));
8434                    Some(self.current_native.replace(function.clone()))
8435                };
8436                let parked = self.pending_new_target.take();
8437                let outer_new_target = std::mem::replace(
8438                    &mut self.active_new_target,
8439                    parked.unwrap_or(Value::Undefined),
8440                );
8441                let result = func(self, this, &args);
8442                self.active_new_target = outer_new_target;
8443                if !frame_less {
8444                    self.native_frames.pop();
8445                    self.current_native = outer.flatten();
8446                }
8447                result
8448            }
8449            Some(NativeCall::Revoker(slots)) => {
8450                // Idempotent: revoking twice answers `undefined` again rather than
8451                // complaining, which is what the spec says and what a `finally` block
8452                // relies on.
8453                let mut state = slots.borrow_mut();
8454                state.target = None;
8455                state.handler = None;
8456                Ok(Value::Undefined)
8457            }
8458            Some(NativeCall::PromiseResolve(promise)) => {
8459                // §27.2.1.3.2 step 4: `[[AlreadyResolved]]` is checked **before** anything
8460                // else, so a resolve after a reject does nothing *and* a resolve after a
8461                // resolve-with-thenable does nothing — the promise is still `Pending` then,
8462                // because the adoption is a queued job.
8463                let value = args.first().cloned().unwrap_or(Value::Undefined);
8464                if !self.claim_resolution(&promise) {
8465                    return Ok(Value::Undefined);
8466                }
8467                // §27.2.1.3.2 steps 7–8: a self-resolution is **rejected, not thrown** —
8468                // the resolve function performs `RejectPromise` and returns `undefined`.
8469                // (`ResolvePromise` itself throws as well, so the engine's own callers see
8470                // it; only this wrapper swallows it.)
8471                let _ = self.resolve_promise_with(&promise, value);
8472                Ok(Value::Undefined)
8473            }
8474            Some(NativeCall::PromiseReject(promise)) => {
8475                let reason = args.first().cloned().unwrap_or(Value::Undefined);
8476                // §27.2.1.3.1 step 3: same one-shot record as `resolve`.
8477                if !self.claim_resolution(&promise) {
8478                    return Ok(Value::Undefined);
8479                }
8480                self.reject_promise(&promise, reason);
8481                Ok(Value::Undefined)
8482            }
8483            Some(NativeCall::ThenShim {
8484                handler,
8485                resolve,
8486                reject,
8487                fulfilled,
8488            }) => {
8489                // `PerformPromiseThen` with a capability: run the handler, then settle
8490                // through the capability's own pair. A throw from the handler is the
8491                // rejection, and a throw from the capability's `resolve` is not caught —
8492                // exactly the spec's `?`.
8493                let value = args.first().cloned().unwrap_or(Value::Undefined);
8494                match handler {
8495                    Some(handler) => {
8496                        match self.call_value(handler, Value::Undefined, vec![value]) {
8497                            Ok(result) => {
8498                                self.call_value(resolve, Value::Undefined, vec![result])?;
8499                            }
8500                            Err(Signal::Throw(reason)) => {
8501                                self.call_value(reject, Value::Undefined, vec![reason])?;
8502                            }
8503                            Err(signal) => return Err(signal),
8504                        }
8505                    }
8506                    None => {
8507                        let handler = if fulfilled { resolve } else { reject };
8508                        self.call_value(handler, Value::Undefined, vec![value])?;
8509                    }
8510                }
8511                Ok(Value::Undefined)
8512            }
8513            Some(NativeCall::CapabilityExecutor { state }) => {
8514                // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
8515                // slot holds a value yet. The test is on the *values*, not on a call count —
8516                // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
8517                // called-twice`'s first case does exactly that), while a second call after a
8518                // real pair is the `TypeError`.
8519                let defined = |name: &str| {
8520                    state
8521                        .own_property(name)
8522                        .and_then(|property| property.value)
8523                        .is_some_and(|value| !matches!(value, Value::Undefined))
8524                };
8525                if defined("resolve") || defined("reject") {
8526                    return Err(self.type_error("promise capability executor called twice"));
8527                }
8528                let resolve = args.first().cloned().unwrap_or(Value::Undefined);
8529                let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
8530                state.define_data("resolve", resolve);
8531                state.define_data("reject", reject);
8532                Ok(Value::Undefined)
8533            }
8534            Some(NativeCall::CombinatorSettle {
8535                state,
8536                index,
8537                fulfilled,
8538            }) => {
8539                let value = args.first().cloned().unwrap_or(Value::Undefined);
8540                self.settle_combinator(&state, index, fulfilled, value)?;
8541                Ok(Value::Undefined)
8542            }
8543            Some(NativeCall::AwaitResume {
8544                coroutine,
8545                promise,
8546                kind,
8547            }) => {
8548                // Resume *inline*, in the reaction that delivered the value. Deferring it
8549                // by another job inserts a tick between every `await` and its
8550                // continuation, which reorders `await` against unrelated `then` chains —
8551                // `f().then(g)` then runs before `f`'s own next statement.
8552                self.drive_async(
8553                    &coroutine,
8554                    &promise,
8555                    kind,
8556                    args.first().cloned().unwrap_or(Value::Undefined),
8557                )
8558                .map(|()| Value::Undefined)
8559            }
8560            Some(NativeCall::ReturnValue(value)) => Ok(value),
8561            Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
8562            Some(NativeCall::FinallyShim {
8563                callback,
8564                fulfilled,
8565                constructor,
8566            }) => {
8567                // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
8568                // own value is discarded; what the caller sees is the *original* outcome,
8569                // delayed until `PromiseResolve(C, result)` has settled.
8570                //
8571                // Two details are observable and both have a test:
8572                //
8573                // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
8574                //   `PerformPromiseThen`. A callback that returns a thenable with its own
8575                //   `then` must have that `then` called
8576                //   (`resolved-observable-then-calls` counts it);
8577                // * only the **fulfil** handler is supplied. A returned promise that
8578                //   *rejects* rejects the whole `finally`, rather than having its failure
8579                //   swallowed and the original value passed through.
8580                let original = args.first().cloned().unwrap_or(Value::Undefined);
8581                let result = match &callback {
8582                    Some(callback) => {
8583                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
8584                    }
8585                    None => Value::Undefined,
8586                };
8587                // `PromiseResolve(C, result)`: a `result` that is already a promise of this
8588                // constructor is reused rather than rewrapped, which is what keeps
8589                // `mp1.finally(() => mp2)` from gaining a layer.
8590                let resolved = self.promise_resolve_for(&constructor, result)?;
8591                let thunk = if fulfilled {
8592                    Callable::ReturnValue(original)
8593                } else {
8594                    Callable::ThrowValue(original)
8595                };
8596                // `length: 0` and `name: ""`, and **not** a constructor — the three things
8597                // `resolved-observable-then-calls-argument` reads off the thunk while it has
8598                // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
8599                // function with no `length` at all.
8600                let thunk = self.builtin_function("", 0, thunk);
8601                let then = self.read_field(&resolved, "then")?;
8602                if !matches!(&then, Value::Object(object) if object.is_callable()) {
8603                    return Err(self.type_error("then is not a function"));
8604                }
8605                self.call_value(then, resolved, vec![Value::Object(thunk)])
8606            }
8607            Some(NativeCall::DisposeStep {
8608                remaining,
8609                promise,
8610                error,
8611                rejected,
8612                awaited,
8613                needs_await,
8614            }) => {
8615                let error = if rejected {
8616                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
8617                    self.merge_dispose_error(reason, error)
8618                } else {
8619                    error
8620                };
8621                self.dispose_step(&remaining, &promise, error, awaited, needs_await)?;
8622                Ok(Value::Undefined)
8623            }
8624            Some(NativeCall::ModuleBinding(cell)) => {
8625                // §10.4.6.8 `[[Get]]` step 4: a binding that has not been initialised yet
8626                // throws rather than reading `undefined`. A namespace can be observed
8627                // before its module has finished evaluating — a cycle, or
8628                // `Object.freeze(ns)` in the importer — and every read of the still-dead
8629                // `let` must be a `ReferenceError`
8630                // (`module-code/namespace/internals/get-str-found-uninit` and seven
8631                // siblings).
8632                let value = cell.get();
8633                if matches!(value, Value::Uninitialized) {
8634                    return Err(Signal::Throw(
8635                        self.make_error("ReferenceError", "module binding is not initialized"),
8636                    ));
8637                }
8638                Ok(value)
8639            }
8640            Some(NativeCall::CompletedReturn {
8641                generator,
8642                promise,
8643                rejected,
8644            }) => {
8645                let value = args.first().cloned().unwrap_or(Value::Undefined);
8646                let outcome = if rejected {
8647                    AsyncOutcome::Error(value)
8648                } else {
8649                    AsyncOutcome::Value(self.iterator_result(value, true)?)
8650                };
8651                self.settle_async_request(&generator, &promise, outcome)?;
8652                Ok(Value::Undefined)
8653            }
8654            Some(NativeCall::YieldResult {
8655                generator,
8656                promise,
8657                done,
8658            }) => {
8659                let value = args.first().cloned().unwrap_or(Value::Undefined);
8660                let result = self.iterator_result(value, done)?;
8661                self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
8662                Ok(Value::Undefined)
8663            }
8664            Some(NativeCall::GeneratorResume {
8665                generator,
8666                promise,
8667                kind,
8668            }) => {
8669                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
8670                // tick and reorders the generator against other chains.
8671                self.step_async_generator(
8672                    &generator,
8673                    &promise,
8674                    kind,
8675                    args.first().cloned().unwrap_or(Value::Undefined),
8676                )
8677                .map(|()| Value::Undefined)
8678            }
8679            Some(NativeCall::SettlePromise {
8680                promise,
8681                value,
8682                rejected,
8683            }) => {
8684                if rejected {
8685                    self.reject_promise(&promise, value);
8686                } else {
8687                    self.fulfill_promise(&promise, value);
8688                }
8689                Ok(Value::Undefined)
8690            }
8691            Some(NativeCall::Bound {
8692                target,
8693                this: bound_this,
8694                leading,
8695            }) => {
8696                let mut all = leading;
8697                all.extend(args);
8698                self.call_value(target, bound_this, all)
8699            }
8700            Some(NativeCall::Bytecode(code, env)) => {
8701                if code.code.kind.is_generator() {
8702                    return self.new_generator(callee, this, args);
8703                }
8704                if code.code.kind.is_async() {
8705                    // Same coroutine machinery as a generator; the difference is only in
8706                    // what the completion does — see `new_async_function`.
8707                    return self.new_async_function(callee, this, args);
8708                }
8709                self.execute(code, env, this, args, callee)
8710            }
8711            None => Err(Signal::Throw(
8712                self.make_error("TypeError", "not a function"),
8713            )),
8714        }
8715    }
8716
8717    /// Give a freshly built function its own `prototype` object.
8718    ///
8719    /// Every function that can be used with `new` carries one, and its
8720    /// `constructor` points back at the function — a reference cycle, which is
8721    /// exactly what the collector's cycle pass exists to reclaim.
8722    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
8723        self.install_function_prototype_with(function, None);
8724    }
8725
8726    /// [`Interp::install_function_prototype`] with an explicit parent for the new
8727    /// `prototype` object.
8728    ///
8729    /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
8730    /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
8731    /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
8732    /// `None` means `%Object.prototype%`.
8733    fn install_function_prototype_with(
8734        &mut self,
8735        function: &Gc<JsObject>,
8736        parent: Option<Gc<JsObject>>,
8737    ) {
8738        let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
8739        let prototype = self.new_object(Some(parent));
8740        let constructor = Value::Object(function.clone());
8741        prototype.define(
8742            "constructor",
8743            Property::with_attributes(constructor, true, false),
8744        );
8745        let value = Value::Object(prototype);
8746        function.define("prototype", Property::prototype_of(value, true));
8747    }
8748
8749    /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
8750    /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
8751    /// [`Interp::install_function_prototype`] — **no `constructor` property**.
8752    ///
8753    /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
8754    /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
8755    /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
8756    /// is `[]` there.
8757    fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
8758        let prototype = self.new_object(Some(parent));
8759        let value = Value::Object(prototype);
8760        function.define("prototype", Property::prototype_of(value, true));
8761    }
8762
8763    /// The `[[Prototype]]` a newly created generator object gets:
8764    /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
8765    ///
8766    /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
8767    /// function's `prototype` is writable, so a script can replace it with anything, and
8768    /// only an *object* is consulted.
8769    fn generator_instance_proto(
8770        &mut self,
8771        function: &Gc<JsObject>,
8772        default: Gc<JsObject>,
8773    ) -> JsResult<Gc<JsObject>> {
8774        match self.get_property(function, "prototype")? {
8775            Some(Value::Object(prototype)) => Ok(prototype),
8776            _ => Ok(default),
8777        }
8778    }
8779
8780    /// A getter or setter that reads or writes the reference cell behind a mapped
8781    /// `arguments` index.
8782    ///
8783    /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
8784    /// count — which is what the collector treats as "a reference from outside the
8785    /// heap". The closure therefore keeps the cell alive for exactly as long as the
8786    /// accessor is reachable, which is the same lifetime the arguments object has.
8787    ///
8788    /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8789    /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8790    /// parameter value and the arguments object reaches the closure, never the other
8791    /// way round. Nothing the collector has to see is hidden.
8792    fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8793        let name = if is_setter { "set" } else { "get" };
8794        let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8795            if is_setter {
8796                cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8797                Ok(Value::Undefined)
8798            } else {
8799                Ok(cell.get())
8800            }
8801        };
8802        self.new_host_function(name, 1, Box::new(func))
8803    }
8804
8805    /// The object `special_object` builds.
8806    ///
8807    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8808    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8809    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8810    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8811    /// write through `arguments` does not reach the parameter.
8812    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8813        match magic {
8814            0 | 1 => {
8815                let args = self.frame().passed().to_vec();
8816                let proto = self.realm.object_proto.clone();
8817                let object = self.new_object(Some(proto));
8818                // The marker `Object.prototype.toString` needs: an arguments object is an
8819                // ordinary object apart from reporting `[object Arguments]`, and that has
8820                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8821                // show up ahead of them in a key listing anyway — it is non-enumerable.
8822                self.internal_set(&object, "_class", self.string("Arguments"));
8823                // `length` is writable and configurable but neither enumerable nor a
8824                // plain data property: `Object.keys(arguments)` lists the indices only,
8825                // which is how `{...arguments}` copies them without the length.
8826                object.define(
8827                    "length",
8828                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
8829                );
8830                // `magic == 1` is sloppy mode, where each index is *mapped* to the
8831                // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8832                // change `a`, and assigning `a` has to change `arguments[0]`.
8833                //
8834                // The shared storage is the parameter's reference cell. The compiler
8835                // gives every parameter of such a function one (see
8836                // `provide_body_arguments`), and the cell outlives the frame, so this
8837                // keeps working after the arguments object escapes.
8838                //
8839                // The index becomes an accessor rather than a data property. A mapped
8840                // index reports as a plain writable/enumerable data property through
8841                // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8842                // the getter/setter pair is only the plumbing underneath.
8843                let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8844                    let frame = self.frame();
8845                    frame
8846                        .code
8847                        .arg_cell
8848                        .iter()
8849                        .map(|cell| {
8850                            (*cell >= 0)
8851                                .then(|| frame.cells.get(*cell as usize).cloned())
8852                                .flatten()
8853                        })
8854                        .collect()
8855                } else {
8856                    Vec::new()
8857                };
8858                // Tell the object which indices are mapped, so
8859                // `Object.getOwnPropertyDescriptor` can report them as the data
8860                // properties the spec describes instead of the accessors that
8861                // implement the aliasing.
8862                if magic == 1 {
8863                    let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8864                    for cell in &mapped_cells {
8865                        table.push(cell.clone());
8866                    }
8867                    object.set_mapped_arguments(table);
8868                }
8869                for (index, value) in args.into_iter().enumerate() {
8870                    match mapped_cells.get(index).cloned().flatten() {
8871                        Some(cell) => {
8872                            let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8873                            let setter = self.new_mapped_arguments_accessor(cell, true);
8874                            object.define(
8875                                &index.to_string(),
8876                                Property::accessor_with(
8877                                    Some(Value::Object(getter)),
8878                                    Some(Value::Object(setter)),
8879                                    true,
8880                                ),
8881                            );
8882                        }
8883                        None => object.define_data(&index.to_string(), value),
8884                    }
8885                }
8886                // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8887                // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8888                // non-enumerable and non-configurable. It is not a nicety — it is the only
8889                // documented way to reach `%ThrowTypeError%`:
8890                //
8891                //     Object.getOwnPropertyDescriptor(function(){"use strict";
8892                //         return arguments;}(), "callee").get
8893                //
8894                // and the whole `ThrowTypeError/` directory is written against that
8895                // expression. Without it 13 cases failed with `cannot read property 'get'
8896                // of undefined`, which reads like a test harness bug rather than a missing
8897                // accessor.
8898                //
8899                // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8900                // writable data property holding the function being called, and
8901                // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8902                // `hasOwnProperty("callee")` hold there.
8903                if magic == 1 {
8904                    let callee = self.frame().callee.clone();
8905                    // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8906                    object.define("callee", Property::with_attributes(callee, true, false));
8907                } else if let Some(thrower) = self.realm.throw_type_error.clone()
8908                    && object.own_property("callee").is_none()
8909                {
8910                    object.define(
8911                        "callee",
8912                        Property {
8913                            getter: Some(Value::Object(thrower.clone())),
8914                            setter: Some(Value::Object(thrower)),
8915                            enumerable: false,
8916                            configurable: false,
8917                            ..Property::default()
8918                        },
8919                    );
8920                }
8921                // An arguments object is iterable: `[...arguments]` and
8922                // `for (const a of arguments)` both work, through the *array* iterator
8923                // because the object is array-like. Without this the whole spread form
8924                // reported "not iterable".
8925                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8926                let values = self
8927                    .realm
8928                    .array_proto
8929                    .own_property("values")
8930                    .and_then(|property| property.value);
8931                if let Some(values) = values {
8932                    object.define_key(
8933                        &iterator_key,
8934                        Property::with_attributes(values, true, false),
8935                    );
8936                }
8937                Ok(Value::Object(object))
8938            }
8939            // `this.active_func`: the constructor `super()` resolves against.
8940            //
8941            // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8942            // own, so it inherits this from the function it was written in along with `this`
8943            // — and that is a lexical relationship, not a stack one: an arrow that escaped
8944            // the constructor and is called back later (`iter.return = () => super()`) has
8945            // the constructor nowhere on the stack. The compiler therefore reads it out of
8946            // a closure variable of the enclosing function, exactly as the reference does
8947            // with its `this_active_func` local.
8948            2 => Ok(self
8949                .current_callee()
8950                .map_or(Value::Undefined, Value::Object)),
8951            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8952            // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8953            // its own either, so the lookup walks out to the nearest non-arrow frame for
8954            // the same reason as `this.active_func` above — without that, `super()` inside
8955            // an arrow passed `undefined` as the new target and the parent constructor was
8956            // then rejected for being invoked without `new`.
8957            3 => Ok(self
8958                .eval_new_target
8959                .clone()
8960                .unwrap_or_else(|| self.frame().new_target.clone())),
8961            // `[[HomeObject]]` of the function being run: what `super` is relative to.
8962            // An arrow has none of its own, so the lookup walks out to the enclosing
8963            // method — which is why `super` works inside an arrow inside a method.
8964            4 => Ok(self
8965                .frames
8966                .iter()
8967                .rev()
8968                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8969                .map_or(Value::Undefined, Value::Object)),
8970            // `import.meta`: the innermost module body's meta object. Outside a module
8971            // the compiler never emits this, so an empty fallback is unreachable rather
8972            // than permissive.
8973            6 => {
8974                let name = self.module_stack.last().cloned();
8975                let meta = name
8976                    .and_then(|name| self.modules.get(&name).cloned())
8977                    .and_then(|module| module.with(|r| r.import_meta.clone()));
8978                Ok(meta.map_or(Value::Undefined, Value::Object))
8979            }
8980            other => Err(Signal::Throw(self.make_error(
8981                "InternalError",
8982                &format!("special_object {other} is not implemented yet"),
8983            ))),
8984        }
8985    }
8986
8987    /// `[[HomeObject]]` of the innermost function that has one, if any.
8988    ///
8989    /// An arrow has none, so the search walks out to the enclosing method — the same
8990    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8991    /// inside a method.
8992    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8993        self.frames
8994            .iter()
8995            .rev()
8996            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8997    }
8998
8999    /// The dispose method a `using` declaration should snapshot, or an error.
9000    ///
9001    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
9002    /// is what makes a resource that only knows the synchronous protocol usable in both
9003    /// forms.
9004    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
9005        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
9006        if value.is_nullish() {
9007            return Ok(Value::Undefined);
9008        }
9009        let Some(object) = value.as_object() else {
9010            return Err(self.type_error("not an object"));
9011        };
9012        let mut method = if await_form {
9013            let found = self.get_property_key(
9014                object,
9015                &self.realm.well_known_key(WellKnown::AsyncDisposable),
9016            )?;
9017            match found {
9018                Some(found) if !found.is_nullish() => Some(found),
9019                _ => self
9020                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
9021            }
9022        } else {
9023            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
9024        };
9025        let Some(found) = method.take() else {
9026            return Err(self.type_error("value is not disposable"));
9027        };
9028        if found.is_nullish() {
9029            return Err(self.type_error("value is not disposable"));
9030        }
9031        let callable = found.as_object().is_some_and(|object| object.is_callable());
9032        if !callable {
9033            return Err(self.type_error("dispose method is not a function"));
9034        }
9035        Ok(found)
9036    }
9037
9038    /// Call one resource's disposer, folding a failure into `error_state`.
9039    ///
9040    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
9041    /// because a captured `using` binding lives in its reference cell and the local slot is
9042    /// stale — a closure over the resource is legal and must not change what is disposed.
9043    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
9044        let value = self.get_loc(slot);
9045        let method = self.get_loc(slot + 1);
9046        // A resource that was never initialised — its declaration threw — or that is
9047        // `null`/`undefined` has nothing to dispose.
9048        if value.is_nullish() || matches!(value, Value::Uninitialized) {
9049            return Ok(error_state);
9050        }
9051        if matches!(method, Value::Undefined | Value::Uninitialized) {
9052            return Ok(error_state);
9053        }
9054        match self.call_value(method, value, Vec::new()) {
9055            Ok(_) => Ok(error_state),
9056            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
9057            Err(other) => Err(other),
9058        }
9059    }
9060
9061    /// Combine a disposal failure with whatever was already going wrong.
9062    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
9063        if matches!(error_state, Value::Uninitialized) {
9064            return new_error;
9065        }
9066        self.new_suppressed_error(new_error, error_state)
9067    }
9068
9069    /// A `SuppressedError` instance built straight from its prototype.
9070    ///
9071    /// Not through the constructor: a script that rewrites
9072    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
9073    /// error wrapping.
9074    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
9075        let proto = self
9076            .realm
9077            .suppressed_error_proto
9078            .clone()
9079            .unwrap_or_else(|| self.realm.error_proto.clone());
9080        let object = self.new_object(Some(proto));
9081        object.define("error", Property::with_attributes(error, true, true));
9082        object.define(
9083            "suppressed",
9084            Property::with_attributes(suppressed, true, true),
9085        );
9086        object.define(
9087            "message",
9088            Property::with_attributes(self.string("SuppressedError"), true, true),
9089        );
9090        self.internal_set(&object, "_class", self.string("Error"));
9091        self.add_stack(&object);
9092        Value::Object(object)
9093    }
9094
9095    /// Call `callee`, or push its frame and let the main loop run it.
9096    ///
9097    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
9098    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
9099    /// continues, so `function f(){ return f() }` costs heap and stops at
9100    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
9101    /// is entered directly, and natives do not re-enter JavaScript in this
9102    /// milestone.
9103    ///
9104    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
9105    /// because the returning frame will.
9106    /// The elements of an array-like value, as a call argument list.
9107    ///
9108    /// `apply` accepts any array-like, not only a real array: the reference reads
9109    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
9110    /// `ToIndex(value)`: `ToIntegerOrInfinity` and then the `2^53 - 1` bound.
9111    ///
9112    /// Used by the paths that take a *length* from script data — the typed-array
9113    /// constructor's array-like argument, `Array.from`. `ToIntegerOrInfinity` runs
9114    /// `ToNumber`, so a Symbol is a `TypeError`; a value past `2^53 - 1` is a
9115    /// `RangeError` rather than a silently clamped count.
9116    pub fn to_index(&mut self, value: &Value) -> JsResult<usize> {
9117        let number = self.to_js_number(value)?;
9118        if number.is_nan() {
9119            return Ok(0);
9120        }
9121        let number = number.trunc();
9122        if number < 0.0 || number > 9_007_199_254_740_991.0 {
9123            return Err(self.range_error("invalid length"));
9124        }
9125        Ok(number as usize)
9126    }
9127
9128    /// `CreateListFromArrayLike(value)`: the elements of an array-like, for `apply` and the
9129    /// other callers that take an argument list from script data.
9130    ///
9131    /// The length is `ToLength`, which *clamps* rather than refusing — the typed-array
9132    /// constructor and `Array.from` need `ToIndex` instead (see
9133    /// [`Interp::to_index`]), which is why they do not go through here.
9134    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
9135        let Some(object) = value.as_object().cloned() else {
9136            if value.is_nullish() {
9137                // `f.apply(this, null)` passes no arguments at all.
9138                return Ok(Vec::new());
9139            }
9140            return Err(self.type_error("createListFromArrayLike called on non-object"));
9141        };
9142        let length = match self.get_property(&object, "length")? {
9143            Some(length) => length.to_number(),
9144            None => 0.0,
9145        };
9146        if !length.is_finite() || length <= 0.0 {
9147            return Ok(Vec::new());
9148        }
9149        let length = (length as usize).min(1_000_000);
9150        let mut args = Vec::with_capacity(length);
9151        for index in 0..length {
9152            let element = self.get_property(&object, &index.to_string())?;
9153            args.push(element.unwrap_or(Value::Undefined));
9154        }
9155        Ok(args)
9156    }
9157
9158    /// Turn a call to a generator function into a generator object.
9159    ///
9160    /// The frame is built exactly as an ordinary call would build it, then detached and
9161    /// stored in the generator before any body instruction runs — which is what makes
9162    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
9163    /// is `initial_yield`, the first instruction of every suspending body.
9164    pub fn new_generator(
9165        &mut self,
9166        function: Value,
9167        this: Value,
9168        args: Vec<Value>,
9169    ) -> JsResult<Value> {
9170        let Some(object) = function.as_object().cloned() else {
9171            return Err(self.type_error("not a generator function"));
9172        };
9173        let Some((code, env)) = bytecode_of(&object) else {
9174            return Err(self.type_error("not a generator function"));
9175        };
9176        let is_async = code.code.kind.is_async();
9177        self.push_frame(code, env, this, args, function)?;
9178        let frame = self.frames.pop().expect("push_frame just pushed it");
9179        // A fresh generator is *suspended at start*: the body has not run, so a
9180        // `return`/`throw` on it finishes without executing anything.
9181        let mut state = GeneratorState {
9182            frame: Some(frame),
9183            phase: GeneratorPhase::SuspendedStart,
9184            parked_on_await: false,
9185            parked_on_yield_star: false,
9186            requests: std::collections::VecDeque::new(),
9187            async_busy: false,
9188            is_async,
9189        };
9190        // Run to the first suspension. For a generator that is `initial_yield`, so no
9191        // body code runs; for a malformed body it would be the first `yield`.
9192        // An `async function*` answers an async generator: same coroutine, but its
9193        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
9194        let default_proto = if is_async {
9195            self.realm
9196                .async_generator_proto
9197                .clone()
9198                .unwrap_or_else(|| self.realm.generator_proto.clone())
9199        } else {
9200            self.realm.generator_proto.clone()
9201        };
9202        // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
9203        // `prototype` object when it is one, the intrinsic otherwise. Every generator having
9204        // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
9205        // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
9206        let proto = self.generator_instance_proto(&object, default_proto)?;
9207        let generator = self.new_object(Some(proto));
9208        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
9209            Ok(_) => {}
9210            Err(error) => return Err(error),
9211        }
9212        generator.with_mut(|data| {
9213            data.kind = ObjectKind::Generator(Box::new(state));
9214        });
9215        Ok(Value::Object(generator))
9216    }
9217
9218    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
9219    ///
9220    /// Returns the `{value, done}` object itself rather than the pair, because a
9221    /// `yield*` suspension already has one — the inner iterator's own result — and the
9222    /// protocol says to hand that straight through rather than nest it.
9223    /// Advance a generator and report *why* it parked.
9224    ///
9225    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
9226    /// "hand this value to the caller" — but an async generator does: an `await` has to
9227    /// settle before it can answer, while a `yield` is the answer.
9228    fn resume_generator_detailed(
9229        &mut self,
9230        generator: &Gc<JsObject>,
9231        kind: ResumeKind,
9232        value: Value,
9233    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9234        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
9235            ObjectKind::Generator(state) => {
9236                let is_async = state.is_async;
9237                Some(std::mem::replace(
9238                    state.as_mut(),
9239                    GeneratorState {
9240                        frame: None,
9241                        phase: GeneratorPhase::Executing,
9242                        parked_on_await: false,
9243                        parked_on_yield_star: false,
9244                        requests: std::collections::VecDeque::new(),
9245                        // **Busy while the body runs**, so a `next()` called *from inside*
9246                        // the body queues instead of being served. §27.6.3.7
9247                        // `AsyncGeneratorResumeNext` returns immediately for the state
9248                        // "executing", and the request is served once the body suspends;
9249                        // with `false` here the re-entrant call found an empty frame and
9250                        // rejected (`request-queue-order-state-executing`).
9251                        async_busy: is_async,
9252                        is_async,
9253                    },
9254                ))
9255            }
9256            _ => None,
9257        }) else {
9258            return Err(self.type_error("not a generator"));
9259        };
9260        let result = self.step_generator(&mut state, kind, value);
9261        // Requests queued *while* the body ran live on the placeholder, because the real
9262        // state is out of the object for the duration. They have to be folded back in
9263        // before the placeholder is overwritten, or the promise they carry never settles.
9264        let queued = generator.with_mut(|data| match &mut data.kind {
9265            ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
9266            _ => std::collections::VecDeque::new(),
9267        });
9268        state.requests.extend(queued);
9269        generator.with_mut(|data| {
9270            data.kind = ObjectKind::Generator(Box::new(state));
9271        });
9272        result
9273    }
9274
9275    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
9276    ///
9277    /// Returns the `{value, done}` object itself rather than the pair, because a
9278    /// `yield*` suspension already has one — the inner iterator's own result — and the
9279    /// protocol says to hand that straight through rather than nest it.
9280    pub fn resume_generator(
9281        &mut self,
9282        generator: &Gc<JsObject>,
9283        kind: ResumeKind,
9284        value: Value,
9285    ) -> JsResult<Value> {
9286        let (value, done, ready, _reason) =
9287            self.resume_generator_detailed(generator, kind, value)?;
9288        if ready {
9289            return Ok(value);
9290        }
9291        self.iterator_result(value, done)
9292    }
9293
9294    /// `next`/`return`/`throw` on an async generator, which answer a promise.
9295    ///
9296    /// The body is the same coroutine a sync generator runs; what changes is that an
9297    /// `await` inside it has to settle before the method can answer, so the step is
9298    /// driven off the job queue rather than returning inline.
9299    pub fn resume_async_generator(
9300        &mut self,
9301        generator: &Gc<JsObject>,
9302        kind: ResumeKind,
9303        value: Value,
9304    ) -> JsResult<Value> {
9305        let promise = self.new_promise();
9306        // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
9307        // that order, and the second value must reach the *second* `yield`.
9308        let idle = generator.with_mut(|data| match &mut data.kind {
9309            ObjectKind::Generator(state) => {
9310                state.requests.push_back(AsyncRequest {
9311                    kind,
9312                    value,
9313                    promise: promise.clone(),
9314                });
9315                !state.async_busy
9316            }
9317            _ => false,
9318        });
9319        if idle {
9320            self.next_async_request(generator)?;
9321        }
9322        Ok(Value::Object(promise))
9323    }
9324
9325    /// Serve the front queued request, if the generator is free to run one.
9326    ///
9327    /// A finished generator answers from the queue without running anything:
9328    /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
9329    /// first, and `throw(e)` rejects.
9330    fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
9331        enum Front {
9332            Idle,
9333            Run(ResumeKind, Value, Gc<JsObject>),
9334            Finished(ResumeKind, Value, Gc<JsObject>),
9335        }
9336        let front = generator.with_mut(|data| match &mut data.kind {
9337            ObjectKind::Generator(state) => {
9338                let Some(request) = state.requests.front() else {
9339                    return Front::Idle;
9340                };
9341                // Busy means a request is still in flight — awaiting inside the body, not
9342                // finished. Serving another now would interleave two requests.
9343                if state.async_busy && state.phase != GeneratorPhase::Completed {
9344                    return Front::Idle;
9345                }
9346                let kind = request.kind;
9347                let value = request.value.clone();
9348                let promise = request.promise.clone();
9349                state.async_busy = true;
9350                if state.phase == GeneratorPhase::Completed {
9351                    Front::Finished(kind, value, promise)
9352                } else {
9353                    Front::Run(kind, value, promise)
9354                }
9355            }
9356            _ => Front::Idle,
9357        });
9358        match front {
9359            Front::Idle => Ok(()),
9360            Front::Run(kind, value, promise) => {
9361                self.step_async_generator(generator, &promise, kind, value)
9362            }
9363            Front::Finished(kind, value, promise) => match kind {
9364                ResumeKind::Throw => {
9365                    self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
9366                }
9367                ResumeKind::Next | ResumeKind::Start => {
9368                    let result = self.iterator_result(Value::Undefined, true)?;
9369                    self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
9370                }
9371                ResumeKind::Return => {
9372                    // `js_async_generator_completed_return`: the value is awaited before it
9373                    // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
9374                    // finished generator answers `1`, not a promise.
9375                    let resolved = match self.promise_resolve_intrinsic(value) {
9376                        Ok(resolved) => resolved,
9377                        Err(Signal::Throw(reason)) => {
9378                            return self.settle_async_request(
9379                                generator,
9380                                &promise,
9381                                AsyncOutcome::Error(reason),
9382                            );
9383                        }
9384                        Err(other) => return Err(other),
9385                    };
9386                    let done = JsObject::function(
9387                        self.heap,
9388                        Some(self.realm.function_proto.clone()),
9389                        Callable::CompletedReturn {
9390                            generator: generator.clone(),
9391                            promise: promise.clone(),
9392                            rejected: false,
9393                        },
9394                    );
9395                    let failed = JsObject::function(
9396                        self.heap,
9397                        Some(self.realm.function_proto.clone()),
9398                        Callable::CompletedReturn {
9399                            generator: generator.clone(),
9400                            promise: promise.clone(),
9401                            rejected: true,
9402                        },
9403                    );
9404                    let Value::Object(resolved) = resolved else {
9405                        return self.settle_async_request(
9406                            generator,
9407                            &promise,
9408                            AsyncOutcome::Error(Value::Undefined),
9409                        );
9410                    };
9411                    self.perform_then(
9412                        &resolved,
9413                        Some(Value::Object(done)),
9414                        Some(Value::Object(failed)),
9415                    )?;
9416                    Ok(())
9417                }
9418            },
9419        }
9420    }
9421
9422    /// Settle the front request and start the next one.
9423    ///
9424    /// Every path out of [`Interp::step_async_generator`] goes through here, so the
9425    /// "busy" flag and the queue cannot drift: a promise settled without releasing the
9426    /// generator would strand every later request.
9427    fn settle_async_request(
9428        &mut self,
9429        generator: &Gc<JsObject>,
9430        promise: &Gc<JsObject>,
9431        outcome: AsyncOutcome,
9432    ) -> JsResult<()> {
9433        let settled = generator.with_mut(|data| match &mut data.kind {
9434            ObjectKind::Generator(state) => {
9435                let front = state.requests.front();
9436                debug_assert!(
9437                    front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
9438                    "a request settled outside its turn"
9439                );
9440                state.requests.pop_front();
9441                state.async_busy = false;
9442                true
9443            }
9444            _ => false,
9445        });
9446        if settled {
9447            match outcome {
9448                AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
9449                AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
9450            }
9451        }
9452        self.next_async_request(generator)
9453    }
9454
9455    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
9456    ///
9457    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
9458    /// disposer runs **synchronously** — the reference starts it before returning, which
9459    /// a test can observe by logging after the call — and the rest follow once their
9460    /// predecessor settles.
9461    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
9462        let promise = self.new_promise();
9463        // §24.4.3.6 `DisposeResources` step 1: `needsAwait` is true as soon as the stack holds
9464        // any resource at all, because every `await using` resource has the async-dispose
9465        // hint — including the null/undefined ones that have nothing to call. If none of them
9466        // turned out to be awaitable, step 4 still performs one `Await(undefined)`, which is
9467        // why `stack.use(null); stack.disposeAsync()` settles one microtask later rather than
9468        // in the tick it was called from (`disposeAsync/explicit-await-for-null`).
9469        let needs_await = !resources.is_empty();
9470        let mut pairs = Vec::with_capacity(resources.len());
9471        for (value, method) in resources {
9472            let pair = self.new_array(vec![value, method]);
9473            pairs.push(Value::Object(pair));
9474        }
9475        let remaining = self.new_array(pairs);
9476        self.dispose_step(
9477            &remaining,
9478            &promise,
9479            Value::Uninitialized,
9480            false,
9481            needs_await,
9482        )?;
9483        Ok(Value::Object(promise))
9484    }
9485
9486    /// One link of the `disposeAsync` chain.
9487    ///
9488    /// Loops while the disposers finish synchronously, and parks on the first thenable it
9489    /// meets — pushing itself back in as the continuation, with the accumulated error
9490    /// carried along so a later failure can still be folded into the `SuppressedError`.
9491    fn dispose_step(
9492        &mut self,
9493        remaining: &Gc<JsObject>,
9494        promise: &Gc<JsObject>,
9495        mut error: Value,
9496        awaited: bool,
9497        needs_await: bool,
9498    ) -> JsResult<()> {
9499        loop {
9500            let length = remaining.array_length().unwrap_or(0);
9501            if length == 0 {
9502                // Step 4: `needsAwait` true and `hasAwaited` false means one `Await(undefined)`
9503                // still has to happen. Re-entering this same step past an already-fulfilled
9504                // promise is exactly one tick, and it keeps the folding of `error` in one place.
9505                if needs_await && !awaited {
9506                    let finished = self.new_array(Vec::new());
9507                    let thunk = JsObject::function(
9508                        self.heap,
9509                        Some(self.realm.function_proto.clone()),
9510                        Callable::DisposeStep {
9511                            remaining: finished.clone(),
9512                            promise: promise.clone(),
9513                            error,
9514                            rejected: false,
9515                            awaited: true,
9516                            needs_await: false,
9517                        },
9518                    );
9519                    let tick = self.promise_resolve_value(Value::Undefined)?;
9520                    if let Value::Object(tick) = tick {
9521                        self.perform_then(
9522                            &tick,
9523                            Some(Value::Object(thunk.clone())),
9524                            Some(Value::Object(thunk)),
9525                        )?;
9526                    }
9527                    return Ok(());
9528                }
9529                if matches!(error, Value::Uninitialized) {
9530                    self.fulfill_promise(promise, Value::Undefined);
9531                } else {
9532                    self.reject_promise(promise, error);
9533                }
9534                return Ok(());
9535            }
9536            let Some(Value::Object(pair)) = remaining
9537                .array_get(length - 1)
9538                .filter(|v| !matches!(v, Value::Hole))
9539            else {
9540                remaining.array_truncate(self.heap, length - 1);
9541                continue;
9542            };
9543            remaining.array_truncate(self.heap, length - 1);
9544            let value = pair.array_get(0).unwrap_or(Value::Undefined);
9545            let Some(Value::Object(method)) = pair.array_get(1) else {
9546                continue;
9547            };
9548            if !method.is_callable() {
9549                continue;
9550            }
9551            match self.call_value(Value::Object(method), value, Vec::new()) {
9552                Ok(result) => {
9553                    if !self.is_thenable(&result)? {
9554                        // Finished synchronously; the next disposer is the next iteration.
9555                        continue;
9556                    }
9557                    let awaited = match self.promise_resolve_value(result) {
9558                        Ok(awaited) => awaited,
9559                        Err(Signal::Throw(reason)) => {
9560                            self.reject_promise(promise, reason);
9561                            return Ok(());
9562                        }
9563                        Err(other) => return Err(other),
9564                    };
9565                    let Value::Object(awaited) = awaited else {
9566                        continue;
9567                    };
9568                    let ok = JsObject::function(
9569                        self.heap,
9570                        Some(self.realm.function_proto.clone()),
9571                        Callable::DisposeStep {
9572                            remaining: remaining.clone(),
9573                            promise: promise.clone(),
9574                            error: error.clone(),
9575                            rejected: false,
9576                            awaited: true,
9577                            needs_await,
9578                        },
9579                    );
9580                    let failed = JsObject::function(
9581                        self.heap,
9582                        Some(self.realm.function_proto.clone()),
9583                        Callable::DisposeStep {
9584                            remaining: remaining.clone(),
9585                            promise: promise.clone(),
9586                            error,
9587                            rejected: true,
9588                            awaited: true,
9589                            needs_await,
9590                        },
9591                    );
9592                    self.perform_then(
9593                        &awaited,
9594                        Some(Value::Object(ok)),
9595                        Some(Value::Object(failed)),
9596                    )?;
9597                    return Ok(());
9598                }
9599                Err(Signal::Throw(thrown)) => {
9600                    error = self.merge_dispose_error(thrown, error);
9601                }
9602                Err(other) => return Err(other),
9603            }
9604        }
9605    }
9606
9607    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
9608    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
9609        let Value::Object(object) = value else {
9610            return Ok(false);
9611        };
9612        Ok(matches!(
9613            self.get_property(object, "then")?,
9614            Some(Value::Object(then)) if then.is_callable()
9615        ))
9616    }
9617
9618    /// One step of an async generator, settling `promise` with an `{value, done}` result.
9619    fn step_async_generator(
9620        &mut self,
9621        generator: &Gc<JsObject>,
9622        promise: &Gc<JsObject>,
9623        kind: ResumeKind,
9624        value: Value,
9625    ) -> JsResult<()> {
9626        // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
9627        // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
9628        // is abrupt — a `constructor` getter that throws — the generator is resumed with a
9629        // *throw* completion instead, so the body's own `try { yield } catch` sees it:
9630        // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
9631        // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
9632        // out of the same read, one as a rejection and one as a rethrow.
9633        //
9634        // Narrow on purpose: only a value that is *already a promise* is inspected, so
9635        // nothing changes for `return 1` and the extra read is a plain data-property
9636        // lookup on the intrinsic case.
9637        if kind == ResumeKind::Return
9638            && let Value::Object(object) = &value
9639            && self.promise_state(object).is_some()
9640            && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
9641        {
9642            return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
9643        }
9644        let stepped = self.resume_generator_detailed(generator, kind, value);
9645        let (value, done, ready, reason) = match stepped {
9646            Ok(stepped) => stepped,
9647            Err(Signal::Throw(reason)) => {
9648                return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
9649            }
9650            Err(other) => return Err(other),
9651        };
9652        // Only an `await` has to wait before the method can answer.
9653        if !done && reason == Some(SuspendKind::Await) {
9654            let awaited = match self.promise_resolve_value(value) {
9655                Ok(awaited) => awaited,
9656                Err(Signal::Throw(reason)) => {
9657                    return self.settle_async_request(
9658                        generator,
9659                        promise,
9660                        AsyncOutcome::Error(reason),
9661                    );
9662                }
9663                Err(other) => return Err(other),
9664            };
9665            let Value::Object(awaited) = awaited else {
9666                return Ok(());
9667            };
9668            let resumed = JsObject::function(
9669                self.heap,
9670                Some(self.realm.function_proto.clone()),
9671                Callable::GeneratorResume {
9672                    generator: generator.clone(),
9673                    promise: promise.clone(),
9674                    kind: ResumeKind::Next,
9675                },
9676            );
9677            let raised = JsObject::function(
9678                self.heap,
9679                Some(self.realm.function_proto.clone()),
9680                Callable::GeneratorResume {
9681                    generator: generator.clone(),
9682                    promise: promise.clone(),
9683                    kind: ResumeKind::Throw,
9684                },
9685            );
9686            self.perform_then(
9687                &awaited,
9688                Some(Value::Object(resumed)),
9689                Some(Value::Object(raised)),
9690            )?;
9691            return Ok(());
9692        }
9693        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
9694        // completes it — both arrive as the settled value rather than as the promise
9695        // object. A plain value skips the round trip, which is also what keeps `yield 1`
9696        // from costing an extra tick.
9697        let awaits_value = self.is_thenable(&value)?;
9698        if awaits_value {
9699            // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
9700            // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
9701            // value that merely gets `yield`ed is awaited by the body's own `Await`, where
9702            // no `PromiseResolve` appears, so that path keeps the shortcut.
9703            let awaited = match if done {
9704                self.promise_resolve_intrinsic(value)
9705            } else {
9706                self.promise_resolve_value(value)
9707            } {
9708                Ok(awaited) => awaited,
9709                Err(Signal::Throw(reason)) => {
9710                    return self.settle_async_request(
9711                        generator,
9712                        promise,
9713                        AsyncOutcome::Error(reason),
9714                    );
9715                }
9716                Err(other) => return Err(other),
9717            };
9718            let Value::Object(awaited) = awaited else {
9719                return Ok(());
9720            };
9721            // A rejected yield throws *at the yield* inside the body, so the rejection
9722            // resumes the generator rather than the method's promise.
9723            let answer = JsObject::function(
9724                self.heap,
9725                Some(self.realm.function_proto.clone()),
9726                Callable::YieldResult {
9727                    generator: generator.clone(),
9728                    promise: promise.clone(),
9729                    done,
9730                },
9731            );
9732            let raise = JsObject::function(
9733                self.heap,
9734                Some(self.realm.function_proto.clone()),
9735                Callable::GeneratorResume {
9736                    generator: generator.clone(),
9737                    promise: promise.clone(),
9738                    kind: ResumeKind::Throw,
9739                },
9740            );
9741            self.perform_then(
9742                &awaited,
9743                Some(Value::Object(answer)),
9744                Some(Value::Object(raise)),
9745            )?;
9746            return Ok(());
9747        }
9748        let result = if ready {
9749            // `yield*` handed back the inner iterator's own result object.
9750            value
9751        } else {
9752            self.iterator_result(value, done)?
9753        };
9754        self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
9755    }
9756
9757    /// The `{value, done}` object an iterator method answers with.
9758    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
9759        let result = self.new_object(Some(self.realm.object_proto.clone()));
9760        result.define_data("value", value);
9761        result.define_data("done", Value::Bool(done));
9762        Ok(Value::Object(result))
9763    }
9764
9765    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
9766    fn step_generator(
9767        &mut self,
9768        state: &mut GeneratorState,
9769        kind: ResumeKind,
9770        value: Value,
9771    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9772        match state.phase {
9773            GeneratorPhase::Executing => {
9774                return Err(self.type_error("cannot invoke a running generator"));
9775            }
9776            GeneratorPhase::Completed => {
9777                // A finished generator answers every resumption without running.
9778                return Ok(match kind {
9779                    ResumeKind::Throw => return Err(Signal::Throw(value)),
9780                    ResumeKind::Return => (value, true, false, None),
9781                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
9782                });
9783            }
9784            GeneratorPhase::SuspendedStart => {
9785                if kind != ResumeKind::Next && kind != ResumeKind::Start {
9786                    // The body never started, so there is nothing to unwind or return
9787                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
9788                    state.frame = None;
9789                    state.phase = GeneratorPhase::Completed;
9790                    return Ok(match kind {
9791                        ResumeKind::Throw => return Err(Signal::Throw(value)),
9792                        _ => (value, true, false, None),
9793                    });
9794                }
9795            }
9796            GeneratorPhase::SuspendedYield => {}
9797        }
9798
9799        let Some(mut frame) = state.frame.take() else {
9800            return Ok((Value::Undefined, true, false, None));
9801        };
9802        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
9803        // number that says which method resumed it; the emitted `if_false` branches on
9804        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
9805        let mut raised = None;
9806        match kind {
9807            ResumeKind::Next | ResumeKind::Start => {
9808                if state.phase == GeneratorPhase::SuspendedYield {
9809                    frame.stack.push(value);
9810                    // An `await` resumes with its value alone; only a `yield` gets the
9811                    // magic number that says which of `next`/`return` resumed it.
9812                    if !state.parked_on_await {
9813                        frame.stack.push(Value::Int(RESUME_NEXT));
9814                    }
9815                }
9816            }
9817            ResumeKind::Return => {
9818                // A `return` on a not-yet-started generator is handled above, so this is
9819                // always a real resumption.
9820                frame.stack.push(value);
9821                frame.stack.push(Value::Int(RESUME_RETURN));
9822            }
9823            ResumeKind::Throw => {
9824                // At a `yield*` the exception is *data* for the delegation: the compiled
9825                // code resumes with the value and magic `2` and calls the inner iterator's
9826                // `throw`. Everywhere else it is raised at the suspension point, so the
9827                // body's own handler sees it.
9828                if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
9829                    frame.stack.push(value);
9830                    frame.stack.push(Value::Int(RESUME_THROW));
9831                } else {
9832                    raised = Some(value);
9833                }
9834            }
9835        }
9836        state.phase = GeneratorPhase::Executing;
9837
9838        let depth = self.frames.len();
9839        self.frames.push(frame);
9840        // A `throw` unwinds from where the frame parked, exactly as if the exception had
9841        // happened at the `yield`.
9842        if let Some(mut exception) = raised {
9843            if self.catch_here(&mut exception).is_none() {
9844                self.pop_frame();
9845                state.phase = GeneratorPhase::Completed;
9846                return Err(Signal::Throw(exception));
9847            }
9848        }
9849
9850        // Only the generator's *own* frame ends the generator. The body may call ordinary
9851        // functions, and those push frames of their own: a `Step::Return` from one of them
9852        // is a nested call finishing, not the generator completing. Miscounting that is
9853        // silent — the generator reports the callee's value as its own result and marks
9854        // itself done — so the depth comparison is load-bearing, not defensive.
9855        let own_frame = depth + 1;
9856        loop {
9857            match self.step() {
9858                Ok(Step::Continue) => {}
9859                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9860                    let mut frame = self.frames.pop().expect("a frame is live");
9861                    // `yield` left the value on the stack; `initial_yield` left nothing.
9862                    let yielded = if reason == SuspendKind::Initial {
9863                        Value::Undefined
9864                    } else {
9865                        frame.stack.pop().unwrap_or(Value::Undefined)
9866                    };
9867                    state.frame = Some(frame);
9868                    state.parked_on_await = reason == SuspendKind::Await;
9869                    state.parked_on_yield_star =
9870                        matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9871                    state.phase = if reason == SuspendKind::Initial {
9872                        GeneratorPhase::SuspendedStart
9873                    } else {
9874                        GeneratorPhase::SuspendedYield
9875                    };
9876                    // `yield*` hands the inner iterator's own result object straight
9877                    // back, so the caller sees one `{value, done}` rather than a nested
9878                    // one — which is why the third field says "already a result".
9879                    return Ok((
9880                        yielded,
9881                        false,
9882                        reason == SuspendKind::YieldStar,
9883                        Some(reason),
9884                    ));
9885                }
9886                Ok(Step::Suspend(_)) => {
9887                    // A `yield` in a frame other than the generator's would mean a
9888                    // generator body entered as an ordinary call, which
9889                    // `call_or_push` prevents.
9890                    self.unwind_to(depth);
9891                    state.phase = GeneratorPhase::Completed;
9892                    return Err(Signal::Throw(self.make_error(
9893                        "InternalError",
9894                        "a generator body ran as an ordinary call",
9895                    )));
9896                }
9897                Ok(Step::Return(value)) => {
9898                    self.pop_frame();
9899                    if self.frames.len() > depth {
9900                        // A nested call finished: hand the value back to its caller and
9901                        // keep running the generator body.
9902                        self.frames
9903                            .last_mut()
9904                            .expect("a caller is live")
9905                            .stack
9906                            .push(value);
9907                        continue;
9908                    }
9909                    state.phase = GeneratorPhase::Completed;
9910                    // The reference closes the generator's closure variables here; ours
9911                    // live in cells the frame owned, which the drop below releases.
9912                    return Ok((value, true, false, None));
9913                }
9914                Err(Signal::Throw(exception)) => {
9915                    // The frame that threw gets the first chance to catch, exactly as in
9916                    // the ordinary call loop; a frame above the generator's is popped and
9917                    // the exception carries on down.
9918                    let mut exception = exception;
9919                    loop {
9920                        if self.frames.len() <= depth {
9921                            // The generator's own frame is gone, so nothing here caught it.
9922                            state.phase = GeneratorPhase::Completed;
9923                            return Err(Signal::Throw(exception));
9924                        }
9925                        if self.catch_here(&mut exception).is_some() {
9926                            break;
9927                        }
9928                        self.pop_frame();
9929                    }
9930                }
9931                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9932            }
9933        }
9934    }
9935
9936    /// Pop frames until `depth` are left, keeping their buffers.
9937    fn unwind_to(&mut self, depth: usize) {
9938        while self.frames.len() > depth {
9939            self.pop_frame();
9940        }
9941    }
9942    fn call_or_push(
9943        &mut self,
9944        callee: Value,
9945        this: Value,
9946        args: Vec<Value>,
9947    ) -> JsResult<Option<Value>> {
9948        if let Value::Object(function) = &callee
9949            && let Some((code, env)) = bytecode_of(function)
9950        {
9951            // Calling a generator function does not run anything: it captures the
9952            // arguments in a frame and hands back the generator object.
9953            if code.code.kind.is_generator() {
9954                return self.new_generator(callee, this, args).map(Some);
9955            }
9956            // An async function answers a promise and runs its body as a coroutine, so it
9957            // takes the same path as a plain call into it.
9958            if code.code.kind.is_async() {
9959                return self.new_async_function(callee, this, args).map(Some);
9960            }
9961            self.push_frame(code, env, this, args, callee)?;
9962            return Ok(None);
9963        }
9964        self.call_value(callee, this, args).map(Some)
9965    }
9966
9967    /// `new callee(args)`.
9968    ///
9969    /// A constructor differs from a plain call in three ways: it gets a fresh object
9970    /// as `this` whose prototype is the constructor's `prototype` property, its
9971    /// return value is *replaced* by that object unless it returns an object itself,
9972    /// and a native constructor is expected to initialise the object it is given
9973    /// rather than build one.
9974    pub fn construct(
9975        &mut self,
9976        callee: Value,
9977        new_target: Value,
9978        args: Vec<Value>,
9979    ) -> JsResult<Value> {
9980        // `new` on a bound function constructs its *target*, prepending the arguments
9981        // the bind fixed and ignoring the bound `this` — a bound function is a
9982        // constructor only when its target is one, and `new` always makes a fresh
9983        // object of the target's prototype rather than reusing the bound receiver.
9984        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9985        // ran the body with `this === null` and threw on `this.x = a`.
9986        let mut callee = callee;
9987        let mut new_target = new_target;
9988        let mut args = args;
9989        loop {
9990            let Some(object) = callee.as_object().cloned() else {
9991                return Err(Signal::Throw(
9992                    self.make_error("TypeError", "not a constructor"),
9993                ));
9994            };
9995            // A proxy of a function constructs through its `construct` trap, and the
9996            // trap's answer is the result directly — no fresh object is made here.
9997            if object.proxy_state().is_some() {
9998                return match self.proxy_construct(&object, args, &new_target)? {
9999                    Some(result) => Ok(result),
10000                    None => Err(Signal::Throw(
10001                        self.make_error("TypeError", "proxy target is not a constructor"),
10002                    )),
10003                };
10004            }
10005            // A generator function has no `[[Construct]]`, and the reference names it in
10006            // the message: `new (function* G(){})()` reports "G is not a constructor".
10007            if object.with(|data| match &data.kind {
10008                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
10009                    code.code.kind.is_generator()
10010                }
10011                _ => false,
10012            }) {
10013                let name = object
10014                    .own_property("name")
10015                    .and_then(|property| property.value)
10016                    .map(|value| value.to_js_string())
10017                    .unwrap_or_default();
10018                return Err(Signal::Throw(
10019                    self.make_error("TypeError", &format!("{name} is not a constructor")),
10020                ));
10021            }
10022            let bound = object.with(|data| match &data.kind {
10023                ObjectKind::Function(Callable::Bound {
10024                    target,
10025                    args: leading,
10026                    ..
10027                }) => Some((target.clone(), leading.clone())),
10028                _ => None,
10029            });
10030            let Some((target, leading)) = bound else {
10031                // Not a bound function, so this object is the callee. §7.2.4
10032                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
10033                // refusals above cover only the built-ins the reference also refuses by
10034                // name. Everything else — a method, an arrow, an async function — has no
10035                // `[[Construct]]` either, and answering "yes" here made
10036                // `new (Array.prototype.map)` build an object instead of throwing.
10037                if !object.is_constructor() {
10038                    let name = object
10039                        .own_property("name")
10040                        .and_then(|property| property.value)
10041                        .map(|value| value.to_js_string())
10042                        .unwrap_or_default();
10043                    return Err(Signal::Throw(
10044                        self.make_error("TypeError", &format!("{name} is not a constructor")),
10045                    ));
10046                }
10047                break;
10048            };
10049            let mut all = leading;
10050            all.extend(args);
10051            args = all;
10052            // A bound function that is its own `new.target` stands in for its target:
10053            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
10054            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
10055            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
10056                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
10057                _ => false,
10058            };
10059            if same_wrapper {
10060                new_target = target.clone();
10061            }
10062            callee = target;
10063        }
10064        let Value::Object(function) = &callee else {
10065            unreachable!("the loop above only breaks on an object");
10066        };
10067        // The fresh object's prototype comes from `new.target`, not from the callee: a
10068        // derived constructor reaches here through `super()`, and the instance must be a
10069        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
10070        // an object inheriting `D.prototype` rather than `C.prototype`.
10071        let prototype_source = match new_target.as_object() {
10072            Some(target) => target.clone(),
10073            None => function.clone(),
10074        };
10075        // A native constructor builds its own instance, through `new_ctor_instance`, once it
10076        // has validated its arguments. Pre-building one here would read
10077        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
10078        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
10079        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
10080        let is_native = function.native_creates_own_instance();
10081        let this = if is_native {
10082            Value::Undefined
10083        } else {
10084            let prototype = self.get_property(&prototype_source, "prototype")?;
10085            let prototype = match prototype {
10086                Some(Value::Object(proto)) => Some(proto),
10087                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
10088                // object, the answer is the realm's *intrinsic* prototype for this
10089                // constructor, not `%Object.prototype%`.
10090                _ => {
10091                    // `GetPrototypeFromConstructor` step 4 is `GetFunctionRealm(constructor)`,
10092                    // and that is a `TypeError` for a revoked proxy. Without it, `new
10093                    // revokedProxy()` quietly produced an `%Object.prototype%` instance —
10094                    // `base-ctor-revoked-proxy` revokes the proxy from inside its own `get`
10095                    // trap, so it is already revoked when this fallback runs.
10096                    if prototype_source.proxy_state().is_some() {
10097                        self.proxy_parts(&prototype_source)?;
10098                    }
10099                    let fallback = self.get_property(function, "prototype")?;
10100                    match fallback {
10101                        Some(Value::Object(proto)) => Some(proto),
10102                        _ => Some(self.realm.object_proto.clone()),
10103                    }
10104                }
10105            };
10106            Value::Object(self.new_object(prototype))
10107        };
10108        // `new.target` inside the body is the constructor that was written, so a bound
10109        // function's target sees itself rather than the bound wrapper.
10110        //
10111        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
10112        // `?`, so assigning `None` after the call would be skipped and the failed
10113        // `new.target` would stay visible to every later native call. The symptom was a
10114        // native constructor refusing a plain call — `var s = Symbol(); new
10115        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
10116        // "FinalizationRegistry is not a constructor".
10117        let outer_new_target = self.pending_new_target.replace(new_target);
10118        let callee = callee.clone();
10119        let result = self.call_value(callee, this.clone(), args);
10120        self.pending_new_target = outer_new_target;
10121        let result = result?;
10122        // A constructor that returns an object overrides `this`; any other return value
10123        // (including `undefined`) is ignored — **except** in a derived constructor, where
10124        // §15.7.1 step 12 makes a non-object return a `TypeError`
10125        // (`Function/internals/Construct/derived-return-val`).
10126        let derived = function.with(|data| match &data.kind {
10127            ObjectKind::Function(Callable::Bytecode { code, .. }) => {
10128                code.code.is_derived_constructor
10129            }
10130            _ => false,
10131        });
10132        Ok(match result {
10133            Value::Object(_) => result,
10134            // A bare `return;` answers `undefined`, which is **legal** even in a derived
10135            // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
10136            Value::Undefined => this,
10137            _ if derived => {
10138                return Err(Signal::Throw(self.make_error(
10139                    "TypeError",
10140                    "derived constructor may only return an object or undefined",
10141                )));
10142            }
10143            _ => this,
10144        })
10145    }
10146
10147    /// `new.target` for the call currently being made.
10148    ///
10149    /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
10150    /// it as `this`), but a *host* constructor that builds its own instance is handed
10151    /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
10152    /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
10153    /// it here.
10154    ///
10155    /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
10156    /// receives for a plain call.
10157    pub fn current_new_target(&self) -> Value {
10158        self.active_new_target.clone()
10159    }
10160
10161    /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
10162    ///
10163    /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
10164    /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
10165    pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
10166        let constructor = self.realm.errors.get("AggregateError").cloned();
10167        let Some(constructor) = constructor else {
10168            return self.make_error("AggregateError", message);
10169        };
10170        let list = self.new_array(errors);
10171        match self.construct(
10172            Value::Object(constructor.clone()),
10173            Value::Object(constructor),
10174            vec![Value::Object(list), self.string(message)],
10175        ) {
10176            Ok(value) => value,
10177            // A user could have replaced `AggregateError` with something that throws; the
10178            // engine still owes the caller a rejection, so it falls back rather than
10179            // turning `Promise.any`'s rejection into a throw.
10180            Err(_) => self.make_error("AggregateError", message),
10181        }
10182    }
10183
10184    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
10185    ///
10186    /// The error classes themselves arrive with the builtins milestone; what
10187    /// matters here is that the thrown value stringifies the way a script printing
10188    /// the caught value expects.
10189    ///
10190    /// `name` and `message` become own properties, which is what makes `e.name` cheap and
10191    /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
10192    /// rely on when they print a caught value.
10193    pub fn make_error(&self, name: &str, message: &str) -> Value {
10194        let proto = self
10195            .realm
10196            .errors
10197            .get(name)
10198            .map(|constructor| self.prototype_of(constructor))
10199            .unwrap_or_else(|| self.realm.error_proto.clone());
10200        let error = self.new_object(Some(proto));
10201        // `name` and `message` are own properties of the instance, which is what
10202        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
10203        // `Error`.
10204        error.define(
10205            "name",
10206            Property::with_attributes(self.string(name), true, false),
10207        );
10208        error.define(
10209            "message",
10210            Property::with_attributes(self.string(message), true, false),
10211        );
10212        // The internal class, which is what tells a printer this is an error rather than a
10213        // plain object with `name` and `message` properties. The constructor path sets it
10214        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
10215        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
10216        // literally `"Error"` in both places — the *name* is read from `name`, which is why
10217        // a `RangeError` still prints as `RangeError`.
10218        self.internal_set(&error, "_class", self.string("Error"));
10219        // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
10220        // answered `false` from `Error.isError` while a constructed one answered `true`,
10221        // because only the constructor set the slot. The reference answers `true` for both
10222        // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
10223        // accessor gated on this slot the omission stopped being cosmetic: `print_error`
10224        // tests `typeof stack === "string"` to decide on a trailing newline, so every
10225        // engine-thrown error lost its blank line.
10226        self.internal_set(&error, "_error_data", Value::Bool(true));
10227        // The trace is captured where the error is *made*, which is where the reference
10228        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
10229        // way out, so a caught engine error already has its stack even if the handler
10230        // never rethrows it.
10231        self.add_stack(&error);
10232        Value::Object(error)
10233    }
10234
10235    /// Give an error object its `stack` property, from the current frame stack.
10236    ///
10237    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
10238    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
10239    /// `stack` a script set, is not rewritten.
10240    pub fn add_stack(&self, object: &Gc<JsObject>) {
10241        self.add_stack_skipping(object, 0);
10242    }
10243
10244    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
10245    ///
10246    /// An `Error` constructor passes 1: the reference builds those traces with
10247    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
10248    /// constructor itself, while a `RangeError` raised inside `toISOString` does
10249    /// report `at toISOString (native)`.
10250    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
10251        if object.has_own("stack") {
10252            return;
10253        }
10254        // The trace is *captured* here but not installed as a property: `stack` is an
10255        // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
10256        // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
10257        // is kept in a hidden slot and the getter materialises it on first read.
10258        //
10259        // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
10260        // shows it — this is the same discipline `_error_data` and `_class` follow.
10261        let trace = self.stack_trace_skipping(skip);
10262        let text = self.string(trace);
10263        self.internal_set(object, "_stack_trace", text);
10264    }
10265
10266    /// The function object currently being called, if any.
10267    ///
10268    /// A native function is a bare `fn` pointer, so it cannot capture which class
10269    /// it belongs to; it reads that from the callee instead. This is also what a
10270    /// stack trace would use.
10271    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
10272        // A native has no frame of its own — it is recorded in `current_native` — so asking
10273        // `frames` answered with the *bytecode caller's* callee. `Error`'s constructor reads
10274        // the class off this, and every plain call therefore built an `Error`:
10275        // `EvalError(1)` had the name `"Error"` (`try/S12.14_A19_T1`).
10276        //
10277        // Only while the native is the innermost thing running. It stays recorded while the
10278        // native drives *through* user code — `Iterator.prototype.take` calls the `next` a
10279        // script wrote — and answering with it there gave that user code the native's callee:
10280        // `super()` looked up the native's prototype instead of its own constructor's.
10281        // `native_frames` records `frames.len()` from before the native ran, so an equal
10282        // length means nothing has been pushed since.
10283        if let Some(native) = &self.current_native
10284            && self
10285                .native_frames
10286                .last()
10287                .is_some_and(|(_, depth)| *depth == self.frames.len())
10288        {
10289            return Some(native.clone());
10290        }
10291        match &self.frames.last()?.callee {
10292            Value::Object(object) => Some(object.clone()),
10293            _ => None,
10294        }
10295    }
10296
10297    /// The `prototype` property of a constructor, falling back to
10298    /// `Object.prototype` for anything that is not shaped like one.
10299    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
10300        constructor
10301            .own_property("prototype")
10302            .and_then(|property| property.value)
10303            .and_then(|value| value.as_object().cloned())
10304            .unwrap_or_else(|| self.realm.object_proto.clone())
10305    }
10306
10307    /// Throw a `TypeError` carrying `message`.
10308    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
10309        Signal::Throw(self.make_error("TypeError", message.as_ref()))
10310    }
10311
10312    /// Throw a `RangeError` carrying `message`.
10313    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
10314        Signal::Throw(self.make_error("RangeError", message.as_ref()))
10315    }
10316
10317    /// A `ReferenceError`, as the value to throw.
10318    ///
10319    /// `throw` uses it for "called on a disposed stack": `DisposableStack.prototype.defer`
10320    /// and its siblings report a `ReferenceError` there, which is what
10321    /// `adopt|defer|move/throws-if-disposed` assert.
10322    pub fn reference_error(&self, message: impl AsRef<str>) -> Signal {
10323        Signal::Throw(self.make_error("ReferenceError", message.as_ref()))
10324    }
10325
10326    /// The `ReferenceError` a read of an uninitialised binding raises.
10327    /// The name of the binding `slot` refers to, for an error message.
10328    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
10329        match kind {
10330            VarSlot::Loc => self
10331                .frame()
10332                .code
10333                .code
10334                .vars
10335                .get(slot)
10336                .map(|v| v.name.clone()),
10337            VarSlot::Closure => self
10338                .frame()
10339                .code
10340                .code
10341                .closure_vars
10342                .get(slot)
10343                .map(|c| c.name.clone()),
10344        }
10345        .unwrap_or_default()
10346    }
10347
10348    /// Whether `slot` names a `const` binding, which rejects every store after its
10349    /// initialiser.
10350    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
10351        match kind {
10352            VarSlot::Loc => self
10353                .frame()
10354                .code
10355                .code
10356                .vars
10357                .get(slot)
10358                .is_some_and(|v| v.is_const),
10359            VarSlot::Closure => self
10360                .frame()
10361                .code
10362                .code
10363                .closure_vars
10364                .get(slot)
10365                .is_some_and(|c| c.is_const),
10366        }
10367    }
10368
10369    /// The `TypeError` a store to a `const` binding raises.
10370    ///
10371    /// `const` is enforced here rather than at compile time because the binding can be
10372    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
10373    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
10374    /// both halves of what "checked store" means: the dead zone is over, and the
10375    /// binding is writable.
10376    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
10377        let name = self.binding_name(slot, kind);
10378        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
10379    }
10380
10381    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
10382        let name = match kind {
10383            VarSlot::Loc => self
10384                .frame()
10385                .code
10386                .code
10387                .vars
10388                .get(slot)
10389                .map(|v| v.name.clone()),
10390            VarSlot::Closure => self
10391                .frame()
10392                .code
10393                .code
10394                .closure_vars
10395                .get(slot)
10396                .map(|c| c.name.clone()),
10397        }
10398        .unwrap_or_default();
10399        // The reference has a wording of its own for `this`, because the dead zone it sits
10400        // in is the derived constructor's rather than a `let`'s: `constructor(){ return; }`
10401        // reports `this is not initialized`.
10402        let message = if name == "this" {
10403            "this is not initialized".to_string()
10404        } else {
10405            format!("cannot access '{name}' before initialization")
10406        };
10407        Signal::Throw(self.make_error("ReferenceError", &message))
10408    }
10409
10410    /// The reference a `make_*_ref` opcode builds, from the object it produced.
10411    fn reference_target(&mut self, offset: usize) -> JsResult<RefTarget> {
10412        match self.peek(offset) {
10413            Value::Object(object) => object.reference().ok_or_else(|| {
10414                self.type_error("a reference operation on something that is not a reference")
10415            }),
10416            _ => Err(self.type_error("a reference operation on a non-object")),
10417        }
10418    }
10419
10420    /// `ResolveBinding(name)` for a name the compiler could only resolve statically as "a
10421    /// global".
10422    ///
10423    /// Three answers, in the order §9.1.1.4 asks them:
10424    ///
10425    /// * a local a direct `eval` declared in this frame — the innermost variable
10426    ///   environment, so it wins;
10427    /// * an existing global binding or an existing property of the global object;
10428    /// * nothing, which is an **unresolvable** reference (base `undefined`) rather than a
10429    ///   failure: reading it throws and a sloppy write creates the global.
10430    fn global_reference(&mut self, name: &crate::value::Wtf8) -> JsResult<RefTarget> {
10431        if let Some((local_vars, phase)) = self.visible_local_vars() {
10432            let key = name.to_string_lossy();
10433            if local_vars.contains(&key)
10434                && let Some(cell) = local_vars.get(&key, phase)
10435            {
10436                return Ok(RefTarget::Cell(cell));
10437            }
10438        }
10439        let key = PropertyKey::String(name.clone());
10440        let global = self.realm.global.clone();
10441        let has = self.has_own_or_inherited(&global, &key)?;
10442        Ok(RefTarget::Property {
10443            base: if has {
10444                Value::Object(global)
10445            } else {
10446                Value::Undefined
10447            },
10448            name: key,
10449        })
10450    }
10451
10452    fn throw_reference(&self, name: &str) -> Signal {
10453        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
10454    }
10455
10456    // -- the instruction loop -----------------------------------------------
10457
10458    // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
10459    // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
10460    // measured at 16% of a tight arithmetic loop's total time.
10461    #[inline(always)]
10462    fn step(&mut self) -> JsResult<Step> {
10463        // The instruction is already decoded (see [`crate::insn`]), so this is an index
10464        // and a `Copy` read rather than a table lookup plus a width switch. Only the
10465        // borrow lives across the boundary; nothing is cloned.
10466        // **One** borrow of the frame: fetch the record, then advance in the same scope.
10467        // The obvious version borrowed it three times (`last` to read, `last_mut` to
10468        // write, and once more inside the handler), and each is a bounds check plus an
10469        // `Option` unwrap — on the one path every instruction takes.
10470        let Some((insn, next)) = ({
10471            let frame = self
10472                .frames
10473                .last_mut()
10474                .expect("step() is only called with a live frame");
10475            // Past the last instruction is a normal return: the compiler ends a function
10476            // with `return`, and a jump to the end of a block lands here.
10477            let insn = frame.insns().get(frame.pc).copied();
10478            match insn {
10479                None => None,
10480                Some(insn) => {
10481                    // A fused record stands for the next few instructions, so the next
10482                    // `pc` is its width ahead — the instructions it replaces are never
10483                    // dispatched. `at` is the byte offset a stack trace reports; it stays
10484                    // an offset because the line table is keyed by bytes.
10485                    frame.at = insn.offset as usize;
10486                    frame.pc += insn.width();
10487                    Some((insn, frame.pc))
10488                }
10489            }
10490        }) else {
10491            return Ok(Step::Return(Value::Undefined));
10492        };
10493        self.check_memory()?;
10494        self.check_interrupt()?;
10495        if insn.fused == crate::insn::Fused::None {
10496            self.execute_instruction(insn.op, insn.a, insn.b, next)
10497        } else {
10498            self.execute_fused(insn)
10499        }
10500    }
10501
10502    /// Run a fused instruction: several bytecode instructions in one dispatch.
10503    ///
10504    /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
10505    /// it cannot throw and cannot allocate — and anything else falls back to the real
10506    /// instructions, in their real order, so an exception leaves the operand stack
10507    /// exactly as it would have been.
10508    #[inline]
10509    fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
10510        use crate::insn::Fused;
10511        let slot = insn.a as usize;
10512        match insn.fused {
10513            // `x = k`: `push k; put_loc x`.
10514            Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
10515            // `x += k`: `get_loc x; push k; add; put_loc x`.
10516            Fused::AddImmLoc => {
10517                let delta = insn.b as i32;
10518                match self.get_loc(slot) {
10519                    Value::Int(left) => {
10520                        // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
10521                        // that built two `Value`s, called a function, and matched on them
10522                        // again to reach this same `checked_add`. It is the innermost
10523                        // operation of every accumulator in every program.
10524                        let answer = match left.checked_add(delta) {
10525                            Some(sum) => Value::Int(sum),
10526                            None => Value::Float(left as f64 + delta as f64),
10527                        };
10528                        self.put_loc(slot, answer);
10529                    }
10530                    other => {
10531                        self.push(other);
10532                        self.push(Value::Int(delta));
10533                        self.binary_add()?;
10534                        let value = self.pop();
10535                        self.put_loc(slot, value);
10536                    }
10537                }
10538            }
10539            // `x += "literal"` and `x += y`: the two shapes that can append in place.
10540            Fused::AddAtomLoc => {
10541                let text = self.atom_wtf8(insn.b as usize);
10542                let right = self.string_wtf8(text);
10543                self.add_into_loc(slot, right)?;
10544            }
10545            Fused::AddLocLoc => {
10546                let source = (insn.a & 0xFFFF) as usize;
10547                let target = (insn.a >> 16) as usize;
10548                let right = self.get_loc(source);
10549                self.add_into_loc(target, right)?;
10550            }
10551            Fused::AddArgLoc => {
10552                let source = (insn.a & 0xFFFF) as usize;
10553                let target = (insn.a >> 16) as usize;
10554                let right = self.get_arg(source);
10555                self.add_into_loc(target, right)?;
10556            }
10557            // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
10558            Fused::PostIncLoc => match self.get_loc(slot) {
10559                Value::Int(left) => {
10560                    let answer = match left.checked_add(1) {
10561                        Some(sum) => Value::Int(sum),
10562                        None => Value::Float(left as f64 + 1.0),
10563                    };
10564                    self.put_loc(slot, answer);
10565                }
10566                other => {
10567                    self.push(other);
10568                    let raw = self.pop();
10569                    let (old, updated) = self.advance_numeric(raw, true)?;
10570                    self.push(old);
10571                    self.push(updated);
10572                    let value = self.pop();
10573                    self.put_loc(slot, value);
10574                    self.pop();
10575                }
10576            },
10577            // `if (!(x < arg)) goto target`: a loop header.
10578            //
10579            // The comparison is computed rather than replayed on the operand stack. That
10580            // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
10581            // that throws: the effects happen in the same order, and a handler truncates
10582            // the stack down to its marker, so the intermediate values are unobservable.
10583            Fused::LtLocArgJump => {
10584                let loc = (insn.a >> 16) as usize;
10585                let arg = (insn.a & 0xFFFF) as usize;
10586                let left = self.get_loc(loc);
10587                let right = self.get_arg(arg);
10588                let taken = match (&left, &right) {
10589                    (Value::Int(left), Value::Int(right)) => !(left < right),
10590                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10591                };
10592                if taken {
10593                    self.frame_mut().pc = insn.b as usize;
10594                }
10595            }
10596            // `i < k` in a loop header, where `k` is an integer literal.
10597            Fused::LtLocImmJump => {
10598                let left = self.get_loc(insn.a as usize);
10599                let right = Value::Int(insn.imm as i32);
10600                let taken = match &left {
10601                    Value::Int(left) => !(*left < insn.imm as i32),
10602                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10603                };
10604                if taken {
10605                    self.frame_mut().pc = insn.b as usize;
10606                }
10607            }
10608            Fused::None => unreachable!("only called for a fused record"),
10609        }
10610        Ok(Step::Continue)
10611    }
10612
10613    /// Run records that cannot call script, cannot throw and cannot change frames.
10614    ///
10615    /// Returns `Some(value)` when the function ran off the end of its instructions (a
10616    /// normal return), and `None` when it stopped in front of an instruction the slow path
10617    /// has to handle — `pc` is written back either way, so `step` resumes at the right
10618    /// place.
10619    ///
10620    /// **The invariant is the whole point.** Every arm here is restricted to work that
10621    /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
10622    /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
10623    /// that the memory limit has to see. An opcode whose operands turn out to need any of
10624    /// that **stops the loop** instead of trying, so the slow path gets the instruction
10625    /// untouched and with its operands still on the stack. That is why the fallback is a
10626    /// `break` and not a duplicated slow arm: a second implementation of the same
10627    /// semantics is how a wrong answer gets in with no test noticing.
10628    ///
10629    /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
10630    /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
10631    fn run_fast(&mut self) -> JsResult<Option<Value>> {
10632        use crate::insn::Fused;
10633        // The outer loop exists only so a `Call` can come back through here: once a
10634        // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
10635        // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
10636        // frame. Re-entering re-reads both from whichever frame is now on top. Every
10637        // other exit from the inner loop returns, so this costs one loop per call.
10638        'outer: loop {
10639            // One reference-count bump per *slow* instruction (a call, an allocation, a
10640            // property access), never one per instruction — that distinction is worth
10641            // two orders of magnitude and was measured as such.
10642            let (code, mut pc) = {
10643                let frame = self.frame();
10644                (frame.code.clone(), frame.pc)
10645            };
10646            let insns = &code.insns;
10647            loop {
10648                let Some(insn) = insns.get(pc).copied() else {
10649                    self.frame_mut().pc = pc;
10650                    return Ok(Some(Value::Undefined));
10651                };
10652                match insn.fused {
10653                    // `x = k`
10654                    Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
10655                    // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
10656                    // object — stops the loop so `binary_add` can decide.
10657                    Fused::AddImmLoc => {
10658                        let slot = insn.a as usize;
10659                        let delta = insn.b as i32;
10660                        let Value::Int(left) = self.get_loc(slot) else {
10661                            return Ok(self.stop(pc));
10662                        };
10663                        let sum = match left.checked_add(delta) {
10664                            Some(sum) => Value::Int(sum),
10665                            None => Value::Float(left as f64 + delta as f64),
10666                        };
10667                        self.put_loc(slot, sum);
10668                    }
10669                    // `x += "literal"` / `x += y`: the operand is a string, so the append
10670                    // either allocates one or grows one. Both are the slow path's business;
10671                    // the fusion's job is only to make the *slot* the sole owner, which is what
10672                    // `execute_fused` needs and what `get_loc` alone destroys.
10673                    Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
10674                        return Ok(self.stop(pc));
10675                    }
10676                    // `x++` on an integer, old value dropped.
10677                    Fused::PostIncLoc => {
10678                        // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
10679                        // value is read in place and overwritten in place, so the reference
10680                        // count it held is released by the same assignment that stores the
10681                        // new one. `get_loc` plus `put_loc` did two borrows, two table
10682                        // lookups and a clone, and this arm is the whole body of a counting
10683                        // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
10684                        let slot = insn.a as usize;
10685                        let frame = self.frames.last_mut().expect("a frame is live");
10686                        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
10687                        let target = if cell < 0 {
10688                            frame.locals.get_mut(slot)
10689                        } else {
10690                            None
10691                        };
10692                        let Some(target) = target else {
10693                            return Ok(self.stop(pc));
10694                        };
10695                        let Value::Int(left) = *target else {
10696                            return Ok(self.stop(pc));
10697                        };
10698                        *target = match left.checked_add(1) {
10699                            Some(sum) => Value::Int(sum),
10700                            None => Value::Float(left as f64 + 1.0),
10701                        };
10702                    }
10703                    // A loop header, `if (!(x < arg)) goto target`, with both sides already
10704                    // integers — which is every `for (i = 0; i < n; i++)` whose counter and
10705                    // bound stayed small integers.
10706                    Fused::LtLocArgJump => {
10707                        let loc = (insn.a >> 16) as usize;
10708                        let arg = (insn.a & 0xFFFF) as usize;
10709                        // One borrow for both slots: this arm *is* the whole loop of a
10710                        // `for (i = 0; i < n; i++)` with an argument bound, so a second
10711                        // `frames.last()` here is paid on every iteration. Measured 7.5% on
10712                        // `dispatch:empty-loop`.
10713                        let (left, right) = {
10714                            let frame = self.frame();
10715                            (frame.read_loc(loc), frame.read_arg(arg))
10716                        };
10717                        // Heavily measured: the bound is very often a `Float` even when the
10718                        // counter is an `Int` — anything that came from `+scriptArgs[2]`,
10719                        // `JSON.parse` or a division is one — so requiring both sides to be
10720                        // `Int` sent every iteration of those loops down the slow path. The
10721                        // comparison below is the same one `relational` makes for two numbers.
10722                        if !is_number(&left) || !is_number(&right) {
10723                            return Ok(self.stop(pc));
10724                        }
10725                        // `if_false` branches on the comparison being false, which is **not**
10726                        // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
10727                        // `>=` is also false and would keep it running forever. Clippy wants the
10728                        // negation folded; that would be a wrong answer.
10729                        let ordered = left.to_number() < right.to_number();
10730                        let take_branch = !ordered;
10731                        if take_branch {
10732                            pc = insn.b as usize;
10733                            continue;
10734                        }
10735                    }
10736                    // The same header with a literal bound: `if (!(x < k)) goto target`.
10737                    // The bound is an immediate, so only the counter needs a type test.
10738                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
10739                    Fused::LtLocImmJump => {
10740                        let left = self.get_loc(insn.a as usize);
10741                        if !is_number(&left) {
10742                            return Ok(self.stop(pc));
10743                        }
10744                        let take_branch = !(left.to_number() < insn.imm as i32 as f64);
10745                        if take_branch {
10746                            pc = insn.b as usize;
10747                            continue;
10748                        }
10749                    }
10750                    Fused::None => match insn.op {
10751                        // -- branches ---------------------------------------------------
10752                        // A jump is an assignment now, because the target is an instruction
10753                        // index. No arithmetic, no resolution table.
10754                        Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10755                            let target = insn.a as usize;
10756                            // A **back-edge** is a loop, and it is the only place an
10757                            // instruction-level checkpoint can stop one: `for(;;){}` compiles
10758                            // to a jump to itself and never leaves this loop, so the
10759                            // per-instruction checks in `step` never run. That is exactly the
10760                            // hole this arm closes — a host's `JS_SetInterruptHandler` did
10761                            // nothing to a `for(;;){}` until it did, which is what
10762                            // `tests/c/embed.c` is for.
10763                            //
10764                            // Polling here rather than on every instruction in this loop is
10765                            // also the reference's choice (`OP_goto` calls
10766                            // `js_poll_interrupts`), and it costs one compare per branch
10767                            // instead of one decrement per instruction.
10768                            if target <= pc {
10769                                self.frame_mut().pc = target;
10770                                self.check_memory()?;
10771                                self.check_interrupt()?;
10772                            }
10773                            pc = target;
10774                            continue;
10775                        }
10776                        // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
10777                        Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
10778                            let taken = self.pop().to_boolean();
10779                            let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
10780                            if taken == want {
10781                                pc = insn.a as usize;
10782                                continue;
10783                            }
10784                        }
10785                        // -- slot access -------------------------------------------------
10786                        // A load's slot is already an operand (see `insn::implicit_operand`);
10787                        // a captured one goes through its cell, which runs no script.
10788                        Opcode::GetLoc
10789                        | Opcode::GetLoc8
10790                        | Opcode::GetLoc0
10791                        | Opcode::GetLoc1
10792                        | Opcode::GetLoc2
10793                        | Opcode::GetLoc3 => {
10794                            let value = self.get_loc(insn.a as usize);
10795                            self.push(value);
10796                        }
10797                        Opcode::PutLoc
10798                        | Opcode::PutLoc8
10799                        | Opcode::PutLoc0
10800                        | Opcode::PutLoc1
10801                        | Opcode::PutLoc2
10802                        | Opcode::PutLoc3 => {
10803                            let value = self.pop();
10804                            self.put_loc(insn.a as usize, value);
10805                        }
10806                        Opcode::GetArg
10807                        | Opcode::GetArg0
10808                        | Opcode::GetArg1
10809                        | Opcode::GetArg2
10810                        | Opcode::GetArg3 => {
10811                            let value = self.get_arg(insn.a as usize);
10812                            self.push(value);
10813                        }
10814                        Opcode::PutArg
10815                        | Opcode::PutArg0
10816                        | Opcode::PutArg1
10817                        | Opcode::PutArg2
10818                        | Opcode::PutArg3 => {
10819                            let value = self.pop();
10820                            self.put_arg(insn.a as usize, value);
10821                        }
10822                        // `a[i]` with an integer index on a dense array: see `fast_array_get`
10823                        // for why a non-hole own element is exactly the slow path's answer.
10824                        // The two operands are *peeked*, so a miss leaves the stack as the
10825                        // slow path expects to find it.
10826                        Opcode::GetArrayEl => {
10827                            // One lookup, not two. The guard used `if …is_some()` and the arm
10828                            // then called it again to get the value — two `peek`s, two
10829                            // `array_get`s and two `Value` clones for one element.
10830                            // `fast_array_get` was 13.1% of `array:indexed`, and the same
10831                            // double call was the first version of the `get_field` fast path.
10832                            let Some(value) = self.fast_array_get() else {
10833                                return Ok(self.stop(pc));
10834                            };
10835                            // `a[i]` consumes both operands and leaves the element in their
10836                            // place: one `truncate` and one write, no `pop`/`push` pair.
10837                            let frame = self.frame_mut();
10838                            frame.stack.truncate(frame.stack.len() - 2);
10839                            frame.stack.push(value);
10840                        }
10841                        // `a[i] = v` on a dense array with an integer index: see
10842                        // `fast_array_set` for why the whole store is one step.
10843                        Opcode::PutArrayEl if self.fast_array_set() => {}
10844                        // `o.x` resolved from the inline cache without leaving the loop.
10845                        //
10846                        // The cache is keyed by `(receiver identity, atom, site)` and a
10847                        // monomorphic read re-validates the same chain every iteration, so
10848                        // each one used to cost a `stop(pc)` — a write of `pc` into the
10849                        // frame, a return out of this loop, a re-dispatch through `step` and
10850                        // a re-entry. `property:monomorphic` spent 18% in
10851                        // `read_field_cached` and 21% in `push`, both across that boundary.
10852                        //
10853                        // The site is `pc + width`, which is exactly the `next` the slow arm
10854                        // passes — the two must agree or every fast lookup misses and
10855                        // re-records the same entry forever.
10856                        //
10857                        // A miss leaves the stack untouched (`fast_field_get` peeks) so the
10858                        // slow arm finds the receiver where it expects it.
10859                        // `name` resolved from the global-variable cache inside the loop.
10860                        //
10861                        // Same shape as `get_field` above and for the same reason: `get_var`
10862                        // was not in the fast loop, so reading a global — which `fib` does
10863                        // once per recursive call, for its own name — cost a `stop(pc)`, a
10864                        // return out of the loop, a `step` re-dispatch and a re-entry, before
10865                        // `get_global` even started its `scopes_are_plain` checks.
10866                        //
10867                        // Everything here is exactly `get_global`'s first branch: not lexical,
10868                        // no `eval` scope, cache hit. Anything else leaves the stack untouched
10869                        // and lets the slow arm decide.
10870                        Opcode::GetVar => {
10871                            let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
10872                                return Ok(self.stop(pc));
10873                            };
10874                            self.push(value);
10875                        }
10876                        Opcode::GetField | Opcode::GetField2 => {
10877                            let Some(value) =
10878                                self.fast_field_get(insn.a as usize, pc + insn.width())
10879                            else {
10880                                return Ok(self.stop(pc));
10881                            };
10882                            if insn.op == Opcode::GetField2 {
10883                                // `get_field2` keeps the receiver for the `call_method` that
10884                                // follows.
10885                                self.push(value);
10886                            } else {
10887                                // `get_field` replaces the receiver, so this is one store over
10888                                // the top slot rather than a `pop` and a `push`: the length
10889                                // never changes, so neither `Vec` arm has a capacity check or a
10890                                // drop to run beyond the one the overwrite itself does.
10891                                let frame = self.frame_mut();
10892                                match frame.stack.last_mut() {
10893                                    Some(slot) => *slot = value,
10894                                    None => return Ok(self.stop(pc)),
10895                                }
10896                            }
10897                        }
10898                        // -- constants ---------------------------------------------------
10899                        Opcode::PushMinus1
10900                        | Opcode::Push0
10901                        | Opcode::Push1
10902                        | Opcode::Push2
10903                        | Opcode::Push3
10904                        | Opcode::Push4
10905                        | Opcode::Push5
10906                        | Opcode::Push6
10907                        | Opcode::Push7
10908                        | Opcode::PushI8
10909                        | Opcode::PushI16
10910                        | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
10911                        // -- stack shuffling ---------------------------------------------
10912                        Opcode::Drop => {
10913                            self.pop();
10914                        }
10915                        // -- arithmetic on two integers ----------------------------------
10916                        //
10917                        // The operands are *looked at* before they are popped, so a non-integer
10918                        // pair leaves the stack exactly as the slow path expects to find it.
10919                        Opcode::Add if self.numeric_pair() => {
10920                            let right = self.pop();
10921                            let left = self.pop();
10922                            // Exactly [`add_numbers`], which is what the slow arm reaches.
10923                            let answer = match (&left, &right) {
10924                                (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10925                                    Some(sum) => Value::Int(sum),
10926                                    None => Value::Float(*a as f64 + *b as f64),
10927                                },
10928                                _ => Value::Float(left.to_number() + right.to_number()),
10929                            };
10930                            self.push(answer);
10931                        }
10932                        Opcode::Sub
10933                        | Opcode::And
10934                        | Opcode::Or
10935                        | Opcode::Xor
10936                        | Opcode::Shl
10937                        | Opcode::Sar
10938                        | Opcode::Shr
10939                            if self.numeric_pair() =>
10940                        {
10941                            let right = self.pop();
10942                            let left = self.pop();
10943                            let answer =
10944                                arithmetic(insn.op, left, right).expect("numbers cannot throw");
10945                            self.push(answer);
10946                        }
10947                        Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10948                            if self.numeric_pair() =>
10949                        {
10950                            let right = self.pop();
10951                            let left = self.pop();
10952                            let answer = self
10953                                .relational(insn.op, left, right)
10954                                .expect("numbers cannot throw");
10955                            self.push(answer);
10956                        }
10957                        // -- calls -------------------------------------------------------
10958                        //
10959                        // A plain call: `callee(arg0, …, argN) -> result`.
10960                        //
10961                        // This arm exists because of one measurement. `call:recursion` had
10962                        // **20.4% of its profile in `execute_instruction`** — the *slow*
10963                        // executor — and `fib`'s recursive call is the only thing in that
10964                        // function which is not a fast arm. Every call therefore left this
10965                        // loop via `stop()`, went through `step()`'s dispatch and
10966                        // `execute_instruction`'s match over every opcode, and came back here
10967                        // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
10968                        //
10969                        // Two things make it safe to do here rather than only in the slow path:
10970                        //
10971                        // * the caller's `pc` is stored *before* the call, which is what
10972                        //   `step` does too — so when the callee returns, the caller resumes
10973                        //   after the call and not at it;
10974                        // * `check_memory` runs, because `step` calls it once per instruction
10975                        //   and a call allocates a frame, its locals and its cells. Skipping
10976                        //   the checkpoint here would let a `--memory-limit` script overshoot
10977                        //   by one call per instruction.
10978                        Opcode::Call
10979                        | Opcode::Call0
10980                        | Opcode::Call1
10981                        | Opcode::Call2
10982                        | Opcode::Call3 => {
10983                            let argc = self.argc_operand(insn.op, insn.a);
10984                            let next = pc + insn.width();
10985                            {
10986                                let frame = self
10987                                    .frames
10988                                    .last_mut()
10989                                    .expect("run_fast() is only called with a live frame");
10990                                // `at` is what a stack trace reports for this frame, so a throw
10991                                // inside the callee has to see the call site and not whatever
10992                                // the last `stop()` left there.
10993                                frame.at = insn.offset as usize;
10994                                frame.pc = next;
10995                            }
10996                            self.check_memory()?;
10997                            self.check_interrupt()?;
10998                            let args = self.pop_n(argc);
10999                            let callee = self.pop();
11000                            // A plain call has no receiver; the callee decides what to do with
11001                            // `undefined` (a sloppy function substitutes the global object).
11002                            if let Some(result) =
11003                                self.call_or_push(callee, Value::Undefined, args)?
11004                            {
11005                                // Native, host, generator, async, bound — no frame was pushed,
11006                                // so this loop is still describing the right function. `pc`
11007                                // is advanced by the loop tail like every other arm; only the
11008                                // frame's copy had to be written here, and it already was.
11009                                self.push(result);
11010                            } else {
11011                                // A bytecode callee: its frame is on top now, and `insns` and
11012                                // `pc` both belong to the caller. Start over on the new frame.
11013                                continue 'outer;
11014                            }
11015                        }
11016                        // -- return ------------------------------------------------------
11017                        Opcode::Return => {
11018                            let value = self.pop();
11019                            self.frame_mut().pc = pc + insn.width();
11020                            return Ok(Some(value));
11021                        }
11022                        Opcode::ReturnUndef => {
11023                            self.frame_mut().pc = pc + insn.width();
11024                            return Ok(Some(Value::Undefined));
11025                        }
11026                        // Everything else needs the slow path.
11027                        _ => return Ok(self.stop(pc)),
11028                    },
11029                }
11030                pc += insn.width();
11031            }
11032        }
11033    }
11034
11035    /// Whether the top two operand-stack values are both numbers.
11036    ///
11037    /// The guard the fast loop uses before it takes an arithmetic record: two numbers
11038    /// cannot run script, so the arm may not throw and may not change frames.
11039    fn numeric_pair(&self) -> bool {
11040        is_number(&self.peek(0)) && is_number(&self.peek(1))
11041    }
11042
11043    /// `a[i]` for a dense array and an integer index, without the string round trip.
11044    ///
11045    /// The slow path answers this by turning `i` into a string (`propkey` →
11046    /// `number_to_string`) and then parsing it straight back (`read_field_key` →
11047    /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
11048    /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
11049    /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
11050    /// without even the cheap `Int` formatting.
11051    ///
11052    /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
11053    /// unambiguously the one the slow path would give:
11054    ///
11055    /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
11056    ///   `2^32-1` is the length, not an index),
11057    /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
11058    ///   typed array or an ordinary object, all of which have their own rules),
11059    /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
11060    ///   starts walking the prototype chain, and `a[i]` on a hole must find
11061    ///   `Array.prototype[i]` if it exists rather than `undefined`.
11062    ///
11063    /// The last condition is the one that makes this safe rather than merely fast: an own
11064    /// element always wins over the prototype, so a non-hole hit needs no further lookup.
11065    /// `get_var` answered from the global-variable cache, or `None`.
11066    ///
11067    /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
11068    /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
11069    /// records nothing — the slow arm is about to walk the chain and record it.
11070    fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
11071        let frame = self.frame();
11072        let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
11073        // "Lexical" is presence in the realm's table, not the closure var's flag: a
11074        // `GlobalRef` forwarded through a nested function has its flags cleared.
11075        if self.realm.globals.contains_key(name) {
11076            return None;
11077        }
11078        if !self.scopes_are_plain() {
11079            return None;
11080        }
11081        let object = &self.realm.global;
11082        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
11083        let cached = self.global_cache[site].as_ref()?;
11084        if !object.upgrades_to(&cached.object) {
11085            return None;
11086        }
11087        object.data_property_at(cached.index, name)
11088    }
11089
11090    /// `o.x` answered entirely from the inline cache, or `None`.
11091    ///
11092    /// Read-only on purpose: a miss must not record an entry, because the slow arm is
11093    /// about to do exactly that and recording it twice would rebuild the chain for every
11094    /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
11095    /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
11096    fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
11097        // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
11098        // an object receiver is a reference-count bump that the answer never needs.
11099        let frame = self.frame();
11100        let object = frame.stack.last()?;
11101        let Value::Object(target) = object else {
11102            return None;
11103        };
11104        // A proxy traps the lookup, so no cache entry ever describes it.
11105        if target.proxy_state().is_some() {
11106            return None;
11107        }
11108        let key = frame.code.atom_keys.get(atom)?;
11109        let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
11110        if cached.key != *key {
11111            return None;
11112        }
11113        Self::cached_hit(target, cached)
11114    }
11115
11116    fn fast_array_get(&self) -> Option<Value> {
11117        let Value::Int(index) = self.peek(0) else {
11118            return None;
11119        };
11120        // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
11121        // set for an `i32`.
11122        if index < 0 {
11123            return None;
11124        }
11125        let Value::Object(object) = self.peek(1) else {
11126            return None;
11127        };
11128        match object.array_get(index as usize) {
11129            Some(value) if !matches!(value, Value::Hole) => Some(value),
11130            _ => None,
11131        }
11132    }
11133
11134    /// `a[i] = v` on a dense array with an integer index, as one store.
11135    ///
11136    /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
11137    /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
11138    /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
11139    /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
11140    /// reference at the time it was measured (14.7x).
11141    ///
11142    /// Every condition here is one the slow path would also have to satisfy before
11143    /// storing into the element vector:
11144    ///
11145    /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
11146    ///   accepts as an index;
11147    /// * the target is an array whose elements are writable (`Object.freeze` clears it);
11148    /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
11149    ///   one inside a recorded descriptor, reports `false` and the caller stops.
11150    ///
11151    /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
11152    /// writes the own element too once `array_set` says it did.
11153    fn fast_array_set(&mut self) -> bool {
11154        // Every test runs *before* anything is popped: a refusal has to leave the stack
11155        // exactly as the slow path expects to find it. Popping first and reporting the
11156        // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
11157        // then ran the slow path with nothing to write.
11158        let Value::Int(index) = self.peek(1) else {
11159            return false;
11160        };
11161        // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
11162        if index < 0 {
11163            return false;
11164        }
11165        // Only a real array: a typed array's elements live in its buffer, a string-like
11166        // object has no element vector, and `array_set` on either does nothing.
11167        let Value::Object(object) = self.peek(2) else {
11168            return false;
11169        };
11170        if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
11171            return false;
11172        }
11173        // A non-extensible array reports `false` here, but the *slow* path has to decide
11174        // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
11175        // that with the key and the stack still intact.
11176        if !object.is_extensible() {
11177            return false;
11178        }
11179        // Inside the logical length, so the store cannot change `length`. Combined with
11180        // extensibility above, the only growth left for `array_set` is filling a hole in
11181        // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
11182        // shape this fast path exists for. A store past the length would grow the array,
11183        // and whether that is allowed is the slow path's question.
11184        if index as usize >= object.array_length().unwrap_or(0) {
11185            return false;
11186        }
11187        // Only an *own element* can take the inline store. A hole is not an own property,
11188        // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
11189        // trap or a setter decides, and where `new Array(1)` with a proxy above it must
11190        // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
11191        // the one case this path used to swallow.
11192        //
11193        // The cost is small: `array:indexed` only reads after a 64-element fill, and
11194        // `array:push` appends past the length, which this path already refused.
11195        if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
11196        {
11197            return false;
11198        }
11199        // The bound `array_set` refuses past. Checking it here keeps that arm from having
11200        // to report a failure after the operands are gone.
11201        if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
11202            return false;
11203        }
11204        let value = self.pop();
11205        self.pop();
11206        self.pop();
11207        object.array_store(self.heap, index as usize, value)
11208    }
11209
11210    /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
11211    fn stop(&mut self, pc: usize) -> Option<Value> {
11212        self.frame_mut().pc = pc;
11213        None
11214    }
11215
11216    fn push(&mut self, value: Value) {
11217        self.frame_mut().stack.push(value);
11218    }
11219
11220    fn pop(&mut self) -> Value {
11221        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
11222    }
11223
11224    fn pop_n(&mut self, count: usize) -> Vec<Value> {
11225        let frame = self.frame_mut();
11226        let start = frame.stack.len().saturating_sub(count);
11227        frame.stack.split_off(start)
11228    }
11229
11230    fn peek(&self, back: usize) -> Value {
11231        let frame = self.frame();
11232        frame
11233            .stack
11234            .get(frame.stack.len().wrapping_sub(1 + back))
11235            .cloned()
11236            .unwrap_or(Value::Undefined)
11237    }
11238
11239    #[allow(clippy::too_many_lines)]
11240    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
11241        use Opcode::*;
11242        match op {
11243            // -- constants and stack shuffling -----------------------------
11244            Nop => {}
11245            PushMinus1 => self.push(Value::Int(-1)),
11246            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
11247                let value = match op {
11248                    Push0 => 0,
11249                    Push1 => 1,
11250                    Push2 => 2,
11251                    Push3 => 3,
11252                    Push4 => 4,
11253                    Push5 => 5,
11254                    Push6 => 6,
11255                    _ => 7,
11256                };
11257                self.push(Value::Int(value));
11258            }
11259            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
11260            PushBigintI32 => {
11261                // The immediate form of a `BigInt` literal; the reference has the same
11262                // split between this and a constant-pool entry.
11263                let value = crate::bigint::BigInt::from_i64(a as i64);
11264                self.push(self.bigint(value));
11265            }
11266            PushTrue => self.push(Value::Bool(true)),
11267            PushFalse => self.push(Value::Bool(false)),
11268            PushEmptyString => self.push(self.string("")),
11269            Undefined => self.push(Value::Undefined),
11270            Null => self.push(Value::Null),
11271            Object => {
11272                let proto = self.realm.object_proto.clone();
11273                self.push(Value::Object(self.new_object(Some(proto))));
11274            }
11275            PushThis => {
11276                let this = self.frame().this.clone();
11277                self.push(this);
11278            }
11279            PushConst | PushConst8 => {
11280                let value = self.constant(a as usize)?;
11281                self.push(value);
11282            }
11283            PushAtomValue => {
11284                let text = self.atom_wtf8(a as usize);
11285                self.push(self.string_wtf8(text));
11286            }
11287            Dup => {
11288                let value = self.peek(0);
11289                self.push(value);
11290            }
11291            Dup2 => {
11292                // `a b -> a b a b`
11293                let b = self.peek(0);
11294                let a = self.peek(1);
11295                self.push(a);
11296                self.push(b);
11297            }
11298            Dup3 => {
11299                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
11300                // prototype and key while reading the current value through them.
11301                let c = self.peek(0);
11302                let b = self.peek(1);
11303                let a = self.peek(2);
11304                self.push(a);
11305                self.push(b);
11306                self.push(c);
11307            }
11308            Swap => {
11309                // `a b -> b a`
11310                let bottom = self.pop();
11311                let top = self.pop();
11312                self.push(bottom);
11313                self.push(top);
11314            }
11315            Perm3 => {
11316                // `a b c -> b a c`, the reference's reordering for a spread method
11317                // call: `obj func array` becomes the `func this array` that `apply`
11318                // takes.
11319                let c = self.pop();
11320                let b = self.pop();
11321                let a = self.pop();
11322                self.push(b);
11323                self.push(a);
11324                self.push(c);
11325            }
11326            Dup1 => {
11327                let value = self.peek(1);
11328                self.push(value);
11329            }
11330            Drop => {
11331                self.pop();
11332            }
11333            Nip => {
11334                // `a b -> b`
11335                let top = self.pop();
11336                self.pop();
11337                self.push(top);
11338            }
11339            Perm4 => {
11340                // `obj prop a b -> a obj prop b`, the reference's reordering for a
11341                // postfix update of a computed element: it puts the *old* value
11342                // underneath the receiver and key so `put_array_el` can consume them
11343                // and leave the old value as the expression's result.
11344                let d = self.pop();
11345                let c = self.pop();
11346                let b = self.pop();
11347                let a = self.pop();
11348                self.push(c);
11349                self.push(a);
11350                self.push(b);
11351                self.push(d);
11352            }
11353            Insert2 => {
11354                // `obj a -> a obj a`
11355                let value = self.pop();
11356                let object = self.pop();
11357                self.push(value.clone());
11358                self.push(object);
11359                self.push(value);
11360            }
11361            Insert3 => {
11362                // `obj prop a -> a obj prop a`
11363                let value = self.pop();
11364                let key = self.pop();
11365                let object = self.pop();
11366                self.push(value.clone());
11367                self.push(object);
11368                self.push(key);
11369                self.push(value);
11370            }
11371            Insert4 => {
11372                // `this obj prop a -> a this obj prop a`
11373                //
11374                // `put_super_value` consumes all four and yields nothing, so the copy
11375                // underneath is what leaves the assignment an expression value.
11376                let value = self.pop();
11377                let key = self.pop();
11378                let object = self.pop();
11379                let receiver = self.pop();
11380                self.push(value.clone());
11381                self.push(receiver);
11382                self.push(object);
11383                self.push(key);
11384                self.push(value);
11385            }
11386            Swap2 => {
11387                // `a b c d -> c d a b`
11388                let d = self.pop();
11389                let c = self.pop();
11390                let b = self.pop();
11391                let a = self.pop();
11392                self.push(c);
11393                self.push(d);
11394                self.push(a);
11395                self.push(b);
11396            }
11397            Rot3l => {
11398                // `x a b -> a b x`
11399                let b = self.pop();
11400                let a = self.pop();
11401                let x = self.pop();
11402                self.push(a);
11403                self.push(b);
11404                self.push(x);
11405            }
11406            Rot3r => {
11407                // `a b c -> c a b`
11408                let c = self.pop();
11409                let b = self.pop();
11410                let a_value = self.pop();
11411                self.push(c);
11412                self.push(a_value);
11413                self.push(b);
11414            }
11415
11416            Rest => {
11417                // `...rest` in a parameter list: the arguments from index `a` on, as a
11418                // real array. It takes nothing off the stack — the arguments are in the
11419                // frame, not on it.
11420                let frame = self.frame();
11421                let from = a as usize;
11422                let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
11423                let array = self.new_array(collected);
11424                self.push(Value::Object(array));
11425            }
11426
11427            // -- slots ------------------------------------------------------
11428            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
11429                let slot = self.slot_operand(op, a);
11430                let value = self.get_loc(slot);
11431                self.push(value);
11432            }
11433            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
11434                let slot = self.slot_operand(op, a);
11435                let value = self.pop();
11436                self.put_loc(slot, value);
11437            }
11438            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
11439                let slot = self.slot_operand(op, a);
11440                let value = self.pop();
11441                self.put_loc(slot, value.clone());
11442                self.push(value);
11443            }
11444            // The `_check` forms are the temporal dead zone: they throw when the
11445            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
11446            // *reads*, so only the two writes may pop — mishandling that quietly
11447            // consumes the value the caller pushed just before.
11448            GetLocCheck => {
11449                let slot = self.slot_operand(op, a);
11450                let value = self.get_loc(slot);
11451                if matches!(value, Value::Uninitialized) {
11452                    return Err(self.dead_zone(slot, VarSlot::Loc));
11453                }
11454                self.push(value);
11455            }
11456            PutLocCheck | SetLocCheck => {
11457                let slot = self.slot_operand(op, a);
11458                let value = self.pop();
11459                // The dead zone is a property of the **slot**, not of the value being
11460                // stored: `x = 1; let x` is a `ReferenceError` because `x` has not been
11461                // initialised yet. Testing the value instead — which is never
11462                // `Uninitialized` in practice — let every such store through, so the check
11463                // only ever fired for an explicit `x = undefined`-shaped accident. Reads
11464                // (`get_loc_check`) were already asking the slot, which is why
11465                // `print(x); let x` threw while `x = 1; let x` did not.
11466                if matches!(self.get_loc(slot), Value::Uninitialized) {
11467                    return Err(self.dead_zone(slot, VarSlot::Loc));
11468                }
11469                // The initialiser goes through `put_loc`, not this, so any store that
11470                // reaches here is a later assignment — which a `const` refuses.
11471                if self.is_read_only(slot, VarSlot::Loc) {
11472                    return Err(self.read_only(slot, VarSlot::Loc));
11473                }
11474                if op == SetLocCheck {
11475                    self.put_loc(slot, value.clone());
11476                    self.push(value);
11477                } else {
11478                    self.put_loc(slot, value);
11479                }
11480            }
11481            PutLocCheckInit => {
11482                // The one store that *initialises* a lexical slot: `this` in a derived
11483                // constructor, which only exists after `super()` has run. A second
11484                // initialisation is the error the reference reports as
11485                // "'this' can be initialized only once".
11486                let slot = self.slot_operand(op, a);
11487                let value = self.pop();
11488                if !matches!(self.get_loc(slot), Value::Uninitialized) {
11489                    return Err(Signal::Throw(self.make_error(
11490                        "ReferenceError",
11491                        "'this' can be initialized only once",
11492                    )));
11493                }
11494                self.put_loc(slot, value);
11495            }
11496            CheckCtor => {
11497                // A class constructor may only run under `new`, which is what makes
11498                // `class A {}; A()` a TypeError.
11499                if matches!(self.frame().new_target, Value::Undefined) {
11500                    return Err(Signal::Throw(self.make_error(
11501                        "TypeError",
11502                        "class constructors must be invoked with 'new'",
11503                    )));
11504                }
11505            }
11506            InitCtor => {
11507                // The body a derived class gets when it declares no constructor:
11508                // forward every argument to the parent constructor, keeping `new.target`.
11509                if matches!(self.frame().new_target, Value::Undefined) {
11510                    return Err(Signal::Throw(self.make_error(
11511                        "TypeError",
11512                        "class constructors must be invoked with 'new'",
11513                    )));
11514                }
11515                let Some(callee) = self.current_callee() else {
11516                    return Err(Signal::Throw(
11517                        self.make_error("TypeError", "no constructor to inherit from"),
11518                    ));
11519                };
11520                let parent = callee.proto().map_or(Value::Null, Value::Object);
11521                let new_target = self.frame().new_target.clone();
11522                let args = self.frame().passed().to_vec();
11523                let result = self.construct(parent, new_target, args)?;
11524                self.push(result);
11525            }
11526            SetLocUninitialized => {
11527                let slot = self.slot_operand(op, a);
11528                self.put_loc(slot, Value::Uninitialized);
11529            }
11530            CloseLoc => {
11531                // "Close" a binding: give it a *fresh* cell holding the current
11532                // value. Closures created before this point keep the old cell and the
11533                // ones created after see the new one, which is what makes every
11534                // iteration of `for (let i ...)` capture its own `i`, and what freezes
11535                // a block-scoped binding when the block ends.
11536                //
11537                // Clearing the slot instead (which this used to do) broke both: a
11538                // closure over a captured block variable read `undefined`, and a loop
11539                // terminated after one iteration.
11540                let slot = self.slot_operand(op, a);
11541                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
11542                if index >= 0 {
11543                    let current = self.frame().cells[index as usize].get();
11544                    let fresh = self.new_cell(current);
11545                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
11546                        *cell = fresh;
11547                    }
11548                }
11549            }
11550            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
11551                let slot = self.slot_operand(op, a);
11552                let value = self.get_arg(slot);
11553                self.push(value);
11554            }
11555            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
11556                let slot = self.slot_operand(op, a);
11557                let value = self.pop();
11558                self.put_arg(slot, value);
11559            }
11560            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
11561                let slot = self.slot_operand(op, a);
11562                let value = self.pop();
11563                self.put_arg(slot, value.clone());
11564                self.push(value);
11565            }
11566
11567            // -- closure variables ------------------------------------------
11568            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
11569                let slot = self.slot_operand(op, a);
11570                // A name a direct `eval` created shadows the binding the compiler chose.
11571                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
11572                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
11573                // and only a runtime lookup can know that.
11574                if let Some(cell) = self.eval_created_local(slot) {
11575                    self.push(cell.get());
11576                    return self.step();
11577                }
11578                let value = self.cell_value(slot)?;
11579                self.push(value);
11580            }
11581            GetVarRefCheck => {
11582                let slot = self.slot_operand(op, a);
11583                let value = self.cell_value(slot)?;
11584                if matches!(value, Value::Uninitialized) {
11585                    return Err(self.dead_zone(slot, VarSlot::Closure));
11586                }
11587                self.push(value);
11588            }
11589            PutVarRefCheckInit => {
11590                // The captured-form twin of `PutLocCheckInit`. Both exist because `super()`
11591                // may be written inside an arrow, and there `this` is a var-ref rather than
11592                // a local.
11593                let slot = self.slot_operand(op, a);
11594                let value = self.pop();
11595                // The wording differs from the local form because the reference reaches
11596                // this case through `get_var_ref_checkthis`, which reports the dead zone
11597                // rather than the double initialisation.
11598                if !matches!(self.cell_value(slot)?, Value::Uninitialized) {
11599                    return Err(Signal::Throw(
11600                        self.make_error("ReferenceError", "this is not initialized"),
11601                    ));
11602                }
11603                self.set_cell(slot, value)?;
11604            }
11605            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
11606                let slot = self.slot_operand(op, a);
11607                let value = self.pop();
11608                if let Some(cell) = self.eval_created_local(slot) {
11609                    cell.set(value);
11610                    return self.step();
11611                }
11612                // Same two rules as `PutLocCheck`: a checked store to a captured binding
11613                // asks the cell about the dead zone, then refuses a `const` whose
11614                // initialiser has already run.
11615                if op == PutVarRefCheck {
11616                    let current = self.cell_value(slot)?;
11617                    if matches!(current, Value::Uninitialized) {
11618                        return Err(self.dead_zone(slot, VarSlot::Closure));
11619                    }
11620                    if self.is_read_only(slot, VarSlot::Closure) {
11621                        return Err(self.read_only(slot, VarSlot::Closure));
11622                    }
11623                }
11624                self.set_cell(slot, value)?;
11625            }
11626            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
11627                let slot = self.slot_operand(op, a);
11628                let value = self.pop();
11629                if let Some(cell) = self.eval_created_local(slot) {
11630                    cell.set(value.clone());
11631                    self.push(value);
11632                    return self.step();
11633                }
11634                self.set_cell(slot, value.clone())?;
11635                self.push(value);
11636            }
11637
11638            // -- globals ----------------------------------------------------
11639            GetVar => {
11640                let value = self.get_global(a as usize)?;
11641                self.push(value);
11642            }
11643            GetVarUndef => {
11644                let slot = a as usize;
11645                // `typeof undeclared` answers `"undefined"`; `typeof x` where `x` is in its
11646                // **dead zone** still throws (§13.5.3 evaluates the operand as a Reference
11647                // and `GetValue`s it, and only the unresolvable case is forgiven).
11648                //
11649                // The distinction is made by asking whether a binding exists at all: a name
11650                // in the realm's lexical table is declared, so a `ReferenceError` from
11651                // reading it is the dead zone talking. Swallowing every error made
11652                // `eval("typeof x; let x;")` print `"undefined"`.
11653                let declared = self.realm.globals.contains_key(&self.global_name(slot));
11654                let value = if declared {
11655                    self.get_global(slot)?
11656                } else {
11657                    match self.get_global(slot) {
11658                        Ok(value) => value,
11659                        Err(Signal::Throw(_)) => Value::Undefined,
11660                        Err(other) => return Err(other),
11661                    }
11662                };
11663                self.push(value);
11664            }
11665            DeleteVar => {
11666                // `delete name` for a name that is not a declared binding. A lexical
11667                // global lives in the reference table and cannot be deleted; anything
11668                // reachable only as a property of the global object is *implicit* —
11669                // `x = 1` with no declaration — and goes away if it is configurable,
11670                // which is what `delete` on an implicit global answers.
11671                let name = self.atom_text(a as usize);
11672                let global = self.realm.global.clone();
11673                let deleted = if self.realm.globals.contains_key(&name) {
11674                    false
11675                } else if global.own_property(&name).is_some() {
11676                    self.delete_property(&global, &name)?
11677                } else {
11678                    true
11679                };
11680                self.push(Value::Bool(deleted));
11681            }
11682            PutVar => {
11683                let value = self.pop();
11684                self.put_global(a as usize, value)?;
11685            }
11686            PutVarInit => {
11687                let slot = a as usize;
11688                let value = self.pop();
11689                self.init_global(slot, value)?;
11690            }
11691
11692            // -- arithmetic -------------------------------------------------
11693            Add => self.binary_add()?,
11694            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
11695                let raw_right = self.pop();
11696                let raw_left = self.pop();
11697                // Two numbers need no `ToPrimitive` at all, which is every `x - y` and
11698                // `flags | mask` in real code.
11699                if is_number(&raw_left) && is_number(&raw_right) {
11700                    self.push(arithmetic(op, raw_left, raw_right)?);
11701                } else {
11702                    // §13.15.3 steps 1–3: **both** operands are made primitive before the
11703                    // disjointness check, left first. Getting the order wrong was observable
11704                    // — `ToPrimitive` on the right ran first, so a `valueOf` log read `b,a`
11705                    // and a throw from the *left* operand never happened
11706                    // (`S11.10.1_A2.3_T1`, `order-of-evaluation`).
11707                    //
11708                    // Doing the check on the *primitives* rather than on the raw values is
11709                    // the second half: `Object(5n) & Object(3n)` has a bigint on neither
11710                    // side of the stack yet, so the old check sent it down the `ToNumber`
11711                    // path and raised "cannot convert bigint to number"
11712                    // (`bigint-non-primitive`).
11713                    let left = self.primitive_of(raw_left)?;
11714                    let right = self.primitive_of(raw_right)?;
11715                    // BigInt arithmetic is a separate path, and not only for the type of
11716                    // the result: `ToNumber` of a bigint throws, so mixing the two must be
11717                    // an error rather than a silent conversion.
11718                    if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
11719                        let value = self.bigint_arithmetic(op, left, right)?;
11720                        self.push(value);
11721                    } else {
11722                        let right = self.numeric(right)?;
11723                        let left = self.numeric(left)?;
11724                        self.push(arithmetic(op, left, right)?);
11725                    }
11726                }
11727            }
11728            Neg => {
11729                let raw = self.pop();
11730                match raw {
11731                    // A bigint negates exactly, however wide it is.
11732                    Value::BigInt(big) => {
11733                        let negated = big.negate();
11734                        self.push(self.bigint(negated));
11735                    }
11736                    other => {
11737                        let value = self.numeric_operand(other)?;
11738                        if let Value::BigInt(big) = &value {
11739                            let negated = big.negate();
11740                            self.push(self.bigint(negated));
11741                        } else {
11742                            self.push(negate(value));
11743                        }
11744                    }
11745                }
11746            }
11747            Plus => {
11748                let value = self.pop();
11749                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
11750                // unary plus is defined to produce a *number*, which a bigint cannot
11751                // become without loss. It used to fall through to `NaN`.
11752                if matches!(value, Value::BigInt(_)) {
11753                    return Err(self.type_error("cannot convert bigint to number"));
11754                }
11755                let numeric = self.numeric_of(value)?;
11756                self.push(numeric);
11757            }
11758            Inc => {
11759                let raw = self.pop();
11760                let (_, updated) = self.advance_numeric(raw, true)?;
11761                self.push(updated);
11762            }
11763            Dec => {
11764                let raw = self.pop();
11765                let (_, updated) = self.advance_numeric(raw, false)?;
11766                self.push(updated);
11767            }
11768            PostInc | PostDec => {
11769                // `x -> x x+1`: the *new* value ends up on top, so the store the
11770                // compiler emits right after (`put_var`) writes the incremented
11771                // one, while the old value stays underneath for the expression's
11772                // own result. Getting this backwards makes `i++` a no-op, which
11773                // turns `while (i < 3)` into an infinite loop.
11774                let raw = self.pop();
11775                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
11776                self.push(old);
11777                self.push(updated);
11778            }
11779            Not => {
11780                let raw = self.pop();
11781                match raw {
11782                    // `~x` on a bigint is `-x - 1`, exact at any width.
11783                    Value::BigInt(big) => {
11784                        let inverted = big.bitnot();
11785                        self.push(self.bigint(inverted));
11786                    }
11787                    other => {
11788                        let value = self.numeric_operand(other)?;
11789                        if let Value::BigInt(big) = &value {
11790                            let inverted = big.bitnot();
11791                            self.push(self.bigint(inverted));
11792                        } else {
11793                            self.push(Value::Int(!value.to_int32()));
11794                        }
11795                    }
11796                }
11797            }
11798            Lnot => {
11799                let value = self.pop();
11800                self.push(Value::Bool(!value.to_boolean()));
11801            }
11802
11803            // -- comparison -------------------------------------------------
11804            Lt | Lte | Gt | Gte => {
11805                let right = self.pop();
11806                let left = self.pop();
11807                let answer = self.relational(op, left, right)?;
11808                self.push(answer);
11809            }
11810            Eq | Neq => {
11811                let right = self.pop();
11812                let left = self.pop();
11813                let equal = self.abstract_equals(left, right)?;
11814                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
11815            }
11816            StrictEq => {
11817                let right = self.pop();
11818                let left = self.pop();
11819                self.push(Value::Bool(left.strict_equals(&right)));
11820            }
11821            StrictNeq => {
11822                let right = self.pop();
11823                let left = self.pop();
11824                self.push(Value::Bool(!left.strict_equals(&right)));
11825            }
11826            IsUndefined => {
11827                // `=== undefined`, which is what a destructuring default tests. It is
11828                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
11829                let value = self.pop();
11830                self.push(Value::Bool(matches!(value, Value::Undefined)));
11831            }
11832            IsUndefinedOrNull => {
11833                let value = self.pop();
11834                self.push(Value::Bool(value.is_nullish()));
11835            }
11836            Typeof => {
11837                let value = self.pop();
11838                self.push(self.string(value.type_of()));
11839            }
11840            ToObject => {
11841                // A destructuring *object* pattern starts here, which is why
11842                // `var {} = null` throws. Only `undefined` and `null` are refused; a
11843                // primitive is boxed.
11844                let value = self.pop();
11845                let object = self.object_from(&value)?;
11846                self.push(Value::Object(object));
11847            }
11848            Instanceof => {
11849                let constructor = self.pop();
11850                let object = self.pop();
11851                // `InstanceofOperator`, not `OrdinaryHasInstance`: the operator consults
11852                // `Symbol.hasInstance` first and throws for a right-hand side that is not an
11853                // object (step 1) or not callable (step 4). Calling `instance_of` directly
11854                // skipped both the protocol and the two `TypeError`s.
11855                let answer = self.instance_of_operator(&object, &constructor)?;
11856                self.push(Value::Bool(answer));
11857            }
11858            In => {
11859                let object = self.pop();
11860                let key = self.pop();
11861                let answer = self.has_property(&key, &object)?;
11862                self.push(Value::Bool(answer));
11863            }
11864            WithHasVar => {
11865                // `obj -> bool`: does this `with` object bind the name?
11866                //
11867                // §9.1.1.2.1 `HasBinding` for an Object Environment Record is **not**
11868                // `HasProperty`: step 2 skips the property entirely when the object's
11869                // `Symbol.unscopables` lists it. So `globalThis[Symbol.unscopables] = {v:
11870                // true}` makes `with (globalThis) { v }` read the *outer* `v`, which is what
11871                // the thirty-odd `unscopables-with` cases assert.
11872                //
11873                // One instruction rather than a hand-expanded sequence of `in`, a
11874                // `Symbol.unscopables` lookup and a second `in`: the same question is asked
11875                // by both the read/write guard and `delete`, and a compiler-side expansion
11876                // would be about ten instructions per name per `with` object.
11877                let object = self.pop();
11878                let name = self.atom_text(a as usize);
11879                let bound = self.with_has_binding(&object, &name)?;
11880                self.push(Value::Bool(bound));
11881            }
11882            WithGetVar => {
11883                // `obj -> value`: the second half of `GetBindingValue`.
11884                let object = self.pop();
11885                let name = self.atom_text(a as usize);
11886                let value = self.with_get_binding(&object, &name)?;
11887                self.push(value);
11888            }
11889            WithPutVar => {
11890                // `obj value ->`: the second half of `SetMutableBinding`. The operand order
11891                // is `put_field`'s (value on top), not the reference's, so that the
11892                // read-modify-write shapes (`perm3`/`insert2`) can be shared with the
11893                // member-expression forms.
11894                let value = self.pop();
11895                let object = self.pop();
11896                let name = self.atom_text(a as usize);
11897                self.with_put_binding(&object, &name, value)?;
11898            }
11899
11900            // -- control flow -----------------------------------------------
11901            Goto | Goto8 | Goto16 => {
11902                self.frame_mut().pc = a as usize;
11903            }
11904            IfTrue | IfTrue8 => {
11905                let value = self.pop();
11906                if value.to_boolean() {
11907                    self.frame_mut().pc = a as usize;
11908                }
11909            }
11910            IfFalse | IfFalse8 => {
11911                let value = self.pop();
11912                if !value.to_boolean() {
11913                    self.frame_mut().pc = a as usize;
11914                }
11915            }
11916            Catch => {
11917                // Pushes the handler target onto the value stack; `unwind` finds it.
11918                self.push(Value::CatchOffset(a));
11919            }
11920            Gosub => {
11921                self.push(Value::ReturnAddress(next as u32));
11922                self.frame_mut().pc = a as usize;
11923            }
11924            Ret => {
11925                let value = self.pop();
11926                match value {
11927                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
11928                    _ => {
11929                        return Err(Signal::Throw(
11930                            self.make_error("InternalError", "invalid return address"),
11931                        ));
11932                    }
11933                }
11934            }
11935            NipCatch => {
11936                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
11937                // including the marker, keeping the top value.
11938                let top = self.pop();
11939                loop {
11940                    match self.pop() {
11941                        Value::CatchOffset(_) | Value::Undefined => break,
11942                        _ => {}
11943                    }
11944                    if self.frame().stack.is_empty() {
11945                        break;
11946                    }
11947                }
11948                self.push(top);
11949            }
11950            Throw => {
11951                let value = self.pop();
11952                return Err(Signal::Throw(value));
11953            }
11954            ThrowError => {
11955                let name = self.atom_text(a as usize);
11956                let (class, message) = match b {
11957                    0 => ("TypeError", format!("'{name}' is read-only")),
11958                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
11959                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
11960                    // `delete super.x` is a syntax-level mistake the reference reports
11961                    // with this wording, not a property-access failure.
11962                    3 => (
11963                        "ReferenceError",
11964                        "unsupported reference to 'super'".to_string(),
11965                    ),
11966                    4 => (
11967                        "TypeError",
11968                        "iterator does not have a throw method".to_string(),
11969                    ),
11970                    5 => (
11971                        "ReferenceError",
11972                        "invalid assignment left-hand side".to_string(),
11973                    ),
11974                    _ => ("TypeError", format!("invalid operation on '{name}'")),
11975                };
11976                return Err(Signal::Throw(self.make_error(class, &message)));
11977            }
11978            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
11979            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
11980            YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
11981            AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
11982            Await => return Ok(Step::Suspend(SuspendKind::Await)),
11983            ReturnAsync => {
11984                // The reference's `return_async` returns `undefined` and lets the resume
11985                // machinery pick the real value off `sp[-1]`, which is how it tells a
11986                // completion from a suspension. Carrying the value explicitly says the
11987                // same thing without the implicit stack slot.
11988                let value = self.pop();
11989                return Ok(Step::Return(value));
11990            }
11991            Return => {
11992                let value = self.pop();
11993                return Ok(Step::Return(value));
11994            }
11995            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
11996
11997            // -- calls ------------------------------------------------------
11998            Call | Call0 | Call1 | Call2 | Call3 => {
11999                let argc = self.argc_operand(op, a);
12000                let args = self.pop_n(argc);
12001                let callee = self.pop();
12002                // A plain call has no receiver; the callee decides what to do with
12003                // `undefined` (a sloppy function substitutes the global object).
12004                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
12005                    self.push(result);
12006                }
12007            }
12008            CallConstructor => {
12009                // `constructor this_obj args… -> object`. The duplicated
12010                // constructor is `new.target`; this milestone does not expose it,
12011                // so the extra copy is simply consumed here.
12012                let argc = a as usize;
12013                let args = self.pop_n(argc);
12014                let new_target = self.pop();
12015                let callee = self.pop();
12016                let result = self.construct(callee, new_target, args)?;
12017                self.push(result);
12018            }
12019            CallMethod => {
12020                let argc = a as usize;
12021                let args = self.pop_n(argc);
12022                let callee = self.pop();
12023                let this = self.pop();
12024                if let Some(result) = self.call_or_push(callee, this, args)? {
12025                    self.push(result);
12026                }
12027            }
12028            Apply => {
12029                // `func this array -> result`, the spread-call form: the compiler
12030                // builds one array of arguments, and all that is left here is to
12031                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
12032                let array = self.pop();
12033                let this = self.pop();
12034                let callee = self.pop();
12035                let args = self.array_like_to_args(&array)?;
12036                if a & 1 != 0 {
12037                    let result = self.construct(callee, this, args)?;
12038                    self.push(result);
12039                } else if let Some(result) = self.call_or_push(callee, this, args)? {
12040                    self.push(result);
12041                }
12042            }
12043            TailCall | TailCallMethod => {
12044                // `tail_call` is `call` whose result is returned immediately — the
12045                // reference jumps straight to `done` instead of storing the value and
12046                // running on. The callee still gets its own frame, so deep tail
12047                // recursion hits the stack limit exactly like plain recursion does;
12048                // marking this frame lets the return path unwind without needing
12049                // instructions after the call.
12050                let argc = if op == TailCallMethod {
12051                    a as usize
12052                } else {
12053                    self.argc_operand(op, a)
12054                };
12055                let args = self.pop_n(argc);
12056                let callee = self.pop();
12057                let this = if op == TailCallMethod {
12058                    self.pop()
12059                } else {
12060                    Value::Undefined
12061                };
12062                if let Value::Object(function) = &callee
12063                    && let Some((code, env)) = bytecode_of(function)
12064                {
12065                    // A generator or async body is not run here at all: calling it only
12066                    // *creates* the generator/coroutine, so it must not inherit this
12067                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
12068                    // onto `f`'s frame, and the first `yield`/`await` then reported
12069                    // "a generator body ran as an ordinary call".
12070                    if code.code.kind.is_generator() || code.code.kind.is_async() {
12071                        let value = self.call_value(callee, this, args)?;
12072                        return Ok(Step::Return(value));
12073                    }
12074                    self.frame_mut().tail = true;
12075                    self.push_frame(code, env, this, args, callee)?;
12076                    return Ok(Step::Continue);
12077                }
12078                // A native callee has no frame to reuse, so its value is simply
12079                // returned.
12080                let value = self.call_value(callee, this, args)?;
12081                return Ok(Step::Return(value));
12082            }
12083
12084            // -- objects ----------------------------------------------------
12085            SpecialObject => {
12086                let value = self.special_object(a)?;
12087                self.push(value);
12088            }
12089            PrivateSymbol => {
12090                // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
12091                // symbol each time it is evaluated, which is why the compiler evaluates it
12092                // once (at class definition) and stores it in a class-scope binding.
12093                let name = self.atom_text(a as usize);
12094                let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
12095                self.push(Value::Symbol(symbol));
12096            }
12097            GetPrivateField => {
12098                // `obj symbol -> value`. A missing private field is a TypeError, which is what
12099                // makes `#x` inaccessible on any object not built by this class.
12100                let symbol = self.pop();
12101                let object = self.pop();
12102                let value = self.read_private_field(&object, &symbol)?;
12103                self.push(value);
12104            }
12105            PutPrivateField => {
12106                // `obj value symbol ->`, and the store is a plain assignment to a property the
12107                // class already created, so there is no setter to consult.
12108                let symbol = self.pop();
12109                let value = self.pop();
12110                let object = self.pop();
12111                self.write_private_field(&object, &symbol, value)?;
12112            }
12113            DefinePrivateField => {
12114                // `obj symbol value -> obj`: a field initialiser creates the property, and
12115                // redefining one is a TypeError ("already exists").
12116                let value = self.pop();
12117                let symbol = self.pop();
12118                let object = self.pop();
12119                self.define_private_field(&object, &symbol, value)?;
12120                self.push(object);
12121            }
12122            PrivateIn => {
12123                // `obj key -> bool`: `#x in o`. The second operand decides which question is
12124                // being asked, which is the reference's `js_operator_private_in`: a *symbol*
12125                // is a field, so this is an own-property test; a *function* is a method or
12126                // accessor, so this is a brand check.
12127                let key = self.pop();
12128                let object = self.pop();
12129                let Some(target) = object.as_object() else {
12130                    return Err(Signal::Throw(
12131                        self.make_error("TypeError", "invalid 'in' operand"),
12132                    ));
12133                };
12134                let present = match &key {
12135                    Value::Object(_) => self.check_brand(target, &key)?,
12136                    _ => target.own_property_key(&self.private_key(&key)?).is_some(),
12137                };
12138                self.push(Value::Bool(present));
12139            }
12140            AddBrand => {
12141                // `obj home ->`: create the class brand on `home` if it has none, then give
12142                // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
12143                // class definition: only the prototype's copy of the symbol is wanted.
12144                let home = self.pop();
12145                let object = self.pop();
12146                self.add_brand(&object, &home)?;
12147            }
12148            CheckBrand => {
12149                // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
12150                // Both stay, because the caller needs them — `nip` halves a read into its
12151                // value and `call_method` uses the pair as receiver and callee.
12152                let function = self.peek(0);
12153                let object = self.peek(1);
12154                let Some(target) = object.as_object() else {
12155                    return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12156                };
12157                if !self.check_brand(target, &function)? {
12158                    return Err(Signal::Throw(
12159                        self.make_error("TypeError", "invalid brand on object"),
12160                    ));
12161                }
12162            }
12163            GetLength => {
12164                // `get_length` is the `.length` read; an array and a string answer
12165                // from their own length, anything else from the property.
12166                let target = self.pop();
12167                let value = match &target {
12168                    Value::Object(object) => match object.array_length() {
12169                        Some(length) => crate::object::length_value(length),
12170                        None => self.read_field(&target, "length")?,
12171                    },
12172                    Value::String(text) => Value::Int(text.utf16_len() as i32),
12173                    _ => self.read_field(&target, "length")?,
12174                };
12175                self.push(value);
12176            }
12177            GetField | GetField2 => {
12178                let object = self.pop();
12179                // Borrowed out of the code object, not cloned: `atom_key` returns an owned
12180                // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
12181                // just below is what lets the borrow outlive the `&mut self` the lookup
12182                // needs — one refcount bump instead of a key clone plus its drop, on the
12183                // hottest property path there is: every `o.x` and every `o.m()` receiver.
12184                let code = self.frame().code.clone();
12185                let key = &code.atom_keys[a as usize];
12186                let value = self.read_field_cached(&object, key, next)?;
12187                if op == GetField2 {
12188                    self.push(object);
12189                }
12190                self.push(value);
12191            }
12192            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
12193                let key = self.pop();
12194                let object = self.pop();
12195                // §7.1.1 `GetValue` step 3 orders these two conversions: `ToObject(V.[[Base]])`
12196                // first, then `ToPropertyKey(V.[[ReferencedName]])`. So a nullish base is a
12197                // `TypeError` and the key is **never coerced** — `null[{toString(){throw}}]`
12198                // throws the TypeError, not the key's exception
12199                // (`S11.3.1_A6_T1`). A write has the opposite order, which is why
12200                // `PutArrayEl` deliberately does not do this.
12201                //
12202                // Only nullish is checked here, and the full boxing is still left to
12203                // `read_field_key`: a string base has an index fast path that turning it
12204                // into a `String` object up front would throw away.
12205                if object.is_nullish() {
12206                    return Err(Signal::Throw(self.make_error(
12207                        "TypeError",
12208                        &format!("cannot read property of {}", object.to_js_string()),
12209                    )));
12210                }
12211                let key = self.propkey(&key)?;
12212                let value = self.read_field_key(&object, &key)?;
12213                if matches!(op, GetArrayEl2 | GetArrayEl3) {
12214                    self.push(object);
12215                }
12216                if op == GetArrayEl3 {
12217                    // The key goes back in its *value* form, which the compiler stores
12218                    // into the target of a destructuring assignment.
12219                    self.push(match &key {
12220                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
12221                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
12222                    });
12223                }
12224                self.push(value);
12225            }
12226            PutField => {
12227                let value = self.pop();
12228                let object = self.pop();
12229                // Borrowed, like the `get_field` arm: `atom_key` would return an owned
12230                // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
12231                // only reads. `this.value = …` is the write half of the hottest loop in
12232                // `property:method-call`, and `own_property_key` was 4.8% of the case.
12233                let code = self.frame().code.clone();
12234                let key = &code.atom_keys[a as usize];
12235                self.write_field_key(&object, key, value)?;
12236            }
12237            PutArrayEl => {
12238                let value = self.pop();
12239                let key = self.pop();
12240                let object = self.pop();
12241                let key = self.propkey(&key)?;
12242                self.write_field_key(&object, &key, value)?;
12243            }
12244            DefineField => {
12245                let value = self.pop();
12246                let object = self.pop();
12247                // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
12248                // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
12249                // three U+FFFD — a property under a different name from the one
12250                // `o["\uD800"]` reads.
12251                let code = self.frame().code.clone();
12252                let key = code.atom_keys[a as usize].clone();
12253                // No naming here. `{m: function(){}}` is named by the *compiler*, which
12254                // emits `set_name` — and only where `NamedEvaluation` applies, so
12255                // `{m: (0, function(){})}` stays anonymous. Naming every function that
12256                // reaches a property definition got that case wrong, and the compiler is
12257                // the only place that can tell the two apart.
12258                self.define_field(&object, &key, value)?;
12259                self.push(object);
12260            }
12261            DefineArrayEl => {
12262                // `obj key value -> obj key`. The *value* form of the key is what goes
12263                // back on the stack — the compiler stores it into the pattern's binding —
12264                // so the symbol is not stringified on the way through.
12265                //
12266                // `define_field` and not `write_field_key`: this is `CreateDataProperty`,
12267                // and only the define algorithm gives `{ ['__proto__']: v }` an ordinary
12268                // own property. Going through `[[Set]]` found `Object.prototype`'s
12269                // `__proto__` accessor on the prototype chain and *changed the prototype*
12270                // instead, and it would have called a user setter from a literal
12271                // (`computed-__proto__`, `__proto__-duplicate-computed`).
12272                let value = self.pop();
12273                let key_value = self.pop();
12274                let object = self.peek(0);
12275                let key = self.propkey(&key_value)?;
12276                self.define_field(&object, &key, value)?;
12277                self.push(key_value);
12278            }
12279            SetHomeObject => {
12280                // `obj func -> obj func`: records the object a method was defined on so
12281                // `super` inside it resolves against that object's prototype.
12282                let function = self.peek(0);
12283                let home = self.peek(1);
12284                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
12285                    function.set_home_object(Some(home.clone()));
12286                }
12287            }
12288            Regexp => {
12289                // `pattern flags -> regexp`. A literal compiles here rather than through the
12290                // constructor, which is both what the reference's dedicated opcode is for
12291                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
12292                let flags = self.pop();
12293                let pattern = self.pop();
12294                let pattern = self.checked_to_wtf8(&pattern)?;
12295                let flags = self.to_js_string(&flags)?;
12296                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
12297                self.push(Value::Object(object));
12298            }
12299            UsingDisposeInit => {
12300                // The error state a disposal accumulates into. Uninitialised means "no
12301                // failure yet"; anything else is the exception being propagated.
12302                self.push(Value::Uninitialized);
12303            }
12304            UsingCheck => {
12305                // `value -> value, method`: validate and snapshot the disposer now, so a
12306                // later change to `Symbol.dispose` cannot change what gets called, and so a
12307                // value that is not disposable fails before the body runs.
12308                let value = self.pop();
12309                let method = self.using_method_for(&value, a as u8 == 1)?;
12310                self.push(value);
12311                self.push(method);
12312            }
12313            UsingDispose => {
12314                // `error_state -> error_state'`: dispose the variable at `slot` — its value
12315                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
12316                // the pending error.
12317                let slot = self.slot_operand(op, a);
12318                let error_state = self.pop();
12319                let merged = self.using_dispose_once(slot, error_state)?;
12320                self.push(merged);
12321            }
12322            UsingDisposeMerge => {
12323                let new_error = self.pop();
12324                let error_state = self.pop();
12325                let merged = self.merge_dispose_error(new_error, error_state);
12326                self.push(merged);
12327            }
12328            UsingDisposeEnd => {
12329                // A disposal that failed replaces the block's normal completion, so the
12330                // error state becomes a real throw here rather than at the call site.
12331                let error_state = self.pop();
12332                if !matches!(error_state, Value::Uninitialized) {
12333                    return Err(Signal::Throw(error_state));
12334                }
12335            }
12336            // -- references -------------------------------------------------
12337            //
12338            // §6.2.5's Reference, as a value the operand stack can carry. Only emitted
12339            // where a direct `eval` could declare a shadowing `var` between the read and
12340            // the store (§13.15.3 resolves the lvalue once), so nothing hot goes through
12341            // here.
12342            MakeLocRef | MakeArgRef | MakeVarRefRef | MakeVarRef => {
12343                let name = self.atom_wtf8(a as usize);
12344                let target = match op {
12345                    // A *global*: the name is looked up afresh, because an `eval` earlier in
12346                    // this very function may already have declared it as a local, and
12347                    // because an implicit global may not exist at all.
12348                    MakeVarRef => self.global_reference(&name)?,
12349                    // A slot. `eval_created_local` is the same override an ordinary
12350                    // `get_var_ref` makes, so `eval("var x = 9"); x *= (…)` reads the eval's
12351                    // `x` while `x *= (eval("var x = 2"), 4)` reads the outer one — the
12352                    // difference is only *when* the reference was taken.
12353                    // A slot. Three cases, and the first two are easy to confuse:
12354                    //
12355                    // * a *local* or *argument* — its cell number is in `loc_cell`/`arg_cell`,
12356                    //   not the slot itself, and `resolve` has already forced it to be
12357                    //   captured so a cell exists;
12358                    // * a *global* reached through the closure table — the cell there is a
12359                    //   placeholder (`is_global_slot`), so the binding has to be reached by
12360                    //   name after all;
12361                    // * anything else in the closure table — a real cell, but a direct `eval`
12362                    //   may have shadowed the name with a fresh local, and that shadow is what
12363                    //   an ordinary read would find.
12364                    MakeVarRefRef if self.is_global_slot(b as usize) => {
12365                        self.global_reference(&name)?
12366                    }
12367                    _ => {
12368                        let slot = b as usize;
12369                        let cell = match op {
12370                            MakeLocRef => self
12371                                .frame()
12372                                .code
12373                                .loc_cell
12374                                .get(slot)
12375                                .copied()
12376                                .filter(|cell| *cell >= 0)
12377                                .and_then(|cell| self.frame().cells.get(cell as usize).cloned()),
12378                            MakeArgRef => self
12379                                .frame()
12380                                .code
12381                                .arg_cell
12382                                .get(slot)
12383                                .copied()
12384                                .filter(|cell| *cell >= 0)
12385                                .and_then(|cell| self.frame().cells.get(cell as usize).cloned()),
12386                            _ => self.eval_created_local(slot),
12387                        };
12388                        match cell.or_else(|| self.frame().env.cells.get(slot).cloned()) {
12389                            Some(cell) => RefTarget::Cell(cell),
12390                            None => {
12391                                return Err(Signal::Throw(self.make_error(
12392                                    "InternalError",
12393                                    "a reference to a slot with no cell",
12394                                )));
12395                            }
12396                        }
12397                    }
12398                };
12399                let object = self.new_object(None);
12400                object.set_reference(target);
12401                self.push(Value::Object(object));
12402            }
12403            GetRefValue => {
12404                // `[ref] -> [ref, value]`: the reference stays, exactly like a `get_field2`,
12405                // so a second half can store through it.
12406                let reference = self.reference_target(0)?;
12407                let value = match reference {
12408                    RefTarget::Cell(cell) => cell.get(),
12409                    RefTarget::Property { base, name } => {
12410                        // An unresolvable reference is a name that is on neither the global
12411                        // binding table nor the global object, and reading one is a
12412                        // `ReferenceError` in every mode (§6.2.5.5).
12413                        if matches!(base, Value::Undefined) {
12414                            return Err(self.throw_reference(
12415                                &name
12416                                    .as_wtf8()
12417                                    .map(|t| t.to_string_lossy().into_owned())
12418                                    .unwrap_or_default(),
12419                            ));
12420                        }
12421                        self.get_property_key(
12422                            base.as_object().ok_or_else(|| {
12423                                self.type_error("a reference base must be an object")
12424                            })?,
12425                            &name,
12426                        )?
12427                        .unwrap_or(Value::Undefined)
12428                    }
12429                };
12430                self.push(value);
12431            }
12432            PutRefValue => {
12433                // `[ref, value] -> []`.
12434                let value = self.pop();
12435                let reference = self.reference_target(0)?;
12436                self.pop();
12437                match reference {
12438                    RefTarget::Cell(cell) => cell.set(value),
12439                    RefTarget::Property { base, name } => {
12440                        if matches!(base, Value::Undefined) {
12441                            // Sloppy code creates the global; strict code refuses
12442                            // (§9.1.1.4.6 `SetMutableBinding` on an unresolvable name).
12443                            if self.current_strict() {
12444                                return Err(self.throw_reference(
12445                                    &name
12446                                        .as_wtf8()
12447                                        .map(|t| t.to_string_lossy().into_owned())
12448                                        .unwrap_or_default(),
12449                                ));
12450                            }
12451                            let global = self.realm.global.clone();
12452                            self.set_property_with_key(
12453                                &global,
12454                                &name,
12455                                value,
12456                                DeleteFailure::Ignore,
12457                            )?;
12458                        } else {
12459                            let object = base.as_object().ok_or_else(|| {
12460                                self.type_error("a reference base must be an object")
12461                            })?;
12462                            self.set_property_with_key(object, &name, value, DeleteFailure::Throw)?;
12463                        }
12464                    }
12465                }
12466            }
12467            UsingDisposeAsync => {
12468                // `error_state -> error_state, promise`: the disposer is called here and
12469                // its result wrapped, so the `await` the compiler emits next is what
12470                // actually waits. Calling it and dropping the result lost every failure
12471                // from an `async [Symbol.asyncDispose]` — the rejection had no handler and
12472                // no path back into the error state
12473                // (`throws-error-as-is-if-only-one-error-during-disposal`).
12474                let slot = self.slot_operand(op, a);
12475                let error_state = self.pop();
12476                let value = self.get_loc(slot);
12477                let method = self.get_loc(slot + 1);
12478                let promise = if value.is_nullish()
12479                    || matches!(value, Value::Uninitialized)
12480                    || matches!(method, Value::Undefined | Value::Uninitialized)
12481                {
12482                    // Nothing to dispose: `await undefined` is a no-op, as it is in the
12483                    // reference (`sp[0] = JS_UNDEFINED`).
12484                    Value::Undefined
12485                } else {
12486                    let result = self.call_value(method, value, Vec::new())?;
12487                    self.promise_resolve_value(result)?
12488                };
12489                self.push(error_state);
12490                self.push(promise);
12491            }
12492            GetSuper => {
12493                // `obj -> obj's prototype`: the starting point of a `super` lookup.
12494                let object = self.pop();
12495                let proto = match &object {
12496                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
12497                    _ => Value::Null,
12498                };
12499                self.push(proto);
12500            }
12501            GetSuperValue => {
12502                // `receiver proto key -> value`, searching from `proto` but reporting to
12503                // `receiver`, which is what `super.g` must do for a getter to see `this`.
12504                //
12505                // Three values in, one out: the receiver is *consumed*, not left under the
12506                // result. Leaving it there was invisible for `super.x` in `return` or
12507                // statement position (the result is what gets popped) and corrupted the
12508                // frame everywhere else — `print(super.x)` left the class where the call
12509                // opcode looks for the receiver and called the class itself.
12510                let key = self.pop();
12511                let proto = self.pop();
12512                let receiver = self.pop();
12513                let value = self.super_read(&receiver, &proto, &key)?;
12514                self.push(value);
12515            }
12516            PutSuperValue => {
12517                // `receiver proto key value ->`: a store that starts at `proto` but
12518                // assigns to `receiver`.
12519                let value = self.pop();
12520                let key = self.pop();
12521                let proto = self.pop();
12522                let receiver = self.pop();
12523                self.super_write(&receiver, &proto, &key, value)?;
12524            }
12525            DefineClass => {
12526                // `parent ctor -> ctor proto`: the constructor becomes the class and a
12527                // fresh prototype object lands on top for the methods to go on.
12528                let name = self.atom_text(a as usize);
12529                let (ctor, proto) = self.define_class(&name, b)?;
12530                self.push(ctor);
12531                self.push(Value::Object(proto));
12532            }
12533            DefineClassComputed => {
12534                // `parent ctor key -> ctor proto key`: the computed name stays put so
12535                // `define_field`-style consumers can still read it.
12536                let key = self.pop();
12537                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
12538                let (ctor, proto) = self.define_class(&name, b)?;
12539                self.push(ctor);
12540                self.push(Value::Object(proto));
12541                self.push(key);
12542            }
12543            DefineMethod => {
12544                let function = self.pop();
12545                let object = self.pop();
12546                // The exact key, like `define_field`: a quoted method key may hold an
12547                // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
12548                // that `o["\uD800"]` finds.
12549                let code = self.frame().code.clone();
12550                let key = code.atom_keys[a as usize].clone();
12551                // A method's `[[HomeObject]]` is the object it was defined on, which is
12552                // what `super` inside it resolves against.
12553                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12554                    function.set_home_object(Some(object.clone()));
12555                }
12556                let name = match key.as_wtf8() {
12557                    Some(text) => text.clone(),
12558                    // A symbol atom — one of the well-known symbols, which the lexer keeps
12559                    // as an atom rather than a runtime value. Its name is the bracketed
12560                    // description, like any other symbol key.
12561                    None => symbol_key_name(&key),
12562                };
12563                self.set_function_name_wtf8(&function, &accessor_prefixed(&name, b));
12564                if let Some(array) = object.as_object()
12565                    && !define_function_property(array, &key, function, b)
12566                {
12567                    return Err(self.type_error("property is not configurable"));
12568                }
12569                self.push(object);
12570            }
12571            DefineMethodComputed => {
12572                let function = self.pop();
12573                let key = self.pop();
12574                let object = self.pop();
12575                let key = self.propkey(&key)?;
12576                // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
12577                // the name: `super` inside a computed method resolves through it. Without
12578                // this, `class B extends A { [k]() { return super.m() } }` read the
12579                // home object as null and threw.
12580                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12581                    function.set_home_object(Some(object.clone()));
12582                }
12583                // A symbol key names the method `[description]`, or `""` without one —
12584                // §7.3.24, the same rule [`Interp::function_name_from_key`] applies to
12585                // `set_name_computed`. Falling back to `to_string` here named every
12586                // `{ [sym](){} }` method `Symbol()` instead.
12587                match &key {
12588                    PropertyKey::Symbol(_) => {
12589                        // The accessor prefix still applies: `get [Symbol.iterator](){}`
12590                        // is named `"get [Symbol.iterator]"`.
12591                        let name = accessor_prefixed(&symbol_key_name(&key), a);
12592                        self.set_function_name_wtf8(&function, &name);
12593                    }
12594                    PropertyKey::String(text) => {
12595                        let name = accessor_prefixed(text, a);
12596                        self.set_function_name_wtf8(&function, &name);
12597                    }
12598                }
12599                if let Some(array) = object.as_object()
12600                    && !define_function_property(array, &key, function, a)
12601                {
12602                    return Err(self.type_error("property is not configurable"));
12603                }
12604                self.push(object);
12605            }
12606            SetProto => {
12607                // `{ __proto__: v }` — §13.2.5.1 step 6: nothing is defined and nothing is
12608                // changed unless `v` is an object or `null`. A primitive was taken as "no
12609                // prototype" instead, so `{ __proto__: undefined }` came out with `null`
12610                // where the answer is an ordinary object
12611                // (`__proto__-value-non-object`).
12612                let proto = self.pop();
12613                let object = self.pop();
12614                if matches!(proto, Value::Null | Value::Object(_))
12615                    && let Some(target) = object.as_object()
12616                {
12617                    target.set_proto(proto.as_object().cloned());
12618                }
12619                self.push(object);
12620            }
12621            CopyDataProperties => {
12622                let exclusion = self.pop();
12623                let source = self.pop();
12624                let target = self.peek(0);
12625                self.copy_properties(&target, &source, &exclusion)?;
12626                self.push(source);
12627                self.push(exclusion);
12628            }
12629            ToPropkey => {
12630                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
12631                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
12632                // ordinary `"Symbol(b)"` property.
12633                let value = self.pop();
12634                let key = match self.propkey(&value)? {
12635                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
12636                    PropertyKey::String(text) => self.string_wtf8(text),
12637                };
12638                self.push(key);
12639            }
12640            SetName => {
12641                let function = self.peek(0);
12642                let name = self.atom_wtf8(a as usize);
12643                self.set_function_name_wtf8(&function, &name);
12644            }
12645            SetNameComputed => {
12646                let key = self.peek(1);
12647                let function = self.peek(0);
12648                let name = self.function_name_from_key(&key)?;
12649                self.set_function_name_wtf8(&function, &name);
12650            }
12651
12652            // -- arrays -----------------------------------------------------
12653            ArrayFrom => {
12654                let count = a as usize;
12655                let elements = self.pop_n(count);
12656                let array = self.new_array(elements);
12657                self.push(Value::Object(array));
12658            }
12659            Append => {
12660                // `array index iterable -> array new_index`
12661                let iterable = self.pop();
12662                self.pop();
12663                let array = self.peek(0);
12664                let added = self.append_enumerate(&array, &iterable)?;
12665                self.push(Value::Int(added));
12666            }
12667
12668            // -- iteration --------------------------------------------------
12669            ForInStart => {
12670                let value = self.pop();
12671                let record = self.for_in_record(&value)?;
12672                self.push(Value::Object(record));
12673            }
12674            ForInNext => {
12675                // `record -> record key done`. The flag is *done*, not "found":
12676                // the compiler tests it with `if_false` to jump back into the body,
12677                // so reporting `true` while keys remain would end the loop at once.
12678                let record = self.peek(0);
12679                match self.for_in_advance(&record)? {
12680                    Some(key) => {
12681                        let text = self.string(key);
12682                        self.push(text);
12683                        self.push(Value::Bool(false));
12684                    }
12685                    None => {
12686                        self.push(Value::Undefined);
12687                        self.push(Value::Bool(true));
12688                    }
12689                }
12690            }
12691            ForOfStart => {
12692                let value = self.pop();
12693                let iterator = self.get_iterator(&value)?;
12694                self.push(iterator.object);
12695                self.push(iterator.next);
12696                self.push(Value::CatchOffset(0));
12697            }
12698            ForOfNext => {
12699                // `iter next catch_offset -> iter next catch_offset value done`.
12700                //
12701                // The operand is how many values sit *above* the iterator triple: a
12702                // destructuring rest element keeps its target array and running index
12703                // there while draining the iterator, so the triple is not at the top.
12704                let extra = a as usize;
12705                let iterator_slot = 2 + extra;
12706                // An exhausted iterator is replaced by `undefined` (see below), so a
12707                // second step must not call `next` again — `Array.from` and a
12708                // destructuring pattern both keep stepping past the end.
12709                let stepped = if matches!(self.peek(iterator_slot), Value::Undefined) {
12710                    Ok((Value::Undefined, true))
12711                } else {
12712                    let iterator = Iterator {
12713                        object: self.peek(iterator_slot),
12714                        next: self.peek(1 + extra),
12715                    };
12716                    self.iterator_step(&iterator)
12717                };
12718                let (value, done) = match stepped {
12719                    Ok(stepped) => stepped,
12720                    Err(signal) => {
12721                        // An exception from `next()` is not an abrupt completion of the
12722                        // *body*, so §7.4.6 does not apply and the iterator must not be
12723                        // closed: `[ , ] = iterable` with a throwing `next` expects
12724                        // `returnCount === 0`. Clearing the slot is how the reference says
12725                        // so (`js_for_of_next`: `sp[offset] = JS_UNDEFINED` before it
12726                        // returns -1), and it is also what makes the destructor below — the
12727                        // exception path's `catch_offset 0` close — a no-op here.
12728                        self.clear_iterator_slot(iterator_slot);
12729                        return Err(signal);
12730                    }
12731                };
12732                if done {
12733                    // The result's `value` is meaningless once the iterator is done:
12734                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
12735                    // rather than binding the generator's return value.
12736                    let top = self.frame().stack.len() - 1 - iterator_slot;
12737                    self.frame_mut().stack[top] = Value::Undefined;
12738                    self.push(Value::Undefined);
12739                    self.push(Value::Bool(true));
12740                } else {
12741                    self.push(value);
12742                    self.push(Value::Bool(false));
12743                }
12744            }
12745            IteratorNext => {
12746                // `iter next catch val -> iter next catch val'`: replace the argument with
12747                // the result of `next(val)`. The triple below stays put, which is why the
12748                // three instructions of the `yield*` loop all address the stack the same way.
12749                let value = self.pop();
12750                let object = self.peek(2);
12751                let next = self.peek(1);
12752                let result = self.call_value(next, object, vec![value])?;
12753                self.push(result);
12754            }
12755            IteratorCall => {
12756                // `iter next catch val -> iter next catch val' flag`.
12757                //
12758                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
12759                // The flag is `true` when the method was missing, which is how the
12760                // caller learns that the inner iterator cannot take part in the
12761                // unwinding.
12762                let value = self.pop();
12763                let object = self.peek(2);
12764                let key = if a & 1 != 0 { "throw" } else { "return" };
12765                let method = self.read_field(&object, key)?;
12766                if matches!(method, Value::Undefined | Value::Null) {
12767                    self.push(value);
12768                    self.push(Value::Bool(true));
12769                } else {
12770                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
12771                    let result = self.call_value(method, object, argument)?;
12772                    self.push(result);
12773                    self.push(Value::Bool(false));
12774                }
12775            }
12776            IteratorCheckObject => {
12777                if !matches!(self.peek(0), Value::Object(_)) {
12778                    return Err(Signal::Throw(
12779                        self.make_error("TypeError", "iterator must return an object"),
12780                    ));
12781                }
12782            }
12783            IteratorClose => {
12784                // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
12785                // calling the iterator's `return` so it can release whatever it holds.
12786                //
12787                // The catch offset goes first, so an exception from `return` is not caught
12788                // by the loop being abandoned. This used to pop the three operands and call
12789                // nothing at all, which made `break` out of a `for of` invisible to an
12790                // iterator with a `return` method.
12791                self.pop();
12792                self.pop();
12793                let iterator = self.pop();
12794                if !matches!(iterator, Value::Undefined) {
12795                    let method = self.read_field(&iterator, "return")?;
12796                    if !matches!(method, Value::Undefined | Value::Null) {
12797                        let result = self.call_value(method, iterator.clone(), Vec::new())?;
12798                        // §7.4.6: a `return` that answers a non-object is a TypeError.
12799                        if !matches!(result, Value::Object(_)) {
12800                            return Err(Signal::Throw(
12801                                self.make_error("TypeError", "iterator must return an object"),
12802                            ));
12803                        }
12804                    }
12805                }
12806            }
12807            Import | ImportDefer | ImportSource => {
12808                // `import(specifier, options)`: the options slot is on top. Both are
12809                // `GetValue`-ed by the compiler, which is why this pops values rather than
12810                // references — and why the validation of `options` (§13.3.10.1 step 10)
12811                // happens inside `dynamic_import`, where its failures can be turned into a
12812                // rejection instead of a throw.
12813                //
12814                // The proposal forms have the same stack shape and no options bag: the
12815                // compiler pushes a literal `undefined`, and the phase is the opcode.
12816                let phase = match op {
12817                    ImportDefer => js_parse::ast::ImportPhase::Defer,
12818                    ImportSource => js_parse::ast::ImportPhase::Source,
12819                    _ => js_parse::ast::ImportPhase::Evaluation,
12820                };
12821                let options = self.pop();
12822                let specifier = self.pop();
12823                let promise = self.dynamic_import(specifier, options, phase)?;
12824                self.push(promise);
12825            }
12826            ForAwaitOfStart => {
12827                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
12828                // `Symbol.iterator` fallback.
12829                let value = self.pop();
12830                let iterator = self.get_async_iterator(&value)?;
12831                self.push(iterator.object);
12832                self.push(iterator.next);
12833                self.push(Value::CatchOffset(0));
12834            }
12835            ForAwaitOfNext => {
12836                // `for await` steps the iterator and leaves the *result* wrapped in a
12837                // promise, so the `await` the compiler emits right after this can suspend
12838                // on it. Unwrapping happens in `iterator_get_value_done`.
12839                let extra = a as usize;
12840                let iterator_slot = 2 + extra;
12841                // The enumerator marker is **disabled for the step**, and
12842                // `iterator_get_value_done` puts it back once the result has survived the
12843                // awaiting. Both halves are load-bearing for the async case:
12844                //
12845                // * a rejection is not "the body threw", so the loop must not close the
12846                //   iterator *again* — the wrapper already did;
12847                // * but until the result arrives the record is live, so a later failure
12848                //   still has to close it.
12849                //
12850                // The reference says the same in one line each
12851                // (`js_for_await_of_next`: `sp[-1] = JS_UNDEFINED; /* disable the catch
12852                // offset so that exceptions do not close the iterator */`).
12853                self.clear_iterator_slot(extra);
12854                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
12855                    Value::Undefined
12856                } else {
12857                    let iterator = Iterator {
12858                        object: self.peek(iterator_slot),
12859                        next: self.peek(1 + extra),
12860                    };
12861                    let next = iterator.next.clone();
12862                    self.call_value(next, iterator.object, Vec::new())?
12863                };
12864                let promise = self.promise_resolve_value(result)?;
12865                self.push(promise);
12866            }
12867            IteratorGetValueDone => {
12868                // `result -> value done`. A missing result object means the iterator was
12869                // already exhausted, which the loop treats as `done`.
12870                let result = self.pop();
12871                // Re-arm the marker `for_await_of_next` disabled; the step got this far, so
12872                // from here on the record is closeable again.
12873                {
12874                    let depth = self.frame().stack.len();
12875                    if depth >= 2 {
12876                        self.frame_mut().stack[depth - 1] = Value::CatchOffset(0);
12877                    }
12878                }
12879                let done = match &result {
12880                    Value::Object(object) => self
12881                        .get_property(object, "done")?
12882                        .is_some_and(|value| value.to_boolean()),
12883                    _ => true,
12884                };
12885                if done {
12886                    // Clear the iterator object so the `iterator_close` the loop emits on
12887                    // its way out has nothing to close: `AsyncIteratorClose` must *not* run
12888                    // on normal completion, and this is where a normal completion is
12889                    // recognised — the same trick `for_of_next` uses, which also replaces
12890                    // the slot with `undefined`.
12891                    //
12892                    // The layout is fixed because only `for await` emits this opcode:
12893                    // `iter next catch [result]`, so the iterator is three below the top.
12894                    let depth = self.frame().stack.len();
12895                    if depth >= 3 {
12896                        self.frame_mut().stack[depth - 3] = Value::Undefined;
12897                    }
12898                    self.push(Value::Undefined);
12899                    self.push(Value::Bool(true));
12900                } else {
12901                    let Value::Object(object) = &result else {
12902                        self.push(Value::Undefined);
12903                        self.push(Value::Bool(true));
12904                        return Ok(Step::Continue);
12905                    };
12906                    let value = self
12907                        .get_property(object, "value")?
12908                        .unwrap_or(Value::Undefined);
12909                    self.push(value);
12910                    self.push(Value::Bool(false));
12911                }
12912            }
12913
12914            Delete => {
12915                // `delete obj[key]`, where the key was just pushed. Deleting an array
12916                // index leaves a *hole* rather than closing the gap, and a
12917                // non-configurable property answers `false` and stays.
12918                let key = self.pop();
12919                let target = self.pop();
12920                let key = self.propkey(&key)?;
12921                let text_label = key.as_str().unwrap_or("").to_string();
12922                let deleted = match &target {
12923                    Value::Object(object) => {
12924                        let object = object.clone();
12925                        self.delete_property_key(&object, &key)?
12926                    }
12927                    // A string's `length` and its index properties are
12928                    // non-configurable, so deleting one answers `false`.
12929                    Value::String(text) => {
12930                        !(text_label == "length"
12931                            || array_index(&text_label)
12932                                .is_some_and(|index| (index as usize) < text.utf16_len()))
12933                    }
12934                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
12935                    // object to delete from, and only a *boxable* primitive has one.
12936                    Value::Undefined | Value::Null => {
12937                        return Err(Signal::Throw(
12938                            self.make_error("TypeError", "cannot convert to object"),
12939                        ));
12940                    }
12941                    // Any other primitive has no own properties; deleting nothing
12942                    // succeeds.
12943                    _ => true,
12944                };
12945                // §13.5.1.2: in strict mode a `delete` that answers `false` is a
12946                // `TypeError` rather than a `false` result. Sloppy mode silently reports
12947                // the refusal, which is why the same statement throws here but not there.
12948                if !deleted && self.current_strict() {
12949                    return Err(Signal::Throw(
12950                        self.make_error("TypeError", "cannot delete property"),
12951                    ));
12952                }
12953                self.push(Value::Bool(deleted));
12954            }
12955
12956            // -- exceptions and bookkeeping ---------------------------------
12957            Fclosure | Fclosure8 => {
12958                let value = self.closure(a as usize)?;
12959                self.push(value);
12960            }
12961
12962            other => {
12963                let name = other.info().name;
12964                return Err(Signal::Throw(self.make_error(
12965                    "InternalError",
12966                    &format!("{name} is not implemented yet"),
12967                )));
12968            }
12969        }
12970        Ok(Step::Continue)
12971    }
12972
12973    // -- operand helpers ----------------------------------------------------
12974
12975    /// The slot index an operand names, taking short forms into account.
12976    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
12977        use Opcode::*;
12978        match op {
12979            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
12980            | SetVarRef0 => 0,
12981            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
12982            | SetVarRef1 => 1,
12983            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
12984            | SetVarRef2 => 2,
12985            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
12986            | SetVarRef3 => 3,
12987            _ => a as usize,
12988        }
12989    }
12990
12991    /// The argument count of a call, taking `call0`…`call3` into account.
12992    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
12993        use Opcode::*;
12994        match op {
12995            Call0 => 0,
12996            Call1 => 1,
12997            Call2 => 2,
12998            Call3 => 3,
12999            _ => a as usize,
13000        }
13001    }
13002
13003    /// The atom's name as a property key.
13004    ///
13005    /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
13006    /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
13007    /// `String::clone` was a heap allocation and a copy — per property access.
13008    /// The atom at `index`, as a property key.
13009    ///
13010    /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
13011    /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
13012    /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
13013    /// 5.3% of `property:monomorphic`.
13014    /// The atom's text, exactly — including an unpaired surrogate.
13015    ///
13016    /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
13017    /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
13018    /// `atom_text` below is for the other kind of use, where the atom is a key in the
13019    /// engine's own tables.
13020    fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
13021        self.frame()
13022            .code
13023            .code
13024            .atoms
13025            .get(index)
13026            .map(|atom| match atom {
13027                Atom::Str(text) => text.clone(),
13028                Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
13029                // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
13030                Atom::Null => crate::value::Wtf8::new(String::new()),
13031            })
13032            .unwrap_or_default()
13033    }
13034
13035    fn atom_text(&self, index: usize) -> String {
13036        self.frame()
13037            .code
13038            .code
13039            .atoms
13040            .get(index)
13041            .map(|atom| match atom {
13042                // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
13043                // compare it to an identifier, and a surrogate-bearing name is reachable
13044                // through `atom_wtf8` where it matters.
13045                Atom::Str(text) => text.to_string_lossy().into_owned(),
13046                Atom::Index(value) => value.to_string(),
13047                // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
13048                // `throw_error`, `delete super.x`) never read it.
13049                Atom::Null => String::new(),
13050            })
13051            .unwrap_or_default()
13052    }
13053
13054    fn constant(&mut self, index: usize) -> JsResult<Value> {
13055        let constant = self.frame().code.code.cpool.get(index).cloned();
13056        Ok(match &constant {
13057            Some(Constant::Number(number)) => Value::Float(*number),
13058            Some(Constant::String(text)) => self.string_wtf8(text.clone()),
13059            Some(Constant::BigInt { digits, radix }) => {
13060                match crate::bigint::BigInt::from_radix(digits, *radix) {
13061                    Some(big) => self.bigint(big),
13062                    // A literal the parser accepted is always parseable; a failure here
13063                    // would be a compiler bug, so it reads as an `InternalError`.
13064                    None => {
13065                        return Err(Signal::Throw(
13066                            self.make_error("InternalError", "unparseable bigint literal"),
13067                        ));
13068                    }
13069                }
13070            }
13071            Some(Constant::Function(_)) => {
13072                return Err(Signal::Throw(
13073                    self.make_error("InternalError", "a bare function constant"),
13074                ));
13075            }
13076            // A tagged template's call site: a frozen array of the cooked chunks with a
13077            // frozen `raw` array beside it, which is what `String.raw` reads back.
13078            //
13079            // §13.2.8.1 caches it on the realm: `runTemplate()` called twice must hand the
13080            // tag the *same* object, and only a registry gives that. The site is
13081            // (code object, constant index) — see [`Realm::template_map`].
13082            Some(Constant::Template { site, cooked, raw }) => {
13083                // Weakly held, and reaped when the map gets crowded: a program that calls
13084                // `eval` with a tagged template in a loop compiles a fresh site each time,
13085                // and keeping a strong handle would grow this map without bound. Losing an
13086                // expired entry costs nothing — nothing is using the object it named.
13087                if let Some(cached) = self
13088                    .realm
13089                    .template_map
13090                    .get(site)
13091                    .and_then(|weak| weak.upgrade())
13092                {
13093                    return Ok(Value::Object(cached));
13094                }
13095                let cooked_values: Vec<Value> = cooked
13096                    .iter()
13097                    .map(|chunk| match chunk {
13098                        Some(text) => self.string_wtf8(text.clone()),
13099                        None => Value::Undefined,
13100                    })
13101                    .collect();
13102                let raw_values: Vec<Value> =
13103                    raw.iter().map(|text| self.string(text.clone())).collect();
13104                let raw_array = self.new_array(raw_values);
13105                let template = self.new_array(cooked_values);
13106                template.define(
13107                    "raw",
13108                    Property::with_attributes(Value::Object(raw_array.clone()), false, false),
13109                );
13110                // `SetIntegrityLevel(…, frozen)`, not just a refusal of new properties: the
13111                // template object's indices have to be non-writable and non-configurable, and
13112                // so does `length`. `set_extensible(false)` alone left every index writable,
13113                // which is what `template-object` checks with `verifyProperty`.
13114                // An array of template strings cannot be a proxy, so neither call can be
13115                // refused — `freeze_object` is `?` rather than best-effort on purpose.
13116                crate::builtins::object::freeze_object(self, &raw_array)?;
13117                crate::builtins::object::freeze_object(self, &template)?;
13118                if self.realm.template_map.len() > 256 {
13119                    self.realm
13120                        .template_map
13121                        .retain(|_, weak| weak.upgrade().is_some());
13122                }
13123                self.realm.template_map.insert(*site, template.downgrade());
13124                Value::Object(template)
13125            }
13126            _ => Value::Undefined,
13127        })
13128    }
13129
13130    /// The reference cell a closure-variable slot names.
13131    ///
13132    /// Two kinds of binding share this addressing: a genuine closure variable
13133    /// (captured from an enclosing function) lives in this frame's environment,
13134    /// while a *declared global* lives in the realm so that a script, a function
13135    /// declaration and their uses all see one binding. A plain `Global` — an
13136    /// undeclared name that may be satisfied by the global object — has no cell at
13137    /// all, which is how `typeof x` still works for a name that does not exist.
13138    /// The reference cell a closure-variable slot names.
13139    ///
13140    /// The environment is resolved once, when the closure is built, and this is
13141    /// just the lookup afterwards. A *declared global* is in there too, pointing at
13142    /// the realm's cell, so a script, a hoisted function declaration and their uses
13143    /// all share one binding. A plain `Global` — a name the script never declared —
13144    /// is read and written through `get_var`/`put_var` by name instead, which is
13145    /// what lets the global object satisfy it.
13146    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
13147        self.frame().env.cells.get(slot).cloned()
13148    }
13149
13150    /// Whether `slot` refers to a global binding through the reference table.
13151    ///
13152    /// A global's cell in the closure environment only exists so the slot has
13153    /// something to point at; the binding itself lives on the global object (a `var`)
13154    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
13155    /// be routed, not performed on the placeholder.
13156    fn is_global_slot(&self, slot: usize) -> bool {
13157        self.frame()
13158            .code
13159            .code
13160            .closure_vars
13161            .get(slot)
13162            .is_some_and(|c| {
13163                // A module's declarations and imports are *not* globals: their cells are
13164                // the module environment's, filled by the host, so the placeholder routing
13165                // must not apply to them.
13166                matches!(
13167                    c.closure_type,
13168                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
13169                )
13170            })
13171    }
13172
13173    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
13174        if self.is_global_slot(slot) {
13175            return self.get_global(slot);
13176        }
13177        Ok(self
13178            .var_ref_cell(slot)
13179            .map(|cell| cell.get())
13180            .unwrap_or(Value::Undefined))
13181    }
13182
13183    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
13184        // A function declaration is hoisted by storing into a global reference before
13185        // the body runs, so this path is also what puts it on the global object.
13186        if self.is_global_slot(slot) {
13187            return self.put_global(slot, value);
13188        }
13189        if let Some(cell) = self.var_ref_cell(slot) {
13190            cell.set(value);
13191        }
13192        Ok(())
13193    }
13194
13195    // -- closures -----------------------------------------------------------
13196
13197    /// Build the closure for the function constant `index`.
13198    ///
13199    /// Every entry in the child's closure table names where its binding lives in
13200    /// *this* frame: a local or argument slot that was marked captured, or a cell
13201    /// this frame is itself holding. That is how a variable three functions deep
13202    /// stays one binding.
13203    fn closure(&mut self, index: usize) -> JsResult<Value> {
13204        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
13205        else {
13206            return Err(Signal::Throw(
13207                self.make_error("InternalError", "fclosure of a non-function"),
13208            ));
13209        };
13210        let mut cells = Vec::with_capacity(function.closure_vars.len());
13211        for closure_var in &function.closure_vars {
13212            let cell = match closure_var.closure_type {
13213                ClosureType::Arg => {
13214                    let slot = closure_var.var_idx as usize;
13215                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
13216                }
13217                ClosureType::Local => {
13218                    let slot = closure_var.var_idx as usize;
13219                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
13220                }
13221                ClosureType::Ref | ClosureType::GlobalRef => {
13222                    // A `Ref` names a cell in this frame's own closure table; a
13223                    // `GlobalRef` also starts there, then resolves by name below.
13224                    let slot = closure_var.var_idx as usize;
13225                    if let Some(cell) = self.frame().env.cells.get(slot) {
13226                        cells.push(cell.clone());
13227                        continue;
13228                    }
13229                    -1
13230                }
13231                _ => -1,
13232            };
13233            if cell >= 0 {
13234                let cell = self.frame().cells[cell as usize].clone();
13235                cells.push(cell);
13236                continue;
13237            }
13238            // A global: the cell is created on demand and shared through the realm,
13239            // so every function sees one binding.
13240            let name = closure_var.name.clone();
13241            let cell = match self.realm.globals.get(&name) {
13242                Some(cell) => cell.clone(),
13243                None => {
13244                    let cell = self.new_cell(Value::Undefined);
13245                    self.realm.globals.insert(name.clone(), cell.clone());
13246                    cell
13247                }
13248            };
13249            cells.push(cell);
13250        }
13251        let name = function.name.clone();
13252        // `.length` is the arity before any default or rest parameter, not the number
13253        // of slots a pattern parameter needs.
13254        let length = function.defined_args;
13255        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
13256        // function and an arrow function do not. A *method* also does not, but that is not
13257        // known here — the method is marked when the `[[HomeObject]]` is attached (see
13258        // `set_home_object`), which is the moment it becomes a method.
13259        let function_kind = function.kind;
13260        let constructible =
13261            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
13262        let code = Gc::new(self.heap, CompiledCode::new(*function));
13263        // A closure built inside an `eval` inherits the eval's view of the enclosing
13264        // bindings, so it can still read them once the eval has returned.
13265        let eval_scope = self
13266            .active_eval_scope
13267            .clone()
13268            .or_else(|| self.frame().env.eval_scope.clone());
13269        // A closure sees the variables a direct `eval` declared in the frame it was
13270        // created in — the ones declared before *and after* it, so the same object is
13271        // shared; only the phase bounds which of them are visible.
13272        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
13273        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
13274        let env = Gc::new(
13275            self.heap,
13276            ClosureEnv {
13277                cells,
13278                eval_scope,
13279                local_vars,
13280                local_phase,
13281            },
13282        );
13283        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
13284        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
13285        // the only thing that carries `Symbol.toStringTag`, so without it
13286        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
13287        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
13288        let proto = match function_kind {
13289            js_compile::bytecode::FunctionKind::AsyncGenerator => self
13290                .realm
13291                .async_generator_function_proto
13292                .clone()
13293                .or_else(|| self.realm.function_proto.clone().into()),
13294            js_compile::bytecode::FunctionKind::Generator => self
13295                .realm
13296                .generator_function_proto
13297                .clone()
13298                .or_else(|| self.realm.function_proto.clone().into()),
13299            js_compile::bytecode::FunctionKind::Async => self
13300                .realm
13301                .async_function_proto
13302                .clone()
13303                .or_else(|| self.realm.function_proto.clone().into()),
13304            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
13305        };
13306        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
13307        object.set_constructible(constructible);
13308        object.define(
13309            "length",
13310            Property::name_or_length(Value::Int(length as i32)),
13311        );
13312        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
13313        // that checks the own-property descriptor fails if the property is missing.
13314        object.define("name", Property::name_or_length(self.string(name)));
13315        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
13316        // when `[[Construct]]` is created, so an async function and an arrow function have
13317        // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
13318        // function) an own `prototype` property, which `builtin.js` checks for absence.
13319        //
13320        // A **generator** function is the exception that is not constructible: it still
13321        // gets a `prototype` field, because that object is what a generator *instance*
13322        // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
13323        // made `function* g(){}; g.prototype` `undefined` and every generator share
13324        // `%GeneratorPrototype%` as its direct prototype.
13325        if constructible {
13326            self.install_function_prototype(&object);
13327        } else if matches!(
13328            function_kind,
13329            js_compile::bytecode::FunctionKind::Generator
13330                | js_compile::bytecode::FunctionKind::AsyncGenerator
13331        ) {
13332            let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
13333                self.realm.generator_proto.clone()
13334            } else {
13335                self.realm
13336                    .async_generator_proto
13337                    .clone()
13338                    .unwrap_or_else(|| self.realm.generator_proto.clone())
13339            };
13340            self.install_generator_prototype(&object, parent);
13341        }
13342        Ok(Value::Object(object))
13343    }
13344
13345    // -- conversions used by the operators ----------------------------------
13346
13347    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
13348        // `+x` is `ToNumber`, which for a string parses it and for an object runs
13349        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
13350        // string, which then behaves differently in every later comparison.
13351        match value {
13352            Value::Int(_) | Value::Float(_) => Ok(value),
13353            other => Ok(Value::Float(self.to_js_number(&other)?)),
13354        }
13355    }
13356
13357    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
13358    ///
13359    /// Returns the *converted* old value and the new one, because the two callers need
13360    /// different halves: `++x` yields the new value, while `x++` yields the old one and
13361    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
13362    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
13363    /// boolean.
13364    ///
13365    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
13366    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
13367    /// a bigint algorithm then ran exactly once.
13368    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
13369        if let Value::BigInt(big) = &value {
13370            let one = crate::bigint::BigInt::from_i64(1);
13371            let next = if up { big.add(&one) } else { big.sub(&one) };
13372            return Ok((value, self.bigint(next)));
13373        }
13374        let old = self.numeric_operand(value)?;
13375        if let Value::BigInt(big) = &old {
13376            let one = crate::bigint::BigInt::from_i64(1);
13377            let next = if up { big.add(&one) } else { big.sub(&one) };
13378            return Ok((old, self.bigint(next)));
13379        }
13380        let new = if up {
13381            increment(old.clone())
13382        } else {
13383            decrement(old.clone())
13384        };
13385        Ok((old, new))
13386    }
13387
13388    /// `ToNumeric` for a unary or update operand: `ToPrimitive(number)`, then either branch.
13389    ///
13390    /// The unary operators are defined on `Numeric`, not on `Number`: `-x` and `~x` are
13391    /// `Numeric::unaryMinus`/`bitwiseNOT`, which a bigint answers exactly. [`Interp::numeric`]
13392    /// is `ToNumber` and collapses a bigint to a float, so an operand that is a *wrapper
13393    /// object* — `-Object(5n)` — lost its bigint-ness before the operator ever saw it and
13394    /// raised "cannot convert bigint to number". A primitive bigint never took that path
13395    /// (`Neg`/`Not` matched `Value::BigInt` first), which is why only the boxed form broke.
13396    fn numeric_operand(&mut self, value: Value) -> JsResult<Value> {
13397        let primitive = match value {
13398            Value::Int(_) | Value::Float(_) | Value::BigInt(_) => value,
13399            other => self.to_primitive(other, Hint::Number)?,
13400        };
13401        match primitive {
13402            Value::BigInt(_) => Ok(primitive),
13403            other => self.numeric(other),
13404        }
13405    }
13406
13407    fn numeric(&mut self, value: Value) -> JsResult<Value> {
13408        // `ToNumber` on an object runs `ToPrimitive` first, which is how
13409        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
13410        // heard at all. Reading the object's own tag instead (`other.to_number()`)
13411        // turned the whole operand into `NaN` and swallowed the exception.
13412        match value {
13413            Value::Int(_) | Value::Float(_) => Ok(value),
13414            other => Ok(Value::Float(self.to_js_number(&other)?)),
13415        }
13416    }
13417
13418    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
13419    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
13420        match value {
13421            Value::BigInt(big) => Ok((**big).clone()),
13422            // The reference words this the same way for every operator, so a failing
13423            // script reads identically; the operator itself adds nothing a caller can use.
13424            _ => Err(Signal::Throw(
13425                self.make_error("TypeError", "cannot convert bigint to number"),
13426            )),
13427        }
13428    }
13429
13430    /// Arithmetic where at least one operand is a `BigInt`.
13431    ///
13432    /// The two numeric types never mix, so a bigint paired with anything else is an error
13433    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
13434    /// that the relational operators handle it separately.
13435    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13436        use Opcode::*;
13437        let a = self.bigint_operand(&left)?;
13438        let b = self.bigint_operand(&right)?;
13439        let result = match op {
13440            Add => a.add(&b),
13441            Sub => a.sub(&b),
13442            Mul => a.mul(&b),
13443            Div | Mod => {
13444                let Some((quotient, remainder)) = a.div_rem(&b) else {
13445                    return Err(Signal::Throw(
13446                        self.make_error("RangeError", "division by zero"),
13447                    ));
13448                };
13449                if op == Div { quotient } else { remainder }
13450            }
13451            Pow => {
13452                let Some(value) = a.pow(&b) else {
13453                    return Err(Signal::Throw(self.make_error(
13454                        "RangeError",
13455                        "BigInt exponent must be non-negative and not absurdly large",
13456                    )));
13457                };
13458                value
13459            }
13460            And => a.bitand(&b),
13461            Or => a.bitor(&b),
13462            Xor => a.bitxor(&b),
13463            Shl | Sar => {
13464                // A shift count is a `BigInt` here, and both directions are exact; a
13465                // negative count would be the other direction, which the spec forbids.
13466                let Some(count) = b.to_i64() else {
13467                    return Err(Signal::Throw(
13468                        self.make_error("RangeError", "BigInt shift count is too large"),
13469                    ));
13470                };
13471                if count < 0 {
13472                    return Err(Signal::Throw(self.make_error(
13473                        "RangeError",
13474                        "BigInt shift count must be non-negative",
13475                    )));
13476                }
13477                if op == Shl {
13478                    a.shl(count as u64)
13479                } else {
13480                    a.shr(count as u64)
13481                }
13482            }
13483            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
13484            _ => {
13485                return Err(Signal::Throw(self.make_error(
13486                    "TypeError",
13487                    "BigInts have no unsigned right shift, use >> instead",
13488                )));
13489            }
13490        };
13491        Ok(self.bigint(result))
13492    }
13493
13494    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
13495    ///
13496    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
13497    /// is on the mathematical values, and nothing is rounded first.
13498    /// `<`, `<=`, `>`, `>=`.
13499    ///
13500    /// Both operands go through `ToPrimitive` **before** the comparison, which is what
13501    /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
13502    /// It is a `?`-returning function for exactly that reason: an object operand can run
13503    /// script, and script can throw. The old version compared `to_number` of the raw
13504    /// values, which answered `false` for every object instead of calling `valueOf` —
13505    /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
13506    /// never ran.
13507    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13508        // The hot arm first: `i < n` with both sides already integers. No conversion, no
13509        // call, nothing that can throw.
13510        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13511            let ordering = Some(left.cmp(right));
13512            return Ok(ordering_answer(op, ordering));
13513        }
13514        // Anything that can run script has to be converted first, in this order.
13515        let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
13516        {
13517            (
13518                self.to_primitive(left, Hint::Number)?,
13519                self.to_primitive(right, Hint::Number)?,
13520            )
13521        } else {
13522            (left, right)
13523        };
13524        let ordering = match (&left, &right) {
13525            // The loop condition `i < n` is integer against integer, and it runs once
13526            // per iteration of every loop in every program. Without this arm it took the
13527            // `to_number` path twice, which is a `match` plus a conversion each.
13528            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
13529            // **Code unit** order, not code point order. They differ exactly where a
13530            // surrogate pair meets a BMP character above U+E000: `"\uDC00" > "\uD800"` is
13531            // true because 0xDC00 > 0xD800, while comparing code points would have turned
13532            // both lone surrogates into U+FFFD and called them equal
13533            // (`greater-than/S11.8.2_A4.12_T1`).
13534            (Value::String(a), Value::String(b)) => Some(compare_code_units(a, b)),
13535            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
13536            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
13537            // is true even though `2.5` has no bigint form.
13538            // §7.2.13 step 3.d-3.e: a bigint against a string goes through
13539            // `StringToBigInt`, **not** `ToNumber` — `"9007199254740993" > 9007199254740992n`
13540            // is true because both sides stay exact integers, which converting the string to
13541            // a double would destroy. A string that is not an integer literal makes the
13542            // whole comparison `undefined`, i.e. `false` for every relational operator.
13543            (Value::BigInt(a), Value::String(text)) => {
13544                string_to_bigint(&text.to_string_lossy()).map(|b| a.cmp(&b))
13545            }
13546            (Value::String(text), Value::BigInt(b)) => {
13547                string_to_bigint(&text.to_string_lossy()).map(|a| b.cmp(&a).reverse())
13548            }
13549            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
13550                let b = self.number_operand(other)?;
13551                if b.is_nan() {
13552                    None
13553                } else {
13554                    compare_bigint_and_f64(a, b)
13555                }
13556            }
13557            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
13558                let a = self.number_operand(other)?;
13559                if a.is_nan() {
13560                    None
13561                } else {
13562                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
13563                }
13564            }
13565            // `ToNumeric` on the pair, which refuses a Symbol rather than answering `NaN`:
13566            // `Object(Symbol()) <= ""` is a `TypeError`, and the total `to_number` made it
13567            // `false` (`Symbol/prototype/Symbol.toPrimitive/…-ordinary-toprimitive`).
13568            _ => self
13569                .to_js_number(&left)?
13570                .partial_cmp(&self.to_js_number(&right)?),
13571        };
13572        Ok(ordering_answer(op, ordering))
13573    }
13574
13575    /// `ToNumber(V)`, refusing a Symbol instead of answering `NaN`.
13576    ///
13577    /// §7.1.4 throws for a Symbol, and the relational operators inherit that: `3n < Symbol()`
13578    /// is a `TypeError`, not `false`. `Value::to_number` is a total function — it has to be,
13579    /// because it is also what `Number(x)` uses — so the check lives here.
13580    fn number_operand(&self, value: &Value) -> JsResult<f64> {
13581        if matches!(value, Value::Symbol(_)) {
13582            return Err(self.type_error("cannot convert symbol to number"));
13583        }
13584        Ok(value.to_number())
13585    }
13586
13587    fn binary_add(&mut self) -> JsResult<()> {
13588        let right = self.pop();
13589        let left = self.pop();
13590        // Two integers add without any of the machinery below: no `ToPrimitive` (an
13591        // `Int` is already primitive), no string check, no bigint check, no allocation.
13592        // `x += 1` in a loop is the single most common instruction sequence in real
13593        // script, and it used to walk every one of those checks before reaching the
13594        // same `checked_add`.
13595        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13596            self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
13597            return Ok(());
13598        }
13599        let left = self.primitive_of(left)?;
13600        let right = self.primitive_of(right)?;
13601        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
13602        // that check comes before the bigint one: `"" + 1n` is a string, not a
13603        // mixed-type error.
13604        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
13605            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
13606            // `TypeError`, the one place a symbol and a string do not mix.
13607            // Keep the operands as strings rather than as bytes: `JsString::concat` decides
13608            // between a copy and a rope from their lengths, and a rope is what turns
13609            // `text += "abc"` in a loop from quadratic into linear.
13610            if let (Value::String(left), Value::String(right)) = (&left, &right) {
13611                // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
13612                // reports as `InternalError: string too long`.
13613                let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
13614                    return Err(Signal::Throw(
13615                        self.make_error("InternalError", "string too long"),
13616                    ));
13617                };
13618                self.push(Value::String(Gc::new(self.heap, joined)));
13619                return Ok(());
13620            }
13621            // At least one operand was not a string, so `ToString` it. This rejects a
13622            // symbol, which is the one place a symbol and a string do not mix.
13623            let left = self.checked_to_wtf8(&left)?;
13624            let right = self.checked_to_wtf8(&right)?;
13625            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
13626            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
13627            let text = left.concat(&right);
13628            self.push(self.string_wtf8(text));
13629            return Ok(());
13630        }
13631        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
13632        // not a conversion.
13633        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
13634            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
13635            self.push(value);
13636            return Ok(());
13637        }
13638        let left = self.numeric(left)?;
13639        let right = self.numeric(right)?;
13640        self.push(add_numbers(left, right));
13641        Ok(())
13642    }
13643
13644    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
13645        self.to_primitive(value, Hint::Default)
13646    }
13647
13648    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
13649    ///
13650    /// The order depends on the hint: the "number" order tries `valueOf` first and
13651    /// `toString` second, the "string" order the other way round, and the default
13652    /// hint uses the number order. A result that is still an object is a `TypeError`,
13653    /// because no built-in `valueOf`/`toString` returns one.
13654    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
13655        let Value::Object(object) = &value else {
13656            return Ok(value);
13657        };
13658        // A Date overrides the default hint to mean "string", which is what
13659        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
13660        // this, `"" + new Date()` would print the milliseconds, not the date.
13661        let hint = if hint == Hint::Default && is_date_object(self, object) {
13662            Hint::String
13663        } else {
13664            hint
13665        };
13666        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
13667        // handed the hint as a string. This is the hook a Date uses for its default hint
13668        // and a script uses to take over conversion entirely.
13669        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
13670        // `GetMethod`, not "is it a callable object": the property has to be read and then
13671        // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
13672        // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
13673        // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
13674        // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
13675        // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
13676        // callable.
13677        match self.get_property_key(object, &key)? {
13678            None | Some(Value::Undefined) | Some(Value::Null) => {}
13679            Some(Value::Object(function)) if function.is_callable() => {
13680                let hint = match hint {
13681                    Hint::String => "string",
13682                    Hint::Number => "number",
13683                    Hint::Default => "default",
13684                };
13685                let hint = self.string(hint);
13686                let result = self.call_value(
13687                    Value::Object(function),
13688                    Value::Object(object.clone()),
13689                    vec![hint],
13690                )?;
13691                if !matches!(result, Value::Object(_)) {
13692                    return Ok(result);
13693                }
13694                return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
13695            }
13696            Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
13697        }
13698        let order: [&str; 2] = match hint {
13699            Hint::String => ["toString", "valueOf"],
13700            Hint::Number | Hint::Default => ["valueOf", "toString"],
13701        };
13702        let receiver = object.clone();
13703        for method in order {
13704            if let Some(function) = self.get_property(&receiver, method)?
13705                && matches!(&function, Value::Object(object) if object.is_callable())
13706            {
13707                let result =
13708                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
13709                if !matches!(result, Value::Object(_)) {
13710                    return Ok(result);
13711                }
13712            }
13713        }
13714        Err(self.type_error("cannot convert object to primitive value"))
13715    }
13716
13717    /// `ToString` with the object case going through `ToPrimitive`.
13718    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
13719        if matches!(value, Value::Object(_)) {
13720            let primitive = self.to_primitive(value.clone(), Hint::String)?;
13721            return Ok(primitive.to_js_string());
13722        }
13723        // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
13724        // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
13725        // callers that want that strictness call [`Interp::to_string_strict`] — putting the
13726        // check here broke `String(Symbol())` and 45 cases that print a symbol.
13727        Ok(value.to_js_string())
13728    }
13729
13730    /// `ToString(value)`, with §7.1.19's symbol refusal.
13731    ///
13732    /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
13733    /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
13734    /// operations and conflating them cost 45 cases in one direction and 6 in the other.
13735    pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
13736        if matches!(value, Value::Symbol(_)) {
13737            return Err(self.type_error("cannot convert a Symbol to a string"));
13738        }
13739        if matches!(value, Value::Object(_)) {
13740            let primitive = self.to_primitive(value.clone(), Hint::String)?;
13741            if matches!(primitive, Value::Symbol(_)) {
13742                return Err(self.type_error("cannot convert a Symbol to a string"));
13743            }
13744            return Ok(primitive.to_js_string());
13745        }
13746        Ok(value.to_js_string())
13747    }
13748
13749    /// `ToString` that keeps the string's code units instead of flattening them.
13750    ///
13751    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
13752    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
13753    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13754        if matches!(value, Value::Symbol(_)) {
13755            return Err(Signal::Throw(
13756                self.make_error("TypeError", "cannot convert symbol to string"),
13757            ));
13758        }
13759        // An object runs `ToPrimitive` first, which may itself produce a symbol.
13760        let value = self.to_primitive(value.clone(), Hint::String)?;
13761        match value {
13762            Value::Symbol(_) => Err(Signal::Throw(
13763                self.make_error("TypeError", "cannot convert symbol to string"),
13764            )),
13765            Value::String(text) => Ok(text.wtf8().clone()),
13766            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
13767        }
13768    }
13769
13770    /// `ToNumber` with the object case going through `ToPrimitive`.
13771    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
13772        let value = if matches!(value, Value::Object(_)) {
13773            self.to_primitive(value.clone(), Hint::Number)?
13774        } else {
13775            value.clone()
13776        };
13777        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
13778        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
13779        // `NaN` to stay total, and the operators check for the bigint themselves — but
13780        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
13781        // refuse, and answering `NaN` made them silently wrong instead.
13782        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
13783        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
13784        match value {
13785            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
13786            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
13787            other => Ok(other.to_number()),
13788        }
13789    }
13790
13791    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
13792    /// [`ElementType::write`].
13793    ///
13794    /// This is separated from the write because both conversions are observable script —
13795    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
13796    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
13797    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
13798    /// setters, and a plain `a[i] = v`.
13799    pub(crate) fn element_value(
13800        &mut self,
13801        element: crate::builtins::typedarray::ElementType,
13802        value: Value,
13803    ) -> JsResult<Value> {
13804        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
13805        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
13806        let primitive = match &value {
13807            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
13808            _ => value,
13809        };
13810        if element.is_bigint() {
13811            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
13812            Ok(Value::BigInt(Gc::new(self.heap, big)))
13813        } else {
13814            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
13815            Ok(Value::Float(self.to_js_number(&primitive)?))
13816        }
13817    }
13818
13819    /// `ToPropertyKey`: what a computed member access uses as its key.
13820    ///
13821    /// A symbol is returned as itself, never stringified — that is what keeps
13822    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
13823    pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
13824        match value {
13825            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
13826            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
13827            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
13828            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
13829            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13830                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
13831                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
13832                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
13833                    other.to_js_string(),
13834                ))),
13835            },
13836            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
13837        }
13838    }
13839
13840    /// `ToPropertyKey` for the callers that can only use a string key.
13841    ///
13842    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
13843    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
13844    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
13845    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
13846    /// program continues with a value nobody asked for.
13847    /// `SetFunctionName`'s name for a computed key, which is not `ToPropertyKey`.
13848    ///
13849    /// §7.3.24 step 1: when the key is a **Symbol**, the name is `"[" + description + "]"`
13850    /// — or the empty string when the symbol has no description. Going through
13851    /// `ToPropertyKey` instead gave `Symbol(test262)` and `Symbol()`, so every
13852    /// `{ [sym](){} }` method had the wrong `name` (`fn-name-fn` and its generated
13853    /// relatives, in both `expressions/object` and `statements/class`).
13854    ///
13855    /// Everything else is an ordinary `ToPropertyKey` — a string key keeps its code units,
13856    /// which is what makes `{ "\uD800": function () {} }.name` the lone surrogate.
13857    fn function_name_from_key(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13858        if let Value::Symbol(symbol) = value {
13859            return Ok(match symbol.description() {
13860                Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
13861                None => crate::value::Wtf8::default(),
13862            });
13863        }
13864        self.propkey_of(value)
13865    }
13866
13867    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13868        use crate::value::Wtf8;
13869        Ok(match value {
13870            // A string key keeps its code units. Going through a lossy `String` would make
13871            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
13872            Value::String(text) => text.wtf8().clone(),
13873            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
13874            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
13875            // falling back to its `ToString` would print `[object Object]`.
13876            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13877                Value::String(text) => text.wtf8().clone(),
13878                other => Wtf8::new(other.to_js_string()),
13879            },
13880            other => Wtf8::new(other.to_js_string()),
13881        })
13882    }
13883
13884    // -- object operations used by instructions -----------------------------
13885
13886    /// Read `object[key]`, returning `undefined` when the property is missing.
13887    ///
13888    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
13889    /// primitive (looking through its prototype) as well as an object — which is what
13890    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
13891    /// argument needs too.
13892    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
13893        self.read_field_key(object, &PropertyKey::from(key))
13894    }
13895
13896    /// [`Interp::read_field`] with a key that may be a symbol.
13897    ///
13898    /// A symbol key never reaches the string shortcuts: a string's `length` and its
13899    /// indices are string properties, and a symbol named `length` is a different
13900    /// property that a string primitive cannot have.
13901    /// [`Interp::read_field_key`], with an inline cache in front of it.
13902    ///
13903    /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
13904    /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
13905    /// without this the engine walked the chain and compared ~40 property names on each
13906    /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
13907    ///
13908    /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
13909    /// missing property. Those answers depend on running code or on state the guard below
13910    /// does not cover, and a wrong answer here is far more expensive than a lookup.
13911    ///
13912    /// A hit is re-validated against the *whole* walked chain, not just the level that
13913    /// answered: the receiver and every prototype down to that level must still be the same
13914    /// object (weakly, so a collected and reallocated object is a miss) with unchanged
13915    /// property-table *lengths* — which is what catches a property appearing on an
13916    /// intermediate prototype and shadowing the cached one.
13917    pub fn read_field_cached(
13918        &mut self,
13919        object: &Value,
13920        key: &PropertyKey,
13921        slot: usize,
13922    ) -> JsResult<Value> {
13923        let index = Self::field_cache_slot(object, key, slot);
13924        let Value::Object(target) = object else {
13925            return self.read_field_key(object, key);
13926        };
13927        if target.proxy_state().is_some() {
13928            return self.read_field_key(object, key);
13929        }
13930        if let Some(cached) = &self.field_cache[index]
13931            && cached.key == *key
13932            && let Some(value) = Self::cached_hit(target, cached)
13933        {
13934            return Ok(value);
13935        }
13936        let value = self.read_field_key(object, key)?;
13937        self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
13938        Ok(value)
13939    }
13940
13941    /// Whether a cache entry still describes this lookup, and if so the value.
13942    ///
13943    /// The guard is the whole point of the entry: identity plus property-table length for
13944    /// every level walked. Re-checked per level rather than once at the receiving end,
13945    /// because a shadowing property can appear anywhere along the chain.
13946    fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
13947        // Level 0 — the receiver itself answered — without the `Gc` clone this loop
13948        // starts with: a clone is a reference-count bump and a drop, and for
13949        // `property:monomorphic` every single hit takes only this arm.
13950        let (weak, len) = cached.chain[0].as_ref()?;
13951        if !target.upgrades_to(weak) {
13952            return None;
13953        }
13954        if cached.level == 0 {
13955            // Length and key and accessor-ness in one borrow: see `cached_property_at`.
13956            return target.cached_property_at(cached.index, &cached.key, *len);
13957        }
13958        if target.props_len() != *len {
13959            return None;
13960        }
13961        let mut level = 1;
13962        let mut current = target.proto()?;
13963        loop {
13964            let (weak, len) = cached.chain[level].as_ref()?;
13965            if !current.upgrades_to(weak) || current.props_len() != *len {
13966                return None;
13967            }
13968            if level == cached.level as usize {
13969                // The level that answered: the value is only reusable while the key is
13970                // still there and still a plain data property.
13971                return current.cached_data_property(cached.index, &cached.key);
13972            }
13973            current = current.proto()?;
13974            level += 1;
13975        }
13976    }
13977
13978    /// Build a cache entry for a lookup that just went through the slow path.
13979    ///
13980    /// Records the chain only when the answer came from a plain data property at a level
13981    /// the fixed-size array can hold; everything else simply leaves the slot empty, which
13982    /// costs the next lookup the walk it would have cost anyway.
13983    fn record_field_lookup(
13984        target: &Gc<JsObject>,
13985        key: &PropertyKey,
13986        _value: Value,
13987    ) -> Option<FieldCache> {
13988        let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
13989            [None, None, None];
13990        let mut current = target.clone();
13991        for level in 0..MAX_CACHED_CHAIN {
13992            chain[level] = Some((current.downgrade(), current.props_len()));
13993            if let Some((found, _)) = current.own_property_index(key) {
13994                // `own_property_index` declines an accessor and a hole, which is exactly
13995                // the set that must not be cached.
13996                return Some(FieldCache {
13997                    key: key.clone(),
13998                    index: found,
13999                    level: level as u8,
14000                    chain,
14001                });
14002            }
14003            current = current.proto()?;
14004        }
14005        None
14006    }
14007
14008    /// Which cache slot a lookup uses.
14009    ///
14010    /// Mixes the object's address, the name and the site, so that two properties of one
14011    /// object, and one property of two objects, land in different slots — which is what lets
14012    /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
14013    /// other iteration.
14014    fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
14015        let mut hash = match object {
14016            Value::Object(object) => object.address(),
14017            _ => 0,
14018        };
14019        hash = hash
14020            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
14021            .rotate_left(17)
14022            .wrapping_add(key.hash_code());
14023        hash = hash.wrapping_add(site.wrapping_mul(31));
14024        // The table is a power of two, so the low bits are the slot.
14025        hash & (FIELD_CACHE_SLOTS - 1)
14026    }
14027
14028    /// Read `key` from `object`, without the inline cache.
14029    ///
14030    /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
14031    /// prototype chain, while the cached form answers an own data property from memory.
14032    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
14033        let text = key.as_str().unwrap_or("");
14034        let Value::Object(object) = object else {
14035            // Reading a property of `undefined`/`null` is the classic TypeError.
14036            if object.is_nullish() {
14037                return Err(Signal::Throw(self.make_error(
14038                    "TypeError",
14039                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
14040                )));
14041            }
14042            // A string has `length` and index access without being boxed.
14043            if let Value::String(value) = object {
14044                if text == "length" {
14045                    return Ok(Value::Int(value.utf16_len() as i32));
14046                }
14047                if let Some(index) = array_index(text) {
14048                    return Ok(match value.wtf8().unit_at(index as usize) {
14049                        Some(unit) => self.string_wtf8(unit),
14050                        None => Value::Undefined,
14051                    });
14052                }
14053            }
14054            // A property of a primitive is looked up on its prototype: this is what
14055            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
14056            let prototype = match object {
14057                Value::String(_) => self.realm.string_proto.clone(),
14058                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
14059                Value::Bool(_) => self.realm.boolean_proto.clone(),
14060                // A symbol's methods live on `Symbol.prototype`, reached the same way —
14061                // `sym.description` reads through the prototype, not off the symbol.
14062                Value::Symbol(_) => self.realm.symbol_proto.clone(),
14063                // …and a bigint's on `BigInt.prototype`, which is how
14064                // `(255n).toString(16)` reaches its method.
14065                Value::BigInt(_) => self.realm.bigint_proto.clone(),
14066                _ => None,
14067            };
14068            if let Some(prototype) = prototype
14069                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
14070            {
14071                return Ok(value);
14072            }
14073            return Ok(Value::Undefined);
14074        };
14075        Ok(self
14076            .get_property_key(object, key)?
14077            .unwrap_or(Value::Undefined))
14078    }
14079
14080    /// The `#name` a private symbol stands for, for error messages.
14081    ///
14082    /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
14083    /// was made from.
14084    fn private_name(symbol: &Value) -> Option<String> {
14085        match symbol {
14086            Value::Symbol(symbol) if symbol.is_private() => Some(
14087                symbol
14088                    .description()
14089                    .map(|text| text.to_string())
14090                    .unwrap_or_default(),
14091            ),
14092            _ => None,
14093        }
14094    }
14095
14096    /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
14097    ///
14098    /// Every private-field opcode takes the symbol the class stored in its own scope; a
14099    /// non-symbol here would be a compiler bug, and the reference guards it with
14100    /// `JS_ThrowTypeErrorNotASymbol`.
14101    fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
14102        match symbol {
14103            Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
14104            _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
14105        }
14106    }
14107
14108    /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
14109    ///
14110    /// Three early errors, all from the reference: a non-object receiver, a non-extensible
14111    /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
14112    /// would hit if the parser did not reject it first.
14113    fn define_private_field(
14114        &mut self,
14115        object: &Value,
14116        symbol: &Value,
14117        value: Value,
14118    ) -> JsResult<()> {
14119        let key = self.private_key(symbol)?;
14120        let Some(target) = object.as_object() else {
14121            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14122        };
14123        if !target.is_extensible() {
14124            return Err(Signal::Throw(
14125                self.make_error("TypeError", "object is not extensible"),
14126            ));
14127        }
14128        if target.own_property_key(&key).is_some() {
14129            let name = Self::private_name(symbol).unwrap_or_default();
14130            return Err(Signal::Throw(self.make_error(
14131                "TypeError",
14132                &format!("private class field '{name}' already exists"),
14133            )));
14134        }
14135        target.define_data_key(&key, value);
14136        Ok(())
14137    }
14138
14139    /// `JS_GetPrivateField`: only an own property, never the prototype chain.
14140    fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
14141        let key = self.private_key(symbol)?;
14142        let Some(target) = object.as_object() else {
14143            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14144        };
14145        match target.own_property_key(&key) {
14146            Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
14147            None => {
14148                let name = Self::private_name(symbol).unwrap_or_default();
14149                Err(Signal::Throw(self.make_error(
14150                    "TypeError",
14151                    &format!("private class field '{name}' does not exist"),
14152                )))
14153            }
14154        }
14155    }
14156
14157    /// `JS_SetPrivateField`: the store half of the same rule.
14158    fn write_private_field(
14159        &mut self,
14160        object: &Value,
14161        symbol: &Value,
14162        value: Value,
14163    ) -> JsResult<()> {
14164        let key = self.private_key(symbol)?;
14165        let Some(target) = object.as_object() else {
14166            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14167        };
14168        if target.write_value_key(&key, value) {
14169            return Ok(());
14170        }
14171        let name = Self::private_name(symbol).unwrap_or_default();
14172        Err(Signal::Throw(self.make_error(
14173            "TypeError",
14174            &format!("private class field '{name}' does not exist"),
14175        )))
14176    }
14177
14178    /// The `in` half: does `object` have this private field?
14179    /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
14180    ///
14181    /// The symbol is created once per class — the first `add_brand` on a given home object
14182    /// makes it, every later one reuses it, which is what ties the prototype, the constructor
14183    /// and each instance to one identity. `obj` being `null` is not an error: the class-level
14184    /// emit for the *instance* brand passes null because all it wants is the symbol.
14185    fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
14186        let Some(home_object) = home.as_object() else {
14187            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14188        };
14189        let symbol = match home_object.private_brand() {
14190            Some(symbol) => symbol,
14191            None => {
14192                let symbol = Gc::new(
14193                    self.heap,
14194                    crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
14195                );
14196                home_object.set_private_brand(symbol.clone());
14197                symbol
14198            }
14199        };
14200        let Some(target) = object.as_object() else {
14201            // Not an object: nothing to brand. The reference does the same, and `undefined`
14202            // here would otherwise turn a field initialiser into a TypeError.
14203            return Ok(());
14204        };
14205        if !target.is_extensible() {
14206            return Err(Signal::Throw(
14207                self.make_error("TypeError", "object is not extensible"),
14208            ));
14209        }
14210        if target.carries_brand(&symbol) {
14211            return Err(Signal::Throw(
14212                self.make_error("TypeError", "private method is already present"),
14213            ));
14214        }
14215        target.add_brand(symbol);
14216        Ok(())
14217    }
14218
14219    /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
14220    ///
14221    /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
14222    /// decides whether to throw.
14223    fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
14224        let Some(function) = function.as_object() else {
14225            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14226        };
14227        let Some(home) = function.home_object() else {
14228            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
14229        };
14230        let Some(brand) = home.private_brand() else {
14231            return Err(Signal::Throw(
14232                self.make_error("TypeError", "expecting <brand> private field"),
14233            ));
14234        };
14235        Ok(object.carries_brand(&brand))
14236    }
14237
14238    /// `CreateDataPropertyOrThrow(object, key, value)` — §7.3.3.
14239    ///
14240    /// What a property definition does: `[[DefineOwnProperty]]` with all three attributes
14241    /// true. Not `[[Set]]`, which walks the prototype chain and may run a setter there.
14242    fn define_field(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
14243        if let Some(target) = object.as_object() {
14244            // `CreateDataProperty` cannot reshape a non-configurable own property: its
14245            // descriptor asks for `writable` and `configurable`, and a non-configurable
14246            // property may become neither (`class C { static ['prototype'] = 1 }` is a
14247            // `TypeError`, since the constructor's `prototype` is both). The general define
14248            // path only validates *partial* descriptors — see the note there — so this has
14249            // to be said here.
14250            if self
14251                .object_get_own_property(target, key)?
14252                .is_some_and(|existing| {
14253                    !existing.configurable && (existing.is_accessor() || !existing.writable)
14254                })
14255            {
14256                return Err(Signal::Throw(self.make_error(
14257                    "TypeError",
14258                    &format!(
14259                        "cannot define property '{key}' of {}",
14260                        Value::Object(target.clone()).to_js_string()
14261                    ),
14262                )));
14263            }
14264            // Only an *array* stores into the element vector. A numeric key
14265            // on an ordinary object is an ordinary property, which is what
14266            // makes `{1: 'a'}` iterate as a key rather than disappear.
14267            let stored = target.is_array()
14268                && key.as_str().and_then(array_index).is_some_and(|index| {
14269                    target.array_set(self.heap, index as usize, value.clone())
14270                });
14271            if !stored {
14272                // `CreateDataPropertyOrThrow`, not a raw table insert: a class
14273                // field is defined with `[[DefineOwnProperty]]`, so a frozen
14274                // receiver throws (`class Test { f = Object.freeze(this); g = 1 }`
14275                // must fail on `g`) and a **proxy** receiver runs its
14276                // `defineProperty` trap (`class-field-is-observable-by-proxy`
14277                // counts the trap's calls). `define_data_key` writes straight into
14278                // the table, which did neither.
14279                // `?` and not `unwrap_or(false)`: a proxy's `defineProperty` trap
14280                // may *throw*, and that exception is the answer
14281                // (`public-class-field-initialization-is-visible-to-proxy` throws
14282                // a `Test262Error` from the trap and expects it, not a `TypeError`).
14283                let defined =
14284                    self.object_define_own_property(target, key, Property::data(value))?;
14285                if !defined {
14286                    let target = Value::Object(target.clone());
14287                    return Err(Signal::Throw(self.make_error(
14288                        "TypeError",
14289                        &format!(
14290                            "cannot define property '{key}' of {}",
14291                            target.to_js_string()
14292                        ),
14293                    )));
14294                }
14295            }
14296        }
14297        Ok(())
14298    }
14299
14300    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
14301        let Value::Object(object) = object else {
14302            // `PutValue` on a property of a primitive is a silent no-op in sloppy mode and a
14303            // `TypeError` in strict mode: `sym.a = 1` on a Symbol must leave `sym.a`
14304            // `undefined` rather than throwing (`Symbol/auto-boxing-non-strict`). `null` and
14305            // `undefined` still throw, with their own message.
14306            if !self.current_strict() && !matches!(object, Value::Null | Value::Undefined) {
14307                return Ok(());
14308            }
14309            return Err(Signal::Throw(self.make_error(
14310                "TypeError",
14311                &format!("cannot set property '{key}' of {}", object.to_js_string()),
14312            )));
14313        };
14314        // The write half of the property inline cache, in effect: an own, writable,
14315        // non-accessor data property already holds this key, so `[[Set]]` has nothing to
14316        // decide — no prototype walk (an own property shadows the chain before a setter
14317        // there could matter), no extensibility check (the object already has the key),
14318        // and no `[[DefineOwnProperty]]`.
14319        //
14320        // `this.value = …` inside a method is the whole write side of
14321        // `property:method-call`, and it was reaching `set_property_with_key` with its
14322        // proxy test, its typed-array test, its array-index test and finally a linear
14323        // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
14324        //
14325        // Every disqualifier is checked here: a proxy traps the set, an array index and
14326        // `length` live outside the property table, and a typed array's element is stored
14327        // through its view's element type.
14328        if object.proxy_state().is_none()
14329            && !object.is_array()
14330            && object.typed_array_element_type().is_none()
14331            && object.write_value_key(key, value.clone())
14332        {
14333            return Ok(());
14334        }
14335        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
14336        let on_failure = if self.frame().code.code.strict {
14337            DeleteFailure::Throw
14338        } else {
14339            DeleteFailure::Ignore
14340        };
14341        self.set_property_with_key(object, key, value, on_failure)
14342    }
14343
14344    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
14345    ///
14346    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
14347    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
14348    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
14349    /// `Number.parseInt(sym)` — so those callers use this instead.
14350    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
14351        if matches!(value, Value::Symbol(_)) {
14352            return Err(Signal::Throw(
14353                self.make_error("TypeError", "cannot convert symbol to string"),
14354            ));
14355        }
14356        // An object runs `ToPrimitive` first, which may itself produce a symbol —
14357        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
14358        let value = self.to_primitive(value.clone(), Hint::String)?;
14359        if matches!(value, Value::Symbol(_)) {
14360            return Err(Signal::Throw(
14361                self.make_error("TypeError", "cannot convert symbol to string"),
14362            ));
14363        }
14364        Ok(value.to_js_string())
14365    }
14366
14367    /// `ToPropertyKey` for a builtin that takes a key argument.
14368    ///
14369    /// Fallible: a key whose `toString` throws has to propagate that error, both for
14370    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
14371    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
14372    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
14373    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
14374        self.propkey(value)
14375    }
14376
14377    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
14378    ///
14379    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
14380    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
14381    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
14382    /// `RangeError` — and why this cannot be a plain `ToNumber`.
14383    /// `ToNumber(value)` for `ArraySetLength`, which the spec performs **twice**.
14384    ///
14385    /// §10.4.2.4 steps 3–5 are `ToUint32(Desc.[[Value]])`, then `ToNumber(Desc.[[Value]])`,
14386    /// then a `RangeError` when they disagree. Two conversions rather than one is
14387    /// observable: a `valueOf` that runs the first time can make `length` non-writable
14388    /// before the second, which turns the store into a refused write
14389    /// (`length/define-own-prop-length-coercion-order`, `…-set`).
14390    pub fn coerce_array_length_twice(&mut self, value: &Value) -> JsResult<u32> {
14391        let first = self.array_length_of(value)?;
14392        let second = self.array_length_of(value)?;
14393        debug_assert_eq!(first, second);
14394        Ok(first)
14395    }
14396
14397    /// `ArraySetLength`'s `ToNumber(value)`, then the `ToUint32` round-trip check.
14398    ///
14399    /// Separate from [`Interp::coerce_array_length_twice`] so the callers that need one
14400    /// conversion can say so; a caller that needs the spec's two uses that instead.
14401    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
14402        let number = match value {
14403            Value::Int(number) => *number as f64,
14404            Value::Float(number) => *number,
14405            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
14406            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
14407            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
14408            // reference answers 0.
14409            Value::Null | Value::Bool(_) | Value::Undefined => value.to_number(),
14410            // A string goes through the full numeric-literal grammar: `"0x00B"` is 11 and
14411            // `"  5  "` is 5, which is exactly what `string_to_number` implements.
14412            Value::String(text) => crate::value::string_to_number(&text.to_string_lossy()),
14413            _ => {
14414                // The primitive comes back through this same conversion, so a wrapper of a
14415                // boolean (`new Boolean(false)`) is `0` rather than the `NaN` that
14416                // `ToNumber("false")` would give — `S15.4.5.1_A1.3_T1` walks every wrapper.
14417                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
14418                return self.array_length_of(&primitive);
14419            }
14420        };
14421        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
14422        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
14423        // is a `RangeError`, not `0`.
14424        if !number.is_finite()
14425            || number.fract() != 0.0
14426            || !(0.0..=u32::MAX as f64).contains(&number)
14427        {
14428            return Err(self.range_error("invalid array length"));
14429        }
14430        Ok(number as u32)
14431    }
14432
14433    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
14434    /// `Object.getOwnPropertySymbols` put in their result array.
14435    pub fn key_value(&self, key: &PropertyKey) -> Value {
14436        match key {
14437            PropertyKey::String(text) => self.string_wtf8(text.clone()),
14438            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
14439        }
14440    }
14441
14442    /// Fill in a String exotic object: `_value`, `length` and the index properties.
14443    ///
14444    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
14445    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
14446    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
14447    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
14448    /// the two paths had drifted; this is the one both now use.
14449    ///
14450    /// The indices are *code units*, so an astral character occupies two of them — the
14451    /// same rule `s.length` and `s[i]` follow.
14452    /// Give an already-created object the internal slot that makes it a wrapper of
14453    /// `value`, so the primitive's prototype methods work on it.
14454    ///
14455    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
14456    /// which are wrappers of their own type holding the empty value.
14457    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
14458        self.internal_set(object, "_value", value);
14459    }
14460
14461    pub(crate) fn init_string_wrapper(
14462        &mut self,
14463        object: &Gc<JsObject>,
14464        text: &Gc<crate::value::JsString>,
14465    ) {
14466        object.define(
14467            "length",
14468            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
14469        );
14470        for index in 0..text.utf16_len() {
14471            if let Some(unit) = text.wtf8().unit_at(index) {
14472                object.define(
14473                    &index.to_string(),
14474                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
14475                    Property::with_attributes(self.string_wtf8(unit), false, true),
14476                );
14477            }
14478        }
14479        object.define_key(
14480            &self.internal_slot("_value"),
14481            Property::with_attributes(Value::String(text.clone()), false, false),
14482        );
14483    }
14484
14485    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
14486    ///
14487    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
14488    /// throws. The wrapper carries its primitive in `_value` — the same slot
14489    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
14490    /// on a boxed value no constructor ever built.
14491    pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
14492        let (prototype, primitive) = match value {
14493            Value::Object(object) => return Ok(object.clone()),
14494            Value::String(text) => {
14495                let object = self.new_object(self.realm.string_proto.clone());
14496                self.init_string_wrapper(&object, text);
14497                return Ok(object);
14498            }
14499            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
14500            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
14501            // A symbol and a bigint box into wrappers whose methods live on
14502            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
14503            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
14504            // branch below instead produced an object with *no* prototype, so those
14505            // methods were unreachable on a box.
14506            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
14507            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
14508            Value::Undefined | Value::Null => {
14509                return Err(Signal::Throw(self.make_error(
14510                    "TypeError",
14511                    &format!("cannot convert {} to object", value.to_js_string()),
14512                )));
14513            }
14514            _ => (None, value.clone()),
14515        };
14516        let object = self.new_object(prototype);
14517        self.internal_set(&object, "_value", primitive);
14518        Ok(object)
14519    }
14520
14521    /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
14522    ///
14523    /// Split out for a reader that has to create the object *before* it knows what it wraps:
14524    /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
14525    /// written before its primitive, so the placeholder has to exist first and be filled in
14526    /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
14527    /// than a second in the deserialiser.
14528    pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
14529        let prototype = match value {
14530            Value::String(_) => self.realm.string_proto.clone(),
14531            Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
14532            Value::Bool(_) => self.realm.boolean_proto.clone(),
14533            Value::Symbol(_) => self.realm.symbol_proto.clone(),
14534            Value::BigInt(_) => self.realm.bigint_proto.clone(),
14535            _ => {
14536                return Err(Signal::Throw(self.make_error(
14537                    "TypeError",
14538                    &format!("cannot box {}", value.to_js_string()),
14539                )));
14540            }
14541        };
14542        object.set_proto(prototype);
14543        if let Value::String(text) = value {
14544            self.init_string_wrapper(object, text);
14545            return Ok(());
14546        }
14547        self.internal_set(object, "_value", value.clone());
14548        Ok(())
14549    }
14550
14551    /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
14552    ///
14553    /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
14554    /// through the `Symbol` function object, so the registry is reachable as a method rather
14555    /// than only from `builtins::symbol`.
14556    pub fn symbol_for(&mut self, key: &str) -> Value {
14557        if let Some(existing) = self.realm.symbol_registry.get(key) {
14558            return existing.clone();
14559        }
14560        let symbol = crate::builtins::symbol::symbol_value(
14561            self,
14562            crate::value::JsSymbol::registered(key.to_string()),
14563        );
14564        self.realm
14565            .symbol_registry
14566            .insert(key.to_string(), symbol.clone());
14567        symbol
14568    }
14569
14570    /// `a == b`, the coercing comparison.
14571    ///
14572    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
14573    /// which is what makes `[] == ""` true: `[]` becomes `""` via
14574    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
14575    /// because the conversion is allowed to call script code, so the two primitive
14576    /// operands are handed back to it.
14577    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
14578        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
14579            return Ok(left.loose_equals(&right));
14580        }
14581        // `null == undefined` holds even though neither is an object.
14582        if matches!(left, Value::Undefined | Value::Null)
14583            && matches!(right, Value::Undefined | Value::Null)
14584        {
14585            return Ok(true);
14586        }
14587        if matches!(left, Value::Undefined | Value::Null)
14588            || matches!(right, Value::Undefined | Value::Null)
14589        {
14590            return Ok(false);
14591        }
14592        // Two objects compare by identity. Only an object *against a primitive* is
14593        // converted, which is why `{} == {}` is false while `[] == ""` is true.
14594        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
14595            return Ok(a.ptr_eq(b));
14596        }
14597        let left = self.to_primitive(left, Hint::Default)?;
14598        let right = self.to_primitive(right, Hint::Default)?;
14599        Ok(left.loose_equals(&right))
14600    }
14601
14602    /// `HasBinding(N)` for an Object Environment Record whose binding object is `object`.
14603    ///
14604    /// §9.1.1.2.1: `HasProperty` **and then** not listed in the object's
14605    /// `Symbol.unscopables`. The `unscopables` object is read with a plain `Get`, so a
14606    /// getter on it runs exactly once per lookup — `with/with-get-unscopables-once` counts
14607    /// the calls.
14608    fn with_has_binding(&mut self, object: &Value, name: &str) -> JsResult<bool> {
14609        let key = PropertyKey::from(name);
14610        if !self.has_property_value(object, &key)? {
14611            return Ok(false);
14612        }
14613        let unscopables_key = self.realm.well_known_key(WellKnown::Unscopables);
14614        let unscopables = self.read_field_key(object, &unscopables_key)?;
14615        let Value::Object(_) = unscopables else {
14616            // `undefined` (the usual case) or a primitive: nothing is excluded.
14617            return Ok(true);
14618        };
14619        let excluded = self.read_field_key(&unscopables, &key)?;
14620        Ok(!excluded.to_boolean())
14621    }
14622
14623    /// `GetBindingValue(N, S)` for an Object Environment Record: §9.1.1.2.4.
14624    ///
14625    /// `HasProperty` is asked a **second** time — the guard already asked it — because the
14626    /// object may have changed in between: `GetBindingValue` step 2 is a fresh lookup, and
14627    /// a proxy sees two `has` traps plus the `get`. The `unscopables` step is *not*
14628    /// repeated: that belongs to `HasBinding`, not to `GetBindingValue`.
14629    ///
14630    /// When the property has gone, strict code throws and sloppy code reads `undefined`
14631    /// from the environment (step 2's `S` is the strictness of the *running* code, not of
14632    /// the declaration).
14633    fn with_get_binding(&mut self, object: &Value, name: &str) -> JsResult<Value> {
14634        let key = PropertyKey::from(name);
14635        if !self.has_property_value(object, &key)? {
14636            if self.frame().code.code.strict {
14637                return Err(self.throw_reference(name));
14638            }
14639            return Ok(Value::Undefined);
14640        }
14641        self.read_field_key(object, &key)
14642    }
14643
14644    /// `SetMutableBinding(N, V, S)` for an Object Environment Record: §9.1.1.2.5.
14645    ///
14646    /// Same second `HasProperty`, and the same strict-mode `ReferenceError` when the
14647    /// property is gone — before the store, which is what makes
14648    /// `set-mutable-binding-binding-deleted-with-typed-array-in-proto-chain-strict-mode`
14649    /// a `ReferenceError` rather than whatever the failed store would have thrown.
14650    fn with_put_binding(&mut self, object: &Value, name: &str, value: Value) -> JsResult<()> {
14651        let key = PropertyKey::from(name);
14652        if !self.has_property_value(object, &key)? && self.frame().code.code.strict {
14653            return Err(self.throw_reference(name));
14654        }
14655        self.write_field_key(object, &key, value)
14656    }
14657
14658    /// `HasProperty(O, P)` on a `Value`, without the `in`-operator error for a primitive.
14659    fn has_property_value(&mut self, object: &Value, key: &PropertyKey) -> JsResult<bool> {
14660        match object {
14661            Value::Object(target) => self.has_property_key(target, key),
14662            // `with` boxes its object when the statement is entered (`to_object`), so a
14663            // primitive cannot arrive here; `false` is the honest answer rather than a
14664            // panic if it ever does.
14665            _ => Ok(false),
14666        }
14667    }
14668
14669    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
14670        let Value::Object(object) = object else {
14671            return Err(Signal::Throw(
14672                self.make_error("TypeError", "cannot use 'in' on a non-object"),
14673            ));
14674        };
14675        let key = self.propkey(key)?;
14676        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
14677        // trap. One implementation, so an array's derived `length` and its inherited holes
14678        // cannot be right in one caller and wrong in another.
14679        self.has_own_or_inherited(object, &key)
14680    }
14681
14682    /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
14683    ///
14684    /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
14685    /// whole reason the operator is a hook rather than a prototype walk.
14686    ///
14687    /// §13.10.2 `InstanceofOperator(O, C)`, which is stricter than
14688    /// [`Interp::ordinary_instance_of`]: step 1 throws when `C` is not an object at all
14689    /// (`true instanceof true`) and step 4 throws when it is an object but not callable
14690    /// (`1 instanceof Math`). Both used to answer `false`, which is `OrdinaryHasInstance`'s
14691    /// rule (its step 2) and not this operator's — so nine `expressions/instanceof` cases
14692    /// expected a `TypeError` and got a value.
14693    pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14694        // Step 1, before any method lookup.
14695        if constructor.as_object().is_none() {
14696            return Err(Signal::Throw(self.make_error(
14697                "TypeError",
14698                "right-hand side of 'instanceof' is not an object",
14699            )));
14700        }
14701        let Value::Object(function) = constructor else {
14702            unreachable!("just checked");
14703        };
14704        // Step 2. A primitive `C` cannot reach here, so `get_property_key` on the object is
14705        // the whole of it.
14706        let key = self.realm.well_known_key(WellKnown::HasInstance);
14707        let method = self.get_property_key(function, &key)?;
14708        if let Some(method) = method
14709            && !matches!(method, Value::Undefined)
14710        {
14711            let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
14712            return Ok(answer.to_boolean());
14713        }
14714        // Step 4.
14715        if !function.is_callable() {
14716            return Err(Signal::Throw(self.make_error(
14717                "TypeError",
14718                "right-hand side of 'instanceof' is not callable",
14719            )));
14720        }
14721        // Step 5.
14722        self.instance_of(object, constructor)
14723    }
14724
14725    /// `OrdinaryHasInstance`: the prototype walk on its own.
14726    pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14727        self.instance_of(object, constructor)
14728    }
14729
14730    /// `IsArray`: an array, or a proxy whose target is one.
14731    ///
14732    /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
14733    /// makes `Array.isArray(new Proxy([], {}))` true.
14734    pub fn is_array_value(&self, value: &Value) -> bool {
14735        match value {
14736            Value::Object(object) => {
14737                if let Some(state) = object.proxy_state() {
14738                    return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
14739                }
14740                object.is_array()
14741            }
14742            _ => false,
14743        }
14744    }
14745
14746    /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
14747    ///
14748    /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
14749    /// in a Rust closure would hide GC values from the collector. A host-supplied job is
14750    /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
14751    /// see [`Interp::enqueue_job_function`].
14752    pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
14753        // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
14754        // the handler is reported rather than lost — the same reason a `then` reaction needs a
14755        // promise to settle.
14756        let promise = self.new_promise();
14757        self.fulfill_promise(&promise, Value::Undefined);
14758        self.jobs.push_back(Job::Reaction {
14759            handler: Some(function),
14760            argument: Value::Undefined,
14761            rejected: false,
14762            promise,
14763        });
14764        Ok(())
14765    }
14766
14767    /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
14768    ///
14769    /// Four of its steps were missing or wrong, and each one is a test262 case in
14770    /// `Function/prototype/Symbol.hasInstance/`:
14771    ///
14772    /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
14773    /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
14774    ///   `[[BoundThis]]` standing in for the object when that is an object), which is why
14775    ///   `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
14776    ///   `prototype` of its own, so without this step the walk below gives `false`;
14777    /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
14778    /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
14779    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14780        let Value::Object(function) = constructor else {
14781            return Ok(false);
14782        };
14783        if !function.is_callable() {
14784            return Ok(false);
14785        }
14786        // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
14787        // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
14788        // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
14789        if let Some((target, this)) = function.bound_target_and_this() {
14790            let object = if this.as_object().is_some() {
14791                this
14792            } else {
14793                object.clone()
14794            };
14795            return self.instance_of(&object, &target);
14796        }
14797        let Value::Object(target) = object else {
14798            return Ok(false);
14799        };
14800        let prototype = self.get_property(function, "prototype")?;
14801        let Some(Value::Object(prototype)) = prototype else {
14802            return Err(Signal::Throw(self.make_error(
14803                "TypeError",
14804                "function has non-object prototype in instanceof check",
14805            )));
14806        };
14807        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
14808        // which is also what makes `proxyOfInstance instanceof C` work.
14809        let mut current = Some(target.clone());
14810        while let Some(object) = current {
14811            if object.ptr_eq(&prototype) {
14812                return Ok(true);
14813            }
14814            current = self.object_prototype_of(&object)?;
14815        }
14816        Ok(false)
14817    }
14818
14819    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
14820    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
14821        if let Some(proto) = self.proxy_get_prototype_of(object)? {
14822            return Ok(proto);
14823        }
14824        if let Some(exotic) = object.exotic()
14825            && let Some(proto) = exotic.get_prototype(self, object)?
14826        {
14827            return Ok(proto);
14828        }
14829        Ok(object.proto())
14830    }
14831
14832    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
14833    pub fn object_set_prototype_of(
14834        &mut self,
14835        object: &Gc<JsObject>,
14836        proto: Option<Gc<JsObject>>,
14837    ) -> JsResult<bool> {
14838        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
14839            return Ok(answer);
14840        }
14841        if let Some(exotic) = object.exotic()
14842            && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
14843        {
14844            return Ok(answer);
14845        }
14846        // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
14847        // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
14848        // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
14849        // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
14850        if self
14851            .internal_get(object, "_immutable_proto")
14852            .is_some_and(|flag| flag.to_boolean())
14853            && !same_proto(object.proto().as_ref(), proto.as_ref())
14854        {
14855            return Ok(false);
14856        }
14857        // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
14858        // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
14859        // inheriting from itself, which every later prototype walk then had to defend
14860        // against — and `Reflect.setPrototypeOf` reported success for an operation the
14861        // language says is impossible.
14862        if let Some(proto) = &proto {
14863            let mut current = Some(proto.clone());
14864            let mut guard = 0;
14865            while let Some(node) = current {
14866                if node.ptr_eq(object) {
14867                    // §10.1.2.1 step 5.a: a cycle is `return false`, not a throw —
14868                    // `Object.setPrototypeOf` turns that `false` into the `TypeError`,
14869                    // while `Reflect.setPrototypeOf` reports it
14870                    // (`setPrototypeOf/return-false-if-target-is-prototype-of-proto`).
14871                    return Ok(false);
14872                }
14873                guard += 1;
14874                if guard > 1000 {
14875                    break;
14876                }
14877                current = node.proto();
14878            }
14879        }
14880        // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
14881        // re-setting it to the *same* one is a no-op `true`. Missing this made
14882        // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
14883        // actually reparent the object — and it is what
14884        // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
14885        // forwarding path has nothing else left to refuse it.
14886        if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
14887            return Ok(false);
14888        }
14889        object.set_proto(proto);
14890        Ok(true)
14891    }
14892
14893    /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
14894    ///
14895    /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
14896    /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
14897    /// already one.
14898    /// `HasProperty(O, P)`.
14899    ///
14900    /// One implementation, shared with the `in` operator. It used to be a second copy that
14901    /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
14902    /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
14903    /// proxy ran the wrong hook and could even disagree with `in`. The
14904    /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
14905    /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
14906    pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
14907        self.has_own_or_inherited(object, key)
14908    }
14909
14910    /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
14911    ///
14912    /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
14913    /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
14914    /// boolean as well, and it needs the receiver to be the one the caller named.
14915    pub fn set_property_with_key_receiver(
14916        &mut self,
14917        object: &Gc<JsObject>,
14918        key: &PropertyKey,
14919        value: Value,
14920        receiver: Option<&Value>,
14921        on_failure: DeleteFailure,
14922    ) -> JsResult<bool> {
14923        let receiver = receiver
14924            .cloned()
14925            .unwrap_or_else(|| Value::Object(object.clone()));
14926        if object.proxy_state().is_some() {
14927            return match self.proxy_set(object, key, value, &receiver)? {
14928                Some(accepted) => Ok(accepted),
14929                None => Ok(true),
14930            };
14931        }
14932        // §10.4.6.7: a module namespace's `[[Set]]` always answers false, whatever the
14933        // receiver. This has to be answered here as well as in the storing path below,
14934        // because `Reflect.set` reports the refusal as a `bool` instead of raising.
14935        if object.module_namespace_marker() {
14936            return Ok(false);
14937        }
14938        // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
14939        // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
14940        // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
14941        // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
14942        //
14943        // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
14944        //
14945        // * `SameValue(O, Receiver)` stores into the buffer, converting first;
14946        // * an *invalid* index with a different receiver answers `true` and does nothing,
14947        //   not even converting `V` (`valueOfCalls` stays 0);
14948        // * a valid index with a different receiver falls through to
14949        //   `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
14950        //   value lands on the **receiver**, unconverted, and can be refused by a
14951        //   non-extensible receiver, an accessor, or a read-only index there.
14952        //
14953        // The last one used to write into the view itself, which left `target[0]` changed
14954        // and `receiver[0]` untouched — backwards.
14955        if object.typed_array_element_type().is_some()
14956            && let Some(numeric) = canonical_numeric_index(key)
14957        {
14958            let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14959            if same {
14960                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14961                return Ok(true);
14962            }
14963            if !typed_array_index_is_valid(object, numeric) {
14964                return Ok(true);
14965            }
14966            let Some(receiver) = receiver.as_object().cloned() else {
14967                return Ok(false);
14968            };
14969            if let Some(existing) = self.object_get_own_property(&receiver, key)? {
14970                if existing.is_accessor() || !existing.writable {
14971                    return Ok(false);
14972                }
14973                let property = Property {
14974                    value: Some(value),
14975                    ..existing
14976                };
14977                return self.object_define_own_property(&receiver, key, property);
14978            }
14979            return self.object_define_own_property(&receiver, key, Property::data(value));
14980        }
14981        // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
14982        // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
14983        // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
14984        // `Reflect.set` to *report* the refusal instead of raising.
14985        //
14986        // A receiver that is not the object turns the whole operation into
14987        // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
14988        // `[[Set]]` rather than a lookup — that is what makes
14989        // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
14990        // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
14991        // writes to `object`, so it cannot express that and is only used when the two are
14992        // the same.
14993        let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14994        if !same {
14995            return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
14996        }
14997        // Same receiver: the plain path below writes into `object`, which is right, but it
14998        // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
14999        // boolean, so the two step-1 refusals have to be read off the own descriptor here.
15000        if let Some(existing) = self.object_get_own_property(object, key)? {
15001            if existing.is_accessor() {
15002                return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
15003                    Some(setter) => {
15004                        self.call_value(setter, receiver, vec![value])?;
15005                        Ok(true)
15006                    }
15007                    None => Ok(false),
15008                };
15009            }
15010            if !existing.writable {
15011                return Ok(false);
15012            }
15013        }
15014        // Otherwise it is an ordinary create-or-write into `object` itself.
15015        self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
15016        Ok(true)
15017    }
15018
15019    /// `[[IsExtensible]]`, with the proxy trap when there is one.
15020    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
15021        if let Some(answer) = self.proxy_is_extensible(object)? {
15022            return Ok(answer);
15023        }
15024        if let Some(exotic) = object.exotic()
15025            && let Some(answer) = exotic.is_extensible(self, object)?
15026        {
15027            return Ok(answer);
15028        }
15029        Ok(object.is_extensible())
15030    }
15031
15032    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
15033    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
15034        if let Some(answer) = self.proxy_prevent_extensions(object)? {
15035            return Ok(answer);
15036        }
15037        // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
15038        //
15039        // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
15040        //
15041        // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
15042        // created with an explicit length, because the buffer can still move it. That is
15043        // what makes `Object.freeze` refuse every such view, including a zero-length one
15044        // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
15045        // plain buffer is allowed.
15046        if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
15047            && buffer
15048                .array_buffer_storage()
15049                .is_some_and(|storage| storage.borrow().is_resizable())
15050        {
15051            return Err(
15052                self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
15053            );
15054        }
15055        if let Some(exotic) = object.exotic()
15056            && let Some(answer) = exotic.prevent_extensions(self, object)?
15057        {
15058            return Ok(answer);
15059        }
15060        object.set_extensible(false);
15061        Ok(true)
15062    }
15063
15064    fn copy_properties(
15065        &mut self,
15066        target: &Value,
15067        source: &Value,
15068        exclusion: &Value,
15069    ) -> JsResult<()> {
15070        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
15071        // does contribute: its index properties are own, enumerable and writable, which
15072        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
15073        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
15074        // is a no-op.
15075        let Some(target) = target.as_object() else {
15076            return Ok(());
15077        };
15078        let source_object = match source {
15079            Value::Object(object) => object.clone(),
15080            Value::String(text) => {
15081                // Untaken keys are the string's indices, which are code units.
15082                for index in 0..text.utf16_len() {
15083                    if let Some(unit) = text.wtf8().unit_at(index) {
15084                        target.define_data(&index.to_string(), self.string_wtf8(unit));
15085                    }
15086                }
15087                return Ok(());
15088            }
15089            _ => return Ok(()),
15090        };
15091        // An object *rest* element passes the keys already taken by the literal part as
15092        // an array of **key values**; a spread passes `null`, which excludes nothing. The
15093        // array is read by its elements rather than by its own property names, and the
15094        // values stay `PropertyKey`s: a computed key can be a symbol, and
15095        // `{[sym]: a, ...rest}` has to leave `sym` out of `rest`
15096        // (`object-rest-proxy-gopd-not-called-on-excluded-keys`). Flattening them to
15097        // strings made a symbol exclusion a no-op.
15098        let mut excluded: Vec<PropertyKey> = Vec::new();
15099        if let Value::Object(list) = exclusion
15100            && let Some(length) = list.array_length()
15101        {
15102            for index in 0..length {
15103                if let Some(value) = list.array_get(index) {
15104                    excluded.push(self.propkey(&value)?);
15105                }
15106            }
15107        }
15108        let source = &source_object;
15109        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
15110        // Reading the property table directly made every spread of a proxy empty.
15111        let keys = self.object_own_property_keys(source)?;
15112        for as_key in keys {
15113            // §7.3.25 step 4 walks `[[OwnPropertyKeys]]`, so **symbol**-keyed properties
15114            // are copied as well — `{...{[Symbol("s")]: 1}}` has one own symbol key.
15115            // Skipping them silently lost every symbol on every spread and every object
15116            // rest element (`obj-rest-order`).
15117            //
15118            if excluded.contains(&as_key) {
15119                continue;
15120            }
15121            let enumerable = self
15122                .object_get_own_property(source, &as_key)?
15123                .is_some_and(|property| property.enumerable);
15124            if !enumerable {
15125                continue;
15126            }
15127            let value = self
15128                .get_property_key(source, &as_key)?
15129                .unwrap_or(Value::Undefined);
15130            target.define_data_key(&as_key, value);
15131        }
15132        Ok(())
15133    }
15134
15135    // -- iteration ---------------------------------------------------------
15136
15137    /// One object's own keys in enumeration order: array indices ascending, then the
15138    /// rest in insertion order.
15139    ///
15140    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
15141    /// whether the key is enumerable, which the caller resolves per key because an
15142    /// array's elements are not in the same store as its named properties.
15143    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
15144        // An index can arrive twice, once from the array's element store and once from
15145        // its property map, so the numeric keys go through a map that keeps the
15146        // enumerable answer if either source gave one.
15147        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
15148        for (key, enumerable) in &own {
15149            if let Some(index) = key.as_str().and_then(array_index) {
15150                let entry = numeric.entry(index).or_insert(false);
15151                *entry = *entry || *enumerable;
15152            }
15153        }
15154        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
15155            .into_iter()
15156            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
15157            .collect();
15158        ordered.extend(
15159            own.into_iter()
15160                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
15161        );
15162        ordered
15163    }
15164
15165    /// Build the key list a `for-in` loop walks.
15166    ///
15167    /// The order is the specification's: own properties before inherited ones, and
15168    /// within one object the integer-like keys in ascending numeric order ahead of the
15169    /// string keys in insertion order. A shadowed key only appears once, and a key that
15170    /// is a non-enumerable own property anywhere nearer is skipped entirely.
15171    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
15172        let record = self.new_object(None);
15173        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
15174        // A proxy supplies its own key list, and — the reason this is not just another
15175        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
15176        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
15177        // descriptor there.
15178        if let Value::Object(object) = value
15179            && object.proxy_state().is_some()
15180        {
15181            let own = self
15182                .proxy_own_keys(object)?
15183                .unwrap_or_else(|| object.own_property_keys());
15184            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
15185            let mut numeric: Vec<u32> = Vec::new();
15186            let mut rest: Vec<PropertyKey> = Vec::new();
15187            for key in own {
15188                match key.as_str().and_then(array_index) {
15189                    Some(index) => numeric.push(index),
15190                    None => rest.push(key),
15191                }
15192            }
15193            numeric.sort_unstable();
15194            ordered.extend(
15195                numeric
15196                    .into_iter()
15197                    .map(|index| PropertyKey::from(index.to_string())),
15198            );
15199            ordered.extend(rest);
15200            for (index, key) in ordered.into_iter().enumerate() {
15201                record.define_data(&index.to_string(), self.key_value(&key));
15202            }
15203            record.define_data("__index", Value::Int(0));
15204            // The mark that makes `for_in_advance` re-ask the proxy per key.
15205            record.define_data("__proxy", Value::Object(object.clone()));
15206            return Ok(record);
15207        }
15208        if let Value::Object(object) = value {
15209            let mut chain = vec![object.clone()];
15210            chain.extend(object.chain());
15211            // Every own string key the walk has seen, enumerable or not. A
15212            // non-enumerable own property still hides a same-named enumerable one
15213            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
15214            // keeps `x` out of the loop even when the prototype has one.
15215            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
15216            for object in chain {
15217                // A namespace's bindings are materialised by `[[GetOwnProperty]]`, and a
15218                // binding still in its dead zone throws there (§10.4.6.8). Enumerating
15219                // through the raw table skipped that, so `for (var k in ns)` on a namespace
15220                // whose module was still evaluating saw the keys and read `undefined`
15221                // (`namespace/internals/enumerate-binding-uninit`).
15222                if object.module_namespace_marker() {
15223                    for key in object.own_property_keys() {
15224                        self.object_get_own_property(&object, &key)?;
15225                    }
15226                }
15227                let mut own: Vec<(crate::value::Wtf8, bool)> = object
15228                    .own_property_keys()
15229                    .iter()
15230                    .filter_map(|key| key.as_wtf8().cloned())
15231                    .map(|key| {
15232                        let enumerable = object
15233                            .own_property(&key.to_string_lossy())
15234                            .map(|property| property.enumerable)
15235                            .unwrap_or(false);
15236                        (key, enumerable)
15237                    })
15238                    .collect();
15239                if let Some(length) = object.array_length() {
15240                    own.retain(|(key, _)| key.as_str() != Some("length"));
15241                    for index in 0..length {
15242                        // A dense element is enumerable; a **hole** is not there at all —
15243                        // and a hole is also what an index with a recorded descriptor
15244                        // leaves behind, in which case the table entry above already
15245                        // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
15246                        // defines index 0 non-enumerable and `for…in` must skip it).
15247                        if let Some(value) = object.array_get(index)
15248                            && !matches!(value, Value::Hole)
15249                        {
15250                            own.push((crate::value::Wtf8::new(index.to_string()), true));
15251                        }
15252                    }
15253                }
15254                // Integer-like keys come first in ascending order, then the rest in
15255                // insertion order — and the ordering is *per object*, not for the chain
15256                // as a whole: one pass over every collected key lifted a prototype's
15257                // `"4"` above the target's own `x`/`y`, which is not the order
15258                // `for…in` reports.
15259                for (key, enumerable) in Self::order_own_keys(own) {
15260                    if visited.contains(&key) {
15261                        continue;
15262                    }
15263                    visited.push(key.clone());
15264                    if enumerable {
15265                        keys.push(key);
15266                    }
15267                }
15268            }
15269        }
15270        for (index, key) in keys.into_iter().enumerate() {
15271            record.define_data(&index.to_string(), self.string_wtf8(key));
15272        }
15273        record.define_data("__index", Value::Int(0));
15274        Ok(record)
15275    }
15276
15277    /// The next key of a `for…in` record, `None` when the loop is done.
15278    ///
15279    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
15280    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
15281    /// the loop reaches it, so a handler that stops reporting a key partway through drops
15282    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
15283    /// key the handler had already withdrawn.
15284    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
15285        let Value::Object(record) = record else {
15286            return Ok(None);
15287        };
15288        let proxy = record
15289            .own_property("__proxy")
15290            .and_then(|property| property.value);
15291        loop {
15292            let index = record
15293                .own_property("__index")
15294                .and_then(|property| property.value)
15295                .map(|value| value.to_int32())
15296                .unwrap_or(0);
15297            let Some(candidate) = record
15298                .own_property(&index.to_string())
15299                .and_then(|property| property.value)
15300            else {
15301                return Ok(None);
15302            };
15303            record.define_data("__index", Value::Int(index + 1));
15304            let text = candidate.to_js_string();
15305            let Some(Value::Object(proxy)) = &proxy else {
15306                return Ok(Some(text));
15307            };
15308            // The candidate is already a key string here, so the lookup does not need a
15309            // second `ToPropertyKey` conversion.
15310            let key = PropertyKey::from(text.as_str());
15311            let live = match self.proxy_get_own_property(proxy, &key)? {
15312                Some(descriptor) => descriptor,
15313                // Not a proxy after all, or it lost its state: fall back to the target.
15314                None => proxy.own_property_key(&key),
15315            };
15316            if live.is_some_and(|property| property.enumerable) {
15317                return Ok(Some(text));
15318            }
15319            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
15320            // next one.
15321        }
15322    }
15323
15324    /// The iterator for `for-of`: the object and its `next` method.
15325    ///
15326    /// An object that already carries a `next` method is used as it is — that is what
15327    /// `arr.values()` returns — and only arrays and strings get the built-in
15328    /// sequence iterator.
15329    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
15330    ///
15331    /// Callers that must choose between the iterable and the array-like protocol — the
15332    /// typed-array constructor is the main one — need to ask *before* committing to one.
15333    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
15334        let key = self.realm.well_known_key(WellKnown::Iterator);
15335        let method = self.read_field_key(value, &key)?;
15336        if matches!(method, Value::Undefined | Value::Null) {
15337            return Ok(false);
15338        }
15339        if !matches!(&method, Value::Object(object) if object.is_callable()) {
15340            return Err(Signal::Throw(
15341                self.make_error("TypeError", "Symbol.iterator is not callable"),
15342            ));
15343        }
15344        Ok(true)
15345    }
15346
15347    /// Collect everything an iterable yields.
15348    ///
15349    /// The cap is a guard against a generator that never ends: an unbounded collect would
15350    /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
15351    /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
15352    /// `MAX_ARRAY_LIKE` in the `Array` builtins.
15353    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
15354        const MAX_ITEMS: usize = 1 << 24;
15355        let iterator = self.get_iterator(value)?;
15356        let mut out = Vec::new();
15357        loop {
15358            let (element, done) = self.iterator_step(&iterator)?;
15359            if done {
15360                return Ok(out);
15361            }
15362            out.push(element);
15363            if out.len() > MAX_ITEMS {
15364                // Close before refusing: the walk is being abandoned, so the iterator's
15365                // `return` has to run (§7.4.6). Leaving it open left a `finally` block
15366                // unrun and a locked resource unreleased.
15367                self.close_iterator_after_throw(&iterator)?;
15368                return Err(self.range_error("iterable is too long to collect"));
15369            }
15370        }
15371    }
15372
15373    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
15374    ///
15375    /// A native constructor calls this once it has validated its arguments, which is the
15376    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
15377    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
15378    /// never reached. The prototype comes from `new.target` when it is an object, and from
15379    /// `default_proto` otherwise.
15380    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
15381        let proto = self.ctor_prototype(default_proto)?;
15382        Ok(self.new_object(Some(proto)))
15383    }
15384
15385    /// An **array** whose prototype comes from `new.target`.
15386    ///
15387    /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
15388    /// instance from `new.target.prototype`, and building a plain array instead made every
15389    /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
15390    pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
15391        let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
15392        Ok(JsObject::array(self.heap, Some(proto), 0))
15393    }
15394
15395    /// `new.target.prototype` when this is a construction, or `None` for a plain call.
15396    ///
15397    /// The `Option` form is for the constructors that build their instance in a helper which
15398    /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
15399    /// from `await`'s internal promise, and only the first has a `new.target`.
15400    fn ctor_prototype_opt(
15401        &mut self,
15402        default_proto: Option<Gc<JsObject>>,
15403    ) -> JsResult<Option<Gc<JsObject>>> {
15404        // `active_new_target`: by the time a native constructor runs, `call_value` has
15405        // already consumed the parked value.
15406        let Some(target) = self
15407            .active_new_target
15408            .as_object()
15409            .cloned()
15410            .map(Value::Object)
15411        else {
15412            return Ok(default_proto);
15413        };
15414        let Some(target) = target.as_object().cloned() else {
15415            return Ok(default_proto);
15416        };
15417        match self.get_property(&target, "prototype")? {
15418            Some(Value::Object(proto)) => Ok(Some(proto)),
15419            _ => Ok(default_proto),
15420        }
15421    }
15422
15423    /// `new.target.prototype`, or `default_proto` when this is a plain call.
15424    fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
15425        let Some(target) = self.active_new_target.as_object().cloned() else {
15426            return Ok(default_proto);
15427        };
15428        match self.get_property(&target, "prototype")? {
15429            Some(Value::Object(proto)) => Ok(proto),
15430            _ => Ok(default_proto),
15431        }
15432    }
15433
15434    /// `CreateDataPropertyOrThrow(O, key, value)`.
15435    ///
15436    /// A *definition*, not an assignment. The difference is visible the moment the target
15437    /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
15438    /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
15439    /// replaces the descriptor. It is a `TypeError` only when the definition itself is
15440    /// refused (`configurable: false`).
15441    ///
15442    /// The fast path exists because this is called once per element by `map`, `filter`,
15443    /// `slice` and friends: a plain array with no custom element descriptors and a writable
15444    /// `length` can store straight into its element vector.
15445    pub fn create_data_property_or_throw(
15446        &mut self,
15447        object: &Gc<JsObject>,
15448        index: usize,
15449        value: Value,
15450    ) -> JsResult<()> {
15451        // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
15452        // an array (that is what `Array.isArray` must say), so the element fast path would
15453        // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
15454        // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
15455        // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
15456        // records the exact trap sequence.
15457        if object.proxy_state().is_none()
15458            && object.is_array()
15459            && object.elements_writable()
15460            && !object.has_element_descriptors()
15461            && object.is_extensible()
15462            && object.array_set(self.heap, index, value.clone())
15463        {
15464            return Ok(());
15465        }
15466        let key = PropertyKey::from(index.to_string());
15467        let property = Property {
15468            value: Some(value),
15469            writable: true,
15470            enumerable: true,
15471            configurable: true,
15472            ..Property::default()
15473        };
15474        // `CreateDataProperty` always asks for the default attributes, so it can only ever
15475        // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
15476        // the rest. Checking here rather than inside `object_define_own_property` is
15477        // deliberate: that function receives a fully-populated `Property` and cannot tell
15478        // an omitted attribute from an explicit `false`, so the generic check it would need
15479        // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
15480        // writable property (that cost eight `Object/defineProperty` tests).
15481        if object.proxy_state().is_none()
15482            && let Some(existing) = self.object_get_own_property(object, &key)?
15483            && !existing.configurable
15484        {
15485            return Err(self.type_error("cannot create the property"));
15486        }
15487        if self.object_define_own_property(object, &key, property)? {
15488            return Ok(());
15489        }
15490        Err(self.type_error("cannot create the property"))
15491    }
15492
15493    /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
15494    ///
15495    /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
15496    /// its callers have; this is the same operation for the named properties a built-in
15497    /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
15498    /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
15499    /// `Array.prototype` cannot see it — while `Set` would run that accessor.
15500    pub fn create_named_data_property_or_throw(
15501        &mut self,
15502        object: &Gc<JsObject>,
15503        key: &str,
15504        value: Value,
15505    ) -> JsResult<()> {
15506        let key = PropertyKey::from(key);
15507        let property = Property {
15508            value: Some(value),
15509            writable: true,
15510            enumerable: true,
15511            configurable: true,
15512            ..Property::default()
15513        };
15514        if object.proxy_state().is_none()
15515            && let Some(existing) = self.object_get_own_property(object, &key)?
15516            && !existing.configurable
15517        {
15518            return Err(self.type_error("cannot create the property"));
15519        }
15520        if self.object_define_own_property(object, &key, property)? {
15521            return Ok(());
15522        }
15523        Err(self.type_error("cannot create the property"))
15524    }
15525
15526    /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
15527    ///
15528    /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
15529    /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
15530    /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
15531    /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
15532    /// run user code and both can throw.
15533    pub fn species_constructor(
15534        &mut self,
15535        object: &Gc<JsObject>,
15536        default: Value,
15537    ) -> JsResult<Value> {
15538        let Some(constructor) = self.get_property(object, "constructor")? else {
15539            return Ok(default);
15540        };
15541        let constructor = match constructor {
15542            Value::Undefined => return Ok(default),
15543            Value::Object(constructor) => constructor,
15544            _ => return Err(self.type_error("constructor is not an object")),
15545        };
15546        let key = self.realm.well_known_key(WellKnown::Species);
15547        let species = self.get_property_key(&constructor, &key)?;
15548        match species {
15549            None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
15550            Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
15551            Some(_) => Err(self.type_error("species is not a constructor")),
15552        }
15553    }
15554
15555    /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
15556    ///
15557    /// The result is an array of `length` holes whose prototype comes from
15558    /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
15559    /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
15560    /// is why the `IsArray` check is the first step and not an optimisation.
15561    pub fn array_species_create(
15562        &mut self,
15563        original: &Value,
15564        length: usize,
15565    ) -> JsResult<Gc<JsObject>> {
15566        // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
15567        // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
15568        // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
15569        // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
15570        // `new_array_of_length` (`slice/create-non-array-invalid-len`).
15571        // `ArrayCreate(length)` is only reached when the result is a **plain array of this
15572        // realm** — the species may be a user function that ignores the length entirely, and
15573        // then `2**53 - 1` is not its problem
15574        // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
15575        // a short proxy and expects the copy loop to run).
15576        let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
15577            if length > ARRAY_CREATE_LIMIT {
15578                return Err(interp.range_error("invalid array length"));
15579            }
15580            Ok(interp.new_array_of_length(length))
15581        };
15582        let Some(object) = original.as_object().cloned() else {
15583            return default(self);
15584        };
15585        if !object.is_array() {
15586            return default(self);
15587        }
15588        // A `constructor` that *is* this realm's `Array` means "the default", and skipping
15589        // it here is what keeps `Array.prototype.map` from calling `Array` at all.
15590        let Some(constructor) = self.get_property(&object, "constructor")? else {
15591            return default(self);
15592        };
15593        let species = match constructor {
15594            Value::Undefined => return Ok(self.new_array_of_length(length)),
15595            Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
15596                return default(self);
15597            }
15598            Value::Object(constructor) => {
15599                let key = self.realm.well_known_key(WellKnown::Species);
15600                match self.get_property_key(&constructor, &key)? {
15601                    None | Some(Value::Undefined) | Some(Value::Null) => {
15602                        return default(self);
15603                    }
15604                    Some(species) => species,
15605                }
15606            }
15607            // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
15608            // is a `TypeError`, not "the default". Treating it as the default made
15609            // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
15610            // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
15611            // `concat/create-ctor-non-object` are the same rule three times.
15612            _ => return Err(self.type_error("constructor is not an object")),
15613        };
15614        // `IsConstructor(species)` decides whether step 7 may construct at all; a species
15615        // that is merely callable is the `create-species-non-ctor` case.
15616        if !matches!(&species, Value::Object(object) if object.is_constructor()) {
15617            return Err(self.type_error("species is not a constructor"));
15618        }
15619        // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
15620        // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
15621        // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
15622        let created = self.construct(
15623            species.clone(),
15624            species,
15625            vec![crate::object::length_value(length)],
15626        )?;
15627        let Some(created) = created.as_object().cloned() else {
15628            return Err(self.type_error("species constructor did not answer an object"));
15629        };
15630        // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
15631        // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
15632        // object, and `create-species-with-non-writable-property` asserts exactly that.
15633        // The length is set for the array case; the generic case is the caller's
15634        // `Set(A, "length", …)`.
15635        if created.is_array() {
15636            created.array_set_length(self.heap, length);
15637        }
15638        Ok(created)
15639    }
15640
15641    /// Whether `object` is this realm's `%Array%`.
15642    fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
15643        self.realm
15644            .array_constructor
15645            .as_ref()
15646            .is_some_and(|array| array.ptr_eq(object))
15647    }
15648
15649    /// A fresh `length`-hole array with the intrinsic prototype.
15650    pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
15651        let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
15652        array.array_set_length(self.heap, length);
15653        array
15654    }
15655
15656    /// Whether this call is a construction, i.e. `new.target` is defined.
15657    ///
15658    /// A native constructor receives `this = undefined` (it builds its own instance), so it
15659    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
15660    /// The native function currently executing, if any.
15661    pub fn current_native(&self) -> Option<Gc<JsObject>> {
15662        self.current_native.clone()
15663    }
15664
15665    /// Whether this call is a construction, i.e. `new.target` is defined.
15666    pub fn is_constructing(&self) -> bool {
15667        // `active_new_target`, not `pending_new_target`: the parked value is consumed by
15668        // `call_value` before a native runs, so by the time a constructor body asks, the
15669        // answer is only in the active slot.
15670        matches!(self.active_new_target, Value::Object(_))
15671    }
15672
15673    /// The `TypeError` a constructor too primitive to have a wrapper raises.
15674    ///
15675    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
15676    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
15677    /// happens inside the native function, which is why the trace carries an
15678    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
15679    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
15680    /// constructor`, and an unnamed one reports the leading space of `" is not a
15681    /// constructor"` because the reference formats the empty name as it is.
15682    ///
15683    /// It is also the answer for a `new.target` that cannot be named at all — not a
15684    /// function, or a throwing `name` getter — where the reference falls back to the bare
15685    /// `not a constructor`.
15686    pub fn not_a_constructor_error(&mut self) -> Signal {
15687        let target = self.active_new_target.clone();
15688        self.not_a_constructor_error_for(target)
15689    }
15690
15691    /// The same `TypeError` for an explicit target, for the callers that check
15692    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
15693    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
15694        let target = match target {
15695            Value::Object(target) if target.is_callable() => target,
15696            _ => return self.type_error("not a constructor"),
15697        };
15698        let name = match self.get_property(&target, "name") {
15699            Ok(Some(value)) => value.to_js_string(),
15700            _ => return self.type_error("not a constructor"),
15701        };
15702        self.type_error(format!("{name} is not a constructor"))
15703    }
15704
15705    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
15706    ///
15707    /// True whenever `new.target` is not the callee itself, or when it has no usable
15708    /// `prototype` — the cases where reading the property is observable at all.
15709    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
15710        match &self.active_new_target {
15711            Value::Object(target) => !target.ptr_eq(callee),
15712            Value::Undefined => false,
15713            _ => true,
15714        }
15715    }
15716
15717    /// The symbol key for one of the engine's own hidden slots.
15718    ///
15719    /// Cached on the realm, so every object of a kind shares one key and a slot can be
15720    /// read back by name.
15721    /// Whether any object on `object`'s **prototype chain** owns an array index.
15722    ///
15723    /// The one question the array methods' dense fast paths have to ask before touching the
15724    /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
15725    /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
15726    /// vector an unreliable answer. Walking the chain once per call is cheap because a
15727    /// prototype almost never holds an index.
15728    pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
15729        let mut current = object.proto();
15730        // Bounded, like every other prototype walk here: a proxy can answer a cycle.
15731        for _ in 0..10_000 {
15732            let Some(proto) = current else {
15733                return false;
15734            };
15735            if proto.has_indexed_own_property() {
15736                return true;
15737            }
15738            current = proto.proto();
15739        }
15740        false
15741    }
15742
15743    /// The hidden symbol a named internal slot is keyed by, created on first use.
15744    ///
15745    /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
15746    /// either keeping a table of its own.
15747    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
15748        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
15749            return PropertyKey::Symbol(symbol.clone());
15750        }
15751        let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
15752        self.realm
15753            .internal_slots
15754            .borrow_mut()
15755            .insert(name, Value::Symbol(symbol.clone()));
15756        PropertyKey::Symbol(symbol)
15757    }
15758
15759    /// Read a hidden slot, or `None` when the object has none of that name.
15760    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
15761        let slots = self.realm.internal_slots.borrow();
15762        let Value::Symbol(symbol) = slots.get(name)? else {
15763            return None;
15764        };
15765        object
15766            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
15767            .and_then(|property| property.value)
15768    }
15769
15770    /// Define a hidden slot.
15771    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
15772        let key = self.internal_slot(name);
15773        object.define_key(&key, Property::with_attributes(value, false, false));
15774    }
15775
15776    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
15777    ///
15778    /// The method is looked up on the value (through its prototype), called with no
15779    /// arguments, and its result becomes the iterator. A generator gets here through
15780    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
15781    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
15782    ///
15783    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
15784    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
15785    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
15786    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
15787    /// does, and a user-defined iterable works without a special case.
15788    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
15789    /// `Symbol.iterator`.
15790    ///
15791    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
15792    /// iterable is legal there, and each value it produces is simply already settled by
15793    /// the time the `await` around it runs.
15794    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15795        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
15796        let method = self.read_field_key(value, &async_key)?;
15797        // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
15798        // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
15799        // is *present but not callable* is a TypeError — it does not mean "try the other
15800        // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
15801        // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
15802        // guard is there to catch.
15803        let absent = matches!(method, Value::Undefined | Value::Null);
15804        if !absent {
15805            let Value::Object(object) = &method else {
15806                return Err(Signal::Throw(
15807                    self.make_error("TypeError", "value is not iterable"),
15808                ));
15809            };
15810            if !object.is_callable() {
15811                return Err(Signal::Throw(
15812                    self.make_error("TypeError", "value is not iterable"),
15813                ));
15814            }
15815        }
15816        if absent {
15817            // §7.4.2 step 5: the synchronous iterator is **wrapped**. `for await` and an async
15818            // generator's `yield*` both reach here, and the wrapper is what puts
15819            // `PromiseResolve(%Promise%, value)` between the sync iterator's `value` and the
15820            // caller — a poisoned `constructor` on that value rejects instead of being
15821            // yielded, and a rejection closes the synchronous iterator first.
15822            let sync = self.get_iterator(value)?;
15823            return self.async_from_sync_iterator(sync);
15824        }
15825        let iterator = self.call_value(method, value.clone(), Vec::new())?;
15826        if !matches!(iterator, Value::Object(_)) {
15827            return Err(Signal::Throw(
15828                self.make_error("TypeError", "iterator is not an object"),
15829            ));
15830        }
15831        let next = self.read_field(&iterator, "next")?;
15832        Ok(Iterator {
15833            object: iterator,
15834            next,
15835        })
15836    }
15837
15838    /// `CreateAsyncFromSyncIterator(syncIteratorRecord)` (§27.1.4.1).
15839    ///
15840    /// The wrapper itself is script (see [`crate::builtins::async_from_sync`]); this only
15841    /// hands it the record and reads back its `next`. Both are properties of the wrapper, so
15842    /// the returned [`Iterator`] steps through `%AsyncFromSyncIteratorPrototype%.next`.
15843    fn async_from_sync_iterator(&mut self, sync: Iterator) -> JsResult<Iterator> {
15844        let Some(factory) = self.realm.async_from_sync.clone() else {
15845            // No wrapper installed (a realm whose heap refused to hold it): fall back to the
15846            // raw synchronous iterator rather than refusing to iterate at all.
15847            return Ok(sync);
15848        };
15849        let wrapper = self.call_value(factory, Value::Undefined, vec![sync.object, sync.next])?;
15850        let next = self.read_field(&wrapper, "next")?;
15851        Ok(Iterator {
15852            object: wrapper,
15853            next,
15854        })
15855    }
15856
15857    /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
15858    /// read — `@@iterator` is **not** consulted.
15859    ///
15860    /// The distinction is observable and test262 exercises it: a set-like object's `keys`
15861    /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
15862    /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
15863    /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
15864    /// refused it with "[object Object] is not iterable".
15865    pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
15866        if !matches!(value, Value::Object(_)) {
15867            return Err(self.type_error("iterator is not an object"));
15868        }
15869        let next = self.read_field(&value, "next")?;
15870        Ok(Iterator {
15871            object: value,
15872            next,
15873        })
15874    }
15875
15876    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15877        let key = self.realm.well_known_key(WellKnown::Iterator);
15878        let method = self.read_field_key(value, &key)?;
15879        let Value::Object(function) = &method else {
15880            return Err(Signal::Throw(self.make_error(
15881                "TypeError",
15882                &format!("{} is not iterable", value.to_js_string()),
15883            )));
15884        };
15885        if !function.is_callable() {
15886            return Err(Signal::Throw(self.make_error(
15887                "TypeError",
15888                &format!("{} is not iterable", value.to_js_string()),
15889            )));
15890        }
15891        let iterator = self.call_value(method, value.clone(), Vec::new())?;
15892        // The spec requires an object here; a primitive iterator has no `next` to call
15893        // and would fail one step later with a confusing message.
15894        if !matches!(iterator, Value::Object(_)) {
15895            return Err(Signal::Throw(
15896                self.make_error("TypeError", "iterator is not an object"),
15897            ));
15898        }
15899        let next = self.read_field(&iterator, "next")?;
15900        Ok(Iterator {
15901            object: iterator,
15902            next,
15903        })
15904    }
15905
15906    /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
15907    /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
15908    /// exception from `return` propagates normally instead of being swallowed. That is the
15909    /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
15910    /// because confusing them is exactly the bug both exist to avoid.
15911    pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
15912        let method = self.read_field(&iterator.object, "return")?;
15913        if matches!(method, Value::Undefined | Value::Null) {
15914            return Ok(());
15915        }
15916        if !matches!(&method, Value::Object(object) if object.is_callable()) {
15917            return Err(self.type_error("iterator return is not a function"));
15918        }
15919        self.call_value(method, iterator.object.clone(), Vec::new())?;
15920        Ok(())
15921    }
15922
15923    /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
15924    /// cannot replace it.
15925    fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
15926        let method = self.read_field(&iterator.object, "return")?;
15927        if matches!(method, Value::Undefined | Value::Null) {
15928            return Ok(());
15929        }
15930        if !matches!(&method, Value::Object(object) if object.is_callable()) {
15931            return Err(self.type_error("iterator return is not a function"));
15932        }
15933        self.call_value(method, iterator.object.clone(), Vec::new())?;
15934        Ok(())
15935    }
15936
15937    /// One step of an internal iterator: the value and whether it is exhausted.
15938    /// Replace the iterator slot of an iteration record with `undefined`.
15939    ///
15940    /// `slot` counts values above it, the same convention `for_of_next`'s operand uses. An
15941    /// `undefined` record is what every close path already treats as "nothing to close", so
15942    /// one store both records "this iterator must not be closed" and keeps
15943    /// [`Interp::catch_here`] from calling `return` on an iterator whose `next` threw.
15944    fn clear_iterator_slot(&mut self, slot: usize) {
15945        let frame = self.frame_mut();
15946        let depth = frame.stack.len();
15947        if depth > slot {
15948            frame.stack[depth - 1 - slot] = Value::Undefined;
15949        }
15950    }
15951
15952    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
15953        // §7.4.4 `IteratorNext`: `Call(iteratorRecord.[[NextMethod]], …)` is where a
15954        // non-callable `next` is rejected — **not** `GetIteratorDirect`, which only reads
15955        // the property. The difference is observable: `[ …{}[yield] ] = it` suspends
15956        // before the first step, so an iterator with no `next` still gets its `return`
15957        // called by `it.return()` instead of failing up front
15958        // (`array-rest-iter-rtrn-close-err`).
15959        if let Value::Object(object) = &iterator.next
15960            && object.is_callable()
15961        {
15962            let result =
15963                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
15964            let Some(result) = result.as_object().cloned() else {
15965                return Err(self.type_error("iterator result is not an object"));
15966            };
15967            let done = self
15968                .get_property(&result, "done")?
15969                .is_some_and(|value| value.to_boolean());
15970            // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
15971            // `done` is false. Reading it unconditionally ran a throwing `value` getter on
15972            // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
15973            // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
15974            // made an unrelated `value` getter observable after the loop was over.
15975            if done {
15976                return Ok((Value::Undefined, true));
15977            }
15978            let value = self
15979                .get_property(&result, "value")?
15980                .unwrap_or(Value::Undefined);
15981            return Ok((value, false));
15982        }
15983        // §7.4.4: `next` was read by `GetIteratorDirect` but its callability is only
15984        // tested at the call. Treating a non-callable `next` as "exhausted" instead made
15985        // `Object.fromEntries({[Symbol.iterator]: () => ({next: null})})` succeed with an
15986        // empty object, where §21.1.2.2's `? IteratorStepValue` must throw a `TypeError`.
15987        Err(Signal::Throw(self.make_error(
15988            "TypeError",
15989            "iterator's next method is not callable",
15990        )))
15991    }
15992
15993    /// `[...iterable]`: append everything the iterator yields, and answer the next
15994    /// index.
15995    ///
15996    /// This goes through the same iterator machinery `for-of` uses rather than copying
15997    /// an array's elements, because a spread source is any iterable: a string spreads
15998    /// into its characters and an array iterator spreads into its results. Handling
15999    /// only arrays made `[..."ab"]` come out empty with no error at all.
16000    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
16001        let Some(target) = array.as_object().cloned() else {
16002            return Ok(0);
16003        };
16004        let start = target.array_length().unwrap_or(0);
16005        let mut added = 0;
16006        let iterator = self.get_iterator(iterable)?;
16007        loop {
16008            let (value, done) = self.iterator_step(&iterator)?;
16009            if done {
16010                break;
16011            }
16012            target.array_set(self.heap, start + added, value);
16013            added += 1;
16014        }
16015        Ok((start + added) as i32)
16016    }
16017
16018    /// How an uncaught exception is reported.
16019    ///
16020    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
16021    /// with `ToString` — `js_std_dump_error` is three lines that end in
16022    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
16023    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
16024    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
16025    ///
16026    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
16027    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
16028    /// `toString`"; it does call it, but only for objects of a class it does not know how
16029    /// to walk, and never for errors, arrays or plain objects.
16030    ///
16031    /// A printer that fails must not take the reporter down with it, so that case falls
16032    /// back to the `ToString` rendering.
16033    pub fn describe_exception(&mut self, value: &Value) -> String {
16034        match crate::print::sprint(self, value) {
16035            Ok(text) => text,
16036            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
16037        }
16038    }
16039
16040    /// The file name of whatever is running, innermost frame first.
16041    ///
16042    /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
16043    /// innermost frame's file name, without distinguishing a module body from a plain
16044    /// script. `import()` uses it as the base for a relative specifier, which is why
16045    /// `import('./x.js')` inside a script resolves next to the script and not next to the
16046    /// process's working directory.
16047    pub fn script_or_module_name(&self) -> Option<String> {
16048        self.script_or_module_name_at(0)
16049    }
16050
16051    /// [`Interp::script_or_module_name`] `level` frames further out.
16052    ///
16053    /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
16054    /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
16055    /// frame without a file name is skipped rather than counted, because a native call
16056    /// pushes no frame of its own and so cannot be a level.
16057    pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
16058        self.frames
16059            .iter()
16060            .rev()
16061            .filter_map(|frame| frame.code.code.filename.clone())
16062            .nth(level)
16063    }
16064
16065    /// The innermost frame name that could be a *file*, skipping `<eval>`-style pseudo-names.
16066    ///
16067    /// `eval` and `std.evalScript` compile their bodies under `<input>` / `<evalScript>`
16068    /// because that is what a stack trace should print, but §19.2.1.1's
16069    /// `GetActiveScriptOrModule` makes an eval'd body belong to the script that called it —
16070    /// never to something called `<input>`. Resolving `import('./x.js')` against a pseudo-name
16071    /// produced the bare specifier `x.js`, which the loader then looked for in the working
16072    /// directory instead of beside the file that called `eval`.
16073    pub fn script_or_module_file_name(&self) -> Option<String> {
16074        self.frames.iter().rev().find_map(|frame| {
16075            let name = frame.code.code.filename.as_deref()?;
16076            (!name.starts_with('<')).then(|| name.to_string())
16077        })
16078    }
16079
16080    /// The current call stack, formatted the way `qjs` prints `error.stack`.
16081    ///
16082    /// One `    at name (file:line:col)` line per active frame, innermost first. The
16083    /// position is the one recorded for the instruction each frame is stopped on, which
16084    /// is why the compiler builds a pc-to-position table per function: without it a
16085    /// trace could only name the function, not the line inside it.
16086    ///
16087    /// A frame whose code has no positions prints just `(file)`, matching the
16088    /// reference's output for stripped bytecode.
16089    pub fn stack_trace(&self) -> String {
16090        self.stack_trace_skipping(0)
16091    }
16092
16093    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
16094    fn stack_trace_skipping(&self, skip: usize) -> String {
16095        // One ordered list, innermost first, so `skip` counts the same thing whether the
16096        // frames it leaves out are native or bytecode. Indices rather than references: a
16097        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
16098        let depth = self.frames.len();
16099        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
16100        // A native entered while `at` bytecode frames were live was called *from* the
16101        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
16102        // entered at the current depth are therefore innermost of all.
16103        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
16104            for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
16105                if *at == wanted {
16106                    order.push((true, index));
16107                }
16108            }
16109        };
16110        push_natives(&mut order, depth);
16111        for index in (0..depth).rev() {
16112            order.push((false, index));
16113            push_natives(&mut order, index);
16114        }
16115        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
16116        // barrier. Natives entered at exactly the barrier depth are the eval entry point
16117        // itself (`evalScript (native)`), and the reference leaves those out too.
16118        if let Some(barrier) = self.trace_barriers.last().copied() {
16119            order.retain(|(is_native, index)| match is_native {
16120                true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
16121                false => *index >= barrier,
16122            });
16123        }
16124
16125        let mut out = String::new();
16126        for (is_native, index) in order.into_iter().skip(skip) {
16127            match is_native {
16128                true => {
16129                    out.push_str("    at ");
16130                    let (native, _) = &self.native_frames[index];
16131                    let name = native
16132                        .own_property("name")
16133                        .and_then(|property| property.value)
16134                        .map(|value| value.to_js_string())
16135                        .unwrap_or_default();
16136                    out.push_str(&name);
16137                    out.push_str(" (native)\n");
16138                }
16139                false => {
16140                    let frame = &self.frames[index];
16141                    let code = &frame.code.code;
16142                    let file = code.filename.as_deref().unwrap_or("<input>");
16143                    // The name comes from the function *object*, not from the compiled code:
16144                    // an anonymous function expression is named by the property it is stored
16145                    // in (`{valueOf: function(){}}`), which only the object knows.
16146                    let bound_name = match &frame.callee {
16147                        Value::Object(object) => {
16148                            object
16149                                .own_property("name")
16150                                .and_then(|property| match property.value {
16151                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
16152                                        Some(text.to_string_lossy().into_owned())
16153                                    }
16154                                    _ => None,
16155                                })
16156                        }
16157                        _ => None,
16158                    };
16159                    // No callee object means the body was entered by the host, so the
16160                    // name has to come from the compiled code. Two cases differ:
16161                    //
16162                    // * an *unnamed* function of any kind — the reference reads the
16163                    //   `name` property, finds it empty, and prints `<anonymous>`;
16164                    // * a *module* body, which has no `name` property at all: the
16165                    //   reference builds that function object with `js_closure2` and
16166                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
16167                    //   so a trace reaching it also prints `<anonymous>` — while a
16168                    //   *script* body prints `<eval>`, its `name`.
16169                    let unnamed = code.name.is_empty() || code.module.is_some();
16170                    out.push_str("    at ");
16171                    match bound_name.as_deref() {
16172                        Some(name) => out.push_str(name),
16173                        None if unnamed => out.push_str("<anonymous>"),
16174                        None => out.push_str(&code.name),
16175                    }
16176                    match code.position_at(frame.at as u32) {
16177                        Some((line, column)) => {
16178                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
16179                        }
16180                        None => out.push_str(&format!(" ({file})\n")),
16181                    }
16182                }
16183            }
16184        }
16185        out
16186    }
16187
16188    /// Give an anonymous function the name of the property it is stored in.
16189    ///
16190    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
16191    /// enumerable and not configurable, and a function that already has a real name
16192    /// keeps it.
16193    ///
16194    /// "Already named" means a *non-empty* name: every function object is created with
16195    /// a `name` of `""` so the property exists on all of them, and treating that empty
16196    /// string as a name left every anonymous function nameless — which is how a stack
16197    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
16198    /// `SetFunctionName`, for a name that came from source text.
16199    fn set_function_name(&mut self, function: &Value, name: &str) {
16200        self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
16201    }
16202
16203    /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
16204    /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
16205    fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
16206        let Value::Object(object) = function else {
16207            return;
16208        };
16209        // `SetFunctionName` applies to *functions* and classes only, and only when they are
16210        // anonymous. Without the callability guard, `{value: someObject}` renamed
16211        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
16212        // on the right-hand side of a property. That is how a `zipKeyed` result object
16213        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
16214        // has no `NamedEvaluation` at all.
16215        if !object.is_callable() {
16216            return;
16217        }
16218        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
16219            && !existing.wtf8().is_empty()
16220        {
16221            return;
16222        }
16223        let text = self.string_wtf8(name.clone());
16224        object.define("name", Property::name_or_length(text));
16225    }
16226
16227    // -- global declarations -----------------------------------------------
16228
16229    /// Declare a global binding, creating its reference cell.
16230    /// Declare a `var` or function global, whose home is the global object.
16231    ///
16232    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
16233    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
16234    /// such as `print`, or a redeclaration — is left alone.
16235    pub fn declare_var_global(&mut self, name: &str) {
16236        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
16237        // global object is exactly the leak `typeof my_var === "undefined"` after
16238        // `eval("var my_var=2")` rules out.
16239        if let Some(scope) = self.eval_scope.last_mut() {
16240            scope.entry(name.to_string()).or_insert(Value::Undefined);
16241            return;
16242        }
16243        // A sloppy direct eval declares into its *caller's* variable environment. Doing
16244        // this on the global object instead made `eval("var c = 1")` inside a parameter
16245        // list overwrite a global `c`, and made two calls to the same function share one
16246        // binding.
16247        if let Some(cell) = self.declare_eval_local(name) {
16248            cell.set(Value::Undefined);
16249            return;
16250        }
16251        // The caller's frame already binds the name, so the declaration is satisfied by
16252        // that binding and there is nothing new to create. Without this the fall-through
16253        // below declared a *global* as well, so `var q; eval("var q = 5")` left a
16254        // `globalThis.q` behind (`eval-code/direct/var-env-var-init-local-exstng`).
16255        if self.eval_caller.flatten().is_some_and(|caller| {
16256            self.eval_bindings
16257                .iter()
16258                .any(|binding| binding.name == name && binding.frame == caller)
16259        }) {
16260            return;
16261        }
16262        let global = self.realm.global.clone();
16263        if global.own_property(name).is_some() {
16264            return;
16265        }
16266        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
16267        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
16268        // whole point of that trick and what lets `Object.defineProperty` reshape it
16269        // afterwards. `eval_scope` is `Some` while an eval is running.
16270        let from_eval = self.eval_depth > 0 || !self.eval_scope.is_empty();
16271        global.define(
16272            name,
16273            Property {
16274                value: Some(Value::Undefined),
16275                writable: true,
16276                enumerable: true,
16277                configurable: from_eval,
16278                ..Property::default()
16279            },
16280        );
16281    }
16282
16283    /// Declare a *lexical* global binding, which starts in its dead zone.
16284    ///
16285    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
16286    /// global object and is created when its initialiser runs.
16287    pub fn declare_global(&mut self, name: &str, is_const: bool) {
16288        if is_const {
16289            self.realm.lexical_consts.insert(name.to_string());
16290        }
16291        if !self.realm.globals.contains_key(name) {
16292            // `Uninitialized` rather than `Undefined`: the binding exists but is not
16293            // readable until its initialiser runs, and that is what `let x` before
16294            // `x = 1` has to observe.
16295            let cell = self.new_cell(Value::Uninitialized);
16296            self.realm.globals.insert(name.to_string(), cell);
16297            self.realm.declared.push(name.to_string());
16298        }
16299    }
16300}
16301
16302/// The bytecode and environment of a function object, if it is a bytecode function.
16303///
16304/// Extracted before a call so no borrow of the object is held across it.
16305fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
16306    function.with(|data| match &data.kind {
16307        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
16308        _ => None,
16309    })
16310}
16311
16312/// A native call target, extracted before the call so no borrow is held.
16313enum NativeCall {
16314    Native(NativeFn),
16315    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
16316    /// not hold that object's `RefCell` borrow.
16317    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
16318    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
16319    Bound {
16320        target: Value,
16321        this: Value,
16322        leading: Vec<Value>,
16323    },
16324    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
16325    Revoker(crate::object::ProxyRef),
16326    /// A promise's `resolve`.
16327    PromiseResolve(Gc<JsObject>),
16328    /// A promise's `reject`.
16329    PromiseReject(Gc<JsObject>),
16330    /// The executor `NewPromiseCapability(C)` hands a user constructor.
16331    CapabilityExecutor {
16332        state: Gc<JsObject>,
16333    },
16334    /// One leg of a `then` that settles through a user capability.
16335    ThenShim {
16336        handler: Option<Value>,
16337        resolve: Value,
16338        reject: Value,
16339        fulfilled: bool,
16340    },
16341    /// One continuation of an `await`.
16342    AwaitResume {
16343        coroutine: Gc<JsObject>,
16344        promise: Gc<JsObject>,
16345        kind: ResumeKind,
16346    },
16347    /// One element of a `Promise` combinator settling.
16348    CombinatorSettle {
16349        state: Gc<JsObject>,
16350        index: usize,
16351        fulfilled: bool,
16352    },
16353    /// One of `Promise.prototype.finally`'s two shims.
16354    FinallyShim {
16355        callback: Option<Value>,
16356        fulfilled: bool,
16357        constructor: Value,
16358    },
16359    /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
16360    ReturnValue(Value),
16361    /// A thunk that throws a fixed value, for `finally`'s `thrower`.
16362    ThrowValue(Value),
16363    /// Settle a promise with a fixed outcome.
16364    SettlePromise {
16365        promise: Gc<JsObject>,
16366        value: Value,
16367        rejected: bool,
16368    },
16369    /// Continue an async generator after its `await` settled.
16370    GeneratorResume {
16371        generator: Gc<JsObject>,
16372        promise: Gc<JsObject>,
16373        kind: ResumeKind,
16374    },
16375    /// Read a module namespace's binding out of its cell.
16376    ModuleBinding(Gc<Cell>),
16377    /// Finish a completed async generator's `return(v)` once `v` has settled.
16378    CompletedReturn {
16379        generator: Gc<JsObject>,
16380        promise: Gc<JsObject>,
16381        rejected: bool,
16382    },
16383    /// Answer a pending async-generator method with `{value, done}`.
16384    YieldResult {
16385        generator: Gc<JsObject>,
16386        promise: Gc<JsObject>,
16387        done: bool,
16388    },
16389    /// One step of `AsyncDisposableStack.disposeAsync`.
16390    DisposeStep {
16391        remaining: Gc<JsObject>,
16392        promise: Gc<JsObject>,
16393        error: Value,
16394        rejected: bool,
16395        awaited: bool,
16396        needs_await: bool,
16397    },
16398}
16399
16400/// What a store does when the object refuses the write.
16401#[derive(Clone, Copy, PartialEq, Eq)]
16402pub enum DeleteFailure {
16403    /// Raise a `TypeError`, which is what strict mode and every built-in does.
16404    Throw,
16405    /// Ignore the write, which is what a sloppy-mode assignment does.
16406    Ignore,
16407}
16408
16409/// Whether `object` is a `Date` instance, by the class tag it carries.
16410///
16411/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
16412/// builtins module depending on the interpreter's conversion order.
16413fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
16414    interp
16415        .internal_get(object, "_class")
16416        .is_some_and(|value| value.to_js_string() == "Date")
16417}
16418
16419/// Which type `ToPrimitive` prefers when it converts an object.
16420#[derive(Clone, Copy, PartialEq, Eq)]
16421pub enum Hint {
16422    /// The default hint, which behaves like [`Hint::Number`].
16423    Default,
16424    /// `Number(obj)` and the arithmetic operators.
16425    Number,
16426    /// `String(obj)` and `ToPropertyKey`.
16427    String,
16428}
16429
16430/// Which table a binding slot indexes, for the messages that name it.
16431#[derive(Clone, Copy)]
16432enum VarSlot {
16433    Loc,
16434    Closure,
16435}
16436
16437/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
16438fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
16439    Ok(this)
16440}
16441
16442/// An internal iterator: the sequence plus a cursor.
16443pub(crate) struct Iterator {
16444    pub(crate) object: Value,
16445    pub(crate) next: Value,
16446}
16447
16448/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
16449/// and plain `a` for a method.
16450///
16451/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
16452/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
16453/// reads `at get a (file:1:2)`.
16454/// The same prefixing, for a name that may hold an unpaired surrogate.
16455fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
16456    let prefix = match flags & 3 {
16457        1 => "get ",
16458        2 => "set ",
16459        _ => return key.clone(),
16460    };
16461    let mut units: Vec<u16> = prefix.encode_utf16().collect();
16462    units.extend_from_slice(&key.to_units());
16463    crate::value::Wtf8::from_units(&units)
16464}
16465
16466/// `SetFunctionName`'s name for a symbol property key: `[description]`, or `""`.
16467///
16468/// §7.3.24 step 1. A symbol without a description names the function the empty string, not
16469/// `Symbol()` — the two are different and test262 checks both.
16470fn symbol_key_name(key: &PropertyKey) -> crate::value::Wtf8 {
16471    let PropertyKey::Symbol(symbol) = key else {
16472        return crate::value::Wtf8::default();
16473    };
16474    match symbol.description() {
16475        Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
16476        None => crate::value::Wtf8::default(),
16477    }
16478}
16479
16480/// Define a method or accessor property, per the `define_method` flag byte.
16481///
16482/// The low two bits pick value/getter/setter and bit 2 marks the property
16483/// enumerable.
16484///
16485/// A getter and a setter arrive as two separate `define_method` instructions, and the
16486/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
16487/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
16488/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
16489/// `JS_DefineProperty`, which leaves the other half alone.
16490fn define_function_property(
16491    object: &Gc<JsObject>,
16492    key: &PropertyKey,
16493    function: Value,
16494    flags: u32,
16495) -> bool {
16496    let enumerable = flags & 4 != 0;
16497    let kind = flags & 3;
16498    let existing = object.own_property_key(key);
16499    let property = match kind {
16500        1 => Property {
16501            getter: Some(function),
16502            // The setter half, if this literal already defined one.
16503            setter: existing
16504                .filter(Property::is_accessor)
16505                .and_then(|p| p.setter),
16506            enumerable,
16507            configurable: true,
16508            ..Property::default()
16509        },
16510        2 => Property {
16511            getter: existing
16512                .filter(Property::is_accessor)
16513                .and_then(|p| p.getter),
16514            setter: Some(function),
16515            enumerable,
16516            configurable: true,
16517            ..Property::default()
16518        },
16519        _ => Property {
16520            value: Some(function),
16521            writable: true,
16522            enumerable,
16523            configurable: true,
16524            ..Property::default()
16525        },
16526    };
16527    object.create_data_property_key(key, property)
16528}
16529
16530// ---------------------------------------------------------------------------
16531// Operand decoding
16532// ---------------------------------------------------------------------------
16533
16534/// How `print` renders a value: the reference's `JS_PrintValue`.
16535///
16536/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
16537/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
16538/// The format is reproduced closely because the test suite compares output text:
16539///
16540/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
16541/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
16542/// * a cycle prints `[circular N]` with `N` the stack index of the object;
16543/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
16544///   end print as `<N empty item(s)>`;
16545/// * a string is quoted inside a container but raw at the top level, which is why
16546///   `print("x")` and `print(["x"])` differ.
16547pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
16548    // A string argument is printed raw: `js_print` converts it with `ToString`
16549    // instead of dumping it, and the quoting only appears inside a container.
16550    if let Value::String(text) = value {
16551        return text.to_string_lossy().into_owned();
16552    }
16553    let mut printer = Printer {
16554        interp,
16555        out: String::new(),
16556        stack: Vec::new(),
16557    };
16558    printer.value(value, 0);
16559    printer.out
16560}
16561
16562/// The internal class name an object carries, when it has one.
16563fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
16564    interp
16565        .internal_get(object, "_class")
16566        .map(|value| value.to_js_string())
16567}
16568
16569/// A string property, looked up the way `GetProperty` does: own first, then the
16570/// prototype chain. Needed because the print formatter holds the interpreter
16571/// immutably and so cannot run getters.
16572fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
16573    let mut current = Some(object.clone());
16574    // Bounded, because a prototype cycle would otherwise loop forever.
16575    for _ in 0..100 {
16576        let node = current?;
16577        if let Some(property) = node.own_property(name)
16578            && let Some(value) = property.value
16579        {
16580            return Some(value.to_js_string());
16581        }
16582        current = node.with(|data| data.proto.clone());
16583    }
16584    None
16585}
16586
16587/// The `JS_PrintValue` state: output, and the objects currently being printed.
16588struct Printer<'a, 'rt> {
16589    /// Kept for the class-name lookups that typed arrays and `Date` will need.
16590    #[allow(dead_code)]
16591    interp: &'a Interp<'rt>,
16592    out: String,
16593    stack: Vec<Gc<JsObject>>,
16594}
16595
16596impl Printer<'_, '_> {
16597    /// Depth past which a container is summarised by its class name.
16598    const MAX_DEPTH: usize = 2;
16599
16600    fn value(&mut self, value: &Value, level: usize) {
16601        match value {
16602            Value::Undefined
16603            | Value::Uninitialized
16604            | Value::Hole
16605            | Value::CatchOffset(_)
16606            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
16607            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
16608            // The printer writes a bigint the way the language spells one, so a dump is
16609            // unambiguous about which kind of number it is showing.
16610            Value::BigInt(big) => {
16611                self.out.push_str(&big.to_decimal_string());
16612                self.out.push('n');
16613            }
16614            Value::Null => self.out.push_str("null"),
16615            Value::Bool(true) => self.out.push_str("true"),
16616            Value::Bool(false) => self.out.push_str("false"),
16617            Value::Int(number) => self.out.push_str(&number.to_string()),
16618            Value::Float(number) => {
16619                self.out
16620                    .push_str(&crate::value::number_to_string_for_print(*number));
16621            }
16622            Value::String(text) => self.print_string(&text.to_string_lossy()),
16623            Value::Object(object) => self.object(object, level),
16624        }
16625    }
16626
16627    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
16628        // A cycle is reported rather than followed; the index is where the object
16629        // already sits in the print stack, which is what the reference shows.
16630        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
16631            self.out.push_str(&format!("[circular {index}]"));
16632            return;
16633        }
16634        if object.is_callable() {
16635            let name = object
16636                .own_property("name")
16637                .and_then(|property| property.value)
16638                .map(|value| value.to_js_string())
16639                .unwrap_or_default();
16640            if name.is_empty() {
16641                self.out.push_str("[Function (anonymous)]");
16642            } else {
16643                self.out.push_str(&format!("[Function {name}]"));
16644            }
16645            return;
16646        }
16647        if level >= Self::MAX_DEPTH {
16648            let class = if object.is_array() { "Array" } else { "Object" };
16649            self.out.push_str(&format!("[{class}]"));
16650            return;
16651        }
16652        // A `RegExp` prints as its own literal, `js_print_regexp`'s `/%s/%s`. Without this
16653        // it fell through to the plain-object form and `print(/x/)` answered `{  }` — no
16654        // properties, so nothing to show, and the value's identity lost.
16655        if let Some(data) = object.regexp() {
16656            let source = crate::builtins::regexp::escaped_source(&data.source);
16657            self.out.push('/');
16658            self.out.push_str(&source.to_string_lossy());
16659            self.out.push('/');
16660            self.out.push_str(&data.flags);
16661            return;
16662        }
16663        // `Date` and `Error` print as themselves rather than as bags of properties:
16664        // the ISO string, and `Name: message` followed by the trace.
16665        if let Some(class) = class_of(self.interp, object) {
16666            if class == "Date" {
16667                self.date(object);
16668                return;
16669            }
16670            if class == "Error" {
16671                self.error(object);
16672                return;
16673            }
16674        }
16675        self.stack.push(object.clone());
16676        if object.is_array() {
16677            self.array(object, level);
16678        } else {
16679            self.plain_object(object, level);
16680        }
16681        self.stack.pop();
16682    }
16683
16684    /// A Date prints as its ISO string; an invalid one falls through to the plain
16685    /// object form, the way the reference falls back when `toISOString` throws.
16686    fn date(&mut self, object: &Gc<JsObject>) {
16687        let value = self
16688            .interp
16689            .internal_get(object, "_date_value")
16690            .map(|value| value.to_number());
16691        match value.and_then(crate::builtins::date::iso_string) {
16692            Some(text) => self.out.push_str(&text),
16693            None => self.plain_object(object, 0),
16694        }
16695    }
16696
16697    /// `Name: message`, then the trace with its trailing newline removed.
16698    fn error(&mut self, object: &Gc<JsObject>) {
16699        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
16700        self.out.push_str(&name);
16701        if let Some(message) = inherited(object, "message")
16702            && !message.is_empty()
16703        {
16704            self.out.push_str(": ");
16705            self.out.push_str(&message);
16706        }
16707        if let Some(stack) = inherited(object, "stack") {
16708            self.out.push('\n');
16709            self.out.push_str(stack.trim_end_matches('\n'));
16710        }
16711    }
16712
16713    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
16714        let elements = object.array_elements().unwrap_or_default();
16715        self.out.push_str("[ ");
16716        // An interior hole means the array is "sparse": the reference prints those
16717        // as `index: value` pairs and says nothing about the holes themselves, while
16718        // a hole run at the end becomes a single `<N empty items>` note.
16719        let last_present = elements
16720            .iter()
16721            .rposition(|value| !matches!(value, Value::Hole));
16722        let has_interior_hole = match last_present {
16723            Some(last) => elements[..last]
16724                .iter()
16725                .any(|value| matches!(value, Value::Hole)),
16726            None => false,
16727        };
16728        let mut first = true;
16729        if has_interior_hole {
16730            let mut index = 0;
16731            while index < elements.len() {
16732                let value = &elements[index];
16733                if matches!(value, Value::Hole) {
16734                    index += 1;
16735                    continue;
16736                }
16737                if !first {
16738                    self.out.push_str(", ");
16739                }
16740                first = false;
16741                self.out.push_str(&format!("{index}: "));
16742                self.value(value, level + 1);
16743                index += 1;
16744            }
16745        } else {
16746            for (index, value) in elements.iter().enumerate() {
16747                if matches!(value, Value::Hole) {
16748                    continue;
16749                }
16750                if !first {
16751                    self.out.push_str(", ");
16752                }
16753                first = false;
16754                let _ = index;
16755                self.value(value, level + 1);
16756            }
16757            if let Some(last) = last_present {
16758                let trailing = elements.len() - last - 1;
16759                if trailing > 0 {
16760                    if !first {
16761                        self.out.push_str(", ");
16762                    }
16763                    self.out.push_str(&format!(
16764                        "<{trailing} empty item{}>",
16765                        if trailing > 1 { "s" } else { "" }
16766                    ));
16767                }
16768            } else if !elements.is_empty() {
16769                let count = elements.len();
16770                self.out.push_str(&format!(
16771                    "<{count} empty item{}>",
16772                    if count > 1 { "s" } else { "" }
16773                ));
16774            }
16775        }
16776        self.out.push_str(" ]");
16777    }
16778
16779    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
16780        self.out.push_str("{ ");
16781        let mut first = true;
16782        for key in object.own_keys() {
16783            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
16784                continue;
16785            };
16786            if !property.enumerable {
16787                continue;
16788            }
16789            if !first {
16790                self.out.push_str(", ");
16791            }
16792            first = false;
16793            self.out
16794                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
16795                    &key.to_string_lossy(),
16796                )));
16797            self.out.push_str(": ");
16798            // An accessor has no value to dump; the reference names the half that
16799            // exists instead of calling it.
16800            if property.is_accessor() {
16801                let text = match (property.getter.is_some(), property.setter.is_some()) {
16802                    (true, true) => "[Getter/Setter]",
16803                    (false, true) => "[Setter]",
16804                    _ => "[Getter]",
16805                };
16806                self.out.push_str(text);
16807            } else {
16808                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
16809            }
16810        }
16811        self.out.push_str(" }");
16812    }
16813
16814    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
16815    fn print_string(&mut self, text: &str) {
16816        self.out.push('"');
16817        for character in text.chars() {
16818            match character {
16819                '"' => self.out.push_str("\\\""),
16820                '\\' => self.out.push_str("\\\\"),
16821                '\n' => self.out.push_str("\\n"),
16822                '\r' => self.out.push_str("\\r"),
16823                '\t' => self.out.push_str("\\t"),
16824                c if (c as u32) < 0x20 => {
16825                    self.out.push_str(&format!("\\u{:04x}", c as u32));
16826                }
16827                c => self.out.push(c),
16828            }
16829        }
16830        self.out.push('"');
16831    }
16832}
16833
16834/// How `print` renders a value.
16835///
16836/// `ToString`, except that negative zero keeps its sign — the reference's host
16837/// printer does that while `String(-0)` is `"0"`.
16838pub fn display(value: &Value) -> String {
16839    match value {
16840        Value::Float(number) => crate::value::number_to_string_for_print(*number),
16841        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
16842            "undefined".to_string()
16843        }
16844        other => other.to_js_string(),
16845    }
16846}
16847
16848// ---------------------------------------------------------------------------
16849// Numeric operators
16850// ---------------------------------------------------------------------------
16851
16852/// `a + b` keeping the `Int` representation when it fits.
16853fn add_numbers(left: Value, right: Value) -> Value {
16854    match (&left, &right) {
16855        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
16856            Some(sum) => Value::Int(sum),
16857            None => Value::Float(*a as f64 + *b as f64),
16858        },
16859        _ => Value::Float(left.to_number() + right.to_number()),
16860    }
16861}
16862
16863/// The arithmetic operators other than `+`, which needs string concatenation.
16864fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16865    use Opcode::*;
16866    // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
16867    // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
16868    // *before* the match, so even the arms that never needed `a` or `b` paid for it.
16869    if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
16870        return Ok(match op {
16871            And => Value::Int(x & y),
16872            Or => Value::Int(x | y),
16873            Xor => Value::Int(x ^ y),
16874            Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
16875            Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
16876            Shr => match (*x as u32) >> ((*y as u32) & 31) {
16877                shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
16878                shifted => Value::Float(shifted as f64),
16879            },
16880            Sub => match x.checked_sub(*y) {
16881                Some(value) => Value::Int(value),
16882                None => Value::Float(*x as f64 - *y as f64),
16883            },
16884            _ => return arithmetic_slow(op, left, right),
16885        });
16886    }
16887    arithmetic_slow(op, left, right)
16888}
16889
16890/// [`arithmetic`] for everything the integer fast path above does not take.
16891fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16892    use Opcode::*;
16893    let (a, b) = (left.to_number(), right.to_number());
16894    Ok(match op {
16895        Sub => match (&left, &right) {
16896            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
16897                Some(value) => Value::Int(value),
16898                None => Value::Float(a - b),
16899            },
16900            _ => Value::Float(a - b),
16901        },
16902        Mul => Value::Float(a * b),
16903        Div => Value::Float(a / b),
16904        Mod => Value::Float(js_mod(a, b)),
16905        Pow => Value::Float(a.powf(b)),
16906        And => Value::Int(left.to_int32() & right.to_int32()),
16907        Or => Value::Int(left.to_int32() | right.to_int32()),
16908        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
16909        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
16910        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
16911        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
16912        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
16913        // fits the small-integer representation stays an `Int`; the rest become a
16914        // float, which is how the reference keeps `n >>> 0` non-negative.
16915        Shr => {
16916            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
16917            match i32::try_from(shifted) {
16918                Ok(value) => Value::Int(value),
16919                Err(_) => Value::Float(shifted as f64),
16920            }
16921        }
16922        _ => Value::Float(a),
16923    })
16924}
16925
16926/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
16927///
16928/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
16929/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
16930/// slow path where the rules live.
16931fn is_number(value: &Value) -> bool {
16932    matches!(value, Value::Int(_) | Value::Float(_))
16933}
16934
16935/// The `Value::Bool` a comparison operator answers for `ordering`.
16936///
16937/// `None` is the unordered case — a `NaN` on either side — and every operator answers
16938/// false for it, including `<=` and `>=`.
16939fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
16940    use Opcode::*;
16941    let answer = match (op, ordering) {
16942        (_, None) => false,
16943        (Lt, Some(ordering)) => ordering.is_lt(),
16944        (Lte, Some(ordering)) => ordering.is_le(),
16945        (Gt, Some(ordering)) => ordering.is_gt(),
16946        (Gte, Some(ordering)) => ordering.is_ge(),
16947        _ => false,
16948    };
16949    Value::Bool(answer)
16950}
16951
16952/// `%`, which follows the sign of the dividend rather than Rust's.
16953fn js_mod(left: f64, right: f64) -> f64 {
16954    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
16955        return f64::NAN;
16956    }
16957    if right.is_infinite() {
16958        return left;
16959    }
16960    let remainder = left % right;
16961    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
16962    // the spec makes the sign match the dividend.
16963    if remainder == 0.0 {
16964        0.0f64.copysign(left)
16965    } else {
16966        remainder
16967    }
16968}
16969
16970fn negate(value: Value) -> Value {
16971    match value {
16972        Value::Int(0) => Value::Float(-0.0),
16973        Value::Int(i) => Value::Int(-i),
16974        other => Value::Float(-other.to_number()),
16975    }
16976}
16977
16978fn increment(value: Value) -> Value {
16979    match value {
16980        Value::Int(i) => match i.checked_add(1) {
16981            Some(next) => Value::Int(next),
16982            None => Value::Float(i as f64 + 1.0),
16983        },
16984        other => Value::Float(other.to_number() + 1.0),
16985    }
16986}
16987
16988fn decrement(value: Value) -> Value {
16989    match value {
16990        Value::Int(i) => match i.checked_sub(1) {
16991            Some(next) => Value::Int(next),
16992            None => Value::Float(i as f64 - 1.0),
16993        },
16994        other => Value::Float(other.to_number() - 1.0),
16995    }
16996}
16997
16998/// Compare a `BigInt` with an `f64` on their mathematical values.
16999///
17000/// Neither side is rounded to the other's precision: the number is split into its integer
17001/// part (compared as an exact bigint) and its fraction, which is what decides the answer
17002/// when the integer parts are equal. An infinite value is larger than every bigint.
17003fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
17004    use std::cmp::Ordering;
17005    if number.is_nan() {
17006        return None;
17007    }
17008    if number.is_infinite() {
17009        return Some(if number > 0.0 {
17010            Ordering::Less
17011        } else {
17012            Ordering::Greater
17013        });
17014    }
17015    // The comparison is **exact**, because rounding it is observable: an f64 is
17016    // `m * 2^e` with `m` a 53-bit integer, so scaling the bigint by the same power of two
17017    // turns this into an integer comparison at any width. Converting the *bigint* to f64
17018    // instead — which is what this used to do once the number was wider than `i128` —
17019    // rounds it to the nearest double, and `0xfffffffffffff7ff…n < Number.MAX_VALUE` is
17020    // decided by a difference of one bit at 2^971, which rounding erases
17021    // (`less-than/bigint-and-number-extremes`).
17022    // Both branches answer `big.cmp(number)`; which side gets scaled depends on the sign of
17023    // the exponent, because scaling the smaller one keeps the shift bounded by the f64's own
17024    // range (at most 1074 bits) instead of by the bigint's width.
17025    let (mantissa, exponent) = decompose_f64(number);
17026    let product = crate::bigint::BigInt::from_i64(mantissa);
17027    Some(if exponent >= 0 {
17028        // `number = mantissa * 2^exponent`, and that product is the exact f64 value.
17029        big.cmp(&product.shl(exponent as u64))
17030    } else {
17031        // `number = mantissa / 2^-exponent`; scale the *bigint* up instead so both sides stay
17032        // integers.
17033        big.shl((-exponent) as u64).cmp(&product)
17034    })
17035}
17036
17037/// `value` as `(mantissa, exponent)` with `value == mantissa * 2^exponent` exactly.
17038///
17039/// `mantissa` carries the sign and is the f64's significand with its implicit bit made
17040/// explicit, so `|mantissa| <= 2^53` and the `i64` conversion is exact. `value` must be
17041/// finite.
17042fn decompose_f64(value: f64) -> (i64, i32) {
17043    let bits = value.abs().to_bits();
17044    let raw_exponent = ((bits >> 52) & 0x7ff) as i32;
17045    let fraction = bits & ((1u64 << 52) - 1);
17046    // A subnormal has no implicit bit and an exponent of `1 - 1023`; a normal one carries a
17047    // leading 1 at bit 52, and the `-1075` folds in the bias and the 52 fraction bits.
17048    let (significand, exponent) = if raw_exponent == 0 {
17049        (fraction, -1074)
17050    } else {
17051        (fraction | (1u64 << 52), raw_exponent - 1075)
17052    };
17053    let significand = significand as i64;
17054    let mantissa = if value < 0.0 {
17055        -significand
17056    } else {
17057        significand
17058    };
17059    (mantissa, exponent)
17060}
17061
17062/// The UTF-16 code unit ordering of two strings, which is what `<` compares.
17063///
17064/// `JsString` caches its code units on first access, so the first `code_unit_at` builds the
17065/// cache and the rest are O(1) — no allocation here, and no decoding in the loop.
17066fn compare_code_units(
17067    a: &crate::value::JsString,
17068    b: &crate::value::JsString,
17069) -> std::cmp::Ordering {
17070    let (left, right) = (a.utf16_len(), b.utf16_len());
17071    for index in 0..left.min(right) {
17072        let (x, y) = (
17073            a.code_unit_at(index).unwrap_or(0),
17074            b.code_unit_at(index).unwrap_or(0),
17075        );
17076        if x != y {
17077            return x.cmp(&y);
17078        }
17079    }
17080    // A proper prefix sorts first, which is what the length comparison gives.
17081    left.cmp(&right)
17082}
17083
17084/// `StringToBigInt(argument)` (§7.1.14): the string read as an **integer** literal.
17085///
17086/// `undefined` — `None` here — for anything that is only a *number* literal: `"0."`,
17087/// `".0"`, `"0e0"` and `"Infinity"` all fail, which is why `1n > "0."` is `false` rather
17088/// than `true` (`greater-than/bigint-and-incomparable-string`). Leading zeros are outside
17089/// the grammar too (`"007"`), and so is whitespace between the sign and the digits.
17090///
17091/// The empty string *is* `0n`: §7.1.14 turns a whitespace-only literal into `0`.
17092fn string_to_bigint(text: &str) -> Option<crate::bigint::BigInt> {
17093    let trimmed = text.trim();
17094    let body = trimmed.strip_prefix(['+', '-']).unwrap_or(trimmed);
17095    let signed = body.len() != trimmed.len();
17096    // A radix prefix admits no sign, and the digits must follow immediately.
17097    let (radix, digits) = if let Some(rest) = body.strip_prefix("0x").or(body.strip_prefix("0X")) {
17098        (16, rest)
17099    } else if let Some(rest) = body.strip_prefix("0o").or(body.strip_prefix("0O")) {
17100        (8, rest)
17101    } else if let Some(rest) = body.strip_prefix("0b").or(body.strip_prefix("0B")) {
17102        (2, rest)
17103    } else {
17104        (10, body)
17105    };
17106    if signed && radix != 10 && signed {
17107        // `StrNonDecimalIntegerLiteral` has no sign.
17108        return None;
17109    }
17110    if radix == 10 && digits.len() > 1 && digits.starts_with('0') {
17111        // `StrUnsignedDecimalLiteral : 0 | NonZeroDigit DecimalDigits?`.
17112        return None;
17113    }
17114    crate::bigint::BigInt::from_string(trimmed)
17115}
17116
17117/// `CanonicalNumericIndexString(argument)` (§7.1.21).
17118///
17119/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
17120/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
17121/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
17122/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
17123/// rather than treating it as `0`.
17124fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
17125    let PropertyKey::String(text) = key else {
17126        // A symbol is never an index.
17127        return None;
17128    };
17129    let text = text.to_string_lossy();
17130    if text == "-0" {
17131        return Some(-0.0);
17132    }
17133    let number: f64 = text.parse().ok()?;
17134    // The round-trip test *is* the definition: only the canonical spelling qualifies.
17135    // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
17136    // `"0.10"` does not.
17137    let rendered = Value::Float(number).to_js_string();
17138    (rendered == text).then_some(number)
17139}
17140
17141/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
17142///
17143/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
17144/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
17145/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
17146/// numeric and invalid, which is why they stop the prototype chain instead of falling
17147/// through it.
17148///
17149/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
17150/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
17151/// `in`, `delete` and `defineProperty` separately to make sure it does not.
17152fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
17153    numeric.is_finite()
17154        && numeric.fract() == 0.0
17155        && !(numeric == 0.0 && numeric.is_sign_negative())
17156        && numeric >= 0.0
17157        && object
17158            .typed_array_length()
17159            .is_some_and(|length| (numeric as usize) < length)
17160}
17161
17162/// `ArrayCreate`'s length bound, `2**32 - 1`.
17163///
17164/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
17165/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
17166/// through — can enforce it without depending on a builtin module.
17167const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;