Skip to main content

quickjs/
interp.rs

1//! The bytecode interpreter.
2//!
3//! The machine is the same shape as the reference's: a value stack per frame, a
4//! program counter into `js_compile`'s resolved bytecode, and a frame chain. Two
5//! properties of that design are worth stating up front because they are visible
6//! everywhere below.
7//!
8//! **Frames are explicit, not recursive.** A JavaScript call pushes a frame onto
9//! [`Interp::frames`] and the loop continues; it never recurses in Rust. Deep
10//! JavaScript recursion therefore costs heap, not C stack, and the depth limit is
11//! ours to enforce rather than the host's to crash.
12//!
13//! **Exceptions live on the value stack.** `catch` pushes a [`Value::CatchOffset`]
14//! marker and an exception is found by walking the frame's stack downwards looking
15//! for the innermost one. There is no side table, which is why a `try` inside a
16//! loop costs nothing until it throws.
17
18use std::collections::{BTreeMap, BTreeSet};
19
20use js_compile::bytecode::{Atom, ClosureType, Constant, Function as CompiledFunction};
21use js_compile::opcode::Opcode;
22use js_gc::{Gc, Heap, WeakGc};
23
24use crate::object::{
25    Callable, ClassDef, ClassId, ClosureEnv, CompiledCode, EvalScope, JsObject, LocalVars,
26    NativeFn, ObjectKind, Opaque, Property, PropertyKey, array_index, has_own, lookup_key,
27    lookup_key_above, same_proto,
28};
29use crate::value::{Cell, Value, number_to_string};
30
31/// Why execution stopped.
32#[derive(Debug, Clone)]
33pub enum Signal {
34    /// A JavaScript exception carrying the thrown value.
35    Throw(Value),
36    /// The runtime ran out of memory.
37    OutOfMemory,
38}
39
40/// What an execution step produced.
41pub type JsResult<T> = std::result::Result<T, Signal>;
42
43/// The result of one instruction.
44enum Step {
45    /// Keep executing the current frame.
46    Continue,
47    /// The current frame returned this value.
48    Return(Value),
49    /// The frame parked at a suspension point, with the yielded value on its stack.
50    ///
51    /// Only a generator or an async function can produce this, and only its own frame —
52    /// a nested ordinary call cannot contain a `yield`. The frame is not popped: it is
53    /// detached and handed to the generator object, which is what lets it resume later
54    /// with its locals and operand stack intact.
55    Suspend(SuspendKind),
56}
57
58/// Why a frame parked, which decides how the resumption is delivered.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum SuspendKind {
61    /// `initial_yield`: the body has not started. The first `next()` resumes *after* it
62    /// without passing a value, because there is no `yield` expression to receive one.
63    Initial,
64    /// `yield expr`: the value is on the stack and the caller gets `{value, done:false}`.
65    Yield,
66    /// `yield* expr` in a *sync* generator: like `Yield`, but the value is already an
67    /// `{value, done}` object from the inner iterator and is handed straight back.
68    YieldStar,
69    /// `yield* expr` in an *async* generator: the compiled shape extracts `.value` first, so
70    /// what was yielded is the plain value and still has to be awaited and wrapped —
71    /// `AsyncGeneratorYield` does `Await(value)` before handing it out. Sharing `YieldStar`
72    /// made it pass a bare value through as if it were an iterator result, so
73    /// `async function* g(){ yield* [1] }` answered `{value: {value: 1, done: false}}`.
74    AsyncYieldStar,
75    /// `await expr`: the value is a promise the async machinery has to settle first.
76    Await,
77}
78
79/// Everything one JavaScript realm owns.
80///
81/// A realm is the set of objects a script can reach without naming them: the global
82/// object, the prototype chain roots, and the global binding cells.
83pub struct Realm {
84    /// The global object.
85    pub global: Gc<JsObject>,
86    /// `Object.prototype`.
87    pub object_proto: Gc<JsObject>,
88    /// `Function.prototype`, which is itself callable.
89    pub function_proto: Gc<JsObject>,
90    /// `Array.prototype`.
91    pub array_proto: Gc<JsObject>,
92    /// The `%Array%` constructor, so `ArraySpeciesCreate` can recognise "the default".
93    pub array_constructor: Option<Gc<JsObject>>,
94    /// The `%Promise%` constructor, for the same reason in `NewPromiseCapability`.
95    pub promise_constructor: Option<Gc<JsObject>>,
96    /// Reference cells for globals declared by the script.
97    ///
98    /// A declared global is read with `get_var` (by name) but written with
99    /// `put_var_ref` (through the cell), so the cell is what makes a function
100    /// declaration and its uses agree on one binding.
101    pub globals: BTreeMap<String, Gc<Cell>>,
102    /// Names of the globals that came from a *declaration*, which are
103    /// non-configurable properties of the global object.
104    pub declared: Vec<String>,
105    /// Names among the lexical globals that are `const`.
106    ///
107    /// `const`-ness cannot be read back off the bytecode in every case: a closure that
108    /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
109    /// path does not carry, so a store through it would look like a plain `let`. The
110    /// realm records it once, at declaration, and answers for every reader.
111    pub lexical_consts: BTreeSet<String>,
112    /// The error constructors by class name, so a runtime error can throw a real
113    /// `TypeError` instance rather than a look-alike object.
114    pub errors: BTreeMap<&'static str, Gc<JsObject>>,
115    /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
116    pub string_proto: Option<Gc<JsObject>>,
117    /// `Number.prototype`.
118    pub number_proto: Option<Gc<JsObject>>,
119    /// `Boolean.prototype`.
120    pub boolean_proto: Option<Gc<JsObject>>,
121    /// `BigInt.prototype`.
122    pub bigint_proto: Option<Gc<JsObject>>,
123    /// `Error.prototype`, the prototype of every error instance.
124    pub error_proto: Gc<JsObject>,
125    /// `Date.prototype`, so the constructor can build an instance in the
126    /// function-call form (`Date()` returns a string) without going through `new`.
127    pub date_proto: Gc<JsObject>,
128    /// `%GeneratorPrototype%`, the prototype of every generator object.
129    pub generator_proto: Gc<JsObject>,
130    /// `Promise.prototype`, the prototype of every promise.
131    pub promise_proto: Option<Gc<JsObject>>,
132    /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
133    pub async_generator_proto: Option<Gc<JsObject>>,
134    /// `Symbol.prototype`.
135    pub symbol_proto: Option<Gc<JsObject>>,
136    /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
137    /// `_date_value`.
138    ///
139    /// These are *symbol* keys on purpose. A `"_value"` property is visible to
140    /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
141    /// language does not have and `new Error()` listed `_class` beside `message` and
142    /// `stack` — and a caller that copies every own property (which
143    /// `Object.create(null, props)` effectively does) tried to write an internal name and
144    /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
145    /// and `JSON.stringify`, while remaining an ordinary traced property.
146    ///
147    /// `RefCell` because interning is memoisation rather than observable state: filling the
148    /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
149    /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
150    /// built while reporting a failure must not require an exclusive borrow.
151    pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
152
153    /// The `Symbol.for` registry: `key -> symbol`.
154    ///
155    /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
156    /// symbol every time within one script while a fresh realm starts empty.
157    pub symbol_registry: BTreeMap<String, Value>,
158    /// `RegExp.prototype`, filled in by the `RegExp` builtin.
159    pub regexp_proto: Option<Gc<JsObject>>,
160    /// The `RegExp` constructor.
161    pub regexp_ctor: Option<Gc<JsObject>>,
162    /// `SuppressedError.prototype`, which `using` builds its aggregates from.
163    ///
164    /// The prototype rather than the constructor on purpose: a script that replaces
165    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
166    /// error wrapping, which the `using` test suite checks explicitly.
167    pub suppressed_error_proto: Option<Gc<JsObject>>,
168    /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
169    pub disposable_stack_proto: Option<Gc<JsObject>>,
170    /// `Map.prototype`.
171    pub map_proto: Option<Gc<JsObject>>,
172    /// `Set.prototype`.
173    pub set_proto: Option<Gc<JsObject>>,
174    /// Every live `FinalizationRegistry`, held weakly.
175    ///
176    /// The cleanup callback has to run from a *safe point* — a place where script is not
177    /// already executing and no engine borrow is held — and the collector cannot enumerate
178    /// heap objects by type. Registering each registry here gives the drain a list to walk.
179    ///
180    /// The handles are weak on purpose: a registry the script dropped must be collectable,
181    /// and it must not be resurrected merely because the drain knew about it. Entries whose
182    /// target has expired are swept out as the drain walks, so the vector does not grow
183    /// without bound in a program that creates many short-lived registries.
184    pub finalization_registries: Vec<WeakGc<JsObject>>,
185    /// `ArrayBuffer.prototype`.
186    pub array_buffer_proto: Option<Gc<JsObject>>,
187    /// `%TypedArray%.prototype`, the prototype every view type inherits from.
188    pub typed_array_proto: Option<Gc<JsObject>>,
189    /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
190    ///
191    /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
192    /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
193    /// `"Object"` and `r instanceof Int32Array` is false.
194    pub typed_array_protos: Vec<Gc<JsObject>>,
195    /// `DataView.prototype`.
196    pub data_view_proto: Option<Gc<JsObject>>,
197    /// The `AsyncDisposableStack` prototype.
198    pub async_disposable_stack_proto: Option<Gc<JsObject>>,
199    /// `Iterator.prototype`.
200    pub iterator_proto: Option<Gc<JsObject>>,
201    /// The `Iterator` constructor itself.
202    ///
203    /// `Iterator.prototype.constructor` is an accessor whose getter has to answer this
204    /// object, and the getter is a bare `fn` pointer that cannot capture it — so the only
205    /// place it can live is the realm.
206    pub iterator_ctor: Option<Gc<JsObject>>,
207    /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
208    ///
209    /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
210    /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
211    /// `[object Iterator Helper]`).
212    pub iterator_helper_proto: Option<Gc<JsObject>>,
213    /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
214    /// that was not already an `Iterator`.
215    ///
216    /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
217    /// untouched and does *not* override `@@toStringTag`, so
218    /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
219    pub iterator_wrap_proto: Option<Gc<JsObject>>,
220    /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
221    pub generator_function_proto: Option<Gc<JsObject>>,
222    /// `%AsyncFunction.prototype%`.
223    pub async_function_proto: Option<Gc<JsObject>>,
224    /// `%AsyncGeneratorFunction.prototype%`.
225    pub async_generator_function_proto: Option<Gc<JsObject>>,
226    /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
227    ///
228    /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
229    /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
230    /// prototype per iterator made every array iterator's prototype distinct.
231    pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
232    /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
233    ///
234    /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
235    /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
236    /// both faster and impossible to break from a script.
237    well_known_symbols: WellKnownSymbols,
238    /// The classes the host registered, and the prototype each one hands its instances.
239    pub host_classes: HostClasses,
240}
241
242/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
243///
244/// One per realm, because a class id is only meaningful within the runtime that handed it
245/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
246/// a host class cannot collide.
247pub struct HostClasses {
248    /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
249    /// `JS_GetOpaque(val, 0)` has to match nothing.
250    next_id: u32,
251    /// What each registered class does.
252    defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
253    /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
254    ///
255    /// A strong reference, so the prototype a host installed outlives every script
256    /// reference to it — which is what `JS_SetClassProto` promises.
257    protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
258}
259
260impl HostClasses {
261    fn new() -> HostClasses {
262        HostClasses {
263            next_id: 1,
264            defs: std::collections::BTreeMap::new(),
265            protos: std::collections::BTreeMap::new(),
266        }
267    }
268
269    /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
270    pub fn register(&mut self, def: ClassDef) -> ClassId {
271        let id = ClassId::from_raw(self.next_id);
272        self.next_id += 1;
273        self.defs.insert(id, std::rc::Rc::new(def));
274        id
275    }
276
277    /// Register `def` under an id the caller already has (`JS_NewClass`).
278    ///
279    /// The C API splits "get an id" from "register a class" because a module may be
280    /// initialised lazily; registering twice under one id replaces the definition, and an
281    /// object created under the old one keeps the old behaviour, since it carries its own
282    /// reference.
283    pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
284        if !id.is_valid() {
285            return false;
286        }
287        // Keep the counter past any id handed out explicitly, so a later `register` cannot
288        // reuse one.
289        self.next_id = self.next_id.max(id.get() + 1);
290        self.defs.insert(id, std::rc::Rc::new(def));
291        true
292    }
293
294    /// What `id` was registered with.
295    pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
296        self.defs.get(&id).cloned()
297    }
298
299    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
300    pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
301        self.protos.insert(id, proto);
302    }
303
304    /// The prototype installed for `id`, if the host installed one.
305    pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
306        self.protos.get(&id).cloned()
307    }
308
309    /// How many classes the host registered.
310    pub fn len(&self) -> usize {
311        self.defs.len()
312    }
313
314    /// Whether no class has been registered.
315    pub fn is_empty(&self) -> bool {
316        self.defs.is_empty()
317    }
318}
319
320impl Default for HostClasses {
321    fn default() -> HostClasses {
322        HostClasses::new()
323    }
324}
325
326/// One binding of the frame that called `eval`, so the eval'd code can read and
327/// write it by name.
328struct EvalBinding {
329    /// The name it was declared with.
330    name: String,
331    /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
332    /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
333    /// a function that declares `a` must find that `a`.
334    frame: usize,
335    /// Which table of that frame it lives in.
336    slot: EvalSlot,
337    /// The slot index within that table.
338    index: usize,
339}
340
341/// Which table of a frame an [`EvalBinding`] indexes.
342#[derive(Clone, Copy)]
343enum EvalSlot {
344    Arg,
345    Local,
346}
347
348/// One activation record.
349struct Frame {
350    /// The bytecode being run.
351    code: Gc<CompiledCode>,
352    /// The cells this closure captured.
353    env: Gc<ClosureEnv>,
354    /// The `this` binding.
355    this: Value,
356    /// Argument slots, sized to the declared parameter count.
357    args: Vec<Value>,
358    /// How many values the caller actually passed, which is what `arguments.length`
359    /// reports and what `...rest` slices from.
360    passed_count: usize,
361    /// The passed values, **only when they do not fit in [`Self::args`]**.
362    ///
363    /// `args` is sized to the declared parameters, so a call that passes no more than
364    /// that already holds every passed value in its first `passed_count` slots — copying
365    /// them here as well was two writes and a buffer per call, on the hottest path in
366    /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
367    /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
368    /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
369    /// its own copy.
370    ///
371    /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
372    /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
373    /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
374    /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
375    /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
376    /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
377    #[allow(clippy::box_collection)]
378    passed_overflow: Option<Box<Vec<Value>>>,
379    /// Local slots.
380    locals: Vec<Value>,
381    /// Reference cells for this frame's own captured bindings.
382    cells: Vec<Gc<Cell>>,
383    /// The operand stack.
384    stack: Vec<Value>,
385    /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
386    local_vars: Option<Gc<LocalVars>>,
387
388    /// Index of the next instruction, not a byte offset.
389    ///
390    /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
391    /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
392    /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
393    /// `Frame`, and `frames.push` copies the whole struct on every call.
394    pc: usize,
395    /// Byte offset of the instruction being executed, which is what a stack trace
396    /// reports. `pc` has already moved past it by the time an instruction runs.
397    ///
398    /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
399    at: usize,
400    /// The callee, so a native builtin can tell which constructor it is.
401    callee: Value,
402    /// `new.target`: the constructor under `new`, `undefined` for a plain call.
403    new_target: Value,
404    /// What this frame costs against [`Interp::stack_limit`], in bytes.
405    ///
406    /// Cached rather than recomputed because it is charged on every call and a call is the
407    /// hottest thing in the interpreter.
408    cost: usize,
409    /// [`Interp::stack_used`] before this frame was pushed.
410    ///
411    /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
412    /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
413    /// leave the counter wrong. There are eight places that drop frames; one subtraction
414    /// forgotten in any of them would leak budget until the depth limit moved.
415    stack_base: usize,
416    /// Whether this frame's body ended in a `tail_call`.
417    ///
418    /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
419    /// with its own frame just like `call` does and only skips storing the result
420    /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
421    /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
422    /// pushed as usual, and this marker makes its return value the *caller's* return
423    /// value without running the instructions after the call.
424    tail: bool,
425}
426
427impl Frame {
428    /// Read a local slot, taking the frame as `self`.
429    ///
430    /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
431    /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
432    /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
433    /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
434    /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
435    #[inline]
436    fn read_loc(&self, slot: usize) -> Value {
437        let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
438        if cell == -1 {
439            return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
440        }
441        match self.cells.get(cell as usize) {
442            Some(cell) => cell.get(),
443            None => Value::Undefined,
444        }
445    }
446
447    /// [`Self::read_loc`] for an argument slot.
448    #[inline]
449    fn read_arg(&self, slot: usize) -> Value {
450        let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
451        if cell == -1 {
452            return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
453        }
454        match self.cells.get(cell as usize) {
455            Some(cell) => cell.get(),
456            None => Value::Undefined,
457        }
458    }
459
460    /// The values the caller actually passed, which is what `arguments` exposes.
461    ///
462    /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
463    fn passed(&self) -> &[Value] {
464        match &self.passed_overflow {
465            Some(values) => values,
466            None => &self.args[..self.passed_count],
467        }
468    }
469
470    /// The decoded instructions of the function this frame runs.
471    ///
472    /// A method rather than `frame.code.insns` at the call site so that the borrow is
473    /// obviously of the frame — the dispatch loop holds one across a `get`.
474    fn insns(&self) -> &[crate::insn::Insn] {
475        &self.code.insns
476    }
477}
478
479impl js_gc::Trace for Frame {
480    fn trace(&self, tracer: &mut js_gc::Tracer) {
481        self.code.trace(tracer);
482        self.env.trace(tracer);
483        self.this.trace(tracer);
484        for value in &self.args {
485            value.trace(tracer);
486        }
487        for value in self.passed() {
488            value.trace(tracer);
489        }
490        for value in &self.locals {
491            value.trace(tracer);
492        }
493        for cell in &self.cells {
494            cell.trace(tracer);
495        }
496        if let Some(local_vars) = &self.local_vars {
497            tracer.visit(local_vars);
498        }
499        for value in &self.stack {
500            value.trace(tracer);
501        }
502        self.callee.trace(tracer);
503        self.new_target.trace(tracer);
504    }
505}
506
507/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
508/// emitted `if_false` treats as "keep going".
509/// How many finished frames' value buffers are kept for reuse.
510const RECYCLE_SLOTS: usize = 8;
511
512/// The largest buffer worth keeping. See [`Interp::free_values`].
513const RECYCLE_MAX_CAPACITY: usize = 4096;
514
515const RESUME_NEXT: i32 = 0;
516/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
517/// generator fall into its `return_async`.
518const RESUME_RETURN: i32 = 1;
519/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
520/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
521/// must forward the exception into the inner iterator rather than finish.
522const RESUME_THROW: i32 = 2;
523
524/// One microtask.
525///
526/// The queue holds *data* rather than closures because its contents are GC values: a
527/// closure would be invisible to the collector, and a pending reaction is exactly the
528/// kind of thing that must keep its handlers and its promise alive.
529pub enum Job {
530    /// A `then` reaction about to run.
531    Reaction {
532        /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
533        handler: Option<Value>,
534        /// The value or reason to call it with.
535        argument: Value,
536        /// Whether the source promise rejected, which decides the pass-through kind.
537        rejected: bool,
538        /// The promise the answer settles.
539        promise: Gc<JsObject>,
540    },
541    /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
542    Thenable {
543        /// The `then` that was found on the value.
544        then: Value,
545        /// The thenable itself, which becomes `then`'s `this`.
546        value: Value,
547        /// The promise being resolved.
548        promise: Gc<JsObject>,
549    },
550    /// A pending `import(specifier)`.
551    Import {
552        /// The specifier, already converted to a string.
553        specifier: String,
554        /// The module that asked, which the specifier resolves against.
555        referrer: String,
556        /// The promise `import()` handed back.
557        promise: Gc<JsObject>,
558    },
559    /// An async generator resuming after the value it awaited settled.
560    GeneratorResume {
561        /// The async generator to continue.
562        generator: Gc<JsObject>,
563        /// The promise the pending method returned.
564        promise: Gc<JsObject>,
565        /// Whether this delivers the value or raises the reason.
566        kind: ResumeKind,
567        /// The settled value, or the rejection reason.
568        value: Value,
569    },
570    /// An async function resuming after the value it awaited settled.
571    Resume {
572        /// The body, parked in a coroutine.
573        coroutine: Gc<JsObject>,
574        /// The promise the async function handed its caller.
575        promise: Gc<JsObject>,
576        /// Whether this resumption delivers a value or raises one.
577        kind: ResumeKind,
578        /// The settled value, or the rejection reason.
579        value: Value,
580    },
581}
582
583/// One macro-task: work the event loop owes the script but has not run yet.
584///
585/// The microtask queue ([`Job`]) is different: those run before the host regains control.
586/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
587/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
588/// logic: the engine decides *what* is due, the host decides *how to wait*.
589///
590/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
591/// reference counting even though nothing else references it — the same rule the `HostFn`
592/// documentation states from the other side (a host closure must not hold a `Gc`, so the
593/// `Gc` lives here instead).
594pub enum Task {
595    /// A `setTimeout` that is due at `due_at`.
596    ///
597    /// There is no `setInterval` variant because the reference has no `os.setInterval` at
598    /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
599    /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
600    /// would give this engine a timer the reference cannot produce, with nothing to
601    /// compare it against.
602    Timer {
603        /// The id `setTimeout` returned, for `clearTimeout`.
604        id: i32,
605        /// What to call when it fires.
606        callback: Value,
607        /// When it becomes runnable, as a monotonic instant.
608        due_at: std::time::Instant,
609    },
610}
611
612/// A descriptor the host has to poll, and which directions have a handler.
613///
614/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
615/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
616/// blocks on it, and the host reports back through [`Interp::fire_fd`].
617#[derive(Debug, Clone, Copy, PartialEq, Eq)]
618pub struct FdInterest {
619    /// The descriptor to watch.
620    pub fd: i32,
621    /// Whether `os.setReadHandler` registered a callback.
622    pub read: bool,
623    /// Whether `os.setWriteHandler` registered a callback.
624    pub write: bool,
625}
626
627/// The callbacks registered for one descriptor, per direction.
628#[derive(Default)]
629pub(crate) struct FdHandlers {
630    /// `os.setReadHandler`'s callback.
631    pub read: Option<Value>,
632    /// `os.setWriteHandler`'s callback.
633    pub write: Option<Value>,
634}
635
636/// The file name `eval` reports, which the reference does not inherit from the caller.
637///
638/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
639/// reference and the names show up in stack traces.
640/// The description of the private symbol a class brand is made from.
641///
642/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
643/// place no script can reach, since no expression can name a private symbol.
644const BRAND_DESCRIPTION: &str = "brand";
645
646/// One validated property lookup.
647///
648/// Covers both own-property hits and prototype hits. The second kind was deliberately left
649/// uncached at first ("a prototype hit depends on more than the object and the name"), and
650/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
651/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
652/// names on every iteration (measured: 100 ns per call over an empty loop).
653pub struct FieldCache {
654    /// The name, so two different properties of one object do not collide.
655    key: PropertyKey,
656    /// Where the value was found, relative to the chain below.
657    index: usize,
658    /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
659    level: u8,
660    /// The receiver and every prototype down to (and including) the level that answered,
661    /// each with the length of its property table at the time.
662    ///
663    /// That length is the whole guard, and it is sufficient for the ways the answer can
664    /// change without a lookup: adding or deleting any property moves it, and a
665    /// same-length rewrite is caught by `cached_data_property` re-checking the key and
666    /// refusing an accessor. Storing the *whole* chain — not just the object that answered
667    /// — is what catches a property appearing on an *intermediate* prototype and shadowing
668    /// the one that was cached.
669    ///
670    /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
671    /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
672    chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
673}
674
675/// How many links of a prototype chain a [`FieldCache`] remembers.
676///
677/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
678/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
679/// at three.
680const MAX_CACHED_CHAIN: usize = 3;
681
682/// A remembered global-variable lookup.
683///
684/// A `var` global is an ordinary property of the global object, so reading one walks the
685/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
686/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
687/// fixed by the bytecode, and the slot in the object's table only changes if the global
688/// object is mutated, which the index-and-name check below catches.
689pub struct GlobalCache {
690    /// The global object the lookup was resolved on, weakly.
691    object: js_gc::WeakGc<JsObject>,
692    /// Index of the data property in the global object's table.
693    index: usize,
694}
695
696/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
697const GLOBAL_CACHE_SLOTS: usize = 1024;
698
699/// How many property lookups are remembered.
700///
701/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
702/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
703/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
704/// lookup itself. Making it bigger stops helping: the working set of a real program's
705/// property sites is bounded by its code size.
706const FIELD_CACHE_SLOTS: usize = 4096;
707
708/// How much the heap may grow past the last `out of memory` before saying it again.
709///
710/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
711/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
712/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
713/// because it looks like it works. The reference gets this for free: it fails inside
714/// `js_malloc`, and its printing path happens not to allocate.
715///
716/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
717/// allocating is stopped within a rounding error of the limit) and far above what a
718/// handler needs.
719const OOM_HYSTERESIS: usize = 64 * 1024;
720
721/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
722pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
723
724/// How many instructions run between polls of [`Interp::interrupt`].
725///
726/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
727/// order of magnitude on both implementations — which is what lets a C driver compare its
728/// output byte for byte (see `scripts/m15-capi.sh --embed`).
729pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
730
731/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
732///
733/// Chosen so that the byte budget is what actually decides for every ordinary
734/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
735/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
736/// millions of frames.
737pub const MAX_FRAMES: usize = 200_000;
738
739const EVAL_FILE: &str = "<input>";
740
741/// The file name `std.evalScript` reports.
742const EVAL_SCRIPT_FILE: &str = "<evalScript>";
743
744/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
745///
746/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
747/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
748fn clamp_delay(delay_ms: f64) -> std::time::Duration {
749    // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
750    // on a float, which reads as a typo even when it is deliberate. Both NaN and a
751    // non-positive delay mean "due now".
752    if delay_ms.is_nan() || delay_ms <= 0.0 {
753        return std::time::Duration::ZERO;
754    }
755    std::time::Duration::from_secs_f64(delay_ms / 1000.0)
756}
757
758impl js_gc::Trace for Task {
759    fn trace(&self, tracer: &mut js_gc::Tracer) {
760        let Task::Timer { callback, .. } = self;
761        callback.trace(tracer);
762    }
763}
764
765/// What one turn of the event loop did, so the caller cannot spin by accident.
766///
767/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
768/// core until the timer is due. Naming the three cases makes the wait explicit.
769#[derive(Debug, Clone, Copy, PartialEq, Eq)]
770pub enum Turn {
771    /// Something ran. Call again immediately — there may be more ready work.
772    Ran,
773    /// Nothing is runnable, but descriptors are registered: the host must poll
774    /// [`Interp::pending_fds`] for at most this long, then report readiness with
775    /// [`Interp::fire_fd`].
776    ///
777    /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
778    /// the failure this project treats as worst — a handler that silently never fires —
779    /// so the two cannot be confused by accident.
780    Poll(std::time::Duration),
781    /// Nothing is runnable yet, but something is pending. Block at most this long, then
782    /// call again.
783    Wait(std::time::Duration),
784    /// Nothing is pending at all: the loop is done.
785    Done,
786}
787
788impl js_gc::Trace for Job {
789    fn trace(&self, tracer: &mut js_gc::Tracer) {
790        match self {
791            Job::Reaction {
792                handler,
793                argument,
794                promise,
795                ..
796            } => {
797                if let Some(handler) = handler {
798                    handler.trace(tracer);
799                }
800                argument.trace(tracer);
801                tracer.visit(promise);
802            }
803            Job::Thenable {
804                then,
805                value,
806                promise,
807            } => {
808                then.trace(tracer);
809                value.trace(tracer);
810                tracer.visit(promise);
811            }
812            Job::Resume {
813                coroutine,
814                promise,
815                value,
816                ..
817            } => {
818                tracer.visit(coroutine);
819                tracer.visit(promise);
820                value.trace(tracer);
821            }
822            Job::Import { promise, .. } => tracer.visit(promise),
823            Job::GeneratorResume {
824                generator,
825                promise,
826                value,
827                ..
828            } => {
829                tracer.visit(generator);
830                tracer.visit(promise);
831                value.trace(tracer);
832            }
833        }
834    }
835}
836
837/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
838#[derive(Debug, Clone, Copy, PartialEq, Eq)]
839pub enum ResumeKind {
840    /// The generator was just created and is being run to its first suspension.
841    Start,
842    /// `next(v)`.
843    Next,
844    /// `return(v)`.
845    Return,
846    /// `throw(e)`.
847    Throw,
848}
849
850/// A generator object's saved execution.
851///
852/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
853/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
854/// separately allocated buffers.
855pub struct GeneratorState {
856    /// The detached frame, or `None` once the generator has finished or while it runs.
857    frame: Option<Frame>,
858    /// How far it got.
859    phase: GeneratorPhase,
860    /// Whether the last suspension was an `await` rather than a `yield`.
861    ///
862    /// The two resume with *different stack shapes*: a `yield` is re-entered with the
863    /// value and a magic number, because the emitted code branches on which method
864    /// resumed it, while an `await` simply continues with its value. Getting this wrong
865    /// leaves an extra value on the operand stack that the next instruction then
866    /// consumes — a wrong answer rather than a crash.
867    parked_on_await: bool,
868    /// Whether the last suspension was a `yield*` rather than a plain `yield`.
869    ///
870    /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
871    /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
872    /// has to be forwarded into the inner iterator's `throw` method instead — which is the
873    /// `rethrow` branch the compiled delegation emits — because that is the whole point of
874    /// delegating. Tracking it as part of the phase, the way the reference splits
875    /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
876    /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
877    /// exception and never reached `xs.throw`.
878    parked_on_yield_star: bool,
879    /// Pending `next`/`return`/`throw` calls, oldest first.
880    ///
881    /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
882    /// called back to back must answer in that order, with the second call's value
883    /// arriving at the *second* `yield`. Running each call straight into the body — which
884    /// is what this engine did before — delivered the last queued value to whichever
885    /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
886    /// `a === b ===` the final argument.
887    ///
888    /// The front entry is the one being served; it stays there (with `async_busy` set)
889    /// until its promise settles, because an `await` inside the body is a suspension of
890    /// the *driver*, not the end of the request.
891    requests: std::collections::VecDeque<AsyncRequest>,
892    /// Whether the front request is in flight.
893    async_busy: bool,
894}
895
896/// How one async-generator request ended.
897enum AsyncOutcome {
898    /// The method answered this `{value, done}`.
899    Value(Value),
900    /// The body threw.
901    Error(Value),
902}
903
904/// One queued `next`/`return`/`throw` on an async generator: the reference's
905/// `JSAsyncGeneratorRequest`.
906pub struct AsyncRequest {
907    /// Which method was called.
908    kind: ResumeKind,
909    /// Its argument.
910    value: Value,
911    /// The promise the method answered.
912    promise: Gc<JsObject>,
913}
914
915/// Which of §27.5.3.3's states a generator is in.
916#[derive(Debug, Clone, Copy, PartialEq, Eq)]
917enum GeneratorPhase {
918    /// Created, `initial_yield` reached, body not entered.
919    SuspendedStart,
920    /// Parked at a `yield`.
921    SuspendedYield,
922    /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
923    Executing,
924    /// Finished; the frame is gone.
925    Completed,
926}
927
928impl js_gc::Trace for GeneratorState {
929    fn trace(&self, tracer: &mut js_gc::Tracer) {
930        if let Some(frame) = &self.frame {
931            frame.trace(tracer);
932        }
933        for request in &self.requests {
934            request.value.trace(tracer);
935            tracer.visit(&request.promise);
936        }
937    }
938}
939
940/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
941/// them in.
942///
943/// Each is a field rather than a map entry because the runtime reads them on hot paths
944/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
945/// failure — reaching a default here means the builtin did not install, and every
946/// accessor panics rather than silently answering `undefined`.
947///
948/// [`builtins::symbol`]: crate::builtins::symbol
949#[derive(Default)]
950pub struct WellKnownSymbols {
951    /// The symbol values, positionally. Empty until `Symbol` installs.
952    symbols: Vec<Value>,
953}
954
955/// Which well-known symbol a caller wants.
956///
957/// A typed accessor beats passing a name around: a typo is a compile error rather than
958/// an `undefined` key that quietly matches nothing.
959#[derive(Debug, Clone, Copy, PartialEq, Eq)]
960pub enum WellKnown {
961    /// `Symbol.toPrimitive`.
962    ToPrimitive,
963    /// `Symbol.iterator`.
964    Iterator,
965    /// `Symbol.match`.
966    Match,
967    /// `Symbol.matchAll`.
968    MatchAll,
969    /// `Symbol.replace`.
970    Replace,
971    /// `Symbol.search`.
972    Search,
973    /// `Symbol.split`.
974    Split,
975    /// `Symbol.toStringTag`.
976    ToStringTag,
977    /// `Symbol.isConcatSpreadable`.
978    IsConcatSpreadable,
979    /// `Symbol.hasInstance`.
980    HasInstance,
981    /// `Symbol.species`.
982    Species,
983    /// `Symbol.unscopables`.
984    Unscopables,
985    /// `Symbol.asyncIterator`.
986    AsyncIterator,
987    /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
988    Disposable,
989    /// `Symbol.asyncDispose` — the awaited form.
990    AsyncDisposable,
991}
992
993impl WellKnown {
994    /// The index `Symbol`'s installer creates this symbol at.
995    fn index(self) -> usize {
996        match self {
997            WellKnown::ToPrimitive => 0,
998            WellKnown::Iterator => 1,
999            WellKnown::Match => 2,
1000            WellKnown::MatchAll => 3,
1001            WellKnown::Replace => 4,
1002            WellKnown::Search => 5,
1003            WellKnown::Split => 6,
1004            WellKnown::ToStringTag => 7,
1005            WellKnown::IsConcatSpreadable => 8,
1006            WellKnown::HasInstance => 9,
1007            WellKnown::Species => 10,
1008            WellKnown::Unscopables => 11,
1009            WellKnown::AsyncIterator => 12,
1010            WellKnown::Disposable => 13,
1011            WellKnown::AsyncDisposable => 14,
1012        }
1013    }
1014}
1015
1016impl Realm {
1017    /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1018    pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1019        self.well_known_symbols.symbols = symbols;
1020    }
1021
1022    /// A well-known symbol.
1023    pub fn well_known(&self, which: WellKnown) -> Value {
1024        self.well_known_symbols
1025            .symbols
1026            .get(which.index())
1027            .cloned()
1028            .unwrap_or(Value::Undefined)
1029    }
1030
1031    /// The well-known symbol as a property key.
1032    pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1033        match self.well_known(which) {
1034            Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1035            // Unreachable once `Symbol` has installed; an empty string key matches
1036            // nothing, which degrades to "the object has no such method".
1037            _ => PropertyKey::from(String::new()),
1038        }
1039    }
1040}
1041
1042/// The interpreter: a realm plus a frame stack.
1043pub struct Interp<'a> {
1044    /// The heap everything is allocated on.
1045    pub heap: &'a Heap,
1046    /// The realm.
1047    pub realm: Realm,
1048    /// Active frames, outermost first.
1049    frames: Vec<Frame>,
1050    /// Value buffers from frames that have finished, reused by the next call.
1051    ///
1052    /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1053    /// the locals and the operand stack — and free all four on return. `call:recursion`
1054    /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1055    /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1056    ///
1057    /// Bounded in both directions: a few buffers per kind, and none larger than
1058    /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1059    /// and keeping its buffer would pin that memory for the rest of the run.
1060    free_values: Vec<Vec<Value>>,
1061    /// A strict-mode `eval`'s own variable scope, while its script runs.
1062    ///
1063    /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1064    /// become a global. Name lookups still fall through to the realm, which is why
1065    /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1066    eval_scope: Option<BTreeMap<String, Value>>,
1067    /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1068    /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1069    eval_depth: usize,
1070    /// The calling frame's own bindings, which the running `eval` can read and write.
1071    ///
1072    /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1073    /// come from the frame, and a write is applied back to the frame (or to the cell
1074    /// the frame captured) when the eval finishes. That is what makes
1075    /// `f("a = 3")` visible to the caller as `a === 3`.
1076    eval_bindings: Vec<EvalBinding>,
1077    /// The calling frame's `arguments`, while an `eval` runs.
1078    ///
1079    /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1080    /// own yet still has to see the caller's `arguments`.
1081    eval_arguments: Option<Value>,
1082    /// The `with` objects live at the moment the running `eval` started, innermost first.
1083    ///
1084    /// `None` outside an eval, which is what keeps a finished block's object from
1085    /// shadowing ordinary bytecode reads.
1086    eval_with: Option<Vec<Gc<JsObject>>>,
1087    /// The bindings the running direct `eval` makes visible, as name → cell.
1088    ///
1089    /// Set for the duration of an eval and then restored, but every closure created
1090    /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1091    /// `eval("f = () => i")` work after the eval has returned.
1092    active_eval_scope: Option<Gc<EvalScope>>,
1093    /// The frame that called the direct `eval` currently running, if any.
1094    ///
1095    /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1096    /// on the global object, which is what keeps
1097    /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1098    /// gives each call its own `x`.
1099    eval_caller: Option<Option<usize>>,
1100    /// The caller's `new.target`, while an `eval` runs.
1101    ///
1102    /// The eval'd code is a script with no constructor of its own, so it inherits the
1103    /// one the enclosing function was called with.
1104    eval_new_target: Option<Value>,
1105    /// `new.target` for the frame about to be pushed.
1106    ///
1107    /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1108    /// value reaches the frame without threading a parameter through every call site.
1109    pending_new_target: Option<Value>,
1110    /// Names of the native functions currently executing, outermost first.
1111    ///
1112    /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1113    /// trace still names it with `(native)` instead of a position, so the names are
1114    /// tracked separately and stitched into [`Interp::stack_trace`].
1115    ///
1116    /// The third field is how many bytecode frames were live when the native was entered,
1117    /// which is what places it *among* them rather than before all of them. Native
1118    /// functions used to be emitted up front on the grounds that they never re-enter
1119    /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1120    /// The natives currently running, innermost last: the function object and the
1121    /// depth it was entered at.
1122    ///
1123    /// The *name* is deliberately not stored. It used to be, read with
1124    /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1125    /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1126    /// benchmark. A stack trace is built rarely; it can read the name then.
1127    native_frames: Vec<(Gc<JsObject>, usize)>,
1128    /// The native function currently executing, for the ones that have to know *which*
1129    /// function they are — a typed-array constructor reads its element type off itself.
1130    ///
1131    /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1132    /// reports whatever the enclosing bytecode frame was called with.
1133    current_native: Option<Gc<JsObject>>,
1134    /// Text written by `print` and friends, in order.
1135    ///
1136    /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1137    /// once at the end, which is also when upstream's line buffering becomes
1138    /// visible for the cases compared here.
1139    pub output: String,
1140    /// Where `print` also writes, as it goes. `output` keeps the full log for
1141    /// [`crate::Context::output`]; this is the live copy, flushed per line.
1142    ///
1143    /// Both exist on purpose. A host that gives a script a sink sees output *when it
1144    /// happens* — which is what a timer callback's `console.log` has to do, and what the
1145    /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1146    /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1147    /// would show a script's output all at once when it finished.
1148    pub output_sink: Option<Box<dyn std::io::Write>>,
1149    /// Where recent property reads found their value.
1150    ///
1151    /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1152    /// table remembering *which object* and *which entry of its property table* answered a
1153    /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1154    /// can move; the property can become an accessor), which is what makes a stale entry a
1155    /// miss rather than a wrong answer.
1156    ///
1157    /// The object is held weakly: a cache that held it strongly would keep up to
1158    /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1159    /// program cannot see and cannot work around.
1160    pub field_cache: Vec<Option<FieldCache>>,
1161    /// Global lookups, by binding slot. See [`GlobalCache`].
1162    global_cache: Vec<Option<GlobalCache>>,
1163    /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1164    /// under its limit. See [`Interp::check_memory`].
1165    pub oom_reported_at: usize,
1166    /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1167    /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1168    ///
1169    /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1170    /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1171    /// host that wants to stop a runaway script must not have to wait for it to return.
1172    ///
1173    /// Two things this cannot do, both of them differences a host can observe:
1174    ///
1175    /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1176    ///   uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1177    ///   needs a signal that the `catch` machinery does not see, which is a change to
1178    ///   [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1179    ///   a host that stops the script itself.
1180    /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1181    ///   also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1182    ///   both, so the difference is when the counter hits zero, not whether it will.
1183    pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1184    /// Instructions until the next [`Interp::interrupt`] poll.
1185    pub interrupt_counter: u32,
1186    /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1187    ///
1188    /// A separate field from [`Interp::uncatchable`] because the two live for different
1189    /// spans. This one is the host's standing request; it survives the start of an
1190    /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1191    /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1192    /// for both was the first attempt and it did nothing at all: the outermost `execute`
1193    /// cleared it before the script it was set for had a chance to throw.
1194    pub uncatchable_next: bool,
1195    /// Whether the exception now unwinding may be caught by a `catch`.
1196    ///
1197    /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1198    /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1199    /// a host stopping a runaway loop is not fought by the loop.
1200    ///
1201    /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1202    /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1203    /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1204    /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1205    pub uncatchable: bool,
1206    /// The most stack a JavaScript call chain may use, in bytes of frame state.
1207    ///
1208    /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1209    /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1210    /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1211    /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1212    /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1213    /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1214    ///
1215    /// The numbers come out close for the same reason a C frame and a heap frame of this
1216    /// shape cost about the same (both are a few hundred bytes, dominated by the value
1217    /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1218    /// and this engine lands in the same neighbourhood — measured, not fudged, by
1219    /// `crates/quickjs-cli/tests/limits.rs`.
1220    pub stack_limit: usize,
1221    /// The most frames that may be live at once, whatever the byte budget says.
1222    ///
1223    /// A second bound for a reason the reference does not have: our frames cost less than
1224    /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1225    /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1226    /// `--stack-size 1G` from being a memory bomb.
1227    pub max_frames: usize,
1228    /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1229    ///
1230    /// Script execution does not return until this has drained, which is what makes
1231    /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1232    /// than never. Reactions append to it while it drains, so the loop is a `while` and
1233    /// not a `for`.
1234    pub(crate) jobs: std::collections::VecDeque<Job>,
1235    /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1236    ///
1237    /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1238    /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1239    pub(crate) tasks: Vec<Task>,
1240    /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1241    /// barrier'd evaluation started.
1242    ///
1243    /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1244    /// lets a REPL report an error from the line it just evaluated without also reporting
1245    /// its own readline loop.
1246    trace_barriers: Vec<usize>,
1247    /// `os.signal` handlers, keyed by signal number.
1248    ///
1249    /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1250    /// a handler cannot be freed while it is still registered.
1251    pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1252    /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1253    ///
1254    /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1255    /// that is only reachable from a host closure could be freed while still registered.
1256    pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1257    /// The next timer id.
1258    ///
1259    /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1260    /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1261    next_timer_id: i32,
1262    /// Errors thrown by timer callbacks, already rendered.
1263    ///
1264    /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1265    /// that throws has no promise behind it. Both are reported by the host at the end of
1266    /// the loop, but only one is fixed up by a later `.catch`.
1267    timer_errors: Vec<String>,
1268    /// The module registry, keyed by canonical name.
1269    pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1270    /// How the host turns a specifier into bytes.
1271    pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1272    /// The module the host was asked to run, for `import.meta.main`.
1273    pub main_module_name: Option<String>,
1274    /// Module bodies currently running, innermost last.
1275    ///
1276    /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1277    /// this is the only place that knows which module that is.
1278    pub module_stack: Vec<String>,
1279    /// Rejections that no handler has claimed, with the promise they belong to.
1280    ///
1281    /// A `then` registered later prunes its entry, which is why the promise is kept: the
1282    /// reason alone cannot say whether somebody eventually listened.
1283    unhandled: Vec<(Gc<JsObject>, Value)>,
1284}
1285
1286impl<'a> Interp<'a> {
1287    /// Build an interpreter over `heap`, with a fresh realm.
1288    pub fn new(heap: &'a Heap) -> Interp<'a> {
1289        let object_proto = JsObject::ordinary(heap, None);
1290        let function_proto = JsObject::function(
1291            heap,
1292            Some(object_proto.clone()),
1293            Callable::Native {
1294                func: |_, _, _| Ok(Value::Undefined),
1295                own_instance: false,
1296            },
1297        );
1298        let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1299        let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1300        let mut interp = Interp {
1301            heap,
1302            realm: Realm {
1303                global,
1304                object_proto,
1305                function_proto,
1306                array_proto,
1307                array_constructor: None,
1308                promise_constructor: None,
1309                globals: BTreeMap::new(),
1310                declared: Vec::new(),
1311                lexical_consts: BTreeSet::new(),
1312                errors: BTreeMap::new(),
1313                string_proto: None,
1314                number_proto: None,
1315                boolean_proto: None,
1316                bigint_proto: None,
1317                error_proto: JsObject::ordinary(heap, None),
1318                date_proto: JsObject::ordinary(heap, None),
1319                generator_proto: JsObject::ordinary(heap, None),
1320                promise_proto: None,
1321                async_generator_proto: None,
1322                symbol_proto: None,
1323                symbol_registry: BTreeMap::new(),
1324                internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1325                regexp_proto: None,
1326                regexp_ctor: None,
1327                suppressed_error_proto: None,
1328                disposable_stack_proto: None,
1329                map_proto: None,
1330                set_proto: None,
1331                finalization_registries: Vec::new(),
1332                array_buffer_proto: None,
1333                typed_array_proto: None,
1334                typed_array_protos: Vec::new(),
1335                data_view_proto: None,
1336                async_disposable_stack_proto: None,
1337                iterator_proto: None,
1338                iterator_ctor: None,
1339                iterator_helper_proto: None,
1340                iterator_wrap_proto: None,
1341                generator_function_proto: None,
1342                async_function_proto: None,
1343                async_generator_function_proto: None,
1344                iterator_protos: std::collections::BTreeMap::new(),
1345                well_known_symbols: WellKnownSymbols::default(),
1346                host_classes: HostClasses::new(),
1347            },
1348            frames: Vec::new(),
1349            free_values: Vec::new(),
1350            global_cache: {
1351                let mut cache = Vec::new();
1352                cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1353                cache
1354            },
1355            eval_scope: None,
1356            eval_depth: 0,
1357            eval_bindings: Vec::new(),
1358            eval_arguments: None,
1359            eval_with: None,
1360            active_eval_scope: None,
1361            eval_caller: None,
1362            pending_new_target: None,
1363            eval_new_target: None,
1364            native_frames: Vec::new(),
1365            current_native: None,
1366            output: String::new(),
1367            output_sink: None,
1368            field_cache: {
1369                let mut cache = Vec::new();
1370                cache.resize_with(FIELD_CACHE_SLOTS, || None);
1371                cache
1372            },
1373            oom_reported_at: 0,
1374            interrupt: None,
1375            interrupt_counter: INTERRUPT_POLL_INTERVAL,
1376            uncatchable_next: false,
1377            uncatchable: false,
1378            // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1379            // absent.
1380            stack_limit: DEFAULT_STACK_SIZE,
1381            max_frames: MAX_FRAMES,
1382            jobs: std::collections::VecDeque::new(),
1383            tasks: Vec::new(),
1384            trace_barriers: Vec::new(),
1385            signal_handlers: std::collections::BTreeMap::new(),
1386            fd_handlers: std::collections::BTreeMap::new(),
1387            next_timer_id: 1,
1388            timer_errors: Vec::new(),
1389            modules: std::collections::BTreeMap::new(),
1390            module_loader: None,
1391            main_module_name: None,
1392            module_stack: Vec::new(),
1393            unhandled: Vec::new(),
1394        };
1395        crate::builtins::install(&mut interp);
1396        interp
1397    }
1398
1399    // -- allocation helpers -------------------------------------------------
1400
1401    /// A new string value.
1402    /// A `BigInt` value from a computed big integer.
1403    pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1404        Value::BigInt(Gc::new(self.heap, value))
1405    }
1406
1407    /// A string value from bytes that are already WTF-8, which is how a string with an
1408    /// unpaired surrogate reaches a `Value`.
1409    pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1410        Value::string_wtf8(self.heap, text)
1411    }
1412
1413    /// A new string value, from text that is valid UTF-8.
1414    pub fn string(&self, text: impl Into<String>) -> Value {
1415        Value::string(self.heap, text)
1416    }
1417
1418    /// A new ordinary object with the given prototype.
1419    pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1420        JsObject::ordinary(self.heap, proto)
1421    }
1422
1423    // -- host classes -------------------------------------------------------
1424
1425    /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1426    pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1427        self.realm.host_classes.register(def)
1428    }
1429
1430    /// Register `def` under an id the host already holds (`JS_NewClass`).
1431    ///
1432    /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1433    /// `JS_NewClass`.
1434    pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1435        self.realm.host_classes.define(id, def)
1436    }
1437
1438    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1439    pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1440        self.realm.host_classes.set_proto(id, proto);
1441    }
1442
1443    /// The prototype installed for `id`, if any.
1444    pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1445        self.realm.host_classes.proto(id)
1446    }
1447
1448    /// A new instance of `id` (`JS_NewObjectProtoClass`).
1449    ///
1450    /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1451    /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1452    /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1453    /// host installed none.
1454    ///
1455    /// Answers `None` for an id that was never registered: the C API would return an
1456    /// exception, and silently making an ordinary object instead would move the failure to
1457    /// the first `JS_GetOpaque` that no longer matches.
1458    pub fn new_host_object(
1459        &mut self,
1460        proto: Option<Gc<JsObject>>,
1461        class_id: ClassId,
1462    ) -> Option<Gc<JsObject>> {
1463        let class = self.realm.host_classes.def(class_id)?;
1464        let proto = proto
1465            .or_else(|| self.realm.host_classes.proto(class_id))
1466            .or_else(|| Some(self.realm.object_proto.clone()));
1467        Some(JsObject::host_object(self.heap, proto, class_id, class))
1468    }
1469
1470    /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1471    ///
1472    /// `None` covers both answers the C API gives as a null pointer — the value is not an
1473    /// object, it is an object of another class, or the class never got a payload. A host
1474    /// that has to tell them apart uses [`JsObject::host_class_id`].
1475    pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1476        let object = value.as_object()?;
1477        if object.host_class_id()? != class_id {
1478            return None;
1479        }
1480        object.host_opaque()
1481    }
1482
1483    /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1484    pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1485        match value.as_object() {
1486            Some(object) => object.set_host_opaque(opaque),
1487            None => false,
1488        }
1489    }
1490
1491    /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1492    ///
1493    /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1494    /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1495    /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1496    /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1497    /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1498    /// said `[object Object]` instead of `[object Array Iterator]`.
1499    ///
1500    /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1501    /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1502    /// its own.
1503    pub fn new_iterator_prototype(
1504        &mut self,
1505        tag: &str,
1506        next: crate::object::NativeFn,
1507    ) -> Gc<JsObject> {
1508        if let Some(existing) = self.realm.iterator_protos.get(tag) {
1509            return existing.clone();
1510        }
1511        let parent = self.realm.iterator_proto.clone();
1512        let proto = self.new_object(parent);
1513        let next = self.new_native("next", 0, next);
1514        proto.define(
1515            "next",
1516            Property::with_attributes(Value::Object(next), true, false),
1517        );
1518        let key = self.realm.well_known_key(WellKnown::Iterator);
1519        let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1520        proto.define_key(
1521            &key,
1522            Property::with_attributes(Value::Object(identity), true, false),
1523        );
1524        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1525        let tag_value = self.string(tag);
1526        // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1527        // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1528        // checks it.
1529        proto.define_key(&tag_key, Property::configurable_only(tag_value));
1530        self.realm
1531            .iterator_protos
1532            .insert(tag.to_string(), proto.clone());
1533        proto
1534    }
1535
1536    /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1537    ///
1538    /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1539    /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1540    /// produced. That is why the two branches are not merged.
1541    pub fn object_own_property_keys(
1542        &mut self,
1543        object: &Gc<JsObject>,
1544    ) -> JsResult<Vec<PropertyKey>> {
1545        if let Some(keys) = self.proxy_own_keys(object)? {
1546            return Ok(keys);
1547        }
1548        // Integer-like keys ascending, then the string keys in insertion order, then the
1549        // symbols — the order every schema that walks an object expects.
1550        let entries = object.property_entries();
1551        let mut numeric: Vec<u32> = Vec::new();
1552        // An integer-indexed exotic object reports its indices as own keys even though they
1553        // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1554        // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1555        // order). The length is asked per call, so a resizable buffer's view reports the
1556        // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1557        if object.typed_array_parts().is_some() {
1558            for index in 0..object.typed_array_length().unwrap_or(0) {
1559                // `u32::try_from` cannot fail for a real length, but the length is a
1560                // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1561                // as an array index and one element beyond is not.
1562                match u32::try_from(index) {
1563                    Ok(index) => numeric.push(index),
1564                    Err(_) => break,
1565                }
1566            }
1567        }
1568        let mut strings: Vec<PropertyKey> = Vec::new();
1569        let mut symbols: Vec<PropertyKey> = Vec::new();
1570        for (key, _) in entries {
1571            match &key {
1572                // A class-private name is never reported by any enumeration: that is the
1573                // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1574                // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1575                // symbol skip, `Object.assign`) therefore cannot see it.
1576                PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1577                PropertyKey::Symbol(_) => symbols.push(key),
1578                PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1579                    Some(index) => {
1580                        if !numeric.contains(&index) {
1581                            numeric.push(index);
1582                        }
1583                    }
1584                    None => strings.push(key),
1585                },
1586            }
1587        }
1588        numeric.sort_unstable();
1589        let mut keys: Vec<PropertyKey> = numeric
1590            .into_iter()
1591            .map(|index| PropertyKey::from(index.to_string()))
1592            .collect();
1593        keys.extend(strings);
1594        keys.extend(symbols);
1595        Ok(keys)
1596    }
1597
1598    /// The state behind a promise object, or `None` when `object` is not one.
1599    pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1600        object.with(|data| match &data.kind {
1601            ObjectKind::Promise(state) => Some(state.clone()),
1602            _ => None,
1603        })
1604    }
1605
1606    /// A new pending promise.
1607    pub fn new_promise(&mut self) -> Gc<JsObject> {
1608        // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1609        // the one place every promise is built, and a subclass that builds its instances
1610        // somewhere else would be invisible to `instanceof`.
1611        let default = self.realm.promise_proto.clone();
1612        // A throwing `new.target.prototype` getter cannot be reported from here — this is
1613        // the raw promise constructor and its result is not `JsResult` — so the rejection is
1614        // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1615        // `prototype` getter therefore still gets a working promise; the alternative is a
1616        // panic, and the throwing path is covered by `Promise`'s own argument validation.
1617        let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1618        let promise = JsObject::ordinary(self.heap, proto);
1619        promise.with_mut(|data| {
1620            data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1621                crate::object::PromiseState::default(),
1622            )));
1623        });
1624        promise
1625    }
1626
1627    /// Fulfil `promise`, unless it has already settled.
1628    ///
1629    /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1630    /// after `reject`, changes nothing.
1631    pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1632        let Some(state) = self.promise_state(promise) else {
1633            return;
1634        };
1635        let reactions = {
1636            let mut state = state.borrow_mut();
1637            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1638                return;
1639            }
1640            state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1641            std::mem::take(&mut state.reactions)
1642        };
1643        self.queue_reactions(reactions, value, false);
1644    }
1645
1646    /// Reject `promise`, unless it has already settled.
1647    pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1648        let Some(state) = self.promise_state(promise) else {
1649            return;
1650        };
1651        let reactions = {
1652            let mut state = state.borrow_mut();
1653            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1654                return;
1655            }
1656            state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1657            std::mem::take(&mut state.reactions)
1658        };
1659        // Remember it only when nothing is listening *now*; a `then` registered later
1660        // prunes the entry in `perform_then`.
1661        if reactions.is_empty() {
1662            self.unhandled.push((promise.clone(), reason.clone()));
1663        }
1664        self.queue_reactions(reactions, reason, true);
1665    }
1666
1667    /// Queue one job per reaction.
1668    ///
1669    /// This is what makes `then` asynchronous even on an already-settled promise:
1670    /// `p.then(f); g()` calls `g` first.
1671    fn queue_reactions(
1672        &mut self,
1673        reactions: Vec<crate::object::PromiseReaction>,
1674        argument: Value,
1675        rejected: bool,
1676    ) {
1677        for reaction in reactions {
1678            let handler = if rejected {
1679                reaction.on_rejected.clone()
1680            } else {
1681                reaction.on_fulfilled.clone()
1682            };
1683            self.jobs.push_back(Job::Reaction {
1684                handler,
1685                argument: argument.clone(),
1686                rejected,
1687                promise: reaction.promise,
1688            });
1689        }
1690    }
1691
1692    /// `NewPromiseCapability` as the executor receives it: the promise plus its
1693    /// resolve/reject pair.
1694    ///
1695    /// The pair are callable objects rather than Rust closures, because the script gets
1696    /// them and may stash them for later.
1697    pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1698        let promise = self.new_promise();
1699        // Both handlers are built-ins with an empty name and length 1, in
1700        // `length`-then-`name` order — `reject-function-property-order` reads the order back
1701        // off `Object.getOwnPropertyNames`.
1702        let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1703        let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1704        (promise, Value::Object(resolve), Value::Object(reject))
1705    }
1706
1707    /// §27.2.1.5 `NewPromiseCapability(C)`.
1708    ///
1709    /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1710    /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1711    /// decide what capability it hands back. That is the whole mechanism behind subclassing
1712    /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1713    /// silently ignored argument.
1714    ///
1715    /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1716    /// the engine's own executor is exactly what `new_promise_capability` builds.
1717    pub fn new_promise_capability_for(
1718        &mut self,
1719        constructor: &Value,
1720    ) -> JsResult<(Value, Value, Value)> {
1721        let Some(object) = constructor.as_object().cloned() else {
1722            return Err(self.type_error("promise constructor is not a constructor"));
1723        };
1724        if !object.is_constructor() {
1725            return Err(self.type_error("promise constructor is not a constructor"));
1726        }
1727        if self
1728            .realm
1729            .promise_constructor
1730            .as_ref()
1731            .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1732        {
1733            let (promise, resolve, reject) = self.new_promise_capability();
1734            return Ok((Value::Object(promise), resolve, reject));
1735        }
1736        let state = self.new_object(Some(self.realm.object_proto.clone()));
1737        // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1738        // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1739        // which only a *custom* constructor can observe, and none of the combinator tests
1740        // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1741        let executor = self.builtin_function(
1742            "",
1743            2,
1744            Callable::CapabilityExecutor {
1745                state: state.clone(),
1746            },
1747        );
1748        let promise = self.construct(
1749            Value::Object(object.clone()),
1750            Value::Object(object),
1751            vec![Value::Object(executor)],
1752        )?;
1753        // The pair is read *after* the constructor returns, so a constructor that never
1754        // called its executor, or called it with non-callables, is the spec's step 11
1755        // `TypeError` — not something the engine can paper over.
1756        let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1757            return Err(self.type_error("promise executor never ran"));
1758        };
1759        let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1760            return Err(self.type_error("promise executor never ran"));
1761        };
1762        for handler in [&resolve, &reject] {
1763            if !matches!(handler, Value::Object(object) if object.is_callable()) {
1764                return Err(self.type_error("promise capability handler is not callable"));
1765            }
1766        }
1767        Ok((promise, resolve, reject))
1768    }
1769
1770    /// §27.2.3.1 `PromiseResolve(C, x)`.
1771    ///
1772    /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1773    /// an `x` that is already a promise of exactly this constructor is handed back
1774    /// unchanged, and anything else gets a fresh capability from `C`.
1775    pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1776        if let Value::Object(object) = &value
1777            && self.promise_state(object).is_some()
1778        {
1779            // `x.constructor === C` means "already the right kind", so no capability is
1780            // built — which is observable through a `resolve` that counts its calls.
1781            let x_constructor = self.get_property(object, "constructor")?;
1782            let same = match (
1783                x_constructor.as_ref().and_then(Value::as_object),
1784                constructor.as_object(),
1785            ) {
1786                (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1787                _ => false,
1788            };
1789            if same {
1790                return Ok(value);
1791            }
1792        }
1793        let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1794        self.call_value(resolve, Value::Undefined, vec![value])?;
1795        Ok(promise)
1796    }
1797
1798    /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1799    /// promise, as `{ value: completion }`.
1800    ///
1801    /// The three cases are the reference's, and they differ on purpose:
1802    ///
1803    /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1804    ///   exception before any promise exists;
1805    /// * a **runtime** error rejects the returned promise;
1806    /// * success resolves it with `{ value }`, where the value is the script's completion
1807    ///   value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1808    ///   {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1809    ///   `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1810    ///   `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1811    ///
1812    /// # What this does not do
1813    ///
1814    /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1815    /// is evaluated in an async context, so `await` outside a function is legal. That needs
1816    /// the parser and the suspension machinery to accept a suspended top-level script, and
1817    /// is not implemented — such source is a syntax error here. Everything else about the
1818    /// flag is reproduced.
1819    pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1820        // The barrier goes up before compiling: a *parse* failure is reported with a trace
1821        // too, and the reference truncates that one at the same place as a runtime failure.
1822        if barrier {
1823            let depth = self.frames.len();
1824            self.trace_barriers.push(depth);
1825        }
1826        // Compiled before the promise exists, so a parse failure propagates as a throw
1827        // instead of being folded into a rejection.
1828        let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1829            Ok(compiled) => compiled,
1830            Err(error) => {
1831                if barrier {
1832                    self.trace_barriers.pop();
1833                }
1834                return Err(error);
1835            }
1836        };
1837        // An async body answers its own promise, and that promise is what the reference
1838        // hands back — the same object, not a wrapper around it. Its resolution value is
1839        // the `{value}` object the compiled epilogue built.
1840        if compiled.kind.is_async() {
1841            let strict = compiled.strict;
1842            let promise = self.run_eval_script(compiled, strict)?;
1843            if barrier {
1844                self.trace_barriers.pop();
1845            }
1846            return Ok(promise);
1847        }
1848        let (promise, resolve, reject) = self.new_promise_capability();
1849        let strict = compiled.strict;
1850        match self.run_eval_script(compiled, strict) {
1851            Ok(value) => {
1852                // `{ value }` is a plain object, so resolving with it adopts nothing even
1853                // when the completion value is itself a promise.
1854                let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1855                self.set_property(&wrapped, "value", value)?;
1856                self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1857            }
1858            Err(Signal::Throw(error)) => {
1859                self.call_value(reject, Value::Undefined, vec![error])?;
1860            }
1861            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1862        }
1863        if barrier {
1864            self.trace_barriers.pop();
1865        }
1866        Ok(Value::Object(promise))
1867    }
1868
1869    /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1870    ///
1871    /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1872    /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1873    /// timer table, where the collector already scans it.
1874    pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1875        let (promise, resolve, _reject) = self.new_promise_capability();
1876        let resolve = self.new_host_function(
1877            "resolve",
1878            1,
1879            Box::new(
1880                move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1881                    let value = args.first().cloned().unwrap_or(Value::Undefined);
1882                    interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1883                },
1884            ),
1885        );
1886        // The timer keeps the resolver alive: it is a property of the timer entry, and the
1887        // timer table is part of what the collector walks.
1888        self.schedule_timer(Value::Object(resolve), delay_ms);
1889        Ok(Value::Object(promise))
1890    }
1891
1892    /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1893    /// new promise resolved with it.
1894    pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1895        if let Value::Object(object) = &value
1896            && self.promise_state(object).is_some()
1897        {
1898            return Ok(value);
1899        }
1900        let promise = self.new_promise();
1901        self.resolve_promise_with(&promise, value)?;
1902        Ok(Value::Object(promise))
1903    }
1904
1905    /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1906    pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1907        // Resolving a promise with itself is a `TypeError`. The check exists because the
1908        // alternative is a chain of self-reactions that never settles.
1909        if let Value::Object(object) = &value
1910            && object.ptr_eq(promise)
1911        {
1912            // The spec rejects *and* throws, so both the promise and the caller see it.
1913            let thrown = self.type_error("cannot resolve a promise with itself");
1914            let Signal::Throw(error) = thrown.clone() else {
1915                unreachable!("type_error always throws")
1916            };
1917            self.reject_promise(promise, error);
1918            return Err(thrown);
1919        }
1920        let then = match &value {
1921            Value::Object(object) => self.get_property(object, "then")?,
1922            _ => None,
1923        };
1924        let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1925        if !callable_then {
1926            // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1927            self.fulfill_promise(promise, value);
1928            return Ok(());
1929        }
1930        // Adopting a thenable is asynchronous — `then` is called from a job, never from
1931        // inside `resolve`, so a script cannot make a promise settle synchronously.
1932        self.jobs.push_back(Job::Thenable {
1933            then: then.expect("checked callable"),
1934            value,
1935            promise: promise.clone(),
1936        });
1937        Ok(())
1938    }
1939
1940    /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
1941    ///
1942    /// `C.resolve` is user code and may answer a plain thenable rather than one of this
1943    /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
1944    ///
1945    /// The property read is **not** short-circuitable even for a real promise: the spec says
1946    /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
1947    /// expects it to run. Skipping the read for promises not only lost the throw, it made
1948    /// the combinator's loop infinite — the test's iterator never sets `done`.
1949    pub fn invoke_then(
1950        &mut self,
1951        thenable: Value,
1952        on_fulfilled: Value,
1953        on_rejected: Value,
1954    ) -> JsResult<()> {
1955        let then = match &thenable {
1956            Value::Object(object) => self.get_property(object, "then")?,
1957            primitive => {
1958                let boxed = self.object_from(primitive)?;
1959                self.get_property(&boxed, "then")?
1960            }
1961        };
1962        let Some(then) = then else {
1963            return Err(self.type_error("thenable has no then method"));
1964        };
1965        if !matches!(&then, Value::Object(object) if object.is_callable()) {
1966            return Err(self.type_error("then is not a function"));
1967        }
1968        self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
1969        Ok(())
1970    }
1971
1972    /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
1973    ///
1974    /// `Promise.prototype.then` in one step: register a reaction and answer the derived
1975    /// promise.
1976    pub fn perform_then(
1977        &mut self,
1978        promise: &Gc<JsObject>,
1979        on_fulfilled: Option<Value>,
1980        on_rejected: Option<Value>,
1981    ) -> JsResult<Value> {
1982        let Some(state) = self.promise_state(promise) else {
1983            return Err(self.type_error("not a promise"));
1984        };
1985        // Whether a rejection handler is being attached decides whether a recorded
1986        // rejection stops being unhandled, so it is read before the values are moved.
1987        let has_rejection_handler = on_rejected.is_some();
1988        let derived = self.new_promise();
1989        let reaction = crate::object::PromiseReaction {
1990            on_fulfilled,
1991            on_rejected,
1992            promise: derived.clone(),
1993        };
1994        let settled = {
1995            let mut state = state.borrow_mut();
1996            // A rejection somebody reacts to is no longer unhandled.
1997            state.handled = true;
1998            match &state.status {
1999                crate::object::PromiseStatus::Pending => {
2000                    state.reactions.push(reaction.clone());
2001                    None
2002                }
2003                crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2004                crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2005            }
2006        };
2007        // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2008        // later, means somebody is listening after all.
2009        if has_rejection_handler {
2010            self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2011        }
2012        if let Some((argument, rejected)) = settled {
2013            let handler = if rejected {
2014                reaction.on_rejected
2015            } else {
2016                reaction.on_fulfilled
2017            };
2018            self.jobs.push_back(Job::Reaction {
2019                handler,
2020                argument,
2021                rejected,
2022                promise: reaction.promise,
2023            });
2024        }
2025        Ok(Value::Object(derived))
2026    }
2027
2028    /// The rejections nobody listened to, formatted the way the reference reports them.
2029    ///
2030    /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2031    /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2032    /// unhandled at the point the queue drains, because a `then` may still be attached
2033    /// before the host acts on it.
2034    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2035        let entries = std::mem::take(&mut self.unhandled);
2036        // Somebody may have attached a handler after the rejection was recorded, so the
2037        // promise is the authority rather than the list.
2038        let still_unhandled: Vec<Value> = entries
2039            .into_iter()
2040            .filter_map(|(promise, reason)| {
2041                let handled = self
2042                    .promise_state(&promise)
2043                    .map(|state| state.borrow().handled)
2044                    .unwrap_or(true);
2045                (!handled).then_some(reason)
2046            })
2047            .collect();
2048        still_unhandled
2049            .into_iter()
2050            .map(|reason| {
2051                let text = self.describe_exception(&reason);
2052                let stack = match &reason {
2053                    Value::Object(object) => self
2054                        .get_property(object, "stack")
2055                        .ok()
2056                        .flatten()
2057                        .map(|value| value.to_js_string())
2058                        // `stack` carries a trailing newline of its own, which would leave
2059                        // a blank line between two reported rejections.
2060                        .map(|text| text.trim_end().to_string())
2061                        .unwrap_or_default(),
2062                    _ => String::new(),
2063                };
2064                if stack.is_empty() {
2065                    format!("Possibly unhandled promise rejection: {text}")
2066                } else {
2067                    format!("Possibly unhandled promise rejection: {text}\n{stack}")
2068                }
2069            })
2070            .collect()
2071    }
2072
2073    /// Run the microtask queue to exhaustion.
2074    ///
2075    /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2076    /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2077    /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2078    ///
2079    /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2080    /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2081    /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2082    pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2083        crate::builtins::json::parse_text(self, text, true)
2084    }
2085
2086    /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2087    ///
2088    /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2089    /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2090    /// immediately, and `setTimeout(f, -1)` is ordinary code.
2091    ///
2092    /// The callback is called with **no arguments**. The reference stores only the function
2093    /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2094    /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2095    /// extra arguments arrive as `undefined`.
2096    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2097        let id = self.next_timer_id;
2098        // Wrap rather than grow: the id reaches the script as an `Int32`.
2099        self.next_timer_id = if self.next_timer_id == i32::MAX {
2100            1
2101        } else {
2102            self.next_timer_id + 1
2103        };
2104        let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2105        self.tasks.push(Task::Timer {
2106            id,
2107            callback,
2108            due_at,
2109        });
2110        id
2111    }
2112
2113    /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2114    /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2115    pub fn cancel_timer(&mut self, id: i32) -> bool {
2116        let before = self.tasks.len();
2117        self.tasks.retain(|task| match task {
2118            Task::Timer { id: task_id, .. } => *task_id != id,
2119        });
2120        self.tasks.len() != before
2121    }
2122
2123    /// How long until the earliest pending timer, or `None` when none is pending.
2124    pub fn next_timeout(&self) -> Option<std::time::Duration> {
2125        let now = std::time::Instant::now();
2126        self.tasks
2127            .iter()
2128            .map(|task| match task {
2129                Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2130            })
2131            .min()
2132    }
2133
2134    /// Run one turn of the event loop.
2135    ///
2136    /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2137    /// run at most one due timer, then drain again. The blocking belongs to the caller
2138    /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2139    /// is how it asks.
2140    ///
2141    /// One timer per turn rather than all of them: a timer callback may schedule another
2142    /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2143    /// starve the microtask queue.
2144    pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2145        self.drain_jobs()?;
2146        let now = std::time::Instant::now();
2147        // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2148        // followed by `setTimeout(g, 1)` must run `g` first.
2149        let due = self
2150            .tasks
2151            .iter()
2152            .enumerate()
2153            .filter(|(_, task)| match task {
2154                Task::Timer { due_at, .. } => *due_at <= now,
2155            })
2156            .min_by_key(|(_, task)| match task {
2157                Task::Timer { due_at, .. } => *due_at,
2158            })
2159            .map(|(index, _)| index);
2160        let Some(index) = due else {
2161            // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2162            // descriptor is registered but no timer is closer, so a script that never
2163            // touches the descriptor still gets control back. Without a cap a handler on a
2164            // descriptor that is never ready would block for as long as the host allows.
2165            let timeout = self
2166                .next_timeout()
2167                .unwrap_or(std::time::Duration::from_secs(10))
2168                .min(std::time::Duration::from_secs(10));
2169            if !self.fd_handlers.is_empty() {
2170                // Blocking on a timer while descriptors are registered would starve them,
2171                // and blocking on the descriptors while a timer is due would delay it; the
2172                // host polls with the earlier of the two deadlines, which this timeout is.
2173                return Ok(Turn::Poll(timeout));
2174            }
2175            return Ok(match self.next_timeout() {
2176                Some(wait) => Turn::Wait(wait),
2177                None => Turn::Done,
2178            });
2179        };
2180        let Task::Timer { callback, .. } = self.tasks.remove(index);
2181        let this = Value::Undefined;
2182        // A throwing timer callback must not stop the loop: the reference reports it and
2183        // keeps going, because the alternative is that one bad timer silently stops every
2184        // later one.
2185        // No arguments: see `schedule_timer` — the reference calls the callback bare.
2186        match self.call_value(callback, this, Vec::new()) {
2187            Ok(_) => {}
2188            Err(Signal::Throw(value)) => {
2189                let text = self.describe_exception(&value);
2190                self.timer_errors.push(text);
2191            }
2192            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2193        }
2194        self.drain_jobs()?;
2195        Ok(Turn::Ran)
2196    }
2197
2198    /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2199    ///
2200    /// `callback` of `None` unregisters that direction, and an entry with neither direction
2201    /// left is removed — the reference does the same, so a script can rely on
2202    /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2203    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2204        let entry = self.fd_handlers.entry(fd).or_default();
2205        if readable {
2206            entry.read = callback;
2207        } else {
2208            entry.write = callback;
2209        }
2210        if entry.read.is_none() && entry.write.is_none() {
2211            self.fd_handlers.remove(&fd);
2212        }
2213    }
2214
2215    /// Register or clear an `os.signal` handler.
2216    ///
2217    /// `None` removes it; the host separately restores the default disposition or sets
2218    /// ignore, because which of those happened is the script's choice (`null` versus
2219    /// `undefined`) and not something this table can express.
2220    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2221        match handler {
2222            Some(handler) => {
2223                self.signal_handlers.insert(signal, handler);
2224            }
2225            None => {
2226                self.signal_handlers.remove(&signal);
2227            }
2228        }
2229    }
2230
2231    /// Run the handler for `signal`, reporting whether one ran.
2232    ///
2233    /// A throwing handler is reported and the loop continues, like a timer's.
2234    pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2235        let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2236            return Ok(false);
2237        };
2238        match self.call_value(handler, Value::Undefined, Vec::new()) {
2239            Ok(_) => {}
2240            Err(Signal::Throw(value)) => {
2241                let text = self.describe_exception(&value);
2242                self.timer_errors.push(text);
2243            }
2244            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2245        }
2246        self.drain_jobs()?;
2247        Ok(true)
2248    }
2249
2250    /// The descriptors the host has to poll, and in which direction.
2251    ///
2252    /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2253    /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2254    /// `os_poll` asks for.
2255    pub fn pending_fds(&self) -> Vec<FdInterest> {
2256        self.fd_handlers
2257            .iter()
2258            .map(|(fd, entry)| FdInterest {
2259                fd: *fd,
2260                read: entry.read.is_some(),
2261                write: entry.write.is_some(),
2262            })
2263            .collect()
2264    }
2265
2266    /// Call the handler registered for `fd`, reporting whether one ran.
2267    ///
2268    /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2269    /// poll iteration and then restarts the loop, because the handler may have changed the
2270    /// registration list underneath it; doing the same here keeps a handler that
2271    /// unregisters itself from being called with stale state.
2272    ///
2273    /// A throwing handler is reported and the loop continues — a bad handler must not stop
2274    /// every later one, exactly as with timers.
2275    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2276        let Some(entry) = self.fd_handlers.get(&fd) else {
2277            return Ok(false);
2278        };
2279        let callback = if readable {
2280            entry.read.clone()
2281        } else if writable {
2282            entry.write.clone()
2283        } else {
2284            None
2285        };
2286        let Some(callback) = callback else {
2287            return Ok(false);
2288        };
2289        self.drain_jobs()?;
2290        match self.call_value(callback, Value::Undefined, Vec::new()) {
2291            Ok(_) => {}
2292            Err(Signal::Throw(value)) => {
2293                let text = self.describe_exception(&value);
2294                self.timer_errors.push(text);
2295            }
2296            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2297        }
2298        self.drain_jobs()?;
2299        Ok(true)
2300    }
2301
2302    /// Take the errors timer callbacks threw, leaving the list empty.
2303    pub fn take_timer_errors(&mut self) -> Vec<String> {
2304        std::mem::take(&mut self.timer_errors)
2305    }
2306
2307    /// Whether anything is still pending: a microtask or a timer.
2308    pub fn has_pending_work(&self) -> bool {
2309        !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2310    }
2311
2312    /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2313    pub fn has_pending_timers_or_jobs(&self) -> bool {
2314        !self.jobs.is_empty() || !self.tasks.is_empty()
2315    }
2316
2317    /// Run every queued microtask, including ones queued while draining.
2318    pub fn drain_jobs(&mut self) -> JsResult<()> {
2319        // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2320        // would spin forever, so the drain is bounded the way the call stack is.
2321        let mut budget = 1_000_000usize;
2322        while let Some(job) = self.jobs.pop_front() {
2323            if budget == 0 {
2324                return Err(Signal::Throw(
2325                    self.make_error("InternalError", "promise job queue did not drain"),
2326                ));
2327            }
2328            budget -= 1;
2329            self.run_job(job)?;
2330            // `FinalizationRegistry` at the job boundary: this is the safe point where the
2331            // engine may run script that the script itself did not ask for. Doing it here
2332            // rather than from a drop hook is what keeps the callback out of arbitrary
2333            // engine bookkeeping — see `builtins::weak`'s header.
2334            crate::builtins::weak::drain_finalizers(self)?;
2335        }
2336        // A script that queued no jobs may still have dropped targets, so the checkpoint
2337        // runs once more after the queue empties.
2338        crate::builtins::weak::drain_finalizers(self)?;
2339        Ok(())
2340    }
2341
2342    /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2343    ///
2344    /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2345    /// `None` and is swept out here. This is also where the realm learns that a registry
2346    /// died, which is why it is a mutation rather than a read.
2347    pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2348        let handles = std::mem::take(&mut self.realm.finalization_registries);
2349        let mut live = Vec::with_capacity(handles.len());
2350        for handle in handles {
2351            let Some(object) = handle.upgrade() else {
2352                continue;
2353            };
2354            let Some(state) = object.finalization_state() else {
2355                continue;
2356            };
2357            live.push((object.clone(), *state));
2358            self.realm.finalization_registries.push(object.downgrade());
2359        }
2360        live
2361    }
2362
2363    /// Run one microtask.
2364    fn run_job(&mut self, job: Job) -> JsResult<()> {
2365        match job {
2366            Job::Reaction {
2367                handler: None,
2368                argument,
2369                rejected,
2370                promise,
2371            } => {
2372                // No handler: the settlement passes straight through to the derived
2373                // promise, which is why `p.catch(f)` ignores fulfilments.
2374                if rejected {
2375                    self.reject_promise(&promise, argument);
2376                } else {
2377                    self.fulfill_promise(&promise, argument);
2378                }
2379                Ok(())
2380            }
2381            Job::Reaction {
2382                handler: Some(handler),
2383                argument,
2384                promise,
2385                ..
2386            } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2387                Ok(answer) => {
2388                    if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2389                        self.reject_promise(&promise, error);
2390                    }
2391                    Ok(())
2392                }
2393                Err(Signal::Throw(reason)) => {
2394                    self.reject_promise(&promise, reason);
2395                    Ok(())
2396                }
2397                Err(other) => Err(other),
2398            },
2399            Job::Thenable {
2400                then,
2401                value,
2402                promise,
2403            } => {
2404                // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2405                // the value it produces settles `promise`.
2406                // The thenable's `then` gets this promise's own pair, so whatever it
2407                // produces settles `promise`.
2408                let resolve = JsObject::function(
2409                    self.heap,
2410                    Some(self.realm.function_proto.clone()),
2411                    Callable::PromiseResolve(promise.clone()),
2412                );
2413                let reject = JsObject::function(
2414                    self.heap,
2415                    Some(self.realm.function_proto.clone()),
2416                    Callable::PromiseReject(promise.clone()),
2417                );
2418                match self.call_value(
2419                    then,
2420                    value,
2421                    vec![Value::Object(resolve), Value::Object(reject)],
2422                ) {
2423                    Ok(_) => Ok(()),
2424                    Err(Signal::Throw(reason)) => {
2425                        self.reject_promise(&promise, reason);
2426                        Ok(())
2427                    }
2428                    Err(other) => Err(other),
2429                }
2430            }
2431            Job::Resume {
2432                coroutine,
2433                promise,
2434                kind,
2435                value,
2436            } => self.drive_async(&coroutine, &promise, kind, value),
2437            Job::GeneratorResume {
2438                generator,
2439                promise,
2440                kind,
2441                value,
2442            } => self.step_async_generator(&generator, &promise, kind, value),
2443            Job::Import {
2444                specifier,
2445                referrer,
2446                promise,
2447            } => {
2448                self.run_dynamic_import(&specifier, &referrer, &promise);
2449                Ok(())
2450            }
2451        }
2452    }
2453
2454    /// One element of a `Promise` combinator settled.
2455    ///
2456    /// The shared state object holds the result array, the number still outstanding, and
2457    /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2458    /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2459    /// to settle, only whatever `Sub` said a capability is.
2460    ///
2461    /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2462    /// and `any` must ignore every later settlement, and `all` must not report a second
2463    /// rejection after the first.
2464    fn settle_combinator(
2465        &mut self,
2466        state: &Gc<JsObject>,
2467        index: usize,
2468        fulfilled: bool,
2469        value: Value,
2470    ) -> JsResult<()> {
2471        let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2472        // Each element settles at most once: a thenable may call `onFulfilled` twice
2473        // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2474        // call a no-op. Without it the second call decremented `remaining` again and settled
2475        // `all` with a short values array (`call-resolve-element-items`).
2476        let done = field("done");
2477        let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2478        let settled = field("settled").is_some_and(|value| value.to_boolean());
2479        if settled {
2480            return Ok(());
2481        }
2482        if let Some(Value::Object(done)) = &done {
2483            if done
2484                .array_get(index)
2485                .is_some_and(|value| value.to_boolean())
2486            {
2487                return Ok(());
2488            }
2489            done.array_set(self.heap, index, Value::Bool(true));
2490        }
2491        let resolve = field("resolve");
2492        let reject = field("reject");
2493        let keys = field("keys");
2494        let results = field("results").and_then(|value| value.as_object().cloned());
2495        // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2496        // promise: the handler is a plain function the constructor chose.
2497        let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2498            if let Some(handler) = handler {
2499                interp.call_value(handler, Value::Undefined, vec![value])?;
2500            }
2501            Ok(())
2502        };
2503        match kind {
2504            // `race`: the first settlement wins and stops the rest.
2505            3 => {
2506                state.define_data("settled", Value::Bool(true));
2507                let handler = if fulfilled { resolve } else { reject };
2508                settle_with(self, handler, value)?;
2509                return Ok(());
2510            }
2511            // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2512            // the first rejection wins outright.
2513            0 | 4 if !fulfilled => {
2514                state.define_data("settled", Value::Bool(true));
2515                settle_with(self, reject, value)?;
2516                return Ok(());
2517            }
2518            // `any`: the first fulfilment wins.
2519            2 if fulfilled => {
2520                state.define_data("settled", Value::Bool(true));
2521                settle_with(self, resolve, value)?;
2522                return Ok(());
2523            }
2524            _ => {}
2525        }
2526        let Some(results) = &results else {
2527            return Ok(());
2528        };
2529        match kind {
2530            4 => {
2531                results.array_set(self.heap, index, value);
2532            }
2533            0 => {
2534                results.array_set(self.heap, index, value);
2535            }
2536            // `allSettled` (and its keyed twin) never rejects; each slot records what
2537            // happened.
2538            1 | 5 => {
2539                let record = self.new_object(Some(self.realm.object_proto.clone()));
2540                if fulfilled {
2541                    record.define_data("status", self.string("fulfilled"));
2542                    record.define_data("value", value);
2543                } else {
2544                    record.define_data("status", self.string("rejected"));
2545                    record.define_data("reason", value);
2546                }
2547                results.array_set(self.heap, index, Value::Object(record));
2548            }
2549            // `any`: a rejection is parked in the errors array and the sweep continues.
2550            2 => {
2551                results.array_set(self.heap, index, value);
2552            }
2553            _ => {}
2554        }
2555        let remaining = field("remaining")
2556            .map(|value| value.to_int32())
2557            .unwrap_or(0);
2558        let left = remaining - 1;
2559        state.define_data("remaining", Value::Int(left));
2560        if left != 0 {
2561            return Ok(());
2562        }
2563        state.define_data("settled", Value::Bool(true));
2564        match kind {
2565            0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2566            // The keyed result: an ordinary object with a **null** prototype, holding the
2567            // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2568            4 | 5 => {
2569                let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2570                settle_with(self, resolve, keyed)?;
2571            }
2572            2 => {
2573                // The rejection is an `AggregateError` whose `errors` is the results array
2574                // itself — the slots are the reasons, in input order.
2575                let errors = results.array_elements().unwrap_or_default();
2576                let error = self.aggregate_error(errors, "all promises were rejected");
2577                settle_with(self, reject, error)?;
2578            }
2579            _ => {}
2580        }
2581        Ok(())
2582    }
2583
2584    /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2585    ///
2586    /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2587    /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2588    /// prototype is load-bearing in both directions: a key called `toString` must not
2589    /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2590    /// (`resolves-empty-object.js`).
2591    pub(crate) fn keyed_result_object(
2592        &mut self,
2593        keys: Option<&Value>,
2594        values: &Gc<JsObject>,
2595    ) -> JsResult<Value> {
2596        let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2597            return Ok(Value::Object(self.new_object(None)));
2598        };
2599        let result = self.new_object(None);
2600        let count = values.array_length().unwrap_or(0);
2601        for index in 0..count {
2602            let Some(key) = keys.array_get(index) else {
2603                continue;
2604            };
2605            let Some(value) = values.array_get(index) else {
2606                continue;
2607            };
2608            let property = Property::with_attributes(value, true, true);
2609            match &key {
2610                Value::Symbol(symbol) => {
2611                    result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2612                }
2613                other => {
2614                    let text = self.to_js_string(other)?;
2615                    result.define_key(&PropertyKey::from(text.as_str()), property);
2616                }
2617            }
2618        }
2619        Ok(Value::Object(result))
2620    }
2621
2622    /// Build an async function's result: a promise whose body runs as a coroutine.
2623    pub fn new_async_function(
2624        &mut self,
2625        function: Value,
2626        this: Value,
2627        args: Vec<Value>,
2628    ) -> JsResult<Value> {
2629        let promise = self.new_promise();
2630        let coroutine = self.new_coroutine(function, this, args)?;
2631        if let Err(Signal::Throw(reason)) =
2632            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2633        {
2634            self.reject_promise(&promise, reason);
2635        }
2636        Ok(Value::Object(promise))
2637    }
2638
2639    /// The coroutine an async body runs in.
2640    ///
2641    /// Generator-shaped and never exposed to the script: what makes `await` work is the
2642    /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2643    /// than growing a second state machine. The difference is only in the ending — a
2644    /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2645    /// Run `code` as an async function body, answering the promise it settles.
2646    ///
2647    /// Used for a module with top-level `await`: its body is an async function whose
2648    /// caller is the host, so there is no function object to pass through
2649    /// [`Interp::new_async_function`].
2650    pub fn run_async_body(
2651        &mut self,
2652        code: Gc<CompiledCode>,
2653        env: Gc<ClosureEnv>,
2654        this: Value,
2655    ) -> JsResult<Value> {
2656        let promise = self.new_promise();
2657        let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2658        if let Err(Signal::Throw(reason)) =
2659            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2660        {
2661            self.reject_promise(&promise, reason);
2662        }
2663        Ok(Value::Object(promise))
2664    }
2665
2666    fn new_coroutine(
2667        &mut self,
2668        function: Value,
2669        this: Value,
2670        args: Vec<Value>,
2671    ) -> JsResult<Gc<JsObject>> {
2672        let Some(object) = function.as_object().cloned() else {
2673            return Err(self.type_error("not a function"));
2674        };
2675        let Some((code, env)) = bytecode_of(&object) else {
2676            return Err(self.type_error("not a function"));
2677        };
2678        self.new_coroutine_from(code, env, this, args)
2679    }
2680
2681    /// Build a coroutine over an already-resolved body.
2682    fn new_coroutine_from(
2683        &mut self,
2684        code: Gc<CompiledCode>,
2685        env: Gc<ClosureEnv>,
2686        this: Value,
2687        args: Vec<Value>,
2688    ) -> JsResult<Gc<JsObject>> {
2689        let function = Value::Undefined;
2690        self.push_frame(code, env, this, args, function)?;
2691        let frame = self.frames.pop().expect("push_frame just pushed it");
2692        let state = GeneratorState {
2693            frame: Some(frame),
2694            phase: GeneratorPhase::SuspendedStart,
2695            parked_on_await: false,
2696            parked_on_yield_star: false,
2697            requests: std::collections::VecDeque::new(),
2698            async_busy: false,
2699        };
2700        let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2701        coroutine.with_mut(|data| {
2702            data.kind = ObjectKind::Generator(Box::new(state));
2703        });
2704        Ok(coroutine)
2705    }
2706
2707    /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2708    /// `await` and `value` is what it awaited.
2709    fn resume_coroutine(
2710        &mut self,
2711        coroutine: &Gc<JsObject>,
2712        kind: ResumeKind,
2713        value: Value,
2714    ) -> JsResult<(Value, bool)> {
2715        let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2716            ObjectKind::Generator(state) => Some(std::mem::replace(
2717                state.as_mut(),
2718                GeneratorState {
2719                    frame: None,
2720                    phase: GeneratorPhase::Executing,
2721                    parked_on_await: false,
2722                    parked_on_yield_star: false,
2723                    requests: std::collections::VecDeque::new(),
2724                    async_busy: false,
2725                },
2726            )),
2727            _ => None,
2728        }) else {
2729            return Err(self.type_error("not a coroutine"));
2730        };
2731        let result = self.step_generator(&mut state, kind, value);
2732        coroutine.with_mut(|data| {
2733            data.kind = ObjectKind::Generator(Box::new(state));
2734        });
2735        let (value, done, _ready, _reason) = result?;
2736        Ok((value, done))
2737    }
2738
2739    /// Advance an async body and settle its promise with the outcome.
2740    fn drive_async(
2741        &mut self,
2742        coroutine: &Gc<JsObject>,
2743        promise: &Gc<JsObject>,
2744        kind: ResumeKind,
2745        value: Value,
2746    ) -> JsResult<()> {
2747        match self.resume_coroutine(coroutine, kind, value) {
2748            Ok((value, true)) => {
2749                // `Ok` with `done` means the body finished *normally*, even when it was
2750                // resumed by a `throw` — `try { await p } catch {}` completes by
2751                // returning. Only the `Err` arm below is a rejection.
2752                //
2753                // Resolving rather than fulfilling matters: `return promise` in an async
2754                // body adopts the inner promise, so `async function f(){ return
2755                // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2756                // promise.
2757                if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2758                    self.reject_promise(promise, reason);
2759                }
2760                Ok(())
2761            }
2762            Ok((value, false)) => {
2763                // Parked on `await`: follow what it awaited and resume with the outcome.
2764                let awaited = match self.promise_resolve_value(value) {
2765                    Ok(awaited) => awaited,
2766                    Err(Signal::Throw(error)) => {
2767                        self.reject_promise(promise, error);
2768                        return Ok(());
2769                    }
2770                    Err(other) => return Err(other),
2771                };
2772                self.hook_await(awaited, coroutine, promise)
2773            }
2774            Err(Signal::Throw(reason)) => {
2775                self.reject_promise(promise, reason);
2776                Ok(())
2777            }
2778            Err(other) => Err(other),
2779        }
2780    }
2781
2782    /// Arrange for `coroutine` to resume when `awaited` settles.
2783    fn hook_await(
2784        &mut self,
2785        awaited: Value,
2786        coroutine: &Gc<JsObject>,
2787        promise: &Gc<JsObject>,
2788    ) -> JsResult<()> {
2789        let resumed = JsObject::function(
2790            self.heap,
2791            Some(self.realm.function_proto.clone()),
2792            Callable::AwaitResume {
2793                coroutine: coroutine.clone(),
2794                promise: promise.clone(),
2795                kind: ResumeKind::Next,
2796            },
2797        );
2798        let raised = JsObject::function(
2799            self.heap,
2800            Some(self.realm.function_proto.clone()),
2801            Callable::AwaitResume {
2802                coroutine: coroutine.clone(),
2803                promise: promise.clone(),
2804                kind: ResumeKind::Throw,
2805            },
2806        );
2807        // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2808        // guarantees one; the fallback keeps a mis-shaped value from panicking.
2809        let Value::Object(awaited) = &awaited else {
2810            self.jobs.push_back(Job::Resume {
2811                coroutine: coroutine.clone(),
2812                promise: promise.clone(),
2813                kind: ResumeKind::Next,
2814                value: awaited,
2815            });
2816            return Ok(());
2817        };
2818        self.perform_then(
2819            awaited,
2820            Some(Value::Object(resumed)),
2821            Some(Value::Object(raised)),
2822        )?;
2823        Ok(())
2824    }
2825
2826    /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2827    /// things an engine keeps outside it — array elements and an array's `length`.
2828    fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2829        if let Some(property) = object.own_property_key(key) {
2830            return Some(property);
2831        }
2832        // An array's elements live in their own vector rather than the property table, so
2833        // a descriptor for one has to be synthesized — with the attributes an element has.
2834        if let Some(index) = key.as_str().and_then(array_index)
2835            && let Some(value) = object.array_get(index as usize)
2836            && !matches!(value, Value::Hole)
2837        {
2838            return Some(Property::data(value));
2839        }
2840        // `length` is an own property of an array that is not in its property table
2841        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2842        // and non-enumerable.
2843        if key.as_str() == Some("length")
2844            && let Some(length) = object.array_length()
2845        {
2846            return Some(Property {
2847                value: Some(crate::object::length_value(length)),
2848                writable: object.length_writable(),
2849                enumerable: false,
2850                configurable: false,
2851                getter: None,
2852                setter: None,
2853            });
2854        }
2855        None
2856    }
2857
2858    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2859    pub fn object_get_own_property(
2860        &mut self,
2861        object: &Gc<JsObject>,
2862        key: &PropertyKey,
2863    ) -> JsResult<Option<Property>> {
2864        if let Some(answer) = self.proxy_get_own_property(object, key)? {
2865            return Ok(answer);
2866        }
2867        if let Some(exotic) = object.exotic()
2868            && let Some(answer) = exotic.get_own_property(self, object, key)?
2869        {
2870            return Ok(answer);
2871        }
2872        // A mapped `arguments` index is a data property as far as script can see: the
2873        // accessor pair that aliases the parameter is plumbing, and exposing it would
2874        // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
2875        // report a `get` where the spec has a `[[Value]]`.
2876        if let Some(index) = key.as_str().and_then(crate::object::array_index)
2877            && let Some(cell) = object.mapped_argument_cell(index as usize)
2878        {
2879            // Non-configurable is *not* the default: an ordinary mapped index is
2880            // configurable, and only becomes non-configurable once something
2881            // redefines it. Preserve whatever the property table currently says.
2882            // The attributes come from whatever the property table holds, because they
2883            // can be changed independently of the mapping; only the *value* and the
2884            // data-property *kind* are the accessor's secret.
2885            let flags = Self::ordinary_own_property(object, key);
2886            if let Some(existing) = &flags
2887                && !existing.is_accessor()
2888            {
2889                // Already demapped: the table entry is the answer, not the cell.
2890                return Ok(flags);
2891            }
2892            return Ok(Some(Property {
2893                value: Some(cell.get()),
2894                writable: true,
2895                enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
2896                configurable: flags.as_ref().is_some_and(|p| p.configurable),
2897                ..Property::default()
2898            }));
2899        }
2900        Ok(Self::ordinary_own_property(object, key))
2901    }
2902
2903    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
2904    /// §7.3.40 `SetterThatIgnoresPrototypeProperties(thisValue, home, propertyKey, value)`.
2905    ///
2906    /// Written for `Error.prototype.stack`'s setter and the exact mechanism
2907    /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
2908    /// abstract operation here rather than a private helper in `error.rs`.
2909    ///
2910    /// The name is the whole point: the setter must behave as if the prototype were not
2911    /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
2912    /// the accessor for every error object in the realm. Everything below follows from that:
2913    ///
2914    /// 1. `thisValue` must be an object — otherwise `TypeError`.
2915    /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
2916    ///    accessor's own home an error rather than a self-shadow.
2917    /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
2918    ///    either has a string or has made a mistake.
2919    /// 4. An existing *own* property decides the path — an own setter is called, an own
2920    ///    non-writable data property is a `TypeError` — and only a missing own property
2921    ///    falls through to defining one.
2922    /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
2923    ///    traps and a non-extensible receiver is a `TypeError`.
2924    ///
2925    /// The installed shape is writable + configurable, not enumerable.
2926    pub fn setter_that_ignores_prototype_properties(
2927        &mut self,
2928        this_value: Value,
2929        home: &Gc<JsObject>,
2930        property_key: &str,
2931        args: &[Value],
2932    ) -> JsResult<Value> {
2933        let Some(receiver) = this_value.as_object().cloned() else {
2934            return Err(self.type_error("setter called on a non-object"));
2935        };
2936        if Gc::ptr_eq(&receiver, home) {
2937            return Err(self.type_error("cannot assign to the accessor's own home object"));
2938        }
2939        // No type check here: §7.3.40 takes an arbitrary `v`, and
2940        // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
2941        // insists on a String is `Error.prototype.stack`'s setter, which does its own check
2942        // before calling this.
2943        let value = args.first().cloned().unwrap_or(Value::Undefined);
2944        let key = PropertyKey::from(property_key);
2945        // Step 4: an own property on the receiver changes what happens, and there are three
2946        // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
2947        // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
2948        // `Set` with `throw = true`, and a test exists for each.
2949        if let Some(existing) = self.object_get_own_property(&receiver, &key)? {
2950            if existing.is_accessor() && existing.setter.is_none() {
2951                // A getter-only own accessor cannot be written through.
2952                return Err(self.type_error("no setter for the own property"));
2953            }
2954            // Everything else — an own data property, or an own accessor *with* a setter —
2955            // takes the `Set` path with `throw = true`. That is what routes a proxy's own
2956            // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
2957            // an own user setter receives the value (`setter-own-accessor`), because
2958            // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
2959            // setter directly is the difference between one code path and two that can
2960            // disagree.
2961            self.set_property(&receiver, property_key, value.clone())?;
2962            return Ok(Value::Undefined);
2963        }
2964        let property = Property {
2965            value: Some(value.clone()),
2966            writable: true,
2967            // Enumerable, despite the accessor it shadows not being. The reference installs
2968            // it that way and six cases check it (`setter-creates-own-property` and friends).
2969            enumerable: true,
2970            configurable: true,
2971            ..Property::default()
2972        };
2973        if !self.object_define_own_property(&receiver, &key, property)? {
2974            return Err(self.type_error("the receiver refused the definition"));
2975        }
2976        Ok(Value::Undefined)
2977    }
2978
2979    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
2980    pub fn object_define_own_property(
2981        &mut self,
2982        object: &Gc<JsObject>,
2983        key: &PropertyKey,
2984        property: Property,
2985    ) -> JsResult<bool> {
2986        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
2987            return Ok(accepted);
2988        }
2989        // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
2990        // non-extensible object. The check lives here rather than in the callers because
2991        // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
2992        // `Array.prototype.filter` uses to store its result, and a species object made
2993        // non-extensible by its own constructor must make that a `TypeError`
2994        // (`target-array-non-extensible`).
2995        if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
2996            return Ok(false);
2997        }
2998        // A host class that intercepts definitions owns the attributes of the properties it
2999        // defines: `_class`-style storage on the native side is the usual reason.
3000        if let Some(exotic) = object.exotic()
3001            && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3002        {
3003            return Ok(accepted);
3004        }
3005        // An array index is stored in the element vector, which can hold a plain value and
3006        // nothing else. An accessor — or a data property with non-default attributes —
3007        // therefore has to live in the property table, and the element slot is blanked so
3008        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3009        // {get})` stored the accessor where no read ever looked, and the array kept
3010        // answering its old value.
3011        // An array's `length` is not stored in the property table, so defining it has to
3012        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3013        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3014        // {value: 1})` reported success and changed nothing.
3015        if key.as_str() == Some("length") && object.is_array() {
3016            // `{writable: false}` on `length` does not change the length, but it does make
3017            // it read-only — after which neither a later `{writable: true}` nor a store
3018            // past the end may succeed.
3019            if property.value.is_none() {
3020                if !object.length_writable() && property.writable {
3021                    return Ok(false);
3022                }
3023                object.set_length_writable(property.writable);
3024                return Ok(true);
3025            }
3026            if !object.length_writable() {
3027                return Ok(false);
3028            }
3029        }
3030        if key.as_str() == Some("length")
3031            && object.is_array()
3032            && let Some(value) = property.value.clone()
3033        {
3034            let requested = value.to_number();
3035            let valid = requested.is_finite()
3036                && requested >= 0.0
3037                && requested.fract() == 0.0
3038                && requested <= u32::MAX as f64;
3039            if !valid {
3040                return Err(self.range_error("invalid array length"));
3041            }
3042            // Truncating deletes the elements above the new length, and a non-configurable
3043            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3044            // makes `a.length = 2` fail rather than quietly drop it.
3045            let current = object.array_length().unwrap_or(0);
3046            let requested = requested as usize;
3047            if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3048                return Ok(false);
3049            }
3050            object.array_set_length(self.heap, requested);
3051            return Ok(true);
3052        }
3053        let plain = property.writable
3054            && property.enumerable
3055            && property.configurable
3056            && !property.is_accessor();
3057        if let Some(index) = key.as_str().and_then(array_index)
3058            && object.is_array()
3059        {
3060            // Growing the array needs a writable `length`: after
3061            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3062            // be added.
3063            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3064                return Ok(false);
3065            }
3066            if plain && property.value.is_some() {
3067                // An ordinary element: the vector is where a read looks first, so it has
3068                // to be the vector that changes — unless the index is too far out to be
3069                // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3070                // one property, because past its own limit it stores the index as an
3071                // ordinary key. Falling through to `define_key` below is the same choice,
3072                // and the alternative was worse: the store used to be *dropped* and the
3073                // length left at 0, which is a silent wrong answer.
3074                let value = property.value.clone().unwrap_or(Value::Undefined);
3075                object.delete_key(key);
3076                if object.array_set(self.heap, index as usize, value) {
3077                    return Ok(true);
3078                }
3079                // Past the dense limit the element lives in the table like any property.
3080                object.note_element_descriptor();
3081                object.define_key(key, property);
3082                // A sparse store past the dense limit still extends `length`, which is what
3083                // `a[a.length] = v` relies on — but only extends: shortening would delete
3084                // the sparse properties above the index, including this one.
3085                if index as usize + 1 > object.array_length().unwrap_or(0) {
3086                    object.array_set_length(self.heap, index as usize + 1);
3087                }
3088                return Ok(true);
3089            }
3090            // A non-plain element — an accessor, or an attribute that is not the default —
3091            // lives in the table while the slot becomes a hole. Recording it keeps every
3092            // later `a[i] = v` off the dense path, where the write would have shadowed the
3093            // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3094            // replace the accessor with a plain data property.
3095            object.note_element_descriptor();
3096            object.define_key(key, property);
3097            // The slot stays, so `length` does not shrink; a hole is not an element, so
3098            // the table entry is now what a read finds.
3099            object.array_set(self.heap, index as usize, Value::Hole);
3100            return Ok(true);
3101        }
3102        object.define_key(key, property);
3103        Ok(true)
3104    }
3105
3106    /// Build a proxy object over `target`, with its traps read from `handler`.
3107    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3108        JsObject::proxy(self.heap, target, handler)
3109    }
3110
3111    /// The `revoke` function for a proxy's slots.
3112    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3113        JsObject::function(
3114            self.heap,
3115            Some(self.realm.function_proto.clone()),
3116            Callable::Revoker(slots),
3117        )
3118    }
3119
3120    /// A new array.
3121    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3122        let array = JsObject::array(
3123            self.heap,
3124            Some(self.realm.array_proto.clone()),
3125            elements.len(),
3126        );
3127        for (index, element) in elements.into_iter().enumerate() {
3128            array.array_set(self.heap, index, element);
3129        }
3130        array
3131    }
3132
3133    /// A new native function object.
3134    ///
3135    /// The observable `name` and `length` are installed as properties here, which is
3136    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3137    /// so `f.name = "x"` behaves like the writable property it is.
3138    /// A native constructor that builds its own instance after validating its arguments.
3139    ///
3140    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3141    /// check runs before `new.target.prototype` is read.
3142    pub fn new_native_ctor(
3143        &self,
3144        name: impl Into<String>,
3145        length: u32,
3146        func: NativeFn,
3147    ) -> Gc<JsObject> {
3148        let function = JsObject::function(
3149            self.heap,
3150            Some(self.realm.function_proto.clone()),
3151            Callable::Native {
3152                func,
3153                own_instance: true,
3154            },
3155        );
3156        function.set_constructible(true);
3157        function.define(
3158            "length",
3159            Property::name_or_length(Value::Int(length as i32)),
3160        );
3161        function.define("name", Property::name_or_length(self.string(name)));
3162        function
3163    }
3164
3165    /// A native constructor that lets `new` build the instance first.
3166    ///
3167    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3168    /// validation that must precede reading `new.target.prototype`, so the object can be
3169    /// created before the implementation runs. Distinct from [`Interp::new_native`],
3170    /// which makes a *method* and therefore not a constructor at all.
3171    pub fn new_native_constructor(
3172        &self,
3173        name: impl Into<String>,
3174        length: u32,
3175        func: NativeFn,
3176    ) -> Gc<JsObject> {
3177        let function = self.new_native(name, length, func);
3178        function.set_constructible(true);
3179        function
3180    }
3181
3182    /// A new host function object: a native closure that carries its own state.
3183    ///
3184    /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3185    /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3186    /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3187    /// this safe: the closure must not capture a `Gc`.
3188    pub fn new_host_function(
3189        &self,
3190        name: impl Into<String>,
3191        length: u32,
3192        func: crate::object::HostFn,
3193    ) -> Gc<JsObject> {
3194        self.new_host_inner(name.into(), length, func, false)
3195    }
3196
3197    /// A host constructor: `new` hands it `this = undefined`, so it validates its
3198    /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3199    pub fn new_host_ctor(
3200        &self,
3201        name: impl Into<String>,
3202        length: u32,
3203        func: crate::object::HostFn,
3204    ) -> Gc<JsObject> {
3205        let function = self.new_host_inner(name.into(), length, func, true);
3206        function.set_constructible(true);
3207        // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3208        // installs its own methods on it, so it starts as a plain object.
3209        let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3210        function.define(
3211            "prototype",
3212            Property {
3213                value: Some(Value::Object(proto)),
3214                writable: true,
3215                enumerable: false,
3216                configurable: false,
3217                ..Property::default()
3218            },
3219        );
3220        function
3221    }
3222
3223    fn new_host_inner(
3224        &self,
3225        name: String,
3226        length: u32,
3227        func: crate::object::HostFn,
3228        own_instance: bool,
3229    ) -> Gc<JsObject> {
3230        let function = JsObject::function(
3231            self.heap,
3232            Some(self.realm.function_proto.clone()),
3233            Callable::Host {
3234                func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3235                own_instance,
3236            },
3237        );
3238        function.define(
3239            "length",
3240            Property::name_or_length(Value::Int(length as i32)),
3241        );
3242        function.define("name", Property::name_or_length(self.string(name)));
3243        function
3244    }
3245
3246    /// A callable object with the `length`/`name` a built-in function has, in that order.
3247    ///
3248    /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3249    /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3250    /// [`JsObject::function`] defines neither, which is why every capability helper built
3251    /// with it reported no own `length` and no own `name` at all.
3252    ///
3253    /// The attributes are the spec's for a built-in: not writable, not enumerable,
3254    /// configurable.
3255    pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3256        let function =
3257            JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3258        function.define(
3259            "length",
3260            Property::name_or_length(Value::Int(length as i32)),
3261        );
3262        function.define("name", Property::name_or_length(self.string(name)));
3263        function
3264    }
3265
3266    /// A new native function object.
3267    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3268        let function = JsObject::function(
3269            self.heap,
3270            Some(self.realm.function_proto.clone()),
3271            Callable::Native {
3272                func,
3273                own_instance: false,
3274            },
3275        );
3276        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3277        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3278        // `length,name` and this listed `name,length`. A bytecode function already gets it
3279        // the right way round; only native ones were built backwards.
3280        function.define(
3281            "length",
3282            Property::name_or_length(Value::Int(length as i32)),
3283        );
3284        function.define("name", Property::name_or_length(self.string(name)));
3285        function
3286    }
3287
3288    /// A new bound function.
3289    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3290        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3291        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3292        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3293        let constructible = target
3294            .as_object()
3295            .is_some_and(|target| target.is_constructor());
3296        let bound = JsObject::function(
3297            self.heap,
3298            Some(self.realm.function_proto.clone()),
3299            Callable::Bound { target, this, args },
3300        );
3301        bound.set_constructible(constructible);
3302        bound
3303    }
3304
3305    /// A new reference cell.
3306    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3307        Gc::new(self.heap, Cell::new(value))
3308    }
3309
3310    // -- running ------------------------------------------------------------
3311
3312    /// Evaluate `code` as a script body and return its completion value.
3313    /// Compile and run `source` for the engine's own use, returning its completion value.
3314    ///
3315    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3316    /// needs to be a real async function, and the engine already runs those as coroutines,
3317    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3318    ///
3319    /// Differences from [`Self::eval_in_global`], both deliberate:
3320    ///
3321    /// * It does **not** drain the microtask queue. Install runs while the realm is still
3322    ///   being built, and the source is an IIFE that only constructs a closure, so there
3323    ///   is nothing to drain — and draining here would run script-queued jobs in the
3324    ///   middle of `install`.
3325    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3326    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3327    ///   and it should not look like the user wrote something wrong.
3328    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3329        let program = match js_parse::parse_script(source) {
3330            Ok(program) => program,
3331            Err(error) => {
3332                let message = format!("builtin source does not parse: {error}");
3333                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3334            }
3335        };
3336        let mut code = match js_compile::compile_script_with_source(&program, source) {
3337            Ok(code) => code,
3338            Err(error) => {
3339                let message = format!("builtin source does not compile: {}", error.message);
3340                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3341            }
3342        };
3343        // The frame has to name something, and `<builtin>` is what a stack trace through
3344        // this code should say.
3345        code.set_filename("<builtin>");
3346        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3347        let closure_vars = compiled.code.closure_vars.clone();
3348        let env = self.global_env(&closure_vars);
3349        let this = Value::Object(self.realm.global.clone());
3350        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3351    }
3352
3353    /// Run an already-parsed script and drain the microtasks it queued.
3354    ///
3355    /// The drain is what lets an `async` function's body advance past its first `await`
3356    /// before the host sees the result: nothing else pumps the job queue.
3357    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3358        let this = Value::Object(self.realm.global.clone());
3359        self.run_script_with_this(code, this)
3360    }
3361
3362    /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3363    ///
3364    /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3365    /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3366    /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3367    /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3368    /// state the next script evaluation tripped over.
3369    pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3370        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3371        let closure_vars = compiled.code.closure_vars.clone();
3372        let env = self.global_env(&closure_vars);
3373        let callee = Value::Undefined;
3374        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3375        // The script is done, so the microtasks it queued run before the host sees the
3376        // result. Without this an `async` function's body would never advance past its
3377        // first `await`, because nothing else drains the queue.
3378        self.drain_jobs()?;
3379        Ok(result)
3380    }
3381
3382    /// Compile and run `source` in global scope, returning its completion value.
3383    ///
3384    /// This is what `eval` and `new Function` use. Running it as a script means it
3385    /// sees the global object and nothing else, which is right for `eval("1+1")` and
3386    /// for a `Function` body; a *direct* eval that reads a local variable would need
3387    /// the compiler to hand its variable environment over, which is not implemented.
3388    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3389        self.eval_in_global_named(source, EVAL_FILE, false)
3390    }
3391
3392    /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3393    ///
3394    /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3395    /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3396    /// through the code, so they cannot share one constant.
3397    pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3398        self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3399    }
3400
3401    /// Evaluate `source` as a global script, reported under `file`.
3402    ///
3403    /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3404    /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3405    /// from inside a C callback, where the interpreter is the running one rather than a
3406    /// context's own.
3407    pub fn eval_in_global_named(
3408        &mut self,
3409        source: &str,
3410        file: &str,
3411        barrier: bool,
3412    ) -> JsResult<Value> {
3413        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3414        // eval-created global binding — configurable, unlike a script's own `var`.
3415        self.eval_depth += 1;
3416        if barrier {
3417            let depth = self.frames.len();
3418            self.trace_barriers.push(depth);
3419        }
3420        let result = self.eval_in_global_inner(source, file);
3421        if barrier {
3422            self.trace_barriers.pop();
3423        }
3424        self.eval_depth -= 1;
3425        result
3426    }
3427
3428    fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3429        let compiled = self.compile_global_script(source, file, false)?;
3430        let strict = compiled.strict;
3431        self.run_eval_script(compiled, strict)
3432    }
3433
3434    /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3435    ///
3436    /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3437    /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3438    /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3439    /// direct eval's is.
3440    pub fn eval_script_with_this(
3441        &mut self,
3442        source: &str,
3443        file: &str,
3444        this: Value,
3445    ) -> JsResult<Value> {
3446        let program = match js_parse::parse_script(source) {
3447            Ok(program) => program,
3448            Err(error) => {
3449                return Err(Signal::Throw(self.syntax_error_at(
3450                    file,
3451                    error.span.start.line,
3452                    error.span.start.column,
3453                    &error.message,
3454                )));
3455            }
3456        };
3457        let mut compiled = match js_compile::compile_script(&program) {
3458            Ok(compiled) => compiled,
3459            Err(error) => {
3460                return Err(Signal::Throw(self.syntax_error_at(
3461                    file,
3462                    error.span.start.line,
3463                    error.span.start.column,
3464                    &error.message,
3465                )));
3466            }
3467        };
3468        compiled.set_filename(file);
3469        self.run_script_with_this(compiled, this)
3470    }
3471
3472    /// Parse and compile `source` as a global script, without running it.
3473    ///
3474    /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3475    /// before a promise exists to reject — while still evaluating in the same eval context
3476    /// (direct-eval strictness, `new.target`, `super`).
3477    fn compile_global_script(
3478        &mut self,
3479        source: &str,
3480        file: &str,
3481        async_body: bool,
3482    ) -> JsResult<CompiledFunction> {
3483        // A *direct* eval inherits the strictness of the code that called it, which is
3484        // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3485        // implicit global. The caller's frame is the innermost one here, because a
3486        // native function does not push a frame of its own.
3487        let strict = self.current_strict();
3488        // `eval` runs in the caller's function context, so `new.target` is legal here
3489        // even though the source is a bare script — and so is `super.x` when the caller
3490        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3491        // caller's, which is what `special_object 4` already does.
3492        let context = js_parse::EvalContext {
3493            in_method: self.enclosing_home_object().is_some(),
3494            // `super()` belongs to a derived constructor, and an eval'd body is not a
3495            // constructor at all: the caller frame's `this` is already built.
3496            in_derived_constructor: false,
3497        };
3498        // A *global* eval is not a function body: `new.target` and `super` are out of
3499        // reach there. Its `{async: true}` form differs in the other direction — the body
3500        // may `await` — so the two flags are independent and the reference sets both from
3501        // the eval type rather than from the caller.
3502        let parsed = if async_body {
3503            js_parse::parse_suspensible_global_eval(source, strict)
3504        } else {
3505            js_parse::parse_eval_script_in(source, strict, context)
3506        };
3507        let program = match parsed {
3508            Ok(program) => program,
3509            Err(error) => {
3510                // The message is bare: the position lives in `fileName`,
3511                // `lineNumber`, `columnNumber` and the stack frame above, which is where
3512                // the reference puts it. An `invalid source: L:C: ` prefix made
3513                // `e.message` differ from the reference while the stack already agreed.
3514                return Err(Signal::Throw(self.syntax_error_at(
3515                    file,
3516                    error.span.start.line,
3517                    error.span.start.column,
3518                    &error.message,
3519                )));
3520            }
3521        };
3522        let mut compiled = match if async_body {
3523            js_compile::compile_script_suspensible(&program)
3524        } else {
3525            js_compile::compile_script(&program)
3526        } {
3527            Ok(compiled) => compiled,
3528            // A construct the compiler does not handle yet is reported the same way a
3529            // parse error is: it happens before anything runs, so the trace is the
3530            // position in the source followed by the caller.
3531            Err(error) => {
3532                return Err(Signal::Throw(self.syntax_error_at(
3533                    file,
3534                    error.span.start.line,
3535                    error.span.start.column,
3536                    &error.message,
3537                )));
3538            }
3539        };
3540        compiled.set_filename(file);
3541        Ok(compiled)
3542    }
3543
3544    /// Run an `eval`'d script in the caller's scope.
3545    ///
3546    /// Three things have to come from the calling frame, because the eval'd code is a
3547    /// script and would otherwise see only the global object:
3548    ///
3549    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3550    /// * `arguments`, exposed as a binding of the eval's own scope, so
3551    ///   `f("arguments.length", 1)` sees the caller's arguments;
3552    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3553    ///   `eval("var v = 1")` into the global object.
3554    ///
3555    /// Locals of the calling function are *not* reachable: that needs the compiler to
3556    /// hand its variable environment over, which this milestone does not do.
3557    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3558        // `this` and `arguments` come from the innermost frame only — those are not
3559        // lexical — while the name bindings come from the whole chain of frames, part
3560        // of it being ordinary scope resolution.
3561        // An arrow has no `this` of its own, so an `eval` inside one inherits the
3562        // enclosing function's receiver — the lexical `this` the arrow was compiled to
3563        // read from its closure.
3564        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3565        // variable environment is the innermost frame of all: an arrow's own body is where
3566        // `var`s declared by an `eval` inside it belong.
3567        let caller_index = self
3568            .frames
3569            .iter()
3570            .rposition(|frame| !frame.code.code.is_arrow)
3571            .or_else(|| self.frames.len().checked_sub(1));
3572        let env_index = self.frames.len().checked_sub(1);
3573        let caller = caller_index.and_then(|index| self.frames.get(index));
3574        let (this, passed) = match caller {
3575            Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3576            // No frame at all: the eval is running at the top level, so there is
3577            // nothing to inherit and the global receiver is right.
3578            None => (Value::Object(self.realm.global.clone()), Vec::new()),
3579        };
3580        // Innermost frame first, so the first binding found for a name is the one that
3581        // shadows the rest. A script frame (`<eval>`) contributes nothing.
3582        let mut bindings: Vec<EvalBinding> = Vec::new();
3583        // The calling function's own bindings, resolved by the compiler at the call
3584        // site. That table is the only reliable answer when a name is declared twice in
3585        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3586        // body means, and guessing by declaration order picks the wrong one as soon as
3587        // two loops in a row use the same name.
3588        // Only a *direct* eval sees the caller's scope. The compiler records a site for
3589        // every direct call — a bare `eval(...)` callee — so finding one at the current
3590        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3591        // callee to a value first and leave no site behind.
3592        let mut direct = false;
3593        let mut resolved_here = false;
3594        if let Some(frame) = self.frames.last() {
3595            let (line, column) = frame
3596                .code
3597                .code
3598                .position_at(frame.at as u32)
3599                .unwrap_or_default();
3600            // The nearest site at or before the current position, not an exact match:
3601            // the recorded position of the `call` instruction is the callee's, which
3602            // sits a few columns inside the call expression the compiler recorded. A
3603            // site is unique per call, so "the closest one behind us" identifies it.
3604            if let Some(site) = frame
3605                .code
3606                .code
3607                .eval_sites
3608                .iter()
3609                .filter(|site| (site.line, site.column) <= (line, column))
3610                .max_by_key(|site| (site.line, site.column))
3611            {
3612                direct = true;
3613                resolved_here = true;
3614                for binding in &site.bindings {
3615                    // An enclosing function's frame sits `owner` levels below the one
3616                    // running the call.
3617                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3618                    else {
3619                        continue;
3620                    };
3621                    bindings.push(EvalBinding {
3622                        name: binding.name.clone(),
3623                        frame,
3624                        slot: if binding.is_arg {
3625                            EvalSlot::Arg
3626                        } else {
3627                            EvalSlot::Local
3628                        },
3629                        index: binding.index as usize,
3630                    });
3631                }
3632            }
3633        }
3634        for frame_index in (0..self.frames.len()).rev() {
3635            // Skip the innermost frame's flat scan when the compiler already answered
3636            // for it; an enclosing frame still needs one, because the eval resolves
3637            // those names dynamically.
3638            if resolved_here && frame_index == self.frames.len() - 1 {
3639                continue;
3640            }
3641            let frame = &self.frames[frame_index];
3642            for (index, arg) in frame.code.code.args.iter().enumerate() {
3643                bindings.push(EvalBinding {
3644                    name: arg.name.clone(),
3645                    frame: frame_index,
3646                    slot: EvalSlot::Arg,
3647                    index,
3648                });
3649            }
3650            for (index, local) in frame.code.code.vars.iter().enumerate() {
3651                bindings.push(EvalBinding {
3652                    name: local.name.clone(),
3653                    frame: frame_index,
3654                    slot: EvalSlot::Local,
3655                    index,
3656                });
3657            }
3658        }
3659        let mut seen = BTreeSet::new();
3660        bindings.retain(|binding| seen.insert(binding.name.clone()));
3661
3662        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
3663        // elements is all the spec's ordinary uses need.
3664        //
3665        // Known divergence: this is bound for a *global* eval too, where there is no
3666        // caller and the reference throws `'arguments' is not defined`. Deciding properly
3667        // needs "does the calling frame have an `arguments` of its own", which is not
3668        // recorded anywhere the runtime can see — the caller of a direct eval has one, a
3669        // script or eval body does not, and `eval(b)` passes the callee as a value so even
3670        // the call-site detection does not answer it. Modelled as a binding in the caller's
3671        // variable environment, this would fall out; that is a larger change than the one
3672        // this comment is attached to.
3673        let arguments = Value::Object(self.new_array(passed));
3674
3675        // Only a *strict* eval gets a variable environment of its own. A sloppy one
3676        // declares its `var`s in the caller's — which for a top-level eval is the global
3677        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
3678        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
3679        // vanish into a scope nobody reads back from.
3680        let previous_scope = if code_strict {
3681            self.eval_scope.replace(BTreeMap::new())
3682        } else {
3683            None
3684        };
3685        let previous_arguments = self.eval_arguments.replace(arguments);
3686        let previous_with = self.eval_with.replace(self.with_objects());
3687        let inherited_new_target = self
3688            .frames
3689            .iter()
3690            .rev()
3691            .find(|frame| !frame.code.code.is_arrow)
3692            .map(|frame| frame.new_target.clone());
3693        let previous_new_target = self
3694            .eval_new_target
3695            .replace(inherited_new_target.unwrap_or(Value::Undefined));
3696        let eval_cells = self.eval_cells_for(&bindings);
3697        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
3698        // A sloppy direct eval declares its `var`s in the caller's variable environment;
3699        // `declare_eval_local` needs to know which frame that is.
3700        // An indirect eval gets the global environment, so nothing of the caller's is
3701        // recorded as the place its `var`s belong.
3702        let previous_caller = self
3703            .eval_caller
3704            .replace(if direct { env_index } else { None });
3705        // The cell-based view of the same bindings, which is what a closure created
3706        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3707        // whose compiler did not put a binding in a cell simply does not appear here —
3708        // reads and writes still work through `eval_bindings`, they just cannot outlive
3709        // the eval.
3710        let previous_eval_scope = self
3711            .active_eval_scope
3712            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3713        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3714        let closure_vars = compiled.code.closure_vars.clone();
3715        let env = self.global_env(&closure_vars);
3716        let callee = Value::Undefined;
3717        // An async body does not run here: it becomes a coroutine and answers a promise,
3718        // which is what makes `await` legal in it. `this` still has to be the caller's
3719        // (for a global eval, the global object), because `this` is not part of `await`.
3720        let result = if compiled.code.kind.is_async() {
3721            self.run_async_body(compiled, env, this)
3722        } else {
3723            self.execute(compiled, env, this, Vec::new(), callee)
3724        };
3725        self.eval_scope = previous_scope;
3726        self.eval_arguments = previous_arguments;
3727        self.eval_with = previous_with;
3728        self.eval_new_target = previous_new_target;
3729        self.eval_bindings = previous_bindings;
3730        self.eval_caller = previous_caller;
3731        self.active_eval_scope = previous_eval_scope;
3732        result
3733    }
3734
3735    /// The cell-backed subset of `bindings`, in the same priority order.
3736    ///
3737    /// Both lookup routes have to agree — the eval's own reads go through
3738    /// [`Interp::eval_binding_value`] and the closures it builds go through
3739    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
3740    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
3741    /// is not in a cell simply does not appear: reads and writes still work, they just
3742    /// cannot be handed to a closure that outlives the eval.
3743    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
3744        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
3745        for binding in bindings {
3746            let Some(frame) = self.frames.get(binding.frame) else {
3747                continue;
3748            };
3749            let cell = match binding.slot {
3750                EvalSlot::Arg => frame
3751                    .code
3752                    .arg_cell
3753                    .get(binding.index)
3754                    .copied()
3755                    .unwrap_or(-1),
3756                EvalSlot::Local => frame
3757                    .code
3758                    .loc_cell
3759                    .get(binding.index)
3760                    .copied()
3761                    .unwrap_or(-1),
3762            };
3763            if cell < 0 {
3764                continue;
3765            }
3766            if let Some(cell) = frame.cells.get(cell as usize) {
3767                names.push((binding.name.clone(), cell.clone()));
3768            }
3769        }
3770        names
3771    }
3772
3773    /// A `SyntaxError` that reports where in the source it happened.
3774    ///
3775    /// Compile-time failures never run, so they have no frame of their own; the
3776    /// reference still puts the position first in the trace, with no function name and
3777    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
3778    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
3779    /// reference borrows), which is how a script reads the position without parsing
3780    /// the trace.
3781    /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
3782    ///
3783    /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
3784    /// `columnNumber`, which is how the reference prints one. A positionless error
3785    /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
3786    /// the reference raises it from `js_resolve_module`, where there is no position.
3787    pub(crate) fn syntax_error_plain(
3788        &mut self,
3789        error: &js_parse::SyntaxError,
3790        file: &str,
3791    ) -> Value {
3792        if error.positionless {
3793            return self.make_error("SyntaxError", &error.message);
3794        }
3795        self.syntax_error_at(
3796            file,
3797            error.span.start.line,
3798            error.span.start.column,
3799            &error.message,
3800        )
3801    }
3802
3803    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
3804        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
3805        let value = self.make_error("SyntaxError", message);
3806        if let Value::Object(object) = &value {
3807            let text = self.string(blamed);
3808            // `stack` is an own data property, and the reference keeps it
3809            // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
3810            object.define("stack", Property::with_attributes(text, true, false));
3811            let name = self.string(file);
3812            object.define("fileName", Property::with_attributes(name, true, true));
3813            object.define(
3814                "lineNumber",
3815                Property::with_attributes(Value::Int(line as i32), true, true),
3816            );
3817            object.define(
3818                "columnNumber",
3819                Property::with_attributes(Value::Int(column as i32), true, true),
3820            );
3821        }
3822        value
3823    }
3824
3825    /// Run a compiled script whose completion value is a function, returning it.
3826    ///
3827    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
3828    /// get the closure out, which keeps the constant-pool plumbing in one place.
3829    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
3830        self.run_script(code)
3831    }
3832
3833    /// The environment of a script or of any function compiled at global scope:
3834    /// every entry is a global binding, so each one resolves to the realm's cell.
3835    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
3836        let mut cells = Vec::with_capacity(closure_vars.len());
3837        for closure_var in closure_vars {
3838            let cell = match closure_var.closure_type {
3839                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
3840                    if closure_var.is_lexical =>
3841                {
3842                    // A lexical declaration: the cell is created here holding the
3843                    // dead-zone marker, which is what makes the binding exist and
3844                    // unreadable before its initialiser runs.
3845                    self.declare_global(&closure_var.name, closure_var.is_const);
3846                    self.realm.globals[&closure_var.name].clone()
3847                }
3848                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
3849                    // A `var` or function declaration becomes a property of the global
3850                    // object, and it exists from here on — which is why
3851                    // `print(v); var v = 1` prints `undefined` instead of raising.
3852                    // Declaring it at instantiation time (rather than at the
3853                    // initialiser) is also what makes it non-configurable: the store
3854                    // then lands on an existing property instead of creating one.
3855                    self.declare_var_global(&closure_var.name);
3856                    // The cell is a placeholder that nothing indexes; it cannot be
3857                    // omitted because the slot has to hold something.
3858                    self.new_cell(Value::Undefined)
3859                }
3860                _ => {
3861                    // An undeclared global is read by name; the cell is a
3862                    // placeholder that nothing indexes.
3863                    self.new_cell(Value::Undefined)
3864                }
3865            };
3866            cells.push(cell);
3867        }
3868        Gc::new(
3869            self.heap,
3870            ClosureEnv {
3871                cells,
3872                eval_scope: None,
3873                local_vars: None,
3874                local_phase: 1,
3875            },
3876        )
3877    }
3878
3879    /// Push a frame and run until it returns.
3880    pub(crate) fn execute(
3881        &mut self,
3882        code: Gc<CompiledCode>,
3883        env: Gc<ClosureEnv>,
3884        this: Value,
3885        args: Vec<Value>,
3886        callee: Value,
3887    ) -> JsResult<Value> {
3888        let depth = self.frames.len();
3889        if depth == 0 {
3890            // A throw that reached the host ends the *active* mode: the next one is catchable
3891            // again. The standing request (`uncatchable_next`) is deliberately untouched — a
3892            // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
3893            // for the throw that evaluation will raise.
3894            self.uncatchable = false;
3895        }
3896        self.push_frame(code, env, this, args, callee)?;
3897        loop {
3898            // The fast loop first: it runs whole runs of records with `pc` in a register.
3899            //
3900            // `step`'s `pc` lives in the frame, so every instruction writes it back and
3901            // reads it again — a store, a load and two bounds checks that a loop body does
3902            // not need, because nothing outside the loop can run in between. This is the
3903            // classic split: advance a register, and only spill it when leaving.
3904            //
3905            // `Some(value)` means the function ended by running off the end of its
3906            // instruction array, which is a normal return.
3907            let step = match self.run_fast() {
3908                Ok(Some(value)) => Ok(Step::Return(value)),
3909                Ok(None) => self.step(),
3910                Err(signal) => Err(signal),
3911            };
3912            match step {
3913                Ok(Step::Continue) => {}
3914                Ok(Step::Return(value)) => {
3915                    self.pop_frame();
3916                    // A frame that ended in a `tail_call` hands its value straight to
3917                    // its caller: nothing after the call can run, so every frame above
3918                    // the callee unwinds with the same value. See [`Frame::tail`] —
3919                    // the reference does not reuse frames either, so recursion depth
3920                    // and the stack-overflow limit behave the same way.
3921                    while self.frames.len() > depth && self.frame().tail {
3922                        self.pop_frame();
3923                    }
3924                    if self.frames.len() == depth {
3925                        return Ok(value);
3926                    }
3927                    // The caller resumes with the value on its stack.
3928                    self.frames
3929                        .last_mut()
3930                        .expect("a caller is live")
3931                        .stack
3932                        .push(value);
3933                }
3934                Err(Signal::Throw(value)) => {
3935                    // The host's standing request becomes the active mode for this unwind,
3936                    // and is consumed here so it does not leak into the next throw.
3937                    if self.uncatchable_next {
3938                        self.uncatchable_next = false;
3939                        self.uncatchable = true;
3940                    }
3941                    // An uncatchable throw walks past every `catch` on the way out. The
3942                    // frames are still popped, because the values they hold have to be
3943                    // dropped — only the search for a handler is skipped.
3944                    if self.uncatchable {
3945                        while self.frames.len() > depth {
3946                            self.frames.pop();
3947                        }
3948                        return Err(Signal::Throw(value));
3949                    }
3950                    // A handler lives on the stack of the frame that is throwing —
3951                    // `catch` pushed it there — so this frame gets the first chance
3952                    // to catch before it is popped.
3953                    let value = value;
3954                    loop {
3955                        if self.frames.len() <= depth {
3956                            return Err(Signal::Throw(value));
3957                        }
3958                        if self.catch_here(value.clone()).is_some() {
3959                            break;
3960                        }
3961                        self.frames.pop();
3962                    }
3963                }
3964                // A `yield` in a frame that `execute` is running directly means a
3965                // generator body was entered as an ordinary call, which only happens if
3966                // the generator check in `call_or_push` was bypassed.
3967                Ok(Step::Suspend(_)) => {
3968                    return Err(Signal::Throw(self.make_error(
3969                        "InternalError",
3970                        "a generator body ran as an ordinary call",
3971                    )));
3972                }
3973                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
3974            }
3975        }
3976    }
3977
3978    /// Install a handler for `value` if this frame has one, resuming at it.
3979    ///
3980    /// The scan is the reference's: walk the frame's stack downwards looking for the
3981    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
3982    /// `0` is an enumerator marker rather than a handler — it exists so that a
3983    /// `break` out of a `for-of` can find and close the iterator — so it is skipped
3984    /// here and the unwinding continues.
3985    fn catch_here(&mut self, value: Value) -> Option<()> {
3986        let frame = self.frames.last_mut()?;
3987        while let Some(top) = frame.stack.pop() {
3988            if let Value::CatchOffset(offset) = top {
3989                if offset == 0 {
3990                    continue;
3991                }
3992                frame.stack.push(value);
3993                frame.pc = offset as usize;
3994                return Some(());
3995            }
3996        }
3997        None
3998    }
3999
4000    fn push_frame(
4001        &mut self,
4002        code: Gc<CompiledCode>,
4003        env: Gc<ClosureEnv>,
4004        this: Value,
4005        mut args: Vec<Value>,
4006        callee: Value,
4007    ) -> JsResult<()> {
4008        // Two bounds, and the byte budget is the one that decides in practice. The
4009        // reference's message is `stack overflow` on an `InternalError`, not V8's
4010        // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4011        // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4012        let frame_cost = Self::frame_cost(&code);
4013        let stack_base = self.stack_used();
4014        if self.frames.len() >= self.max_frames
4015            || stack_base.saturating_add(frame_cost) > self.stack_limit
4016        {
4017            return Err(Signal::Throw(
4018                self.make_error("InternalError", "stack overflow"),
4019            ));
4020        }
4021        let arg_count = code.code.args.len();
4022        // How many were actually passed, which `arguments.length` reports and
4023        // `assert(x)` depends on: a call with one argument must not look like a call
4024        // with one argument and an explicit `undefined`.
4025        let passed = args.len();
4026        // Missing arguments are `undefined` in their slots; extra ones are dropped
4027        // from the slots but still reachable through `arguments`.
4028        //
4029        // A call that passes no more than the declared parameters needs **no** copy:
4030        // after the resize below, `args[..passed]` *is* the passed values. Only the
4031        // extra ones — which `truncate` is about to drop — have to be kept, and they are
4032        // the rare case. This used to copy every call: one `Value` clone per argument
4033        // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4034        let passed_overflow = (passed > arg_count).then(|| {
4035            let mut values = self.take_values(passed, Value::Undefined);
4036            values[..passed].clone_from_slice(&args[..passed]);
4037            values
4038        });
4039        // Only when the counts differ, which for the overwhelmingly common call — as many
4040        // arguments as parameters — is never. `resize` followed by `truncate` on equal
4041        // lengths is two length compares and nothing else, but this is the hottest few
4042        // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4043        if passed != arg_count {
4044            args.resize(arg_count, Value::Undefined);
4045            args.truncate(arg_count);
4046        }
4047        let cell_count = code.code.var_ref_count as usize;
4048        let mut cells = Vec::with_capacity(cell_count);
4049        for _ in 0..cell_count {
4050            cells.push(self.new_cell(Value::Undefined));
4051        }
4052        let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4053        // A captured argument lives in its cell, not in the argument slot, so the
4054        // incoming value has to be moved there before the body runs.
4055        for (slot, cell) in code.arg_cell.iter().enumerate() {
4056            if *cell >= 0
4057                && let Some(value) = args.get(slot).cloned()
4058            {
4059                cells[*cell as usize].set(value);
4060            }
4061        }
4062        // Sloppy mode substitutes the global object for a missing receiver and boxes a
4063        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4064        // reports `object`. Strict mode passes the value through untouched.
4065        let this = if code.code.strict {
4066            this
4067        } else if this.is_nullish() {
4068            Value::Object(self.realm.global.clone())
4069        } else if matches!(this, Value::Object(_)) {
4070            this
4071        } else {
4072            match crate::builtins::this_object(self, &this) {
4073                Ok(boxed) => Value::Object(boxed),
4074                Err(_) => this,
4075            }
4076        };
4077        let stack_depth = code.code.stack_size as usize + 1;
4078        // Taken before the `push` borrows `self.frames`, because the operand stack comes
4079        // out of the same recycle pool the locals did.
4080        let stack = self.take_values(stack_depth, Value::Undefined);
4081        self.frames.push(Frame {
4082            code,
4083            env,
4084            this,
4085            args,
4086            passed_count: passed,
4087            passed_overflow: passed_overflow.map(Box::new),
4088            locals,
4089            cells,
4090            local_vars: None,
4091            // Exactly the depth the compiler computed, so the operand stack never
4092            // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4093            // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4094            // the buffer between calls, so "exactly" costs nothing after the first one.
4095            stack,
4096            pc: 0,
4097            at: 0,
4098            callee,
4099            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4100            cost: frame_cost,
4101            stack_base,
4102            tail: false,
4103        });
4104        Ok(())
4105    }
4106
4107    /// A value buffer of `len` slots, from the recycle pool when there is one.
4108    ///
4109    /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4110    fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4111        // A frame with no locals asks for nothing, and that is most frames: taking a
4112        // buffer out of the pool, clearing it and resizing it to zero is four operations
4113        // and a pool pop for an empty `Vec`, which is free to construct.
4114        if len == 0 {
4115            return Vec::new();
4116        }
4117        let mut buffer = self.free_values.pop().unwrap_or_default();
4118        buffer.clear();
4119        buffer.resize(len, fill);
4120        buffer
4121    }
4122
4123    /// Return a finished frame's value buffers for the next call to reuse.
4124    fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4125        for mut buffer in [
4126            std::mem::take(&mut frame.locals),
4127            frame
4128                .passed_overflow
4129                .take()
4130                .map(|buffer| *buffer)
4131                .unwrap_or_default(),
4132            std::mem::take(&mut frame.stack),
4133        ] {
4134            // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4135            // GC root: it kept every value the frame held reachable, which is invisible
4136            // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4137            // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4138            // exactly that within one run — the target `{}` of a finished IIFE was still
4139            // in its operand stack, in the pool.
4140            buffer.clear();
4141            // A buffer with no capacity is what `Vec::new` is; putting it back would just
4142            // fill the pool with nothing to offer.
4143            if free_values.len() < RECYCLE_SLOTS
4144                && buffer.capacity() > 0
4145                && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4146            {
4147                free_values.push(buffer);
4148            }
4149        }
4150    }
4151
4152    /// Pop a finished frame and keep its buffers.
4153    ///
4154    /// Every place that drops a frame goes through here: a recycled buffer is also where
4155    /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4156    /// nothing but the reuse.
4157    fn pop_frame(&mut self) -> Option<()> {
4158        // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4159        // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4160        let last = self.frames.len().checked_sub(1)?;
4161        Self::recycle(&mut self.free_values, &mut self.frames[last]);
4162        self.frames.truncate(last);
4163        Some(())
4164    }
4165
4166    /// Poll the host's interrupt handler, if one is installed.
4167    ///
4168    /// The counter is what keeps this off the hot path when nobody asked: the early return is
4169    /// one `Option` test, and with no handler installed the whole function is that test —
4170    /// `check_memory` next door already costs more, so this cannot be what shows up in a
4171    /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4172    #[inline]
4173    fn check_interrupt(&mut self) -> JsResult<()> {
4174        if self.interrupt.is_none() {
4175            return Ok(());
4176        }
4177        if self.interrupt_counter > 0 {
4178            self.interrupt_counter -= 1;
4179            return Ok(());
4180        }
4181        self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4182        // The closure is taken out for the duration so that a handler which re-enters the
4183        // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4184        let mut handler = self.interrupt.take().expect("checked above");
4185        let abort = handler();
4186        self.interrupt = Some(handler);
4187        if abort {
4188            // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4189            // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4190            // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4191            // documentation says.
4192            self.uncatchable = true;
4193            return Err(Signal::Throw(
4194                self.make_error("InternalError", "interrupted"),
4195            ));
4196        }
4197        Ok(())
4198    }
4199
4200    /// A memory checkpoint: does the heap still fit under its limit?
4201    ///
4202    /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4203    /// a `Cell` read and a predictable branch, and the point of asking that often is that
4204    /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4205    /// only at calls would let it run until the machine died, which is the exact failure
4206    /// `--memory-limit` exists to prevent.
4207    ///
4208    /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4209    /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4210    /// script that catches it, drops the reference and carries on is legitimate: measured
4211    /// on `qjs --memory-limit 1M`, the engine recovers.
4212    fn check_memory(&mut self) -> JsResult<()> {
4213        // One `Cell` read and a predictable branch when no limit is set, and an integer
4214        // compare when one is. Containers report their own growth as it happens
4215        // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4216        // walking it here was the first version and it was O(live) per 256 instructions,
4217        // which turned a 100k-element push loop into a five-minute one.
4218        let Some(limit) = self.heap.memory_limit() else {
4219            return Ok(());
4220        };
4221        let used = self.heap.used_bytes();
4222        if used <= limit {
4223            // Back under the limit — a collection or a dropped reference did it. The next
4224            // time it goes over is a new failure, not a repeat of this one.
4225            self.oom_reported_at = 0;
4226            return Ok(());
4227        }
4228        // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4229        // block runs normally after `out of memory` — it allocates nothing, so nothing
4230        // fails. A check that re-fired on every instruction made the handler itself throw,
4231        // which is a dead end: the error became unobservable from script.
4232        //
4233        // Comparing against the total at the last report gives the same behaviour: the
4234        // handler runs while the total is unchanged, and the very next allocation over the
4235        // limit fails.
4236        if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4237        {
4238            return Ok(());
4239        }
4240        self.oom_reported_at = used;
4241        Err(Signal::Throw(
4242            self.make_error("InternalError", "out of memory"),
4243        ))
4244    }
4245
4246    /// Fail before allocating `payload` bytes, if they would not fit.
4247    ///
4248    /// For the allocations whose size comes from script data — `new Array(n)`,
4249    /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4250    /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4251    /// answering NULL for the one big request.
4252    pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4253        if self.heap.fits(payload) {
4254            return Ok(());
4255        }
4256        Err(Signal::Throw(
4257            self.make_error("InternalError", "out of memory"),
4258        ))
4259    }
4260
4261    /// Bytes of frame state the live call chain accounts for.
4262    pub fn stack_used(&self) -> usize {
4263        match self.frames.last() {
4264            Some(frame) => frame.stack_base + frame.cost,
4265            None => 0,
4266        }
4267    }
4268
4269    /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4270    ///
4271    /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4272    /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4273    /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4274    /// instead. That is the whole difference between the two models: it rations C stack, we
4275    /// ration frame state, and both quantities are dominated by the value slots — which is
4276    /// why the two depths come out comparable rather than merely proportional.
4277    fn frame_cost(code: &CompiledCode) -> usize {
4278        let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4279        std::mem::size_of::<Frame>()
4280            + std::mem::size_of::<Value>() * slots
4281            + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4282    }
4283
4284    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4285    ///
4286    /// Only names the eval created are here: a name the frame already declared statically
4287    /// is written through to its own slot instead, so this cannot shadow a real local.
4288    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4289        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4290        let (local_vars, phase) = self.visible_local_vars()?;
4291        if !local_vars.contains(name) {
4292            return None;
4293        }
4294        local_vars.get(name, phase)
4295    }
4296
4297    /// The variables a direct `eval` declared, as the code currently running sees them.
4298    ///
4299    /// Inside an eval that is the *caller's* set — the eval's own variable environment
4300    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4301    /// else it is the current frame's, falling back to the frame the closure was created
4302    /// in.
4303    /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4304    ///
4305    /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4306    /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4307    /// refcount operations (the clone out of the frame, the drop at the end of the match)
4308    /// just to be asked `is_none`.
4309    fn has_visible_local_vars(&self) -> bool {
4310        let index = match self.eval_caller.flatten() {
4311            Some(caller) => caller,
4312            None => match self.frames.len().checked_sub(1) {
4313                Some(top) => top,
4314                None => return false,
4315            },
4316        };
4317        match self.frames.get(index) {
4318            Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4319            None => false,
4320        }
4321    }
4322
4323    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4324        // While an `eval` runs, its own frame is on top but its variable environment is
4325        // the *caller's* — so the caller is what the lookup has to start from.
4326        let (index, phase) = match self.eval_caller.flatten() {
4327            Some(caller) => (
4328                caller,
4329                if self.in_parameter_list_at(caller) {
4330                    0
4331                } else {
4332                    1
4333                },
4334            ),
4335            None => (
4336                self.frames.len().checked_sub(1)?,
4337                if self.in_parameter_list() { 0 } else { 1 },
4338            ),
4339        };
4340        let frame = self.frames.get(index)?;
4341        // The frame's own variables, or — for an arrow, which has no variable environment
4342        // of its own — the one it was created in, which `ClosureEnv` carries.
4343        if let Some(local_vars) = frame.local_vars.clone() {
4344            return Some((local_vars, phase));
4345        }
4346        frame
4347            .env
4348            .local_vars
4349            .clone()
4350            .map(|local_vars| (local_vars, frame.env.local_phase))
4351    }
4352
4353    /// Whether the innermost frame is still evaluating its parameter list.
4354    ///
4355    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4356    /// and a closure created there may only see that much of [`LocalVars`].
4357    fn in_parameter_list(&self) -> bool {
4358        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4359    }
4360
4361    /// [`Interp::in_parameter_list`] for a specific frame.
4362    fn in_parameter_list_at(&self, frame: usize) -> bool {
4363        let Some(frame) = self.frames.get(frame) else {
4364            return false;
4365        };
4366        let code = &frame.code.code;
4367        if !code.has_parameter_expressions {
4368            return false;
4369        }
4370        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4371        // function as its body and let a direct `eval` act accordingly.
4372        if code.body_start == (0, 0) {
4373            return false;
4374        }
4375        match code.position_at(frame.at as u32) {
4376            Some(position) => position < code.body_start,
4377            None => false,
4378        }
4379    }
4380
4381    fn frame(&self) -> &Frame {
4382        self.frames.last().expect("a frame is live")
4383    }
4384
4385    fn frame_mut(&mut self) -> &mut Frame {
4386        self.frames.last_mut().expect("a frame is live")
4387    }
4388
4389    // -- slot access --------------------------------------------------------
4390
4391    /// Move a local's value out, leaving `undefined` in the slot.
4392    ///
4393    /// `None` for a captured slot: its value lives in a cell shared with every closure
4394    /// that closed over it, so it can never be exclusively ours and must not be taken.
4395    ///
4396    /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4397    /// for every read and fatal for this one — a clone is exactly the second handle that
4398    /// rules out growing the string in place.
4399    fn take_loc(&mut self, slot: usize) -> Option<Value> {
4400        let frame = self.frames.last_mut()?;
4401        if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4402            return None;
4403        }
4404        frame
4405            .locals
4406            .get_mut(slot)
4407            .map(|value| std::mem::replace(value, Value::Undefined))
4408    }
4409
4410    /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4411    /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4412    ///
4413    /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4414    /// it** — the value is put back before the general path runs — so a `valueOf` that
4415    /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4416    /// error as it would have without the fusion. This is why the in-place attempt is a
4417    /// `take` and not a `get`: an optimisation that changes what an exception observes is
4418    /// a wrong answer with a good excuse.
4419    fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4420        // The take is `matches!`-guarded on the *right* operand only, and the taken value
4421        // is put back on every path that does not append. An earlier version wrote the two
4422        // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4423        // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4424        // through with its value already taken and dropped: the general path below then
4425        // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4426        // A wrong answer, from an optimisation, with every test green.
4427        if matches!(right, Value::String(_))
4428            && let Some(taken) = self.take_loc(slot)
4429        {
4430            if let Value::String(mut left) = taken {
4431                let appended = match left.get_mut() {
4432                    Some(string) => string.append_in_place(
4433                        // The pattern is the one `matches!` just checked.
4434                        match &right {
4435                            Value::String(text) => text,
4436                            _ => unreachable!("guarded above"),
4437                        },
4438                    ),
4439                    None => None,
4440                };
4441                self.put_loc(slot, Value::String(left));
4442                if let Some(added) = appended {
4443                    // The buffer grew where it stood, so the heap's running total has to
4444                    // be told: `measure_used` would report the new length, and the two must
4445                    // agree or the subtraction at free time leaves the counter wrong.
4446                    self.heap.adjust_payload(added as isize);
4447                    return Ok(());
4448                }
4449            } else {
4450                self.put_loc(slot, taken);
4451            }
4452        }
4453        // The two-number case, without an operand stack round trip. Everything below
4454        // this point is the *general* path: push both, call `binary_add`, pop the answer,
4455        // store it — five operations and two `Value` clones for what is one integer add.
4456        // `AddImmLoc` already answers this shape that way; the fusion above it was written
4457        // for string append and never got the numeric half, so `t += i` — a counting loop
4458        // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4459        let left = self.get_loc(slot);
4460        if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4461            self.put_loc(
4462                slot,
4463                match a.checked_add(*b) {
4464                    Some(sum) => Value::Int(sum),
4465                    None => Value::Float(*a as f64 + *b as f64),
4466                },
4467            );
4468            return Ok(());
4469        }
4470        self.push(left);
4471        self.push(right);
4472        self.binary_add()?;
4473        let value = self.pop();
4474        self.put_loc(slot, value);
4475        Ok(())
4476    }
4477
4478    fn get_arg(&self, slot: usize) -> Value {
4479        self.frame().read_arg(slot)
4480    }
4481
4482    fn put_arg(&mut self, slot: usize, value: Value) {
4483        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4484        if cell == -1 {
4485            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4486                *slot = value;
4487            }
4488        } else {
4489            self.frame().cells[cell as usize].set(value);
4490        }
4491    }
4492
4493    fn get_loc(&self, slot: usize) -> Value {
4494        // The cell mapping is `-1` for every slot that was not captured — which is all of
4495        // them in a function that creates no closure. `Frame::read_loc` tests that first,
4496        // so the common case is one array read and a clone: 20% of every loop iteration
4497        // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4498        // sample of `dispatch:arith`).
4499        self.frame().read_loc(slot)
4500    }
4501
4502    fn put_loc(&mut self, slot: usize, value: Value) {
4503        // One borrow instead of three, and the cell check on the frame we already hold.
4504        let frame = self.frames.last_mut().expect("a frame is live");
4505        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4506        if cell < 0 {
4507            if let Some(slot) = frame.locals.get_mut(slot) {
4508                *slot = value;
4509            }
4510        } else if let Some(cell) = frame.cells.get(cell as usize) {
4511            cell.set(value);
4512        }
4513    }
4514
4515    // -- globals ------------------------------------------------------------
4516
4517    /// The name a global-slot operand refers to.
4518    fn global_name(&self, slot: usize) -> String {
4519        self.frame()
4520            .code
4521            .code
4522            .closure_vars
4523            .get(slot)
4524            .map(|c| c.name.clone())
4525            .unwrap_or_default()
4526    }
4527
4528    /// The facts about a global binding that decide where it lives.
4529    ///
4530    /// A script's globals split in two, and the split is observable: `var` and
4531    /// function declarations become properties of the global object (`globalThis.v`
4532    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4533    /// declarations live in the global *lexical* environment and are invisible there
4534    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4535    /// `is_lexical` flag means the answer is already in the bytecode.
4536    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4537        let name = self.global_name(slot);
4538        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4539        // while forwarding a reference through a nested function is built with the
4540        // flags cleared, so `const c` would look like an ordinary `var` from inside a
4541        // closure. Presence in the realm's lexical table is the same fact, recorded
4542        // once, and every slot sees it.
4543        let lexical = self.realm.globals.contains_key(&name);
4544        let is_const = self.realm.lexical_consts.contains(&name);
4545        (name, lexical, is_const)
4546    }
4547
4548    /// The value of `name` in the innermost active `with` object, if any.
4549    ///
4550    /// The active objects are the [`VarKind::With`] locals of every frame still running,
4551    /// innermost frame first and innermost block first within one. Walking frames rather
4552    /// than keeping a separate stack is what makes a closure called from inside a `with`
4553    /// see it, and what keeps the object alive only as long as the block is.
4554    /// The innermost active `with` object that has `name`, if any.
4555    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4556        let objects = self.eval_with.clone().unwrap_or_default();
4557        for object in objects {
4558            let key = self.string(name.to_string());
4559            if self
4560                .has_property(&key, &Value::Object(object.clone()))
4561                .ok()?
4562            {
4563                return Some(object);
4564            }
4565        }
4566        None
4567    }
4568
4569    /// Every active `with` object, innermost first.
4570    fn with_objects(&self) -> Vec<Gc<JsObject>> {
4571        let mut objects = Vec::new();
4572        for frame in self.frames.iter().rev() {
4573            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4574                if var.kind != js_compile::VarKind::With {
4575                    continue;
4576                }
4577                // A captured binding lives in its cell and not in the slot list, so the
4578                // cell is consulted first — a closure created inside the block is exactly
4579                // what makes the object captured. Before the store runs the slot still
4580                // holds `undefined`, and a `with` object is always boxed, so a non-object
4581                // entry is simply not in scope yet.
4582                let value = frame
4583                    .code
4584                    .loc_cell
4585                    .get(index)
4586                    .copied()
4587                    .filter(|cell| *cell >= 0)
4588                    .and_then(|cell| frame.cells.get(cell as usize))
4589                    .map(|cell| cell.get())
4590                    .or_else(|| frame.locals.get(index).cloned());
4591                if let Some(Value::Object(object)) = value {
4592                    objects.push(object);
4593                }
4594            }
4595        }
4596        objects
4597    }
4598
4599    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4600        for object in self.eval_with.clone().unwrap_or_default() {
4601            let key = self.string(name.to_string());
4602            if self.has_property(&key, &Value::Object(object.clone()))? {
4603                return Ok(Some(self.read_field(&Value::Object(object), name)?));
4604            }
4605        }
4606        Ok(None)
4607    }
4608
4609    /// Whether every scope between here and the global object is an ordinary one.
4610    ///
4611    /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4612    /// bytecode resolved; when any is live the general path has to run in full order. When
4613    /// none is — every ordinary program — a global read is a property read and nothing
4614    /// else, and that is worth caching.
4615    fn scopes_are_plain(&self) -> bool {
4616        self.eval_caller.is_none()
4617            && self.eval_with.is_none()
4618            && self.eval_arguments.is_none()
4619            && self.eval_bindings.is_empty()
4620            && self.eval_scope.is_none()
4621            // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4622            // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4623            // its `ClosureEnv`, so the test has to be the same one the general path makes.
4624            // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4625            // upstream corpus caught and no unit test did.
4626            && !self.has_visible_local_vars()
4627            && self.frame().env.eval_scope.is_none()
4628    }
4629
4630    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4631        // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4632        // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4633        // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4634        // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4635        // borrow outlive the `&mut self` the lookup needs.
4636        //
4637        // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4638        // forwarded through a nested function has its flags cleared, so the flag cannot
4639        // be believed.
4640        let code = self.frame().code.clone();
4641        let name = code
4642            .code
4643            .closure_vars
4644            .get(slot)
4645            .map(|c| c.name.as_str())
4646            .unwrap_or_default();
4647        let lexical = self.realm.globals.contains_key(name);
4648        // The common case, first: an ordinary global `var`, with a cache in front of the
4649        // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4650        // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4651        // cache hit and return without touching any of it.
4652        if !lexical && self.scopes_are_plain() {
4653            return self.get_plain_global(name, slot);
4654        }
4655        if name == "arguments"
4656            && let Some(arguments) = &self.eval_arguments
4657        {
4658            return Ok(arguments.clone());
4659        }
4660        // A `with` block around the *call site* is part of the scope an `eval` sees, so
4661        // the objects live when the eval started are consulted before anything else. The
4662        // snapshot is taken at entry rather than scanning the frames on every read: a
4663        // block that has already finished still leaves its object in the slot, and a
4664        // bytecode read outside the block must not see it.
4665        if let Some(value) = self.with_lookup(name)? {
4666            return Ok(value);
4667        }
4668        // A variable a direct `eval` declared shadows everything the compiler resolved,
4669        // including an enclosing function's binding: the eval put it in the caller's own
4670        // variable environment, which is nearer than any captured scope.
4671        if let Some((local_vars, phase)) = self.visible_local_vars()
4672            && let Some(cell) = local_vars.get(name, phase)
4673        {
4674            return Ok(cell.get());
4675        }
4676        // The frame that called `eval` is the innermost scope the eval'd code sees, so
4677        // its local `a` wins over a global `a`.
4678        if let Some(value) = self.eval_binding_value(name) {
4679            return Ok(value);
4680        }
4681        // A closure created by an `eval` resolves its free names against the bindings
4682        // that eval saw, even after the eval (and its frames) are gone.
4683        if let Some(cell) = self
4684            .frame()
4685            .env
4686            .eval_scope
4687            .as_ref()
4688            .and_then(|scope| scope.get(name))
4689        {
4690            let value = cell.get();
4691            if matches!(value, Value::Uninitialized) {
4692                return Err(self.throw_reference(name));
4693            }
4694            return Ok(value);
4695        }
4696        // A binding declared by the strict `eval` currently running shadows anything
4697        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
4698        if let Some(scope) = &self.eval_scope
4699            && let Some(value) = scope.get(name)
4700        {
4701            return Ok(value.clone());
4702        }
4703        if lexical {
4704            // A lexical global is a binding in a side table, so the dead zone is
4705            // visible and it is nowhere on the global object.
4706            if let Some(cell) = self.realm.globals.get(name) {
4707                let value = cell.get();
4708                if matches!(value, Value::Uninitialized) {
4709                    return Err(self.throw_reference(name));
4710                }
4711                return Ok(value);
4712            }
4713            return Err(self.throw_reference(name));
4714        }
4715        // A `var` global is an ordinary property, so the prototype chain and the
4716        // global object's own builtins are all reachable through it.
4717        match self.get_property(&self.realm.global.clone(), name)? {
4718            Some(value) => Ok(value),
4719            None => Err(self.throw_reference(name)),
4720        }
4721    }
4722
4723    /// Read a plain global `var`: a cached own data property, or the full lookup.
4724    ///
4725    /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
4726    /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
4727    fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
4728        let object = self.realm.global.clone();
4729        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4730        if let Some(cached) = &self.global_cache[site]
4731            && object.upgrades_to(&cached.object)
4732            && let Some(value) = object.data_property_at(cached.index, name)
4733        {
4734            return Ok(value);
4735        }
4736        // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
4737        // chain exactly as before, then remember the answer if it is worth remembering.
4738        let Some(value) = self.get_property(&object, name)? else {
4739            return Err(self.throw_reference(name));
4740        };
4741        if let Some(index) = object.own_data_index(name) {
4742            self.global_cache[site] = Some(GlobalCache {
4743                object: object.downgrade(),
4744                index,
4745            });
4746        }
4747        Ok(value)
4748    }
4749
4750    /// Store to a global binding.
4751    ///
4752    /// Returns a signal when the store is refused: a `const` global may only be
4753    /// written by its initialiser, and a non-configurable `var` global may not be
4754    /// deleted but is always writable.
4755    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4756        let (name, lexical, is_const) = self.global_binding(slot);
4757
4758        // An assignment inside a `with` writes through to the object that supplies the
4759        // name, which for an `eval` means consulting the same chain `get_global` does.
4760        if let Some(owner) = self.with_owner(&name) {
4761            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
4762            return Ok(());
4763        }
4764        // A variable the running eval *declared* takes the write before any caller
4765        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
4766        // environment even when an enclosing function has a `var c` of its own.
4767        if self.eval_caller.flatten().is_some()
4768            && let Some((local_vars, phase)) = self.visible_local_vars()
4769            && local_vars.contains(&name)
4770            && let Some(cell) = local_vars.get(&name, phase)
4771        {
4772            cell.set(value);
4773            return Ok(());
4774        }
4775        // A binding of the frame that called `eval` takes the write, which is what
4776        // makes `f("a = 3")` change the caller's `a`.
4777        if self.set_eval_binding(&name, &value)? {
4778            return Ok(());
4779        }
4780        // A closure that outlived its `eval` writes through to the same cell it reads.
4781        if let Some(cell) = self
4782            .frame()
4783            .env
4784            .eval_scope
4785            .as_ref()
4786            .and_then(|scope| scope.get(&name))
4787            .cloned()
4788        {
4789            cell.set(value);
4790            return Ok(());
4791        }
4792        // Inside a strict `eval`, a name it declared itself is stored there. An
4793        // *assignment* to a name nobody declared is not a declaration, so it falls
4794        // through: strict mode raises `ReferenceError` for it, which is what
4795        // `eval("1 + (@not_def = 1)")` has to do.
4796        if let Some(scope) = self.eval_scope.as_mut()
4797            && scope.contains_key(&name)
4798        {
4799            scope.insert(name, value);
4800            return Ok(());
4801        }
4802        if lexical {
4803            if let Some(cell) = self.realm.globals.get(&name).cloned() {
4804                if is_const && !matches!(cell.get(), Value::Uninitialized) {
4805                    return Err(self.read_only_global(&name));
4806                }
4807                cell.set(value);
4808                return Ok(());
4809            }
4810            // Writing an undeclared lexical global is a `ReferenceError` in strict
4811            // mode and a silent global creation otherwise; creating the cell here
4812            // keeps both paths from losing the value.
4813            let cell = self.new_cell(value);
4814            self.realm.globals.insert(name, cell);
4815            return Ok(());
4816        }
4817        // A variable a direct `eval` declared in this call shadows the global object, even
4818        // when the global already has a property of that name — `var c = "global"` at the
4819        // top level must not capture `eval("var c = 1")` inside a function.
4820        if let Some((local_vars, phase)) = self.visible_local_vars()
4821            && local_vars.contains(&name)
4822            && let Some(cell) = local_vars.get(&name, phase)
4823        {
4824            cell.set(value);
4825            return Ok(());
4826        }
4827        // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
4828        // remembered a global's slot index since M12b, but the *store* side never did: it
4829        // converted the name to a `PropertyKey` (two allocations) and then scanned the
4830        // global object's whole table — which holds every builtin — on every assignment to
4831        // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
4832        // full global lookup per iteration; measured with a counter, `s` as a global made
4833        // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
4834        //
4835        // Re-validated exactly like the read: same object, same index, still the name, and
4836        // — the one extra check a store needs — still writable. A global that is an
4837        // accessor, non-writable, or inherited fails here and falls through to the full
4838        // path below, which reports the failure the way it always did.
4839        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4840        let global = self.realm.global.clone();
4841        if let Some(cached) = &self.global_cache[site]
4842            && global.upgrades_to(&cached.object)
4843            && global.write_data_at(cached.index, &name, value.clone())
4844        {
4845            return Ok(());
4846        }
4847        match global.own_property(&name) {
4848            // A `var` global is writable, so the store goes straight through — but
4849            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
4850            // store (a non-writable or accessor-without-setter global) is a silent
4851            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
4852            // split every other assignment has.
4853            Some(_) => {
4854                let on_failure = if self.current_strict() {
4855                    DeleteFailure::Throw
4856                } else {
4857                    DeleteFailure::Ignore
4858                };
4859                let result = self.set_property_with(&global, &name, value, on_failure);
4860                // Teach the cache the slot for a plain writable own data property, which is
4861                // what a declared `var` is. Without this the fast path above could never
4862                // fire for a global that is only ever *written* — its entry would have to
4863                // be put there by a read of the same slot, and a write-only loop has none.
4864                if result.is_ok()
4865                    && let Some(index) = global.own_data_index(&name)
4866                {
4867                    self.global_cache[site] = Some(GlobalCache {
4868                        object: global.downgrade(),
4869                        index,
4870                    });
4871                }
4872                result
4873            }
4874            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
4875            // declaration creates a *configurable* property, which is what makes it
4876            // deletable and is the one way a global differs from a declared `var`.
4877            // In strict mode the same store is a `ReferenceError` instead: that is the
4878            // whole point of strict mode, and creating the global silently meant
4879            // `"use strict"; x = 1` looked like it worked.
4880            None => {
4881                if self.current_strict() {
4882                    return Err(self.throw_reference(&name));
4883                }
4884                // A direct eval declares here rather than on the global object: its
4885                // `var`s belong to the caller's variable environment. `declare_eval_local`
4886                // also covers a plain assignment to a variable an earlier eval made.
4887                if let Some(cell) = self.declare_eval_local(&name) {
4888                    cell.set(value);
4889                    return Ok(());
4890                }
4891                global.define_data(&name, value);
4892                Ok(())
4893            }
4894        }
4895    }
4896
4897    /// The value of a binding of the frame that called `eval`, if there is one.
4898    fn eval_binding_value(&self, name: &str) -> Option<Value> {
4899        let binding = self
4900            .eval_bindings
4901            .iter()
4902            .find(|binding| binding.name == name)?;
4903        let owner = self.frames.get(binding.frame)?;
4904        let (slot, index) = (binding.slot, binding.index);
4905        Some(match slot {
4906            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4907                cell if cell >= 0 => owner
4908                    .cells
4909                    .get(cell as usize)
4910                    .map(|cell| cell.get())
4911                    .unwrap_or(Value::Undefined),
4912                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
4913            },
4914            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4915                cell if cell >= 0 => owner
4916                    .cells
4917                    .get(cell as usize)
4918                    .map(|cell| cell.get())
4919                    .unwrap_or(Value::Undefined),
4920                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
4921            },
4922        })
4923    }
4924
4925    /// Write to a binding of the frame that called `eval`.
4926    ///
4927    /// `Ok(false)` means no binding matched and the caller should keep looking. A
4928    /// matched binding can still refuse the store, which is why this is fallible: a
4929    /// `const` is read-only everywhere, and a named function expression's own name is
4930    /// read-only in strict mode.
4931    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
4932        let Some(binding) = self
4933            .eval_bindings
4934            .iter()
4935            .find(|binding| binding.name == name)
4936        else {
4937            return Ok(false);
4938        };
4939        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
4940        let strict = self.current_strict();
4941        let Some(owner) = self.frames.get_mut(frame) else {
4942            return Ok(false);
4943        };
4944        match slot {
4945            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4946                cell if cell >= 0 => {
4947                    if let Some(cell) = owner.cells.get(cell as usize) {
4948                        cell.set(value.clone());
4949                    }
4950                }
4951                _ => {
4952                    if let Some(slot) = owner.args.get_mut(index) {
4953                        *slot = value.clone();
4954                    }
4955                }
4956            },
4957            EvalSlot::Local => {
4958                let declared = owner.code.code.vars.get(index);
4959                // A `const` is read-only even through `eval`. The realm records this for
4960                // globals (see `lexical_consts`), but a local's `const`-ness is only in
4961                // the bytecode, so this is where it has to be enforced.
4962                if declared.is_some_and(|var| var.is_const) {
4963                    return Err(self.read_only_local(name));
4964                }
4965                // The name of a named function expression is read-only too, but only
4966                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
4967                // such a name is ignored, the same as a direct store would be.
4968                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
4969                    return if strict {
4970                        Err(self.read_only_local(name))
4971                    } else {
4972                        Ok(true)
4973                    };
4974                }
4975                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4976                    cell if cell >= 0 => {
4977                        if let Some(cell) = owner.cells.get(cell as usize) {
4978                            cell.set(value.clone());
4979                        }
4980                    }
4981                    _ => {
4982                        if let Some(slot) = owner.locals.get_mut(index) {
4983                            *slot = value.clone();
4984                        }
4985                    }
4986                }
4987            }
4988        }
4989        Ok(true)
4990    }
4991
4992    /// The `TypeError` an assignment to a read-only binding raises.
4993    fn read_only_local(&self, name: &str) -> Signal {
4994        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4995    }
4996
4997    /// Declare `name` as a variable of the frame that called the running `eval`.
4998    ///
4999    /// `None` when there is no direct eval in progress, or it was called from the top
5000    /// level — then the caller's variable environment *is* the global one and the
5001    /// existing path is right.
5002    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5003        let caller = self.eval_caller.flatten()?;
5004        // The bottom frame is the top-level script, whose variable environment *is* the
5005        // global one — so `eval("var x = 1")` at the top level still creates a global.
5006        if caller == 0 {
5007            return None;
5008        }
5009        // A name the eval's *own* variable environment already binds is not a new
5010        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5011        // `arguments`, and creating a second binding would leave the first — the one
5012        // closures read — untouched. A binding of an *outer* frame does not count: a
5013        // declaration shadows it rather than writing through.
5014        if self
5015            .eval_bindings
5016            .iter()
5017            .any(|binding| binding.name == name && binding.frame == caller)
5018        {
5019            return None;
5020        }
5021        let phase = if self.in_parameter_list_at(caller) {
5022            0
5023        } else {
5024            1
5025        };
5026        self.frame_local_vars(caller)?;
5027        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5028        if let Some(cell) = local_vars.get(name, 1) {
5029            return Some(cell);
5030        }
5031        let cell = self.new_cell(Value::Undefined);
5032        Some(local_vars.declare(name, phase, cell))
5033    }
5034
5035    /// Make sure `frame` has a `LocalVars`, creating it on demand.
5036    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5037        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5038            return Some(local_vars.clone());
5039        }
5040        let local_vars = Gc::new(self.heap, LocalVars::new());
5041        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5042        Some(local_vars)
5043    }
5044
5045    /// Whether the realm already has a binding for `name`, lexically or as an *own*
5046    /// property of the global object. Used to decide whether a store inside an
5047    /// `eval` writes through to the realm or declares a binding of its own.
5048    ///
5049    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5050    /// write to `Object.prototype.toString`, and must not shadow it either.
5051    fn global_knows(&mut self, name: &str) -> bool {
5052        if self.realm.globals.contains_key(name) {
5053            return true;
5054        }
5055        self.realm.global.own_property(name).is_some()
5056    }
5057
5058    /// Whether the code currently running is strict.
5059    ///
5060    /// Read off the frame's function, which is where the parser's answer ended up; a
5061    /// native function never runs strict-only checks, and there is no frame at all
5062    /// before the first script.
5063    pub fn current_strict(&self) -> bool {
5064        self.frames
5065            .last()
5066            .is_some_and(|frame| frame.code.code.strict)
5067    }
5068
5069    /// Initialise a declared global, which is what ends its dead zone.
5070    ///
5071    /// A `var` global becomes a property of the global object: writable, so a later
5072    /// assignment goes through, and non-configurable, so `delete` refuses.
5073    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5074        let (name, lexical, _) = self.global_binding(slot);
5075        // A `var` declared by the strict `eval` currently running belongs to the
5076        // eval's scope, not to the global object: `eval("var v = 1")` must not make
5077        // `typeof v` answer `"number"` afterwards. A name the realm already has is
5078        // initialised in place, which is what a re-declaration inside eval does.
5079        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5080            self.eval_scope
5081                .as_mut()
5082                .expect("checked above")
5083                .insert(name, value);
5084            return Ok(());
5085        }
5086        if let Some(scope) = self.eval_scope.as_mut()
5087            && scope.contains_key(&name)
5088        {
5089            scope.insert(name, value);
5090            return Ok(());
5091        }
5092        if lexical {
5093            // The cell exists (created at declaration time) holding the dead-zone
5094            // marker; storing the value is what makes the binding readable.
5095            if let Some(cell) = self.realm.globals.get(&name).cloned() {
5096                cell.set(value);
5097                return Ok(());
5098            }
5099            let cell = self.new_cell(value);
5100            self.realm.globals.insert(name, cell);
5101            return Ok(());
5102        }
5103        let global = self.realm.global.clone();
5104        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5105        // to answer `false` and leave the binding in place. `with_attributes` ties
5106        // `configurable` to `writable`, so the property is built field by field.
5107        global.define(
5108            &name,
5109            Property {
5110                value: Some(value),
5111                writable: true,
5112                enumerable: true,
5113                configurable: false,
5114                ..Property::default()
5115            },
5116        );
5117        Ok(())
5118    }
5119
5120    /// The `TypeError` a store to a `const` global raises.
5121    fn read_only_global(&self, name: &str) -> Signal {
5122        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5123    }
5124
5125    // -- properties ---------------------------------------------------------
5126
5127    /// Read `object[key]`, following the prototype chain.
5128    ///
5129    /// An inherited accessor runs with the *receiver* as `this`, which is why the
5130    /// lookup returns the owner rather than just the value.
5131    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5132        self.get_property_key(object, &PropertyKey::from(key))
5133    }
5134
5135    /// [`Interp::get_property`] with a key that may be a symbol.
5136    pub fn get_property_key(
5137        &mut self,
5138        object: &Gc<JsObject>,
5139        key: &PropertyKey,
5140    ) -> JsResult<Option<Value>> {
5141        self.get_property_key_for(object, None, key)
5142    }
5143
5144    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5145    ///
5146    /// The receiver matters when the property is found on a *prototype*: a getter has to
5147    /// see the object the read started from. For a primitive that is the primitive
5148    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5149    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5150    /// the owner.
5151    pub fn get_property_key_for(
5152        &mut self,
5153        object: &Gc<JsObject>,
5154        receiver: Option<&Value>,
5155        key: &PropertyKey,
5156    ) -> JsResult<Option<Value>> {
5157        // A proxy answers for itself, before any of the shortcuts below: `new
5158        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5159        // have.
5160        if object.proxy_state().is_some() {
5161            let receiver = receiver
5162                .cloned()
5163                .unwrap_or_else(|| Value::Object(object.clone()));
5164            return self.proxy_get(object, &receiver, key);
5165        }
5166        // A host class's `get_property` trap replaces the whole read, prototype walk
5167        // included — that is what makes a native accessor free rather than a JavaScript
5168        // getter call.
5169        if let Some(exotic) = object.exotic() {
5170            let receiver_value = receiver
5171                .cloned()
5172                .unwrap_or_else(|| Value::Object(object.clone()));
5173            if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5174                return Ok(Some(value));
5175            }
5176            // With no `get_property` trap, a `get_own_property` trap still answers for the
5177            // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5178            // and the hook lives exactly there. A key the trap reports as absent is still
5179            // looked for on the prototype, which is why the search resumes *above*.
5180            if let Some(property) = exotic.get_own_property(self, object, key)? {
5181                return match property {
5182                    Some(property) => self.read_property(property, object, receiver),
5183                    None => match lookup_key_above(object, key) {
5184                        Some((_, property)) => self.read_property(property, object, receiver),
5185                        None => Ok(None),
5186                    },
5187                };
5188            }
5189        }
5190        // The element-vector and `length` shortcuts are string-only: an array index
5191        // has no symbol spelling.
5192        if let Some(text) = key.as_str() {
5193            if let Some(value) = self.own_element(object, text) {
5194                return Ok(Some(value));
5195            }
5196            // `length` is not stored as a property: an array's length is its element
5197            // count, and keeping one copy of it is what makes `push`/`pop` and
5198            // `a.length = n` agree.
5199            if let Some(length) = object.array_length()
5200                && text == "length"
5201            {
5202                // Not `Value::Int(length as i32)`: see [`length_value`].
5203                return Ok(Some(crate::object::length_value(length)));
5204            }
5205        }
5206        match lookup_key(object, key) {
5207            Some((_, property)) => self.read_property(property, object, receiver),
5208            None => Ok(None),
5209        }
5210    }
5211
5212    /// The value a property read answers.
5213    ///
5214    /// One place rather than three, because an accessor has to run with the *receiver* as
5215    /// `this` whether the descriptor came from the property table, an exotic
5216    /// `get_own_property` trap, or a prototype above one.
5217    fn read_property(
5218        &mut self,
5219        property: Property,
5220        object: &Gc<JsObject>,
5221        receiver: Option<&Value>,
5222    ) -> JsResult<Option<Value>> {
5223        if property.is_accessor() {
5224            match &property.getter {
5225                Some(getter) if !matches!(getter, Value::Undefined) => {
5226                    let receiver = receiver
5227                        .cloned()
5228                        .unwrap_or_else(|| Value::Object(object.clone()));
5229                    self.call_value(getter.clone(), receiver, Vec::new())
5230                        .map(Some)
5231                }
5232                // An accessor with no getter reads as `undefined`.
5233                _ => Ok(Some(Value::Undefined)),
5234            }
5235        } else {
5236            Ok(property.value)
5237        }
5238    }
5239
5240    /// `super.key` — start the search at `proto`, but report to `receiver`.
5241    ///
5242    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5243    /// found on the prototype of a class has to see the *instance* as `this`, and a
5244    /// plain property read off `proto` would lose that.
5245    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5246        let start = self.require_object(proto)?;
5247        let key = self.propkey(key)?;
5248        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5249        if matches!(proto, Value::Null) {
5250            return Ok(Value::Undefined);
5251        }
5252        match lookup_key(&start, &key) {
5253            Some((_, property)) if property.is_accessor() => match &property.getter {
5254                Some(getter) if !matches!(getter, Value::Undefined) => {
5255                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
5256                }
5257                _ => Ok(Value::Undefined),
5258            },
5259            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5260            None => Ok(Value::Undefined),
5261        }
5262    }
5263
5264    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5265    ///
5266    /// A setter found on the prototype runs with `receiver` as `this`; a data property
5267    /// is shadowed by a new own property on the receiver, the same rule an ordinary
5268    /// assignment follows.
5269    fn super_write(
5270        &mut self,
5271        receiver: &Value,
5272        proto: &Value,
5273        key: &Value,
5274        value: Value,
5275    ) -> JsResult<()> {
5276        let target = self.require_object(receiver)?;
5277        let key = self.propkey(key)?;
5278        if !matches!(proto, Value::Null)
5279            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5280        {
5281            if property.is_accessor() {
5282                if let Some(setter) = &property.setter
5283                    && !matches!(setter, Value::Undefined)
5284                {
5285                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5286                }
5287                return Ok(());
5288            }
5289            // A data property on the prototype is writable or not; reading `owner` at
5290            // all is only for the attribute check.
5291            if !property.writable {
5292                return Err(self.type_error(format!("'{key}' is read-only")));
5293            }
5294            let _ = owner;
5295        }
5296        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5297    }
5298
5299    /// The object a `super` operation needs, or the `TypeError` the spec raises.
5300    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5301        match value.as_object() {
5302            Some(object) => Ok(object.clone()),
5303            None => Err(Signal::Throw(
5304                self.make_error("TypeError", "value is not an object"),
5305            )),
5306        }
5307    }
5308
5309    /// Build the class object `define_class` produces.
5310    ///
5311    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5312    /// whose prototype property is a fresh object inheriting from the parent's
5313    /// prototype, and whose own prototype is the parent constructor — which is what makes
5314    /// a static method inherited too.
5315    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5316        let ctor = self.pop();
5317        let parent = self.pop();
5318        let Value::Object(function) = &ctor else {
5319            return Err(Signal::Throw(
5320                self.make_error("TypeError", "class constructor must be a function"),
5321            ));
5322        };
5323        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5324        // but gives the instances no prototype at all.
5325        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5326            match &parent {
5327                Value::Null => (Some(self.realm.function_proto.clone()), None),
5328                Value::Object(parent_class) => {
5329                    if !parent_class.is_callable() {
5330                        return Err(Signal::Throw(
5331                            self.make_error("TypeError", "parent class must be constructor"),
5332                        ));
5333                    }
5334                    let proto = self.get_property(parent_class, "prototype")?;
5335                    match proto {
5336                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5337                        Some(Value::Null) => (Some(parent_class.clone()), None),
5338                        _ => {
5339                            return Err(Signal::Throw(self.make_error(
5340                                "TypeError",
5341                                "parent prototype must be an object or null",
5342                            )));
5343                        }
5344                    }
5345                }
5346                _ => {
5347                    return Err(Signal::Throw(
5348                        self.make_error("TypeError", "parent class must be constructor"),
5349                    ));
5350                }
5351            }
5352        } else {
5353            (
5354                Some(self.realm.function_proto.clone()),
5355                Some(self.realm.object_proto.clone()),
5356            )
5357        };
5358        let proto = self.new_object(parent_proto);
5359        function.set_proto(parent_ctor);
5360        // A class is not callable without `new`, and its `prototype` is not writable —
5361        // both follow from being a class and are what `class A {}; A()` throws on.
5362        function.set_class_constructor(true);
5363        function.set_home_object(None);
5364        self.set_function_name(&ctor, name);
5365        self.define_class_properties(function, &ctor, &proto)?;
5366        Ok((ctor, proto))
5367    }
5368
5369    /// Give the constructor its `prototype` and `length`, and the prototype its
5370    /// `constructor` back-pointer.
5371    fn define_class_properties(
5372        &mut self,
5373        function: &Gc<JsObject>,
5374        ctor: &Value,
5375        proto: &Gc<JsObject>,
5376    ) -> JsResult<()> {
5377        proto.define(
5378            "constructor",
5379            Property::with_attributes(ctor.clone(), true, false),
5380        );
5381        function.define(
5382            "prototype",
5383            Property::prototype_of(Value::Object(proto.clone()), false),
5384        );
5385        if let Some((code, _)) = bytecode_of(function) {
5386            let length = code.code.defined_args;
5387            function.define(
5388                "length",
5389                Property::name_or_length(Value::Int(length as i32)),
5390            );
5391        }
5392        Ok(())
5393    }
5394
5395    /// The own array element `key` names, if this object has one.
5396    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5397        let index = array_index(key)?;
5398        // A typed array's elements live in its buffer, not in a property list: reading one
5399        // goes through the view's element type so a bounds check and a detached buffer are
5400        // both handled there.
5401        if object.typed_array_parts().is_some() {
5402            return object.typed_array_element(index as usize);
5403        }
5404        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5405        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5406        // search early, which is why `Array.prototype[1] = 9` could not be seen through
5407        // `[1,,3][1]`.
5408        match object.array_get(index as usize) {
5409            Some(Value::Hole) | None => None,
5410            other => other,
5411        }
5412    }
5413
5414    /// Store `object[key] = value`, honouring setters and inherited properties.
5415    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5416        self.set_property_with(object, key, value, DeleteFailure::Throw)
5417    }
5418
5419    /// Store a property, choosing what to do when the object refuses.
5420    ///
5421    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5422    /// mode, which is the one place assignment differs by mode. Native code (the array
5423    /// methods, `JSON`) always asks for the throw.
5424    pub fn set_property_with(
5425        &mut self,
5426        object: &Gc<JsObject>,
5427        key: &str,
5428        value: Value,
5429        on_failure: DeleteFailure,
5430    ) -> JsResult<()> {
5431        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5432    }
5433
5434    /// [`Interp::set_property_with`] with a key that may be a symbol.
5435    pub fn set_property_with_key(
5436        &mut self,
5437        object: &Gc<JsObject>,
5438        key: &PropertyKey,
5439        value: Value,
5440        on_failure: DeleteFailure,
5441    ) -> JsResult<()> {
5442        self.set_property_with_key_receiver_aware(object, key, value, on_failure, true)
5443    }
5444
5445    /// As [`Interp::set_property_with_key`], with the receiver explicit.
5446    ///
5447    /// `same_receiver` is `SameValue(O, Receiver)` from §10.4.5.5 step 1.b.i, and the two
5448    /// branches it separates are observable in opposite directions: when the receiver *is*
5449    /// the view the element store converts `V` first and then asks whether the index is
5450    /// valid (`Set/resized-out-of-bounds-to-in-bounds-index`, where a `valueOf` puts the
5451    /// index back in bounds), and when it is not, an invalid index returns `true` without
5452    /// converting anything (`key-is-out-of-bounds-receiver-is-not-object`).
5453    fn set_property_with_key_receiver_aware(
5454        &mut self,
5455        object: &Gc<JsObject>,
5456        key: &PropertyKey,
5457        value: Value,
5458        on_failure: DeleteFailure,
5459        same_receiver: bool,
5460    ) -> JsResult<()> {
5461        // A proxy's `set` trap decides, and its `false` means the same thing an
5462        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5463        if object.proxy_state().is_some() {
5464            let receiver = Value::Object(object.clone());
5465            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5466                return match (accepted, on_failure) {
5467                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5468                    (false, DeleteFailure::Throw) => {
5469                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5470                    }
5471                };
5472            }
5473        }
5474        // A host class's `set_property` trap decides for itself. `Some(false)` is a
5475        // refusal and means exactly what a proxy's `false` means.
5476        if let Some(exotic) = object.exotic() {
5477            let receiver = Value::Object(object.clone());
5478            if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5479                return match (accepted, on_failure) {
5480                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5481                    (false, DeleteFailure::Throw) => {
5482                        Err(self.type_error(format!("property '{key}' is read-only")))
5483                    }
5484                };
5485            }
5486        }
5487        // The element and `length` shortcuts only exist for string keys: an array
5488        // index has no symbol spelling, and a symbol named `length` is an ordinary
5489        // property.
5490        let text = key.as_str();
5491        // A typed array's elements are a window onto its buffer: the store has to go
5492        // through the view's element type so the value is wrapped (or clamped) and so an
5493        // out-of-range or detached write is a silent no-op, as the spec says.
5494        if let Some(text) = text
5495            && let Some(index) = array_index(text)
5496            && let Some(element) = object.typed_array_element_type()
5497        {
5498            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5499            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5500            // in `Interp`, because it is script-observable and the storage borrow inside
5501            // `typed_array_set` must not be held across it.
5502            //
5503            // It runs even for an index that is out of bounds *now*, because `V` itself can
5504            // put it back in bounds: `TypedArraySetElement` converts first and asks
5505            // `IsValidIntegerIndex` afterwards, which is what
5506            // `Set/resized-out-of-bounds-to-in-bounds-index` asserts (a `valueOf` that
5507            // resizes a 0-byte buffer to 1 makes `ta[0] = value` store 100). The write is
5508            // still a no-op when the index stays out of bounds, which is why the extra
5509            // length check that used to guard this has no job left.
5510            if !same_receiver && index as usize >= object.typed_array_length().unwrap_or(0) {
5511                return Ok(());
5512            }
5513            let stored = self.element_value(element, value)?;
5514            if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
5515                return Err(self.type_error(reason));
5516            }
5517            return Ok(());
5518        }
5519        if let Some(text) = text
5520            && let Some(index) = array_index(text)
5521            && object.is_array()
5522        {
5523            // An accessor defined on an index lives in the property table while the
5524            // element slot is a hole, so the store has to go through the property first.
5525            // Writing the vector directly skipped the setter entirely.
5526            if let Some(existing) = object.own_property_key(key) {
5527                if existing.is_accessor() {
5528                    return match existing.setter.clone() {
5529                        Some(setter) if !matches!(setter, Value::Undefined) => {
5530                            let receiver = Value::Object(object.clone());
5531                            self.call_value(setter, receiver, vec![value]).map(|_| ())
5532                        }
5533                        _ => match on_failure {
5534                            DeleteFailure::Throw => Err(self.type_error(format!(
5535                                "cannot set property '{text}', it has only a getter"
5536                            ))),
5537                            DeleteFailure::Ignore => Ok(()),
5538                        },
5539                    };
5540                }
5541                if !existing.writable {
5542                    return match on_failure {
5543                        DeleteFailure::Throw => {
5544                            Err(self.type_error(format!("'{text}' is read-only")))
5545                        }
5546                        DeleteFailure::Ignore => Ok(()),
5547                    };
5548                }
5549            }
5550            {
5551                // Growing the array needs a writable `length`.
5552                if (index as usize) >= object.array_length().unwrap_or(0)
5553                    && !object.length_writable()
5554                {
5555                    return match on_failure {
5556                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5557                        DeleteFailure::Ignore => Ok(()),
5558                    };
5559                }
5560                // Adding an index past the end makes the array longer, which a
5561                // non-extensible array refuses.
5562                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5563                    return match on_failure {
5564                        DeleteFailure::Throw => Err(self.type_error(format!(
5565                            "cannot add property '{key}', object is not extensible"
5566                        ))),
5567                        DeleteFailure::Ignore => Ok(()),
5568                    };
5569                }
5570                if object.element_is_locked(index) {
5571                    return match on_failure {
5572                        DeleteFailure::Throw => {
5573                            Err(self.type_error(format!("'{key}' is read-only")))
5574                        }
5575                        DeleteFailure::Ignore => Ok(()),
5576                    };
5577                }
5578                // The element vector is only half of `[[Set]]` for an index: the
5579                // prototype chain is consulted first, and a setter there answers instead
5580                // of the element store. This branch used to write the element directly, so
5581                // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5582                // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5583                // the reference calls the setter and the array keeps no own index.
5584                if let Some((owner, property)) = lookup_key(object, key)
5585                    && !owner.ptr_eq(object)
5586                {
5587                    match &property {
5588                        property if property.is_accessor() => {
5589                            match &property.setter {
5590                                Some(setter) if !matches!(setter, Value::Undefined) => {
5591                                    let receiver = Value::Object(object.clone());
5592                                    self.call_value(setter.clone(), receiver, vec![value])?;
5593                                }
5594                                _ => {
5595                                    return match on_failure {
5596                                        DeleteFailure::Throw => Err(self.type_error(format!(
5597                                            "cannot set property '{text}', it has only a getter"
5598                                        ))),
5599                                        DeleteFailure::Ignore => Ok(()),
5600                                    };
5601                                }
5602                            }
5603                            return Ok(());
5604                        }
5605                        property if !property.writable => {
5606                            return match on_failure {
5607                                DeleteFailure::Throw => {
5608                                    Err(self.type_error(format!("'{text}' is read-only")))
5609                                }
5610                                DeleteFailure::Ignore => Ok(()),
5611                            };
5612                        }
5613                        _ => {}
5614                    }
5615                }
5616                if object.array_set(self.heap, index as usize, value.clone()) {
5617                    return Ok(());
5618                }
5619                // Past the dense limit the slot is too far out to be worth one `Value`
5620                // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
5621                // constant time by keeping the index as an ordinary property. The store
5622                // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
5623                // to a legal program.
5624                object.define_key(key, Property::with_attributes(value, true, true));
5625                // Extend, never shorten: the index may be *inside* the current length (a
5626                // huge `length` with a sparse store), and shortening would delete the
5627                // sparse properties above it — including the one just stored.
5628                if index as usize + 1 > object.array_length().unwrap_or(0) {
5629                    object.array_set_length(self.heap, index as usize + 1);
5630                }
5631                return Ok(());
5632            }
5633        }
5634        if text == Some("length") && object.is_array() {
5635            if !object.length_writable() {
5636                return match on_failure {
5637                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5638                    DeleteFailure::Ignore => Ok(()),
5639                };
5640            }
5641            let length = value.to_number();
5642            if length.is_finite() && length >= 0.0 {
5643                let length = length as usize;
5644                // `a.length = n` with `n` below a non-configurable element cannot
5645                // drop that element, so the whole assignment fails. The spec makes
5646                // this a `TypeError` rather than a silent no-op, in any mode.
5647                if let Some(blocked) = object.first_undeletable_at_or_above(length) {
5648                    // Sloppy mode stops the truncation at the blocking element
5649                    // instead of failing; strict mode raises.
5650                    // Both modes stop at the blocking element; they differ in
5651                    // whether that is reported. The reference truncates *then*
5652                    // throws, so the array is left in the shortened state.
5653                    object.array_truncate(self.heap, blocked + 1);
5654                    return match on_failure {
5655                        DeleteFailure::Throw => {
5656                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
5657                        }
5658                        DeleteFailure::Ignore => Ok(()),
5659                    };
5660                }
5661                object.array_set_length(self.heap, length);
5662                return Ok(());
5663            }
5664        }
5665        if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
5666        {
5667            return match on_failure {
5668                DeleteFailure::Throw => Err(self.type_error(format!(
5669                    "cannot add property {}, object is not extensible",
5670                    key
5671                ))),
5672                DeleteFailure::Ignore => Ok(()),
5673            };
5674        }
5675        if let Some((owner, property)) = self.lookup_for_write(object, key)? {
5676            if property.is_accessor() {
5677                match &property.setter {
5678                    Some(setter) if !matches!(setter, Value::Undefined) => {
5679                        let receiver = Value::Object(object.clone());
5680                        self.call_value(setter.clone(), receiver, vec![value])?;
5681                    }
5682                    // §10.1.9.2 step 3: an accessor with no setter refuses the write.
5683                    // Sloppy code swallows that refusal, strict code raises — the same
5684                    // rule the read-only *data* property below follows, and skipping it
5685                    // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
5686                    // return silently. The reference answers `TypeError: 'x' is
5687                    // read-only`.
5688                    _ => {
5689                        return match on_failure {
5690                            DeleteFailure::Throw => {
5691                                Err(self.type_error(format!("'{key}' is read-only")))
5692                            }
5693                            DeleteFailure::Ignore => Ok(()),
5694                        };
5695                    }
5696                }
5697                return Ok(());
5698            }
5699            // A non-writable data property refuses the write, own **or inherited**: an
5700            // own one stops here because nothing may change it, and an inherited one
5701            // because §10.1.9.2 step 4 refuses to create the shadowing own property.
5702            //
5703            // The `ptr_eq` this used to carry meant an inherited read-only property fell
5704            // through to `define_data_key` and *did* create the shadow — `var o =
5705            // Object.create(Object.freeze({x: 1})); o.x = 9` answered `9` and
5706            // `o.hasOwnProperty('x')` answered `true`, where the reference answers `1`
5707            // and `false`.
5708            if !property.writable {
5709                return match on_failure {
5710                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
5711                    DeleteFailure::Ignore => Ok(()),
5712                };
5713            }
5714            // An existing writable own property keeps its attributes: only the value
5715            // moves. Redefining instead would reset them, which is how a
5716            // non-configurable global `var` used to become deletable.
5717            if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
5718                return Ok(());
5719            }
5720        }
5721        // No own data property: create one, shadowing whatever the prototype holds.
5722        object.define_data_key(key, value);
5723        Ok(())
5724    }
5725
5726    /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
5727    ///
5728    /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
5729    /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
5730    /// a virtual accessor gets its setter run without implementing `set_property` at all.
5731    /// Answering `Some(None)` from the hook does not end the search: the key may still be on
5732    /// the prototype, so the walk resumes above the object.
5733    fn lookup_for_write(
5734        &mut self,
5735        object: &Gc<JsObject>,
5736        key: &PropertyKey,
5737    ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
5738        let Some(exotic) = object.exotic() else {
5739            return Ok(lookup_key(object, key));
5740        };
5741        Ok(match exotic.get_own_property(self, object, key)? {
5742            Some(Some(property)) => Some((object.clone(), property)),
5743            Some(None) => lookup_key_above(object, key),
5744            None => lookup_key(object, key),
5745        })
5746    }
5747
5748    /// Delete `object[key]`.
5749    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
5750        self.delete_property_key(object, &PropertyKey::from(key))
5751    }
5752
5753    /// [`Interp::delete_property`] with a key that may be a symbol.
5754    pub fn delete_property_key(
5755        &mut self,
5756        object: &Gc<JsObject>,
5757        key: &PropertyKey,
5758    ) -> JsResult<bool> {
5759        // A proxy decides for itself, and may even throw; the invariant checks live in
5760        // `proxy_delete`.
5761        if let Some(answer) = self.proxy_delete(object, key)? {
5762            return Ok(answer);
5763        }
5764        // A host class's `delete_property` trap decides; `false` is a refusal, which the
5765        // caller reports as a failed delete.
5766        if let Some(exotic) = object.exotic()
5767            && let Some(answer) = exotic.delete_property(self, object, key)?
5768        {
5769            return Ok(answer);
5770        }
5771        let mapped_index = key.as_str().and_then(array_index);
5772        if let Some(index) = mapped_index
5773            && let Some(length) = object.array_length()
5774            && (index as usize) < length
5775        {
5776            // An accessor defined on an index lives in the property table rather than the
5777            // element vector, so both have to be cleared: `delete` after
5778            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
5779            object.delete_key(key);
5780            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
5781            // index stops answering `in`.
5782            if object.element_is_undeletable(index) {
5783                return Ok(false);
5784            }
5785            // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
5786            // so a later `defineProperty(arguments, "0", {value})` writes to the object
5787            // and no longer through to the parameter. A refused delete leaves the
5788            // mapping alone.
5789            object.drop_mapped_argument(index as usize);
5790            object.array_set(self.heap, index as usize, Value::Hole);
5791            return Ok(true);
5792        }
5793        // The same for an object that is not an array: only a delete that actually
5794        // removed the property ends the alias.
5795        let deleted = object.delete_key(key);
5796        if deleted && let Some(index) = mapped_index {
5797            object.drop_mapped_argument(index as usize);
5798        }
5799        Ok(deleted)
5800    }
5801
5802    // -- proxy traps --------------------------------------------------------
5803    //
5804    // A proxy's internal methods all look the same: ask the handler for the trap, call it
5805    // with the target and the operation's own arguments, then check the answer against
5806    // the target. The checks are not decoration — they are what stops a proxy from
5807    // reporting a `non-configurable` property as missing, which would let a frozen object
5808    // be rewritten by standing in front of it.
5809
5810    /// The target and handler of `object`, or `None` when it is not a proxy.
5811    ///
5812    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
5813    /// one has to fail: the slots the traps would have been read from are gone.
5814    fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
5815        let Some(state) = object.proxy_state() else {
5816            return Ok(None);
5817        };
5818        let state = state.borrow();
5819        match (&state.target, &state.handler) {
5820            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
5821            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
5822        }
5823    }
5824
5825    /// Call `handler[name]`, or answer `None` when the trap is absent.
5826    ///
5827    /// A trap that is present but not callable is a `TypeError` rather than "no trap":
5828    /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
5829    /// back to the target.
5830    fn proxy_trap(
5831        &mut self,
5832        handler: &Value,
5833        name: &str,
5834        args: Vec<Value>,
5835    ) -> JsResult<Option<Value>> {
5836        let Value::Object(table) = handler else {
5837            return Err(self.type_error("proxy handler is not an object"));
5838        };
5839        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
5840        match trap {
5841            Value::Undefined => Ok(None),
5842            Value::Object(function) if function.is_callable() => {
5843                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
5844                Ok(Some(answer))
5845            }
5846            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
5847        }
5848    }
5849
5850    /// Whether `object`'s own property `key` is one the target refuses to lose.
5851    ///
5852    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
5853    /// its value behind the target's back. This goes through
5854    /// [`Self::ordinary_own_property`] rather than the property table so that an array's
5855    /// elements and its `length` — both fixed, both outside the table — are covered.
5856    fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
5857        Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
5858    }
5859
5860    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
5861    fn proxy_get(
5862        &mut self,
5863        object: &Gc<JsObject>,
5864        receiver: &Value,
5865        key: &PropertyKey,
5866    ) -> JsResult<Option<Value>> {
5867        let Some((target, handler)) = self.proxy_parts(object)? else {
5868            return Ok(None);
5869        };
5870        let key_value = self.key_value(key);
5871        let Some(result) = self.proxy_trap(
5872            &handler,
5873            "get",
5874            vec![Value::Object(target.clone()), key_value, receiver.clone()],
5875        )?
5876        else {
5877            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
5878            // inherited getter still sees the proxy.
5879            return Ok(Some(
5880                self.get_property_key_for(&target, Some(receiver), key)?
5881                    .unwrap_or(Value::Undefined),
5882            ));
5883        };
5884        if let Some(fixed) = Self::is_fixed_property(&target, key) {
5885            if fixed.is_accessor() {
5886                // A fixed accessor with no getter must read as `undefined`.
5887                let has_getter = fixed
5888                    .getter
5889                    .as_ref()
5890                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
5891                if !has_getter && !matches!(result, Value::Undefined) {
5892                    return Err(self.type_error(format!(
5893                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
5894                    )));
5895                }
5896            } else if !fixed.writable {
5897                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5898                if !fixed_value.same_value(&result) {
5899                    return Err(self.type_error(format!(
5900                        "proxy 'get' disagrees with the non-configurable property '{key}'"
5901                    )));
5902                }
5903            }
5904        }
5905        Ok(Some(result))
5906    }
5907
5908    /// `[[Set]]` on a proxy.
5909    ///
5910    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
5911    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
5912    /// read-only store has.
5913    fn proxy_set(
5914        &mut self,
5915        object: &Gc<JsObject>,
5916        key: &PropertyKey,
5917        value: Value,
5918        receiver: &Value,
5919    ) -> JsResult<Option<bool>> {
5920        let Some((target, handler)) = self.proxy_parts(object)? else {
5921            return Ok(None);
5922        };
5923        let key_value = self.key_value(key);
5924        let Some(result) = self.proxy_trap(
5925            &handler,
5926            "set",
5927            vec![
5928                Value::Object(target.clone()),
5929                key_value,
5930                value.clone(),
5931                receiver.clone(),
5932            ],
5933        )?
5934        else {
5935            // No trap: store on the target, which is where an ordinary proxy write lands.
5936            self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
5937            return Ok(Some(true));
5938        };
5939        if !result.to_boolean() {
5940            return Ok(Some(false));
5941        }
5942        if let Some(fixed) = Self::is_fixed_property(&target, key) {
5943            if fixed.is_accessor() {
5944                let has_setter = fixed
5945                    .setter
5946                    .as_ref()
5947                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
5948                if !has_setter {
5949                    return Err(self.type_error(format!(
5950                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
5951                    )));
5952                }
5953            } else if !fixed.writable {
5954                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5955                if !fixed_value.same_value(&value) {
5956                    return Err(self.type_error(format!(
5957                        "proxy 'set' changed the non-configurable property '{key}'"
5958                    )));
5959                }
5960            }
5961        }
5962        // A new property cannot appear on a target that refuses new properties.
5963        if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
5964            return Err(self.type_error(format!(
5965                "proxy 'set' added '{key}' to a non-extensible target"
5966            )));
5967        }
5968        Ok(Some(true))
5969    }
5970
5971    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
5972    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5973        let Some((target, handler)) = self.proxy_parts(object)? else {
5974            return Ok(None);
5975        };
5976        let key_value = self.key_value(key);
5977        let Some(result) = self.proxy_trap(
5978            &handler,
5979            "has",
5980            vec![Value::Object(target.clone()), key_value],
5981        )?
5982        else {
5983            return Ok(Some(self.has_own_or_inherited(&target, key)?));
5984        };
5985        if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5986            return Err(self.type_error(format!(
5987                "proxy 'has' denied the non-configurable property '{key}'"
5988            )));
5989        }
5990        // A non-extensible target cannot grow, so every own property it *has* is fixed.
5991        if !result.to_boolean()
5992            && !target.is_extensible()
5993            && Self::ordinary_own_property(&target, key).is_some()
5994        {
5995            return Err(self.type_error(format!(
5996                "proxy 'has' denied the own property '{key}' of a non-extensible target"
5997            )));
5998        }
5999        Ok(Some(result.to_boolean()))
6000    }
6001
6002    /// `[[Delete]]` on a proxy.
6003    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6004        let Some((target, handler)) = self.proxy_parts(object)? else {
6005            return Ok(None);
6006        };
6007        let key_value = self.key_value(key);
6008        let Some(result) = self.proxy_trap(
6009            &handler,
6010            "deleteProperty",
6011            vec![Value::Object(target.clone()), key_value],
6012        )?
6013        else {
6014            return Ok(Some(self.delete_property_key(&target, key)?));
6015        };
6016        if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
6017            return Err(self.type_error(format!(
6018                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
6019            )));
6020        }
6021        if result.to_boolean()
6022            && !target.is_extensible()
6023            && Self::ordinary_own_property(&target, key).is_some()
6024        {
6025            return Err(self.type_error(format!(
6026                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
6027            )));
6028        }
6029        Ok(Some(result.to_boolean()))
6030    }
6031
6032    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
6033    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
6034        let Some((target, handler)) = self.proxy_parts(object)? else {
6035            return Ok(None);
6036        };
6037        let Some(result) =
6038            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
6039        else {
6040            // No trap: the target's own keys, already in the order an object reports.
6041            return Ok(Some(self.object_own_property_keys(&target)?));
6042        };
6043        // `CreateListFromArrayLike` with the string-or-symbol restriction.
6044        let list = self.list_from_array_like(&result, true)?;
6045        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
6046        for value in list {
6047            let key = self.propkey(&value)?;
6048            if keys.contains(&key) {
6049                return Err(self.type_error(format!(
6050                    "proxy 'ownKeys' returned the duplicate key '{key}'"
6051                )));
6052            }
6053            keys.push(key);
6054        }
6055        for (key, property) in target.property_entries() {
6056            if !property.configurable && !keys.contains(&key) {
6057                return Err(self.type_error(format!(
6058                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
6059                )));
6060            }
6061            if !target.is_extensible() && !keys.contains(&key) {
6062                return Err(self.type_error(format!(
6063                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
6064                )));
6065            }
6066        }
6067        if !target.is_extensible() {
6068            let own = target.property_entries().len();
6069            if keys.len() != own {
6070                return Err(
6071                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
6072                );
6073            }
6074        }
6075        Ok(Some(keys))
6076    }
6077
6078    /// `[[GetOwnProperty]]` on a proxy.
6079    fn proxy_get_own_property(
6080        &mut self,
6081        object: &Gc<JsObject>,
6082        key: &PropertyKey,
6083    ) -> JsResult<Option<Option<Property>>> {
6084        let Some((target, handler)) = self.proxy_parts(object)? else {
6085            return Ok(None);
6086        };
6087        let key_value = self.key_value(key);
6088        let Some(result) = self.proxy_trap(
6089            &handler,
6090            "getOwnPropertyDescriptor",
6091            vec![Value::Object(target.clone()), key_value],
6092        )?
6093        else {
6094            // No trap: the target's own descriptor is the answer. This has to go through
6095            // the same synthesis an ordinary object gets, because a proxy's own property
6096            // table is empty by design — reading it directly reported `undefined` for
6097            // every key, including an array's indices and `length`.
6098            return Ok(Some(Self::ordinary_own_property(&target, key)));
6099        };
6100        let answer = if matches!(result, Value::Undefined) {
6101            None
6102        } else {
6103            Some(self.property_from_descriptor(&result)?)
6104        };
6105        let fixed = Self::is_fixed_property(&target, key);
6106        match (&answer, &fixed) {
6107            // A non-configurable property cannot be reported as absent.
6108            (None, Some(_)) => {
6109                return Err(self.type_error(format!(
6110                    "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
6111                )));
6112            }
6113            (Some(descriptor), Some(fixed)) => {
6114                if descriptor.configurable {
6115                    return Err(self.type_error(format!(
6116                        "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
6117                    )));
6118                }
6119                if fixed.is_accessor() != descriptor.is_accessor() {
6120                    return Err(self.type_error(format!(
6121                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6122                    )));
6123                }
6124                if !fixed.is_accessor() && !fixed.writable {
6125                    let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
6126                    let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
6127                    if !fixed_value.same_value(&reported) {
6128                        return Err(self.type_error(format!(
6129                            "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
6130                        )));
6131                    }
6132                }
6133            }
6134            _ => {}
6135        }
6136        Ok(Some(answer))
6137    }
6138
6139    /// `[[DefineOwnProperty]]` on a proxy.
6140    fn proxy_define_property(
6141        &mut self,
6142        object: &Gc<JsObject>,
6143        key: &PropertyKey,
6144        property: Property,
6145    ) -> JsResult<Option<bool>> {
6146        let Some((target, handler)) = self.proxy_parts(object)? else {
6147            return Ok(None);
6148        };
6149        let key_value = self.key_value(key);
6150        let descriptor = self.descriptor_from_property(&property);
6151        let Some(result) = self.proxy_trap(
6152            &handler,
6153            "defineProperty",
6154            vec![Value::Object(target.clone()), key_value, descriptor],
6155        )?
6156        else {
6157            return Ok(None);
6158        };
6159        if !result.to_boolean() {
6160            return Ok(Some(false));
6161        }
6162        let fixed = Self::is_fixed_property(&target, key);
6163        let creating = Self::ordinary_own_property(&target, key).is_none();
6164        if creating && !target.is_extensible() {
6165            return Err(self.type_error(format!(
6166                "proxy 'defineProperty' added '{key}' to a non-extensible target"
6167            )));
6168        }
6169        if let Some(fixed) = fixed {
6170            if property.configurable {
6171                return Err(self.type_error(format!(
6172                    "proxy 'defineProperty' made the non-configurable '{key}' configurable"
6173                )));
6174            }
6175            if !fixed.writable && property.writable && !fixed.is_accessor() {
6176                return Err(self.type_error(format!(
6177                    "proxy 'defineProperty' made the read-only '{key}' writable"
6178                )));
6179            }
6180        }
6181        Ok(Some(true))
6182    }
6183
6184    /// `[[GetPrototypeOf]]` on a proxy.
6185    fn proxy_get_prototype_of(
6186        &mut self,
6187        object: &Gc<JsObject>,
6188    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
6189        let Some((target, handler)) = self.proxy_parts(object)? else {
6190            return Ok(None);
6191        };
6192        let Some(result) = self.proxy_trap(
6193            &handler,
6194            "getPrototypeOf",
6195            vec![Value::Object(target.clone())],
6196        )?
6197        else {
6198            return Ok(Some(target.proto()));
6199        };
6200        let proto = match &result {
6201            Value::Null => None,
6202            Value::Object(proto) => Some(proto.clone()),
6203            _ => {
6204                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
6205            }
6206        };
6207        if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
6208            return Err(self.type_error(
6209                "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
6210            ));
6211        }
6212        Ok(Some(proto))
6213    }
6214
6215    /// `[[SetPrototypeOf]]` on a proxy.
6216    fn proxy_set_prototype_of(
6217        &mut self,
6218        object: &Gc<JsObject>,
6219        proto: Option<Gc<JsObject>>,
6220    ) -> JsResult<Option<bool>> {
6221        let Some((target, handler)) = self.proxy_parts(object)? else {
6222            return Ok(None);
6223        };
6224        let proto_value = match &proto {
6225            Some(proto) => Value::Object(proto.clone()),
6226            None => Value::Null,
6227        };
6228        let Some(result) = self.proxy_trap(
6229            &handler,
6230            "setPrototypeOf",
6231            vec![Value::Object(target.clone()), proto_value],
6232        )?
6233        else {
6234            target.set_proto(proto);
6235            return Ok(Some(true));
6236        };
6237        if result.to_boolean()
6238            && !target.is_extensible()
6239            && !same_proto(proto.as_ref(), target.proto().as_ref())
6240        {
6241            return Err(self.type_error(
6242                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
6243            ));
6244        }
6245        Ok(Some(result.to_boolean()))
6246    }
6247
6248    /// `[[IsExtensible]]` on a proxy.
6249    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6250        let Some((target, handler)) = self.proxy_parts(object)? else {
6251            return Ok(None);
6252        };
6253        let Some(result) = self.proxy_trap(
6254            &handler,
6255            "isExtensible",
6256            vec![Value::Object(target.clone())],
6257        )?
6258        else {
6259            return Ok(Some(target.is_extensible()));
6260        };
6261        // The answer is not the proxy's to invent: it must agree with the target, or a
6262        // script could learn `false` while the target keeps accepting new properties.
6263        if result.to_boolean() != target.is_extensible() {
6264            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
6265        }
6266        Ok(Some(result.to_boolean()))
6267    }
6268
6269    /// `[[PreventExtensions]]` on a proxy.
6270    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6271        let Some((target, handler)) = self.proxy_parts(object)? else {
6272            return Ok(None);
6273        };
6274        let Some(result) = self.proxy_trap(
6275            &handler,
6276            "preventExtensions",
6277            vec![Value::Object(target.clone())],
6278        )?
6279        else {
6280            target.set_extensible(false);
6281            return Ok(Some(true));
6282        };
6283        if result.to_boolean() && target.is_extensible() {
6284            return Err(self.type_error(
6285                "proxy 'preventExtensions' reported success but the target is still extensible",
6286            ));
6287        }
6288        Ok(Some(result.to_boolean()))
6289    }
6290
6291    /// `[[Call]]` on a proxy, through the `apply` trap.
6292    fn proxy_apply(
6293        &mut self,
6294        object: &Gc<JsObject>,
6295        this: Value,
6296        args: Vec<Value>,
6297    ) -> JsResult<Option<Value>> {
6298        let Some((target, handler)) = self.proxy_parts(object)? else {
6299            return Ok(None);
6300        };
6301        // The trap gets the arguments as one array, which is the shape the spec passes
6302        // and the shape `apply` traps are written against (`args[0]` is the first one).
6303        let arguments = self.new_array(args.clone());
6304        let this_for_trap = this.clone();
6305        let Some(result) = self.proxy_trap(
6306            &handler,
6307            "apply",
6308            vec![
6309                Value::Object(target.clone()),
6310                this_for_trap,
6311                Value::Object(arguments),
6312            ],
6313        )?
6314        else {
6315            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
6316        };
6317        Ok(Some(result))
6318    }
6319
6320    /// `[[Construct]]` on a proxy, through the `construct` trap.
6321    fn proxy_construct(
6322        &mut self,
6323        object: &Gc<JsObject>,
6324        args: Vec<Value>,
6325        new_target: &Value,
6326    ) -> JsResult<Option<Value>> {
6327        let Some((target, handler)) = self.proxy_parts(object)? else {
6328            return Ok(None);
6329        };
6330        if !target.is_callable() {
6331            return Err(self.type_error("proxy target is not a constructor"));
6332        }
6333        let arguments = self.new_array(args.clone());
6334        let Some(result) = self.proxy_trap(
6335            &handler,
6336            "construct",
6337            vec![
6338                Value::Object(target.clone()),
6339                Value::Object(arguments),
6340                new_target.clone(),
6341            ],
6342        )?
6343        else {
6344            return Ok(Some(self.construct(
6345                Value::Object(target),
6346                new_target.clone(),
6347                args,
6348            )?));
6349        };
6350        if !matches!(result, Value::Object(_)) {
6351            return Err(self.type_error("proxy 'construct' must return an object"));
6352        }
6353        Ok(Some(result))
6354    }
6355
6356    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
6357    pub(crate) fn has_own_or_inherited(
6358        &mut self,
6359        object: &Gc<JsObject>,
6360        key: &PropertyKey,
6361    ) -> JsResult<bool> {
6362        // The object itself first: it may be a proxy, and then the answer is its trap's.
6363        if let Some(answer) = self.proxy_has(object, key)? {
6364            return Ok(answer);
6365        }
6366        // An integer-indexed exotic object answers a canonical numeric index from
6367        // `IsValidIntegerIndex` alone (§10.4.5.4 step 1.b.i) — **without** walking the
6368        // prototype chain. That is observable: a view the buffer has been resized away from
6369        // has no indices, so `2 in view` is `false` even when
6370        // `Object.getPrototypeOf(view)[2]` exists. Falling through to the chain answered
6371        // `true`, which is what `TypedArray/out-of-bounds-behaves-like-detached` catches.
6372        // The `[[HasProperty]]` that `in` compiles to goes through here, which is why the
6373        // same rule is repeated in `has_property_key` rather than living only there.
6374        if object.typed_array_parts().is_some()
6375            && let Some(index) = key.as_str().and_then(array_index)
6376        {
6377            return Ok(object
6378                .typed_array_length()
6379                .is_some_and(|length| (index as usize) < length));
6380        }
6381        // A host class answers `in` for its own keys, which may live nowhere in a property
6382        // table — `"x" in point` is true because the class says so, not because a property
6383        // exists.
6384        if let Some(exotic) = object.exotic()
6385            && let Some(answer) = exotic.has_property(self, object, key)?
6386        {
6387            return Ok(answer);
6388        }
6389        // `has_own` rather than `own_property_key`: an array's elements and its derived
6390        // `length` are invisible to the property table, and `Array.prototype` is an array.
6391        // A host class's `get_own_property` counts too, because the reference's
6392        // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
6393        // lives — a class with only `get_own_property` answers `in` through it.
6394        if self.exotic_has_own(object, key)? {
6395            return Ok(true);
6396        }
6397        // A hole is *not* the end of the search: the chain may still have the key, which
6398        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
6399        for ancestor in object.chain() {
6400            // A proxy further up the chain answers for itself.
6401            if let Some(answer) = self.proxy_has(&ancestor, key)? {
6402                return Ok(answer);
6403            }
6404            // Same for a host class: a prototype may be one, and `in` reaches it.
6405            if let Some(exotic) = ancestor.exotic()
6406                && let Some(answer) = exotic.has_property(self, &ancestor, key)?
6407            {
6408                return Ok(answer);
6409            }
6410            if self.exotic_has_own(&ancestor, key)? {
6411                return Ok(true);
6412            }
6413        }
6414        Ok(false)
6415    }
6416
6417    /// Whether `object` reports `key` as an own property, its class's `get_own_property`
6418    /// trap included.
6419    ///
6420    /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
6421    /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
6422    fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
6423        if let Some(exotic) = object.exotic()
6424            && let Some(answer) = exotic.get_own_property(self, object, key)?
6425        {
6426            return Ok(answer.is_some());
6427        }
6428        Ok(has_own(object, key))
6429    }
6430
6431    /// `CreateListFromArrayLike`, optionally restricted to property keys.
6432    ///
6433    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
6434    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
6435    /// `TypeError` instead of a property named `"1.5"`.
6436    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
6437        let object = self.object_from(value)?;
6438        let length = self
6439            .get_property(&object, "length")?
6440            .map(|value| value.to_number())
6441            .unwrap_or(0.0);
6442        if !length.is_finite() || length < 0.0 {
6443            return Err(self.type_error("invalid array-like length"));
6444        }
6445        let length = length as usize;
6446        let mut items = Vec::with_capacity(length.min(1024));
6447        for index in 0..length {
6448            let item = self
6449                .get_property(&object, &index.to_string())?
6450                .unwrap_or(Value::Undefined);
6451            if keys_only && matches!(&item, Value::Symbol(_)) {
6452                items.push(item);
6453                continue;
6454            }
6455            if keys_only && !matches!(&item, Value::String(_)) {
6456                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
6457            }
6458            items.push(item);
6459        }
6460        Ok(items)
6461    }
6462
6463    /// A `Property` from the descriptor object a trap returned.
6464    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
6465        let object = self.object_from(value)?;
6466        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
6467            interp.get_property(&object, name)
6468        };
6469        let getter = field(self, "get")?;
6470        let setter = field(self, "set")?;
6471        let accessor = getter.is_some() || setter.is_some();
6472        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
6473            Ok(interp
6474                .get_property(&object, name)?
6475                .is_some_and(|value| value.to_boolean()))
6476        };
6477        let enumerable = boolean(self, "enumerable")?;
6478        let configurable = boolean(self, "configurable")?;
6479        if accessor {
6480            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
6481                return Err(
6482                    self.type_error("a descriptor cannot be both a data property and an accessor")
6483                );
6484            }
6485            Ok(Property {
6486                getter: getter.or(Some(Value::Undefined)),
6487                setter: setter.or(Some(Value::Undefined)),
6488                enumerable,
6489                configurable,
6490                writable: false,
6491                value: None,
6492            })
6493        } else {
6494            Ok(Property {
6495                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
6496                writable: boolean(self, "writable")?,
6497                enumerable,
6498                configurable,
6499                getter: None,
6500                setter: None,
6501            })
6502        }
6503    }
6504
6505    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
6506    fn descriptor_from_property(&mut self, property: &Property) -> Value {
6507        let object = self.new_object(None);
6508        if property.is_accessor() {
6509            let getter = property.getter.clone().unwrap_or(Value::Undefined);
6510            let setter = property.setter.clone().unwrap_or(Value::Undefined);
6511            object.define_data("get", getter);
6512            object.define_data("set", setter);
6513        } else {
6514            let value = property.value.clone().unwrap_or(Value::Undefined);
6515            object.define_data("value", value);
6516            object.define_data("writable", Value::Bool(property.writable));
6517        }
6518        object.define_data("enumerable", Value::Bool(property.enumerable));
6519        object.define_data("configurable", Value::Bool(property.configurable));
6520        Value::Object(object)
6521    }
6522
6523    // -- calling ------------------------------------------------------------
6524
6525    /// Call `callee` with `this` and `args`.
6526    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
6527        let Value::Object(function) = &callee else {
6528            // `typeof x === "function"` is not enough to make `x()` legal: only a
6529            // callable object is. `null` and `undefined` need no special wording
6530            // here — their `ToString` already reads the way the reference's does.
6531            let what = format!("{} is not a function", callee.to_js_string());
6532            return Err(Signal::Throw(self.make_error("TypeError", &what)));
6533        };
6534        // A proxy of a function is called through its `apply` trap. It has no
6535        // `ObjectKind::Function` of its own, so this has to come before the dispatch
6536        // below, and a proxy of a non-function has nothing to forward to.
6537        if function.proxy_state().is_some() {
6538            return match self.proxy_apply(function, this, args)? {
6539                Some(result) => Ok(result),
6540                None => Err(Signal::Throw(
6541                    self.make_error("TypeError", "proxy target is not callable"),
6542                )),
6543            };
6544        }
6545        let callable = function.with(|data| match &data.kind {
6546            ObjectKind::Function(callable) => match callable {
6547                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
6548                // The `Rc` is cloned out so the borrow of this object's data is released
6549                // before the closure runs: the closure may touch the same object.
6550                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
6551                Callable::Bound {
6552                    target,
6553                    this,
6554                    args: leading,
6555                } => Some(NativeCall::Bound {
6556                    target: target.clone(),
6557                    this: this.clone(),
6558                    leading: leading.clone(),
6559                }),
6560                Callable::Bytecode { code, env } => {
6561                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
6562                }
6563                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
6564                Callable::PromiseResolve(promise) => {
6565                    Some(NativeCall::PromiseResolve(promise.clone()))
6566                }
6567                Callable::PromiseReject(promise) => {
6568                    Some(NativeCall::PromiseReject(promise.clone()))
6569                }
6570                Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
6571                    state: state.clone(),
6572                }),
6573                Callable::ThenShim {
6574                    handler,
6575                    resolve,
6576                    reject,
6577                    fulfilled,
6578                } => Some(NativeCall::ThenShim {
6579                    handler: handler.clone(),
6580                    resolve: resolve.clone(),
6581                    reject: reject.clone(),
6582                    fulfilled: *fulfilled,
6583                }),
6584                Callable::AwaitResume {
6585                    coroutine,
6586                    promise,
6587                    kind,
6588                } => Some(NativeCall::AwaitResume {
6589                    coroutine: coroutine.clone(),
6590                    promise: promise.clone(),
6591                    kind: *kind,
6592                }),
6593                Callable::CombinatorSettle {
6594                    state,
6595                    index,
6596                    fulfilled,
6597                } => Some(NativeCall::CombinatorSettle {
6598                    state: state.clone(),
6599                    index: *index,
6600                    fulfilled: *fulfilled,
6601                }),
6602                Callable::FinallyShim {
6603                    callback,
6604                    fulfilled,
6605                    constructor,
6606                } => Some(NativeCall::FinallyShim {
6607                    callback: callback.clone(),
6608                    fulfilled: *fulfilled,
6609                    constructor: constructor.clone(),
6610                }),
6611                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
6612                Callable::CompletedReturn {
6613                    generator,
6614                    promise,
6615                    rejected,
6616                } => Some(NativeCall::CompletedReturn {
6617                    generator: generator.clone(),
6618                    promise: promise.clone(),
6619                    rejected: *rejected,
6620                }),
6621                Callable::YieldResult {
6622                    generator,
6623                    promise,
6624                    done,
6625                } => Some(NativeCall::YieldResult {
6626                    generator: generator.clone(),
6627                    promise: promise.clone(),
6628                    done: *done,
6629                }),
6630                Callable::DisposeStep {
6631                    remaining,
6632                    promise,
6633                    error,
6634                    rejected,
6635                } => Some(NativeCall::DisposeStep {
6636                    remaining: remaining.clone(),
6637                    promise: promise.clone(),
6638                    error: error.clone(),
6639                    rejected: *rejected,
6640                }),
6641                Callable::GeneratorResume {
6642                    generator,
6643                    promise,
6644                    kind,
6645                } => Some(NativeCall::GeneratorResume {
6646                    generator: generator.clone(),
6647                    promise: promise.clone(),
6648                    kind: *kind,
6649                }),
6650                Callable::SettlePromise {
6651                    promise,
6652                    value,
6653                    rejected,
6654                } => Some(NativeCall::SettlePromise {
6655                    promise: promise.clone(),
6656                    value: value.clone(),
6657                    rejected: *rejected,
6658                }),
6659            },
6660            _ => None,
6661        });
6662        match callable {
6663            Some(NativeCall::Host(func)) => {
6664                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
6665                // function by name rather than stopping at the caller.
6666                let frame_less = function
6667                    .own_property("_frame_less")
6668                    .and_then(|property| property.value)
6669                    .is_some_and(|value| value.to_boolean());
6670                let outer = if frame_less {
6671                    None
6672                } else {
6673                    self.native_frames
6674                        .push((function.clone(), self.frames.len()));
6675                    Some(self.current_native.replace(function.clone()))
6676                };
6677                let result = {
6678                    let mut body = func.borrow_mut();
6679                    body(self, this, &args)
6680                };
6681                if !frame_less {
6682                    self.native_frames.pop();
6683                    self.current_native = outer.flatten();
6684                }
6685                result
6686            }
6687            Some(NativeCall::Native(func)) => {
6688                // A function marked `_frame_less` is one the reference implements
6689                // without a call frame — `eval` is the only one so far.
6690                let frame_less = function
6691                    .own_property("_frame_less")
6692                    .and_then(|property| property.value)
6693                    .is_some_and(|value| value.to_boolean());
6694                let outer = if frame_less {
6695                    None
6696                } else {
6697                    self.native_frames
6698                        .push((function.clone(), self.frames.len()));
6699                    Some(self.current_native.replace(function.clone()))
6700                };
6701                let result = func(self, this, &args);
6702                if !frame_less {
6703                    self.native_frames.pop();
6704                    self.current_native = outer.flatten();
6705                }
6706                result
6707            }
6708            Some(NativeCall::Revoker(slots)) => {
6709                // Idempotent: revoking twice answers `undefined` again rather than
6710                // complaining, which is what the spec says and what a `finally` block
6711                // relies on.
6712                let mut state = slots.borrow_mut();
6713                state.target = None;
6714                state.handler = None;
6715                Ok(Value::Undefined)
6716            }
6717            Some(NativeCall::PromiseResolve(promise)) => {
6718                // One-shot: a second call is silently ignored, which
6719                // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
6720                let value = args.first().cloned().unwrap_or(Value::Undefined);
6721                self.resolve_promise_with(&promise, value)?;
6722                Ok(Value::Undefined)
6723            }
6724            Some(NativeCall::PromiseReject(promise)) => {
6725                let reason = args.first().cloned().unwrap_or(Value::Undefined);
6726                self.reject_promise(&promise, reason);
6727                Ok(Value::Undefined)
6728            }
6729            Some(NativeCall::ThenShim {
6730                handler,
6731                resolve,
6732                reject,
6733                fulfilled,
6734            }) => {
6735                // `PerformPromiseThen` with a capability: run the handler, then settle
6736                // through the capability's own pair. A throw from the handler is the
6737                // rejection, and a throw from the capability's `resolve` is not caught —
6738                // exactly the spec's `?`.
6739                let value = args.first().cloned().unwrap_or(Value::Undefined);
6740                match handler {
6741                    Some(handler) => {
6742                        match self.call_value(handler, Value::Undefined, vec![value]) {
6743                            Ok(result) => {
6744                                self.call_value(resolve, Value::Undefined, vec![result])?;
6745                            }
6746                            Err(Signal::Throw(reason)) => {
6747                                self.call_value(reject, Value::Undefined, vec![reason])?;
6748                            }
6749                            Err(signal) => return Err(signal),
6750                        }
6751                    }
6752                    None => {
6753                        let handler = if fulfilled { resolve } else { reject };
6754                        self.call_value(handler, Value::Undefined, vec![value])?;
6755                    }
6756                }
6757                Ok(Value::Undefined)
6758            }
6759            Some(NativeCall::CapabilityExecutor { state }) => {
6760                // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
6761                // slot holds a value yet. The test is on the *values*, not on a call count —
6762                // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
6763                // called-twice`'s first case does exactly that), while a second call after a
6764                // real pair is the `TypeError`.
6765                let defined = |name: &str| {
6766                    state
6767                        .own_property(name)
6768                        .and_then(|property| property.value)
6769                        .is_some_and(|value| !matches!(value, Value::Undefined))
6770                };
6771                if defined("resolve") || defined("reject") {
6772                    return Err(self.type_error("promise capability executor called twice"));
6773                }
6774                let resolve = args.first().cloned().unwrap_or(Value::Undefined);
6775                let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
6776                state.define_data("resolve", resolve);
6777                state.define_data("reject", reject);
6778                Ok(Value::Undefined)
6779            }
6780            Some(NativeCall::CombinatorSettle {
6781                state,
6782                index,
6783                fulfilled,
6784            }) => {
6785                let value = args.first().cloned().unwrap_or(Value::Undefined);
6786                self.settle_combinator(&state, index, fulfilled, value)?;
6787                Ok(Value::Undefined)
6788            }
6789            Some(NativeCall::AwaitResume {
6790                coroutine,
6791                promise,
6792                kind,
6793            }) => {
6794                // Resume *inline*, in the reaction that delivered the value. Deferring it
6795                // by another job inserts a tick between every `await` and its
6796                // continuation, which reorders `await` against unrelated `then` chains —
6797                // `f().then(g)` then runs before `f`'s own next statement.
6798                self.drive_async(
6799                    &coroutine,
6800                    &promise,
6801                    kind,
6802                    args.first().cloned().unwrap_or(Value::Undefined),
6803                )
6804                .map(|()| Value::Undefined)
6805            }
6806            Some(NativeCall::FinallyShim {
6807                callback,
6808                fulfilled,
6809                constructor,
6810            }) => {
6811                // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
6812                // that settles with the *original* outcome once the callback's result has
6813                // settled. The callback's own value is discarded — that is the whole
6814                // difference between `finally` and `then`.
6815                let original = args.first().cloned().unwrap_or(Value::Undefined);
6816                let result = match &callback {
6817                    Some(callback) => {
6818                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
6819                    }
6820                    None => Value::Undefined,
6821                };
6822                // `PromiseResolve(C, result)`, not the intrinsic: a `result` that is
6823                // already a promise of this constructor is reused rather than rewrapped.
6824                let resolved = self.promise_resolve_for(&constructor, result)?;
6825                let Value::Object(resolved) = resolved else {
6826                    return Ok(original);
6827                };
6828                // The wait is a chained promise rather than a bare return, so a callback
6829                // that returns a slow promise really does delay the continuation.
6830                let waiting = self.new_promise();
6831                let pass = JsObject::function(
6832                    self.heap,
6833                    Some(self.realm.function_proto.clone()),
6834                    Callable::SettlePromise {
6835                        promise: waiting.clone(),
6836                        value: original,
6837                        rejected: !fulfilled,
6838                    },
6839                );
6840                let pass = Value::Object(pass);
6841                // Whichever way the callback's promise settles, the original outcome wins.
6842                self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
6843                Ok(Value::Object(waiting))
6844            }
6845            Some(NativeCall::DisposeStep {
6846                remaining,
6847                promise,
6848                error,
6849                rejected,
6850            }) => {
6851                let error = if rejected {
6852                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
6853                    self.merge_dispose_error(reason, error)
6854                } else {
6855                    error
6856                };
6857                self.dispose_step(&remaining, &promise, error)?;
6858                Ok(Value::Undefined)
6859            }
6860            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
6861            Some(NativeCall::CompletedReturn {
6862                generator,
6863                promise,
6864                rejected,
6865            }) => {
6866                let value = args.first().cloned().unwrap_or(Value::Undefined);
6867                let outcome = if rejected {
6868                    AsyncOutcome::Error(value)
6869                } else {
6870                    AsyncOutcome::Value(self.iterator_result(value, true)?)
6871                };
6872                self.settle_async_request(&generator, &promise, outcome)?;
6873                Ok(Value::Undefined)
6874            }
6875            Some(NativeCall::YieldResult {
6876                generator,
6877                promise,
6878                done,
6879            }) => {
6880                let value = args.first().cloned().unwrap_or(Value::Undefined);
6881                let result = self.iterator_result(value, done)?;
6882                self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
6883                Ok(Value::Undefined)
6884            }
6885            Some(NativeCall::GeneratorResume {
6886                generator,
6887                promise,
6888                kind,
6889            }) => {
6890                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
6891                // tick and reorders the generator against other chains.
6892                self.step_async_generator(
6893                    &generator,
6894                    &promise,
6895                    kind,
6896                    args.first().cloned().unwrap_or(Value::Undefined),
6897                )
6898                .map(|()| Value::Undefined)
6899            }
6900            Some(NativeCall::SettlePromise {
6901                promise,
6902                value,
6903                rejected,
6904            }) => {
6905                if rejected {
6906                    self.reject_promise(&promise, value);
6907                } else {
6908                    self.fulfill_promise(&promise, value);
6909                }
6910                Ok(Value::Undefined)
6911            }
6912            Some(NativeCall::Bound {
6913                target,
6914                this: bound_this,
6915                leading,
6916            }) => {
6917                let mut all = leading;
6918                all.extend(args);
6919                self.call_value(target, bound_this, all)
6920            }
6921            Some(NativeCall::Bytecode(code, env)) => {
6922                if code.code.kind.is_generator() {
6923                    return self.new_generator(callee, this, args);
6924                }
6925                if code.code.kind.is_async() {
6926                    // Same coroutine machinery as a generator; the difference is only in
6927                    // what the completion does — see `new_async_function`.
6928                    return self.new_async_function(callee, this, args);
6929                }
6930                self.execute(code, env, this, args, callee)
6931            }
6932            None => Err(Signal::Throw(
6933                self.make_error("TypeError", "not a function"),
6934            )),
6935        }
6936    }
6937
6938    /// Give a freshly built function its own `prototype` object.
6939    ///
6940    /// Every function that can be used with `new` carries one, and its
6941    /// `constructor` points back at the function — a reference cycle, which is
6942    /// exactly what the collector's cycle pass exists to reclaim.
6943    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
6944        let prototype = self.new_object(Some(self.realm.object_proto.clone()));
6945        let constructor = Value::Object(function.clone());
6946        prototype.define(
6947            "constructor",
6948            Property::with_attributes(constructor, true, false),
6949        );
6950        let value = Value::Object(prototype);
6951        function.define("prototype", Property::prototype_of(value, true));
6952    }
6953
6954    /// A getter or setter that reads or writes the reference cell behind a mapped
6955    /// `arguments` index.
6956    ///
6957    /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
6958    /// count — which is what the collector treats as "a reference from outside the
6959    /// heap". The closure therefore keeps the cell alive for exactly as long as the
6960    /// accessor is reachable, which is the same lifetime the arguments object has.
6961    ///
6962    /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
6963    /// borrow would not be reclaimed; that is acceptable here because the cell holds a
6964    /// parameter value and the arguments object reaches the closure, never the other
6965    /// way round. Nothing the collector has to see is hidden.
6966    fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
6967        let name = if is_setter { "set" } else { "get" };
6968        let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
6969            if is_setter {
6970                cell.set(args.first().cloned().unwrap_or(Value::Undefined));
6971                Ok(Value::Undefined)
6972            } else {
6973                Ok(cell.get())
6974            }
6975        };
6976        self.new_host_function(name, 1, Box::new(func))
6977    }
6978
6979    /// The object `special_object` builds.
6980    ///
6981    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
6982    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
6983    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
6984    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
6985    /// write through `arguments` does not reach the parameter.
6986    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
6987        match magic {
6988            0 | 1 => {
6989                let args = self.frame().passed().to_vec();
6990                let proto = self.realm.object_proto.clone();
6991                let object = self.new_object(Some(proto));
6992                // The marker `Object.prototype.toString` needs: an arguments object is an
6993                // ordinary object apart from reporting `[object Arguments]`, and that has
6994                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
6995                // show up ahead of them in a key listing anyway — it is non-enumerable.
6996                self.internal_set(&object, "_class", self.string("Arguments"));
6997                // `length` is writable and configurable but neither enumerable nor a
6998                // plain data property: `Object.keys(arguments)` lists the indices only,
6999                // which is how `{...arguments}` copies them without the length.
7000                object.define(
7001                    "length",
7002                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
7003                );
7004                // `magic == 1` is sloppy mode, where each index is *mapped* to the
7005                // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
7006                // change `a`, and assigning `a` has to change `arguments[0]`.
7007                //
7008                // The shared storage is the parameter's reference cell. The compiler
7009                // gives every parameter of such a function one (see
7010                // `provide_body_arguments`), and the cell outlives the frame, so this
7011                // keeps working after the arguments object escapes.
7012                //
7013                // The index becomes an accessor rather than a data property. A mapped
7014                // index reports as a plain writable/enumerable data property through
7015                // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
7016                // the getter/setter pair is only the plumbing underneath.
7017                let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
7018                    let frame = self.frame();
7019                    frame
7020                        .code
7021                        .arg_cell
7022                        .iter()
7023                        .map(|cell| {
7024                            (*cell >= 0)
7025                                .then(|| frame.cells.get(*cell as usize).cloned())
7026                                .flatten()
7027                        })
7028                        .collect()
7029                } else {
7030                    Vec::new()
7031                };
7032                // Tell the object which indices are mapped, so
7033                // `Object.getOwnPropertyDescriptor` can report them as the data
7034                // properties the spec describes instead of the accessors that
7035                // implement the aliasing.
7036                if magic == 1 {
7037                    let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
7038                    for cell in &mapped_cells {
7039                        table.push(cell.clone());
7040                    }
7041                    object.set_mapped_arguments(table);
7042                }
7043                for (index, value) in args.into_iter().enumerate() {
7044                    match mapped_cells.get(index).cloned().flatten() {
7045                        Some(cell) => {
7046                            let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
7047                            let setter = self.new_mapped_arguments_accessor(cell, true);
7048                            object.define(
7049                                &index.to_string(),
7050                                Property::accessor_with(
7051                                    Some(Value::Object(getter)),
7052                                    Some(Value::Object(setter)),
7053                                    true,
7054                                ),
7055                            );
7056                        }
7057                        None => object.define_data(&index.to_string(), value),
7058                    }
7059                }
7060                // §10.4.4: a *mapped* arguments object carries `callee` as a writable,
7061                // non-enumerable, configurable data property holding the function being
7062                // called. A strict (unmapped) one gets no such property at all; the
7063                // spec's poison-pill accessor for it is unreachable in this engine
7064                // because a strict `arguments.callee` is already a compile-time error.
7065                //
7066                // The legacy `S10.6_*` tests predate that restriction and ask only that
7067                // `arguments.hasOwnProperty("callee")` be true in sloppy mode.
7068                if magic == 1 {
7069                    let callee = self.frame().callee.clone();
7070                    // `{ DontEnum }`: `for (var x in arguments)` must not list it.
7071                    object.define("callee", Property::with_attributes(callee, true, false));
7072                }
7073                // An arguments object is iterable: `[...arguments]` and
7074                // `for (const a of arguments)` both work, through the *array* iterator
7075                // because the object is array-like. Without this the whole spread form
7076                // reported "not iterable".
7077                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
7078                let values = self
7079                    .realm
7080                    .array_proto
7081                    .own_property("values")
7082                    .and_then(|property| property.value);
7083                if let Some(values) = values {
7084                    object.define_key(
7085                        &iterator_key,
7086                        Property::with_attributes(values, true, false),
7087                    );
7088                }
7089                Ok(Value::Object(object))
7090            }
7091            // `this.active_func`: the constructor `super()` resolves against.
7092            //
7093            // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
7094            // own, so it inherits this from the function it was written in along with `this`
7095            // — and that is a lexical relationship, not a stack one: an arrow that escaped
7096            // the constructor and is called back later (`iter.return = () => super()`) has
7097            // the constructor nowhere on the stack. The compiler therefore reads it out of
7098            // a closure variable of the enclosing function, exactly as the reference does
7099            // with its `this_active_func` local.
7100            2 => Ok(self
7101                .current_callee()
7102                .map_or(Value::Undefined, Value::Object)),
7103            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
7104            // inherited from the caller inside an `eval`. An arrow has no `new.target` of
7105            // its own either, so the lookup walks out to the nearest non-arrow frame for
7106            // the same reason as `this.active_func` above — without that, `super()` inside
7107            // an arrow passed `undefined` as the new target and the parent constructor was
7108            // then rejected for being invoked without `new`.
7109            3 => Ok(self
7110                .eval_new_target
7111                .clone()
7112                .unwrap_or_else(|| self.frame().new_target.clone())),
7113            // `[[HomeObject]]` of the function being run: what `super` is relative to.
7114            // An arrow has none of its own, so the lookup walks out to the enclosing
7115            // method — which is why `super` works inside an arrow inside a method.
7116            4 => Ok(self
7117                .frames
7118                .iter()
7119                .rev()
7120                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
7121                .map_or(Value::Undefined, Value::Object)),
7122            // `import.meta`: the innermost module body's meta object. Outside a module
7123            // the compiler never emits this, so an empty fallback is unreachable rather
7124            // than permissive.
7125            6 => {
7126                let name = self.module_stack.last().cloned();
7127                let meta = name
7128                    .and_then(|name| self.modules.get(&name).cloned())
7129                    .and_then(|module| module.with(|r| r.import_meta.clone()));
7130                Ok(meta.map_or(Value::Undefined, Value::Object))
7131            }
7132            other => Err(Signal::Throw(self.make_error(
7133                "InternalError",
7134                &format!("special_object {other} is not implemented yet"),
7135            ))),
7136        }
7137    }
7138
7139    /// `[[HomeObject]]` of the innermost function that has one, if any.
7140    ///
7141    /// An arrow has none, so the search walks out to the enclosing method — the same
7142    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
7143    /// inside a method.
7144    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
7145        self.frames
7146            .iter()
7147            .rev()
7148            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
7149    }
7150
7151    /// The dispose method a `using` declaration should snapshot, or an error.
7152    ///
7153    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
7154    /// is what makes a resource that only knows the synchronous protocol usable in both
7155    /// forms.
7156    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
7157        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
7158        if value.is_nullish() {
7159            return Ok(Value::Undefined);
7160        }
7161        let Some(object) = value.as_object() else {
7162            return Err(self.type_error("not an object"));
7163        };
7164        let mut method = if await_form {
7165            let found = self.get_property_key(
7166                object,
7167                &self.realm.well_known_key(WellKnown::AsyncDisposable),
7168            )?;
7169            match found {
7170                Some(found) if !found.is_nullish() => Some(found),
7171                _ => self
7172                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
7173            }
7174        } else {
7175            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
7176        };
7177        let Some(found) = method.take() else {
7178            return Err(self.type_error("value is not disposable"));
7179        };
7180        if found.is_nullish() {
7181            return Err(self.type_error("value is not disposable"));
7182        }
7183        let callable = found.as_object().is_some_and(|object| object.is_callable());
7184        if !callable {
7185            return Err(self.type_error("dispose method is not a function"));
7186        }
7187        Ok(found)
7188    }
7189
7190    /// Call one resource's disposer, folding a failure into `error_state`.
7191    ///
7192    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
7193    /// because a captured `using` binding lives in its reference cell and the local slot is
7194    /// stale — a closure over the resource is legal and must not change what is disposed.
7195    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
7196        let value = self.get_loc(slot);
7197        let method = self.get_loc(slot + 1);
7198        // A resource that was never initialised — its declaration threw — or that is
7199        // `null`/`undefined` has nothing to dispose.
7200        if value.is_nullish() || matches!(value, Value::Uninitialized) {
7201            return Ok(error_state);
7202        }
7203        if matches!(method, Value::Undefined | Value::Uninitialized) {
7204            return Ok(error_state);
7205        }
7206        match self.call_value(method, value, Vec::new()) {
7207            Ok(_) => Ok(error_state),
7208            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
7209            Err(other) => Err(other),
7210        }
7211    }
7212
7213    /// Combine a disposal failure with whatever was already going wrong.
7214    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
7215        if matches!(error_state, Value::Uninitialized) {
7216            return new_error;
7217        }
7218        self.new_suppressed_error(new_error, error_state)
7219    }
7220
7221    /// A `SuppressedError` instance built straight from its prototype.
7222    ///
7223    /// Not through the constructor: a script that rewrites
7224    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
7225    /// error wrapping.
7226    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
7227        let proto = self
7228            .realm
7229            .suppressed_error_proto
7230            .clone()
7231            .unwrap_or_else(|| self.realm.error_proto.clone());
7232        let object = self.new_object(Some(proto));
7233        object.define("error", Property::with_attributes(error, true, true));
7234        object.define(
7235            "suppressed",
7236            Property::with_attributes(suppressed, true, true),
7237        );
7238        object.define(
7239            "message",
7240            Property::with_attributes(self.string("SuppressedError"), true, true),
7241        );
7242        self.internal_set(&object, "_class", self.string("Error"));
7243        self.add_stack(&object);
7244        Value::Object(object)
7245    }
7246
7247    /// Call `callee`, or push its frame and let the main loop run it.
7248    ///
7249    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
7250    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
7251    /// continues, so `function f(){ return f() }` costs heap and stops at
7252    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
7253    /// is entered directly, and natives do not re-enter JavaScript in this
7254    /// milestone.
7255    ///
7256    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
7257    /// because the returning frame will.
7258    /// The elements of an array-like value, as a call argument list.
7259    ///
7260    /// `apply` accepts any array-like, not only a real array: the reference reads
7261    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
7262    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
7263        let Some(object) = value.as_object().cloned() else {
7264            if value.is_nullish() {
7265                // `f.apply(this, null)` passes no arguments at all.
7266                return Ok(Vec::new());
7267            }
7268            return Err(self.type_error("createListFromArrayLike called on non-object"));
7269        };
7270        let length = match self.get_property(&object, "length")? {
7271            Some(length) => length.to_number(),
7272            None => 0.0,
7273        };
7274        if !length.is_finite() || length <= 0.0 {
7275            return Ok(Vec::new());
7276        }
7277        let length = (length as usize).min(1_000_000);
7278        let mut args = Vec::with_capacity(length);
7279        for index in 0..length {
7280            let element = self.get_property(&object, &index.to_string())?;
7281            args.push(element.unwrap_or(Value::Undefined));
7282        }
7283        Ok(args)
7284    }
7285
7286    /// Turn a call to a generator function into a generator object.
7287    ///
7288    /// The frame is built exactly as an ordinary call would build it, then detached and
7289    /// stored in the generator before any body instruction runs — which is what makes
7290    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
7291    /// is `initial_yield`, the first instruction of every suspending body.
7292    pub fn new_generator(
7293        &mut self,
7294        function: Value,
7295        this: Value,
7296        args: Vec<Value>,
7297    ) -> JsResult<Value> {
7298        let Some(object) = function.as_object().cloned() else {
7299            return Err(self.type_error("not a generator function"));
7300        };
7301        let Some((code, env)) = bytecode_of(&object) else {
7302            return Err(self.type_error("not a generator function"));
7303        };
7304        let is_async = code.code.kind.is_async();
7305        self.push_frame(code, env, this, args, function)?;
7306        let frame = self.frames.pop().expect("push_frame just pushed it");
7307        // A fresh generator is *suspended at start*: the body has not run, so a
7308        // `return`/`throw` on it finishes without executing anything.
7309        let mut state = GeneratorState {
7310            frame: Some(frame),
7311            phase: GeneratorPhase::SuspendedStart,
7312            parked_on_await: false,
7313            parked_on_yield_star: false,
7314            requests: std::collections::VecDeque::new(),
7315            async_busy: false,
7316        };
7317        // Run to the first suspension. For a generator that is `initial_yield`, so no
7318        // body code runs; for a malformed body it would be the first `yield`.
7319        // An `async function*` answers an async generator: same coroutine, but its
7320        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
7321        let proto = if is_async {
7322            self.realm
7323                .async_generator_proto
7324                .clone()
7325                .unwrap_or_else(|| self.realm.generator_proto.clone())
7326        } else {
7327            self.realm.generator_proto.clone()
7328        };
7329        let generator = self.new_object(Some(proto));
7330        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
7331            Ok(_) => {}
7332            Err(error) => return Err(error),
7333        }
7334        generator.with_mut(|data| {
7335            data.kind = ObjectKind::Generator(Box::new(state));
7336        });
7337        Ok(Value::Object(generator))
7338    }
7339
7340    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7341    ///
7342    /// Returns the `{value, done}` object itself rather than the pair, because a
7343    /// `yield*` suspension already has one — the inner iterator's own result — and the
7344    /// protocol says to hand that straight through rather than nest it.
7345    /// Advance a generator and report *why* it parked.
7346    ///
7347    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
7348    /// "hand this value to the caller" — but an async generator does: an `await` has to
7349    /// settle before it can answer, while a `yield` is the answer.
7350    fn resume_generator_detailed(
7351        &mut self,
7352        generator: &Gc<JsObject>,
7353        kind: ResumeKind,
7354        value: Value,
7355    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7356        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
7357            ObjectKind::Generator(state) => Some(std::mem::replace(
7358                state.as_mut(),
7359                GeneratorState {
7360                    frame: None,
7361                    phase: GeneratorPhase::Executing,
7362                    parked_on_await: false,
7363                    parked_on_yield_star: false,
7364                    requests: std::collections::VecDeque::new(),
7365                    async_busy: false,
7366                },
7367            )),
7368            _ => None,
7369        }) else {
7370            return Err(self.type_error("not a generator"));
7371        };
7372        let result = self.step_generator(&mut state, kind, value);
7373        generator.with_mut(|data| {
7374            data.kind = ObjectKind::Generator(Box::new(state));
7375        });
7376        result
7377    }
7378
7379    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7380    ///
7381    /// Returns the `{value, done}` object itself rather than the pair, because a
7382    /// `yield*` suspension already has one — the inner iterator's own result — and the
7383    /// protocol says to hand that straight through rather than nest it.
7384    pub fn resume_generator(
7385        &mut self,
7386        generator: &Gc<JsObject>,
7387        kind: ResumeKind,
7388        value: Value,
7389    ) -> JsResult<Value> {
7390        let (value, done, ready, _reason) =
7391            self.resume_generator_detailed(generator, kind, value)?;
7392        if ready {
7393            return Ok(value);
7394        }
7395        self.iterator_result(value, done)
7396    }
7397
7398    /// `next`/`return`/`throw` on an async generator, which answer a promise.
7399    ///
7400    /// The body is the same coroutine a sync generator runs; what changes is that an
7401    /// `await` inside it has to settle before the method can answer, so the step is
7402    /// driven off the job queue rather than returning inline.
7403    pub fn resume_async_generator(
7404        &mut self,
7405        generator: &Gc<JsObject>,
7406        kind: ResumeKind,
7407        value: Value,
7408    ) -> JsResult<Value> {
7409        let promise = self.new_promise();
7410        // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
7411        // that order, and the second value must reach the *second* `yield`.
7412        let idle = generator.with_mut(|data| match &mut data.kind {
7413            ObjectKind::Generator(state) => {
7414                state.requests.push_back(AsyncRequest {
7415                    kind,
7416                    value,
7417                    promise: promise.clone(),
7418                });
7419                !state.async_busy
7420            }
7421            _ => false,
7422        });
7423        if idle {
7424            self.next_async_request(generator)?;
7425        }
7426        Ok(Value::Object(promise))
7427    }
7428
7429    /// Serve the front queued request, if the generator is free to run one.
7430    ///
7431    /// A finished generator answers from the queue without running anything:
7432    /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
7433    /// first, and `throw(e)` rejects.
7434    fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
7435        enum Front {
7436            Idle,
7437            Run(ResumeKind, Value, Gc<JsObject>),
7438            Finished(ResumeKind, Value, Gc<JsObject>),
7439        }
7440        let front = generator.with_mut(|data| match &mut data.kind {
7441            ObjectKind::Generator(state) => {
7442                let Some(request) = state.requests.front() else {
7443                    return Front::Idle;
7444                };
7445                // Busy means a request is still in flight — awaiting inside the body, not
7446                // finished. Serving another now would interleave two requests.
7447                if state.async_busy && state.phase != GeneratorPhase::Completed {
7448                    return Front::Idle;
7449                }
7450                let kind = request.kind;
7451                let value = request.value.clone();
7452                let promise = request.promise.clone();
7453                state.async_busy = true;
7454                if state.phase == GeneratorPhase::Completed {
7455                    Front::Finished(kind, value, promise)
7456                } else {
7457                    Front::Run(kind, value, promise)
7458                }
7459            }
7460            _ => Front::Idle,
7461        });
7462        match front {
7463            Front::Idle => Ok(()),
7464            Front::Run(kind, value, promise) => {
7465                self.step_async_generator(generator, &promise, kind, value)
7466            }
7467            Front::Finished(kind, value, promise) => match kind {
7468                ResumeKind::Throw => {
7469                    self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
7470                }
7471                ResumeKind::Next | ResumeKind::Start => {
7472                    let result = self.iterator_result(Value::Undefined, true)?;
7473                    self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
7474                }
7475                ResumeKind::Return => {
7476                    // `js_async_generator_completed_return`: the value is awaited before it
7477                    // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
7478                    // finished generator answers `1`, not a promise.
7479                    let resolved = match self.promise_resolve_value(value) {
7480                        Ok(resolved) => resolved,
7481                        Err(Signal::Throw(reason)) => {
7482                            return self.settle_async_request(
7483                                generator,
7484                                &promise,
7485                                AsyncOutcome::Error(reason),
7486                            );
7487                        }
7488                        Err(other) => return Err(other),
7489                    };
7490                    let done = JsObject::function(
7491                        self.heap,
7492                        Some(self.realm.function_proto.clone()),
7493                        Callable::CompletedReturn {
7494                            generator: generator.clone(),
7495                            promise: promise.clone(),
7496                            rejected: false,
7497                        },
7498                    );
7499                    let failed = JsObject::function(
7500                        self.heap,
7501                        Some(self.realm.function_proto.clone()),
7502                        Callable::CompletedReturn {
7503                            generator: generator.clone(),
7504                            promise: promise.clone(),
7505                            rejected: true,
7506                        },
7507                    );
7508                    let Value::Object(resolved) = resolved else {
7509                        return self.settle_async_request(
7510                            generator,
7511                            &promise,
7512                            AsyncOutcome::Error(Value::Undefined),
7513                        );
7514                    };
7515                    self.perform_then(
7516                        &resolved,
7517                        Some(Value::Object(done)),
7518                        Some(Value::Object(failed)),
7519                    )?;
7520                    Ok(())
7521                }
7522            },
7523        }
7524    }
7525
7526    /// Settle the front request and start the next one.
7527    ///
7528    /// Every path out of [`Interp::step_async_generator`] goes through here, so the
7529    /// "busy" flag and the queue cannot drift: a promise settled without releasing the
7530    /// generator would strand every later request.
7531    fn settle_async_request(
7532        &mut self,
7533        generator: &Gc<JsObject>,
7534        promise: &Gc<JsObject>,
7535        outcome: AsyncOutcome,
7536    ) -> JsResult<()> {
7537        let settled = generator.with_mut(|data| match &mut data.kind {
7538            ObjectKind::Generator(state) => {
7539                let front = state.requests.front();
7540                debug_assert!(
7541                    front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
7542                    "a request settled outside its turn"
7543                );
7544                state.requests.pop_front();
7545                state.async_busy = false;
7546                true
7547            }
7548            _ => false,
7549        });
7550        if settled {
7551            match outcome {
7552                AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
7553                AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
7554            }
7555        }
7556        self.next_async_request(generator)
7557    }
7558
7559    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
7560    ///
7561    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
7562    /// disposer runs **synchronously** — the reference starts it before returning, which
7563    /// a test can observe by logging after the call — and the rest follow once their
7564    /// predecessor settles.
7565    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
7566        let promise = self.new_promise();
7567        let mut pairs = Vec::with_capacity(resources.len());
7568        for (value, method) in resources {
7569            let pair = self.new_array(vec![value, method]);
7570            pairs.push(Value::Object(pair));
7571        }
7572        let remaining = self.new_array(pairs);
7573        self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
7574        Ok(Value::Object(promise))
7575    }
7576
7577    /// One link of the `disposeAsync` chain.
7578    ///
7579    /// Loops while the disposers finish synchronously, and parks on the first thenable it
7580    /// meets — pushing itself back in as the continuation, with the accumulated error
7581    /// carried along so a later failure can still be folded into the `SuppressedError`.
7582    fn dispose_step(
7583        &mut self,
7584        remaining: &Gc<JsObject>,
7585        promise: &Gc<JsObject>,
7586        mut error: Value,
7587    ) -> JsResult<()> {
7588        loop {
7589            let length = remaining.array_length().unwrap_or(0);
7590            if length == 0 {
7591                if matches!(error, Value::Uninitialized) {
7592                    self.fulfill_promise(promise, Value::Undefined);
7593                } else {
7594                    self.reject_promise(promise, error);
7595                }
7596                return Ok(());
7597            }
7598            let Some(Value::Object(pair)) = remaining
7599                .array_get(length - 1)
7600                .filter(|v| !matches!(v, Value::Hole))
7601            else {
7602                remaining.array_truncate(self.heap, length - 1);
7603                continue;
7604            };
7605            remaining.array_truncate(self.heap, length - 1);
7606            let value = pair.array_get(0).unwrap_or(Value::Undefined);
7607            let Some(Value::Object(method)) = pair.array_get(1) else {
7608                continue;
7609            };
7610            if !method.is_callable() {
7611                continue;
7612            }
7613            match self.call_value(Value::Object(method), value, Vec::new()) {
7614                Ok(result) => {
7615                    if !self.is_thenable(&result)? {
7616                        // Finished synchronously; the next disposer is the next iteration.
7617                        continue;
7618                    }
7619                    let awaited = match self.promise_resolve_value(result) {
7620                        Ok(awaited) => awaited,
7621                        Err(Signal::Throw(reason)) => {
7622                            self.reject_promise(promise, reason);
7623                            return Ok(());
7624                        }
7625                        Err(other) => return Err(other),
7626                    };
7627                    let Value::Object(awaited) = awaited else {
7628                        continue;
7629                    };
7630                    let ok = JsObject::function(
7631                        self.heap,
7632                        Some(self.realm.function_proto.clone()),
7633                        Callable::DisposeStep {
7634                            remaining: remaining.clone(),
7635                            promise: promise.clone(),
7636                            error: error.clone(),
7637                            rejected: false,
7638                        },
7639                    );
7640                    let failed = JsObject::function(
7641                        self.heap,
7642                        Some(self.realm.function_proto.clone()),
7643                        Callable::DisposeStep {
7644                            remaining: remaining.clone(),
7645                            promise: promise.clone(),
7646                            error,
7647                            rejected: true,
7648                        },
7649                    );
7650                    self.perform_then(
7651                        &awaited,
7652                        Some(Value::Object(ok)),
7653                        Some(Value::Object(failed)),
7654                    )?;
7655                    return Ok(());
7656                }
7657                Err(Signal::Throw(thrown)) => {
7658                    error = self.merge_dispose_error(thrown, error);
7659                }
7660                Err(other) => return Err(other),
7661            }
7662        }
7663    }
7664
7665    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
7666    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
7667        let Value::Object(object) = value else {
7668            return Ok(false);
7669        };
7670        Ok(matches!(
7671            self.get_property(object, "then")?,
7672            Some(Value::Object(then)) if then.is_callable()
7673        ))
7674    }
7675
7676    /// One step of an async generator, settling `promise` with an `{value, done}` result.
7677    fn step_async_generator(
7678        &mut self,
7679        generator: &Gc<JsObject>,
7680        promise: &Gc<JsObject>,
7681        kind: ResumeKind,
7682        value: Value,
7683    ) -> JsResult<()> {
7684        let stepped = self.resume_generator_detailed(generator, kind, value);
7685        let (value, done, ready, reason) = match stepped {
7686            Ok(stepped) => stepped,
7687            Err(Signal::Throw(reason)) => {
7688                return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
7689            }
7690            Err(other) => return Err(other),
7691        };
7692        // Only an `await` has to wait before the method can answer.
7693        if !done && reason == Some(SuspendKind::Await) {
7694            let awaited = match self.promise_resolve_value(value) {
7695                Ok(awaited) => awaited,
7696                Err(Signal::Throw(reason)) => {
7697                    return self.settle_async_request(
7698                        generator,
7699                        promise,
7700                        AsyncOutcome::Error(reason),
7701                    );
7702                }
7703                Err(other) => return Err(other),
7704            };
7705            let Value::Object(awaited) = awaited else {
7706                return Ok(());
7707            };
7708            let resumed = JsObject::function(
7709                self.heap,
7710                Some(self.realm.function_proto.clone()),
7711                Callable::GeneratorResume {
7712                    generator: generator.clone(),
7713                    promise: promise.clone(),
7714                    kind: ResumeKind::Next,
7715                },
7716            );
7717            let raised = JsObject::function(
7718                self.heap,
7719                Some(self.realm.function_proto.clone()),
7720                Callable::GeneratorResume {
7721                    generator: generator.clone(),
7722                    promise: promise.clone(),
7723                    kind: ResumeKind::Throw,
7724                },
7725            );
7726            self.perform_then(
7727                &awaited,
7728                Some(Value::Object(resumed)),
7729                Some(Value::Object(raised)),
7730            )?;
7731            return Ok(());
7732        }
7733        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
7734        // completes it — both arrive as the settled value rather than as the promise
7735        // object. A plain value skips the round trip, which is also what keeps `yield 1`
7736        // from costing an extra tick.
7737        let awaits_value = self.is_thenable(&value)?;
7738        if awaits_value {
7739            let awaited = match self.promise_resolve_value(value) {
7740                Ok(awaited) => awaited,
7741                Err(Signal::Throw(reason)) => {
7742                    return self.settle_async_request(
7743                        generator,
7744                        promise,
7745                        AsyncOutcome::Error(reason),
7746                    );
7747                }
7748                Err(other) => return Err(other),
7749            };
7750            let Value::Object(awaited) = awaited else {
7751                return Ok(());
7752            };
7753            // A rejected yield throws *at the yield* inside the body, so the rejection
7754            // resumes the generator rather than the method's promise.
7755            let answer = JsObject::function(
7756                self.heap,
7757                Some(self.realm.function_proto.clone()),
7758                Callable::YieldResult {
7759                    generator: generator.clone(),
7760                    promise: promise.clone(),
7761                    done,
7762                },
7763            );
7764            let raise = JsObject::function(
7765                self.heap,
7766                Some(self.realm.function_proto.clone()),
7767                Callable::GeneratorResume {
7768                    generator: generator.clone(),
7769                    promise: promise.clone(),
7770                    kind: ResumeKind::Throw,
7771                },
7772            );
7773            self.perform_then(
7774                &awaited,
7775                Some(Value::Object(answer)),
7776                Some(Value::Object(raise)),
7777            )?;
7778            return Ok(());
7779        }
7780        let result = if ready {
7781            // `yield*` handed back the inner iterator's own result object.
7782            value
7783        } else {
7784            self.iterator_result(value, done)?
7785        };
7786        self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
7787    }
7788
7789    /// The `{value, done}` object an iterator method answers with.
7790    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
7791        let result = self.new_object(Some(self.realm.object_proto.clone()));
7792        result.define_data("value", value);
7793        result.define_data("done", Value::Bool(done));
7794        Ok(Value::Object(result))
7795    }
7796
7797    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
7798    fn step_generator(
7799        &mut self,
7800        state: &mut GeneratorState,
7801        kind: ResumeKind,
7802        value: Value,
7803    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7804        match state.phase {
7805            GeneratorPhase::Executing => {
7806                return Err(self.type_error("cannot invoke a running generator"));
7807            }
7808            GeneratorPhase::Completed => {
7809                // A finished generator answers every resumption without running.
7810                return Ok(match kind {
7811                    ResumeKind::Throw => return Err(Signal::Throw(value)),
7812                    ResumeKind::Return => (value, true, false, None),
7813                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
7814                });
7815            }
7816            GeneratorPhase::SuspendedStart => {
7817                if kind != ResumeKind::Next && kind != ResumeKind::Start {
7818                    // The body never started, so there is nothing to unwind or return
7819                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
7820                    state.frame = None;
7821                    state.phase = GeneratorPhase::Completed;
7822                    return Ok(match kind {
7823                        ResumeKind::Throw => return Err(Signal::Throw(value)),
7824                        _ => (value, true, false, None),
7825                    });
7826                }
7827            }
7828            GeneratorPhase::SuspendedYield => {}
7829        }
7830
7831        let Some(mut frame) = state.frame.take() else {
7832            return Ok((Value::Undefined, true, false, None));
7833        };
7834        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
7835        // number that says which method resumed it; the emitted `if_false` branches on
7836        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
7837        let mut raised = None;
7838        match kind {
7839            ResumeKind::Next | ResumeKind::Start => {
7840                if state.phase == GeneratorPhase::SuspendedYield {
7841                    frame.stack.push(value);
7842                    // An `await` resumes with its value alone; only a `yield` gets the
7843                    // magic number that says which of `next`/`return` resumed it.
7844                    if !state.parked_on_await {
7845                        frame.stack.push(Value::Int(RESUME_NEXT));
7846                    }
7847                }
7848            }
7849            ResumeKind::Return => {
7850                // A `return` on a not-yet-started generator is handled above, so this is
7851                // always a real resumption.
7852                frame.stack.push(value);
7853                frame.stack.push(Value::Int(RESUME_RETURN));
7854            }
7855            ResumeKind::Throw => {
7856                // At a `yield*` the exception is *data* for the delegation: the compiled
7857                // code resumes with the value and magic `2` and calls the inner iterator's
7858                // `throw`. Everywhere else it is raised at the suspension point, so the
7859                // body's own handler sees it.
7860                if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
7861                    frame.stack.push(value);
7862                    frame.stack.push(Value::Int(RESUME_THROW));
7863                } else {
7864                    raised = Some(value);
7865                }
7866            }
7867        }
7868        state.phase = GeneratorPhase::Executing;
7869
7870        let depth = self.frames.len();
7871        self.frames.push(frame);
7872        // A `throw` unwinds from where the frame parked, exactly as if the exception had
7873        // happened at the `yield`.
7874        if let Some(exception) = raised {
7875            if self.catch_here(exception.clone()).is_none() {
7876                self.pop_frame();
7877                state.phase = GeneratorPhase::Completed;
7878                return Err(Signal::Throw(exception));
7879            }
7880        }
7881
7882        // Only the generator's *own* frame ends the generator. The body may call ordinary
7883        // functions, and those push frames of their own: a `Step::Return` from one of them
7884        // is a nested call finishing, not the generator completing. Miscounting that is
7885        // silent — the generator reports the callee's value as its own result and marks
7886        // itself done — so the depth comparison is load-bearing, not defensive.
7887        let own_frame = depth + 1;
7888        loop {
7889            match self.step() {
7890                Ok(Step::Continue) => {}
7891                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
7892                    let mut frame = self.frames.pop().expect("a frame is live");
7893                    // `yield` left the value on the stack; `initial_yield` left nothing.
7894                    let yielded = if reason == SuspendKind::Initial {
7895                        Value::Undefined
7896                    } else {
7897                        frame.stack.pop().unwrap_or(Value::Undefined)
7898                    };
7899                    state.frame = Some(frame);
7900                    state.parked_on_await = reason == SuspendKind::Await;
7901                    state.parked_on_yield_star =
7902                        matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
7903                    state.phase = if reason == SuspendKind::Initial {
7904                        GeneratorPhase::SuspendedStart
7905                    } else {
7906                        GeneratorPhase::SuspendedYield
7907                    };
7908                    // `yield*` hands the inner iterator's own result object straight
7909                    // back, so the caller sees one `{value, done}` rather than a nested
7910                    // one — which is why the third field says "already a result".
7911                    return Ok((
7912                        yielded,
7913                        false,
7914                        reason == SuspendKind::YieldStar,
7915                        Some(reason),
7916                    ));
7917                }
7918                Ok(Step::Suspend(_)) => {
7919                    // A `yield` in a frame other than the generator's would mean a
7920                    // generator body entered as an ordinary call, which
7921                    // `call_or_push` prevents.
7922                    self.unwind_to(depth);
7923                    state.phase = GeneratorPhase::Completed;
7924                    return Err(Signal::Throw(self.make_error(
7925                        "InternalError",
7926                        "a generator body ran as an ordinary call",
7927                    )));
7928                }
7929                Ok(Step::Return(value)) => {
7930                    self.pop_frame();
7931                    if self.frames.len() > depth {
7932                        // A nested call finished: hand the value back to its caller and
7933                        // keep running the generator body.
7934                        self.frames
7935                            .last_mut()
7936                            .expect("a caller is live")
7937                            .stack
7938                            .push(value);
7939                        continue;
7940                    }
7941                    state.phase = GeneratorPhase::Completed;
7942                    // The reference closes the generator's closure variables here; ours
7943                    // live in cells the frame owned, which the drop below releases.
7944                    return Ok((value, true, false, None));
7945                }
7946                Err(Signal::Throw(exception)) => {
7947                    // The frame that threw gets the first chance to catch, exactly as in
7948                    // the ordinary call loop; a frame above the generator's is popped and
7949                    // the exception carries on down.
7950                    let exception = exception;
7951                    loop {
7952                        if self.frames.len() <= depth {
7953                            // The generator's own frame is gone, so nothing here caught it.
7954                            state.phase = GeneratorPhase::Completed;
7955                            return Err(Signal::Throw(exception));
7956                        }
7957                        if self.catch_here(exception.clone()).is_some() {
7958                            break;
7959                        }
7960                        self.pop_frame();
7961                    }
7962                }
7963                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
7964            }
7965        }
7966    }
7967
7968    /// Pop frames until `depth` are left, keeping their buffers.
7969    fn unwind_to(&mut self, depth: usize) {
7970        while self.frames.len() > depth {
7971            self.pop_frame();
7972        }
7973    }
7974    fn call_or_push(
7975        &mut self,
7976        callee: Value,
7977        this: Value,
7978        args: Vec<Value>,
7979    ) -> JsResult<Option<Value>> {
7980        if let Value::Object(function) = &callee
7981            && let Some((code, env)) = bytecode_of(function)
7982        {
7983            // Calling a generator function does not run anything: it captures the
7984            // arguments in a frame and hands back the generator object.
7985            if code.code.kind.is_generator() {
7986                return self.new_generator(callee, this, args).map(Some);
7987            }
7988            // An async function answers a promise and runs its body as a coroutine, so it
7989            // takes the same path as a plain call into it.
7990            if code.code.kind.is_async() {
7991                return self.new_async_function(callee, this, args).map(Some);
7992            }
7993            self.push_frame(code, env, this, args, callee)?;
7994            return Ok(None);
7995        }
7996        self.call_value(callee, this, args).map(Some)
7997    }
7998
7999    /// `new callee(args)`.
8000    ///
8001    /// A constructor differs from a plain call in three ways: it gets a fresh object
8002    /// as `this` whose prototype is the constructor's `prototype` property, its
8003    /// return value is *replaced* by that object unless it returns an object itself,
8004    /// and a native constructor is expected to initialise the object it is given
8005    /// rather than build one.
8006    pub fn construct(
8007        &mut self,
8008        callee: Value,
8009        new_target: Value,
8010        args: Vec<Value>,
8011    ) -> JsResult<Value> {
8012        // `new` on a bound function constructs its *target*, prepending the arguments
8013        // the bind fixed and ignoring the bound `this` — a bound function is a
8014        // constructor only when its target is one, and `new` always makes a fresh
8015        // object of the target's prototype rather than reusing the bound receiver.
8016        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
8017        // ran the body with `this === null` and threw on `this.x = a`.
8018        let mut callee = callee;
8019        let mut new_target = new_target;
8020        let mut args = args;
8021        loop {
8022            let Some(object) = callee.as_object().cloned() else {
8023                return Err(Signal::Throw(
8024                    self.make_error("TypeError", "not a constructor"),
8025                ));
8026            };
8027            // A proxy of a function constructs through its `construct` trap, and the
8028            // trap's answer is the result directly — no fresh object is made here.
8029            if object.proxy_state().is_some() {
8030                return match self.proxy_construct(&object, args, &new_target)? {
8031                    Some(result) => Ok(result),
8032                    None => Err(Signal::Throw(
8033                        self.make_error("TypeError", "proxy target is not a constructor"),
8034                    )),
8035                };
8036            }
8037            // A generator function has no `[[Construct]]`, and the reference names it in
8038            // the message: `new (function* G(){})()` reports "G is not a constructor".
8039            if object.with(|data| match &data.kind {
8040                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
8041                    code.code.kind.is_generator()
8042                }
8043                _ => false,
8044            }) {
8045                let name = object
8046                    .own_property("name")
8047                    .and_then(|property| property.value)
8048                    .map(|value| value.to_js_string())
8049                    .unwrap_or_default();
8050                return Err(Signal::Throw(
8051                    self.make_error("TypeError", &format!("{name} is not a constructor")),
8052                ));
8053            }
8054            let bound = object.with(|data| match &data.kind {
8055                ObjectKind::Function(Callable::Bound {
8056                    target,
8057                    args: leading,
8058                    ..
8059                }) => Some((target.clone(), leading.clone())),
8060                _ => None,
8061            });
8062            let Some((target, leading)) = bound else {
8063                // Not a bound function, so this object is the callee. §7.2.4
8064                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
8065                // refusals above cover only the built-ins the reference also refuses by
8066                // name. Everything else — a method, an arrow, an async function — has no
8067                // `[[Construct]]` either, and answering "yes" here made
8068                // `new (Array.prototype.map)` build an object instead of throwing.
8069                if !object.is_constructor() {
8070                    let name = object
8071                        .own_property("name")
8072                        .and_then(|property| property.value)
8073                        .map(|value| value.to_js_string())
8074                        .unwrap_or_default();
8075                    return Err(Signal::Throw(
8076                        self.make_error("TypeError", &format!("{name} is not a constructor")),
8077                    ));
8078                }
8079                break;
8080            };
8081            let mut all = leading;
8082            all.extend(args);
8083            args = all;
8084            // A bound function that is its own `new.target` stands in for its target:
8085            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
8086            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
8087            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
8088                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
8089                _ => false,
8090            };
8091            if same_wrapper {
8092                new_target = target.clone();
8093            }
8094            callee = target;
8095        }
8096        let Value::Object(function) = &callee else {
8097            unreachable!("the loop above only breaks on an object");
8098        };
8099        // The fresh object's prototype comes from `new.target`, not from the callee: a
8100        // derived constructor reaches here through `super()`, and the instance must be a
8101        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
8102        // an object inheriting `D.prototype` rather than `C.prototype`.
8103        let prototype_source = match new_target.as_object() {
8104            Some(target) => target.clone(),
8105            None => function.clone(),
8106        };
8107        // A native constructor builds its own instance, through `new_ctor_instance`, once it
8108        // has validated its arguments. Pre-building one here would read
8109        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
8110        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
8111        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
8112        let is_native = function.native_creates_own_instance();
8113        let this = if is_native {
8114            Value::Undefined
8115        } else {
8116            let prototype = self.get_property(&prototype_source, "prototype")?;
8117            let prototype = match prototype {
8118                Some(Value::Object(proto)) => Some(proto),
8119                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
8120                // object, the answer is the realm's *intrinsic* prototype for this
8121                // constructor, not `%Object.prototype%`.
8122                _ => {
8123                    let fallback = self.get_property(function, "prototype")?;
8124                    match fallback {
8125                        Some(Value::Object(proto)) => Some(proto),
8126                        _ => Some(self.realm.object_proto.clone()),
8127                    }
8128                }
8129            };
8130            Value::Object(self.new_object(prototype))
8131        };
8132        // `new.target` inside the body is the constructor that was written, so a bound
8133        // function's target sees itself rather than the bound wrapper.
8134        //
8135        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
8136        // `?`, so assigning `None` after the call would be skipped and the failed
8137        // `new.target` would stay visible to every later native call. The symptom was a
8138        // native constructor refusing a plain call — `var s = Symbol(); new
8139        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
8140        // "FinalizationRegistry is not a constructor".
8141        let outer_new_target = self.pending_new_target.replace(new_target);
8142        let result = self.call_value(callee, this.clone(), args);
8143        self.pending_new_target = outer_new_target;
8144        let result = result?;
8145        // A constructor that returns an object overrides `this`; any other return
8146        // value (including `undefined`) is ignored.
8147        Ok(match result {
8148            Value::Object(_) => result,
8149            _ => this,
8150        })
8151    }
8152
8153    /// `new.target` for the call currently being made.
8154    ///
8155    /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
8156    /// it as `this`), but a *host* constructor that builds its own instance is handed
8157    /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
8158    /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
8159    /// it here.
8160    ///
8161    /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
8162    /// receives for a plain call.
8163    pub fn current_new_target(&self) -> Value {
8164        self.pending_new_target.clone().unwrap_or(Value::Undefined)
8165    }
8166
8167    /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
8168    ///
8169    /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
8170    /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
8171    pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
8172        let constructor = self.realm.errors.get("AggregateError").cloned();
8173        let Some(constructor) = constructor else {
8174            return self.make_error("AggregateError", message);
8175        };
8176        let list = self.new_array(errors);
8177        match self.construct(
8178            Value::Object(constructor.clone()),
8179            Value::Object(constructor),
8180            vec![Value::Object(list), self.string(message)],
8181        ) {
8182            Ok(value) => value,
8183            // A user could have replaced `AggregateError` with something that throws; the
8184            // engine still owes the caller a rejection, so it falls back rather than
8185            // turning `Promise.any`'s rejection into a throw.
8186            Err(_) => self.make_error("AggregateError", message),
8187        }
8188    }
8189
8190    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
8191    ///
8192    /// The error classes themselves arrive with the builtins milestone; what
8193    /// matters here is that the thrown value stringifies the way a script printing
8194    /// the caught value expects.
8195    ///
8196    /// `name` and `message` become own properties, which is what makes `e.name` cheap and
8197    /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
8198    /// rely on when they print a caught value.
8199    pub fn make_error(&self, name: &str, message: &str) -> Value {
8200        let proto = self
8201            .realm
8202            .errors
8203            .get(name)
8204            .map(|constructor| self.prototype_of(constructor))
8205            .unwrap_or_else(|| self.realm.error_proto.clone());
8206        let error = self.new_object(Some(proto));
8207        // `name` and `message` are own properties of the instance, which is what
8208        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
8209        // `Error`.
8210        error.define(
8211            "name",
8212            Property::with_attributes(self.string(name), true, false),
8213        );
8214        error.define(
8215            "message",
8216            Property::with_attributes(self.string(message), true, false),
8217        );
8218        // The internal class, which is what tells a printer this is an error rather than a
8219        // plain object with `name` and `message` properties. The constructor path sets it
8220        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
8221        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
8222        // literally `"Error"` in both places — the *name* is read from `name`, which is why
8223        // a `RangeError` still prints as `RangeError`.
8224        self.internal_set(&error, "_class", self.string("Error"));
8225        // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
8226        // answered `false` from `Error.isError` while a constructed one answered `true`,
8227        // because only the constructor set the slot. The reference answers `true` for both
8228        // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
8229        // accessor gated on this slot the omission stopped being cosmetic: `print_error`
8230        // tests `typeof stack === "string"` to decide on a trailing newline, so every
8231        // engine-thrown error lost its blank line.
8232        self.internal_set(&error, "_error_data", Value::Bool(true));
8233        // The trace is captured where the error is *made*, which is where the reference
8234        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
8235        // way out, so a caught engine error already has its stack even if the handler
8236        // never rethrows it.
8237        self.add_stack(&error);
8238        Value::Object(error)
8239    }
8240
8241    /// Give an error object its `stack` property, from the current frame stack.
8242    ///
8243    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
8244    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
8245    /// `stack` a script set, is not rewritten.
8246    pub fn add_stack(&self, object: &Gc<JsObject>) {
8247        self.add_stack_skipping(object, 0);
8248    }
8249
8250    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
8251    ///
8252    /// An `Error` constructor passes 1: the reference builds those traces with
8253    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
8254    /// constructor itself, while a `RangeError` raised inside `toISOString` does
8255    /// report `at toISOString (native)`.
8256    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
8257        if object.has_own("stack") {
8258            return;
8259        }
8260        // The trace is *captured* here but not installed as a property: `stack` is an
8261        // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
8262        // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
8263        // is kept in a hidden slot and the getter materialises it on first read.
8264        //
8265        // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
8266        // shows it — this is the same discipline `_error_data` and `_class` follow.
8267        let trace = self.stack_trace_skipping(skip);
8268        let text = self.string(trace);
8269        self.internal_set(object, "_stack_trace", text);
8270    }
8271
8272    /// The function object currently being called, if any.
8273    ///
8274    /// A native function is a bare `fn` pointer, so it cannot capture which class
8275    /// it belongs to; it reads that from the callee instead. This is also what a
8276    /// stack trace would use.
8277    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
8278        match &self.frames.last()?.callee {
8279            Value::Object(object) => Some(object.clone()),
8280            _ => None,
8281        }
8282    }
8283
8284    /// The `prototype` property of a constructor, falling back to
8285    /// `Object.prototype` for anything that is not shaped like one.
8286    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
8287        constructor
8288            .own_property("prototype")
8289            .and_then(|property| property.value)
8290            .and_then(|value| value.as_object().cloned())
8291            .unwrap_or_else(|| self.realm.object_proto.clone())
8292    }
8293
8294    /// Throw a `TypeError` carrying `message`.
8295    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
8296        Signal::Throw(self.make_error("TypeError", message.as_ref()))
8297    }
8298
8299    /// Throw a `RangeError` carrying `message`.
8300    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
8301        Signal::Throw(self.make_error("RangeError", message.as_ref()))
8302    }
8303
8304    /// The `ReferenceError` a read of an uninitialised binding raises.
8305    /// The name of the binding `slot` refers to, for an error message.
8306    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
8307        match kind {
8308            VarSlot::Loc => self
8309                .frame()
8310                .code
8311                .code
8312                .vars
8313                .get(slot)
8314                .map(|v| v.name.clone()),
8315            VarSlot::Closure => self
8316                .frame()
8317                .code
8318                .code
8319                .closure_vars
8320                .get(slot)
8321                .map(|c| c.name.clone()),
8322        }
8323        .unwrap_or_default()
8324    }
8325
8326    /// Whether `slot` names a `const` binding, which rejects every store after its
8327    /// initialiser.
8328    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
8329        match kind {
8330            VarSlot::Loc => self
8331                .frame()
8332                .code
8333                .code
8334                .vars
8335                .get(slot)
8336                .is_some_and(|v| v.is_const),
8337            VarSlot::Closure => self
8338                .frame()
8339                .code
8340                .code
8341                .closure_vars
8342                .get(slot)
8343                .is_some_and(|c| c.is_const),
8344        }
8345    }
8346
8347    /// The `TypeError` a store to a `const` binding raises.
8348    ///
8349    /// `const` is enforced here rather than at compile time because the binding can be
8350    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
8351    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
8352    /// both halves of what "checked store" means: the dead zone is over, and the
8353    /// binding is writable.
8354    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
8355        let name = self.binding_name(slot, kind);
8356        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
8357    }
8358
8359    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
8360        let name = match kind {
8361            VarSlot::Loc => self
8362                .frame()
8363                .code
8364                .code
8365                .vars
8366                .get(slot)
8367                .map(|v| v.name.clone()),
8368            VarSlot::Closure => self
8369                .frame()
8370                .code
8371                .code
8372                .closure_vars
8373                .get(slot)
8374                .map(|c| c.name.clone()),
8375        }
8376        .unwrap_or_default();
8377        Signal::Throw(self.make_error(
8378            "ReferenceError",
8379            &format!("cannot access '{name}' before initialization"),
8380        ))
8381    }
8382
8383    fn throw_reference(&self, name: &str) -> Signal {
8384        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
8385    }
8386
8387    // -- the instruction loop -----------------------------------------------
8388
8389    // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
8390    // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
8391    // measured at 16% of a tight arithmetic loop's total time.
8392    #[inline(always)]
8393    fn step(&mut self) -> JsResult<Step> {
8394        // The instruction is already decoded (see [`crate::insn`]), so this is an index
8395        // and a `Copy` read rather than a table lookup plus a width switch. Only the
8396        // borrow lives across the boundary; nothing is cloned.
8397        // **One** borrow of the frame: fetch the record, then advance in the same scope.
8398        // The obvious version borrowed it three times (`last` to read, `last_mut` to
8399        // write, and once more inside the handler), and each is a bounds check plus an
8400        // `Option` unwrap — on the one path every instruction takes.
8401        let Some((insn, next)) = ({
8402            let frame = self
8403                .frames
8404                .last_mut()
8405                .expect("step() is only called with a live frame");
8406            // Past the last instruction is a normal return: the compiler ends a function
8407            // with `return`, and a jump to the end of a block lands here.
8408            let insn = frame.insns().get(frame.pc).copied();
8409            match insn {
8410                None => None,
8411                Some(insn) => {
8412                    // A fused record stands for the next few instructions, so the next
8413                    // `pc` is its width ahead — the instructions it replaces are never
8414                    // dispatched. `at` is the byte offset a stack trace reports; it stays
8415                    // an offset because the line table is keyed by bytes.
8416                    frame.at = insn.offset as usize;
8417                    frame.pc += insn.width();
8418                    Some((insn, frame.pc))
8419                }
8420            }
8421        }) else {
8422            return Ok(Step::Return(Value::Undefined));
8423        };
8424        self.check_memory()?;
8425        self.check_interrupt()?;
8426        if insn.fused == crate::insn::Fused::None {
8427            self.execute_instruction(insn.op, insn.a, insn.b, next)
8428        } else {
8429            self.execute_fused(insn)
8430        }
8431    }
8432
8433    /// Run a fused instruction: several bytecode instructions in one dispatch.
8434    ///
8435    /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
8436    /// it cannot throw and cannot allocate — and anything else falls back to the real
8437    /// instructions, in their real order, so an exception leaves the operand stack
8438    /// exactly as it would have been.
8439    #[inline]
8440    fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
8441        use crate::insn::Fused;
8442        let slot = insn.a as usize;
8443        match insn.fused {
8444            // `x = k`: `push k; put_loc x`.
8445            Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
8446            // `x += k`: `get_loc x; push k; add; put_loc x`.
8447            Fused::AddImmLoc => {
8448                let delta = insn.b as i32;
8449                match self.get_loc(slot) {
8450                    Value::Int(left) => {
8451                        // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
8452                        // that built two `Value`s, called a function, and matched on them
8453                        // again to reach this same `checked_add`. It is the innermost
8454                        // operation of every accumulator in every program.
8455                        let answer = match left.checked_add(delta) {
8456                            Some(sum) => Value::Int(sum),
8457                            None => Value::Float(left as f64 + delta as f64),
8458                        };
8459                        self.put_loc(slot, answer);
8460                    }
8461                    other => {
8462                        self.push(other);
8463                        self.push(Value::Int(delta));
8464                        self.binary_add()?;
8465                        let value = self.pop();
8466                        self.put_loc(slot, value);
8467                    }
8468                }
8469            }
8470            // `x += "literal"` and `x += y`: the two shapes that can append in place.
8471            Fused::AddAtomLoc => {
8472                let text = self.atom_wtf8(insn.b as usize);
8473                let right = self.string_wtf8(text);
8474                self.add_into_loc(slot, right)?;
8475            }
8476            Fused::AddLocLoc => {
8477                let source = (insn.a & 0xFFFF) as usize;
8478                let target = (insn.a >> 16) as usize;
8479                let right = self.get_loc(source);
8480                self.add_into_loc(target, right)?;
8481            }
8482            Fused::AddArgLoc => {
8483                let source = (insn.a & 0xFFFF) as usize;
8484                let target = (insn.a >> 16) as usize;
8485                let right = self.get_arg(source);
8486                self.add_into_loc(target, right)?;
8487            }
8488            // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
8489            Fused::PostIncLoc => match self.get_loc(slot) {
8490                Value::Int(left) => {
8491                    let answer = match left.checked_add(1) {
8492                        Some(sum) => Value::Int(sum),
8493                        None => Value::Float(left as f64 + 1.0),
8494                    };
8495                    self.put_loc(slot, answer);
8496                }
8497                other => {
8498                    self.push(other);
8499                    let raw = self.pop();
8500                    let (old, updated) = self.advance_numeric(raw, true)?;
8501                    self.push(old);
8502                    self.push(updated);
8503                    let value = self.pop();
8504                    self.put_loc(slot, value);
8505                    self.pop();
8506                }
8507            },
8508            // `if (!(x < arg)) goto target`: a loop header.
8509            //
8510            // The comparison is computed rather than replayed on the operand stack. That
8511            // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
8512            // that throws: the effects happen in the same order, and a handler truncates
8513            // the stack down to its marker, so the intermediate values are unobservable.
8514            Fused::LtLocArgJump => {
8515                let loc = (insn.a >> 16) as usize;
8516                let arg = (insn.a & 0xFFFF) as usize;
8517                let left = self.get_loc(loc);
8518                let right = self.get_arg(arg);
8519                let taken = match (&left, &right) {
8520                    (Value::Int(left), Value::Int(right)) => !(left < right),
8521                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8522                };
8523                if taken {
8524                    self.frame_mut().pc = insn.b as usize;
8525                }
8526            }
8527            // `i < k` in a loop header, where `k` is an integer literal.
8528            Fused::LtLocImmJump => {
8529                let left = self.get_loc(insn.a as usize);
8530                let right = Value::Int(insn.imm as i32);
8531                let taken = match &left {
8532                    Value::Int(left) => !(*left < insn.imm as i32),
8533                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8534                };
8535                if taken {
8536                    self.frame_mut().pc = insn.b as usize;
8537                }
8538            }
8539            Fused::None => unreachable!("only called for a fused record"),
8540        }
8541        Ok(Step::Continue)
8542    }
8543
8544    /// Run records that cannot call script, cannot throw and cannot change frames.
8545    ///
8546    /// Returns `Some(value)` when the function ran off the end of its instructions (a
8547    /// normal return), and `None` when it stopped in front of an instruction the slow path
8548    /// has to handle — `pc` is written back either way, so `step` resumes at the right
8549    /// place.
8550    ///
8551    /// **The invariant is the whole point.** Every arm here is restricted to work that
8552    /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
8553    /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
8554    /// that the memory limit has to see. An opcode whose operands turn out to need any of
8555    /// that **stops the loop** instead of trying, so the slow path gets the instruction
8556    /// untouched and with its operands still on the stack. That is why the fallback is a
8557    /// `break` and not a duplicated slow arm: a second implementation of the same
8558    /// semantics is how a wrong answer gets in with no test noticing.
8559    ///
8560    /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
8561    /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
8562    fn run_fast(&mut self) -> JsResult<Option<Value>> {
8563        use crate::insn::Fused;
8564        // The outer loop exists only so a `Call` can come back through here: once a
8565        // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
8566        // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
8567        // frame. Re-entering re-reads both from whichever frame is now on top. Every
8568        // other exit from the inner loop returns, so this costs one loop per call.
8569        'outer: loop {
8570            // One reference-count bump per *slow* instruction (a call, an allocation, a
8571            // property access), never one per instruction — that distinction is worth
8572            // two orders of magnitude and was measured as such.
8573            let (code, mut pc) = {
8574                let frame = self.frame();
8575                (frame.code.clone(), frame.pc)
8576            };
8577            let insns = &code.insns;
8578            loop {
8579                let Some(insn) = insns.get(pc).copied() else {
8580                    self.frame_mut().pc = pc;
8581                    return Ok(Some(Value::Undefined));
8582                };
8583                match insn.fused {
8584                    // `x = k`
8585                    Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
8586                    // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
8587                    // object — stops the loop so `binary_add` can decide.
8588                    Fused::AddImmLoc => {
8589                        let slot = insn.a as usize;
8590                        let delta = insn.b as i32;
8591                        let Value::Int(left) = self.get_loc(slot) else {
8592                            return Ok(self.stop(pc));
8593                        };
8594                        let sum = match left.checked_add(delta) {
8595                            Some(sum) => Value::Int(sum),
8596                            None => Value::Float(left as f64 + delta as f64),
8597                        };
8598                        self.put_loc(slot, sum);
8599                    }
8600                    // `x += "literal"` / `x += y`: the operand is a string, so the append
8601                    // either allocates one or grows one. Both are the slow path's business;
8602                    // the fusion's job is only to make the *slot* the sole owner, which is what
8603                    // `execute_fused` needs and what `get_loc` alone destroys.
8604                    Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
8605                        return Ok(self.stop(pc));
8606                    }
8607                    // `x++` on an integer, old value dropped.
8608                    Fused::PostIncLoc => {
8609                        // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
8610                        // value is read in place and overwritten in place, so the reference
8611                        // count it held is released by the same assignment that stores the
8612                        // new one. `get_loc` plus `put_loc` did two borrows, two table
8613                        // lookups and a clone, and this arm is the whole body of a counting
8614                        // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
8615                        let slot = insn.a as usize;
8616                        let frame = self.frames.last_mut().expect("a frame is live");
8617                        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
8618                        let target = if cell < 0 {
8619                            frame.locals.get_mut(slot)
8620                        } else {
8621                            None
8622                        };
8623                        let Some(target) = target else {
8624                            return Ok(self.stop(pc));
8625                        };
8626                        let Value::Int(left) = *target else {
8627                            return Ok(self.stop(pc));
8628                        };
8629                        *target = match left.checked_add(1) {
8630                            Some(sum) => Value::Int(sum),
8631                            None => Value::Float(left as f64 + 1.0),
8632                        };
8633                    }
8634                    // A loop header, `if (!(x < arg)) goto target`, with both sides already
8635                    // integers — which is every `for (i = 0; i < n; i++)` whose counter and
8636                    // bound stayed small integers.
8637                    Fused::LtLocArgJump => {
8638                        let loc = (insn.a >> 16) as usize;
8639                        let arg = (insn.a & 0xFFFF) as usize;
8640                        // One borrow for both slots: this arm *is* the whole loop of a
8641                        // `for (i = 0; i < n; i++)` with an argument bound, so a second
8642                        // `frames.last()` here is paid on every iteration. Measured 7.5% on
8643                        // `dispatch:empty-loop`.
8644                        let (left, right) = {
8645                            let frame = self.frame();
8646                            (frame.read_loc(loc), frame.read_arg(arg))
8647                        };
8648                        // Heavily measured: the bound is very often a `Float` even when the
8649                        // counter is an `Int` — anything that came from `+scriptArgs[2]`,
8650                        // `JSON.parse` or a division is one — so requiring both sides to be
8651                        // `Int` sent every iteration of those loops down the slow path. The
8652                        // comparison below is the same one `relational` makes for two numbers.
8653                        if !is_number(&left) || !is_number(&right) {
8654                            return Ok(self.stop(pc));
8655                        }
8656                        // `if_false` branches on the comparison being false, which is **not**
8657                        // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
8658                        // `>=` is also false and would keep it running forever. Clippy wants the
8659                        // negation folded; that would be a wrong answer.
8660                        let ordered = left.to_number() < right.to_number();
8661                        let take_branch = !ordered;
8662                        if take_branch {
8663                            pc = insn.b as usize;
8664                            continue;
8665                        }
8666                    }
8667                    // The same header with a literal bound: `if (!(x < k)) goto target`.
8668                    // The bound is an immediate, so only the counter needs a type test.
8669                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
8670                    Fused::LtLocImmJump => {
8671                        let left = self.get_loc(insn.a as usize);
8672                        if !is_number(&left) {
8673                            return Ok(self.stop(pc));
8674                        }
8675                        let take_branch = !(left.to_number() < insn.imm as i32 as f64);
8676                        if take_branch {
8677                            pc = insn.b as usize;
8678                            continue;
8679                        }
8680                    }
8681                    Fused::None => match insn.op {
8682                        // -- branches ---------------------------------------------------
8683                        // A jump is an assignment now, because the target is an instruction
8684                        // index. No arithmetic, no resolution table.
8685                        Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
8686                            let target = insn.a as usize;
8687                            // A **back-edge** is a loop, and it is the only place an
8688                            // instruction-level checkpoint can stop one: `for(;;){}` compiles
8689                            // to a jump to itself and never leaves this loop, so the
8690                            // per-instruction checks in `step` never run. That is exactly the
8691                            // hole this arm closes — a host's `JS_SetInterruptHandler` did
8692                            // nothing to a `for(;;){}` until it did, which is what
8693                            // `tests/c/embed.c` is for.
8694                            //
8695                            // Polling here rather than on every instruction in this loop is
8696                            // also the reference's choice (`OP_goto` calls
8697                            // `js_poll_interrupts`), and it costs one compare per branch
8698                            // instead of one decrement per instruction.
8699                            if target <= pc {
8700                                self.frame_mut().pc = target;
8701                                self.check_memory()?;
8702                                self.check_interrupt()?;
8703                            }
8704                            pc = target;
8705                            continue;
8706                        }
8707                        // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
8708                        Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
8709                            let taken = self.pop().to_boolean();
8710                            let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
8711                            if taken == want {
8712                                pc = insn.a as usize;
8713                                continue;
8714                            }
8715                        }
8716                        // -- slot access -------------------------------------------------
8717                        // A load's slot is already an operand (see `insn::implicit_operand`);
8718                        // a captured one goes through its cell, which runs no script.
8719                        Opcode::GetLoc
8720                        | Opcode::GetLoc8
8721                        | Opcode::GetLoc0
8722                        | Opcode::GetLoc1
8723                        | Opcode::GetLoc2
8724                        | Opcode::GetLoc3 => {
8725                            let value = self.get_loc(insn.a as usize);
8726                            self.push(value);
8727                        }
8728                        Opcode::PutLoc
8729                        | Opcode::PutLoc8
8730                        | Opcode::PutLoc0
8731                        | Opcode::PutLoc1
8732                        | Opcode::PutLoc2
8733                        | Opcode::PutLoc3 => {
8734                            let value = self.pop();
8735                            self.put_loc(insn.a as usize, value);
8736                        }
8737                        Opcode::GetArg
8738                        | Opcode::GetArg0
8739                        | Opcode::GetArg1
8740                        | Opcode::GetArg2
8741                        | Opcode::GetArg3 => {
8742                            let value = self.get_arg(insn.a as usize);
8743                            self.push(value);
8744                        }
8745                        Opcode::PutArg
8746                        | Opcode::PutArg0
8747                        | Opcode::PutArg1
8748                        | Opcode::PutArg2
8749                        | Opcode::PutArg3 => {
8750                            let value = self.pop();
8751                            self.put_arg(insn.a as usize, value);
8752                        }
8753                        // `a[i]` with an integer index on a dense array: see `fast_array_get`
8754                        // for why a non-hole own element is exactly the slow path's answer.
8755                        // The two operands are *peeked*, so a miss leaves the stack as the
8756                        // slow path expects to find it.
8757                        Opcode::GetArrayEl => {
8758                            // One lookup, not two. The guard used `if …is_some()` and the arm
8759                            // then called it again to get the value — two `peek`s, two
8760                            // `array_get`s and two `Value` clones for one element.
8761                            // `fast_array_get` was 13.1% of `array:indexed`, and the same
8762                            // double call was the first version of the `get_field` fast path.
8763                            let Some(value) = self.fast_array_get() else {
8764                                return Ok(self.stop(pc));
8765                            };
8766                            // `a[i]` consumes both operands and leaves the element in their
8767                            // place: one `truncate` and one write, no `pop`/`push` pair.
8768                            let frame = self.frame_mut();
8769                            frame.stack.truncate(frame.stack.len() - 2);
8770                            frame.stack.push(value);
8771                        }
8772                        // `a[i] = v` on a dense array with an integer index: see
8773                        // `fast_array_set` for why the whole store is one step.
8774                        Opcode::PutArrayEl if self.fast_array_set() => {}
8775                        // `o.x` resolved from the inline cache without leaving the loop.
8776                        //
8777                        // The cache is keyed by `(receiver identity, atom, site)` and a
8778                        // monomorphic read re-validates the same chain every iteration, so
8779                        // each one used to cost a `stop(pc)` — a write of `pc` into the
8780                        // frame, a return out of this loop, a re-dispatch through `step` and
8781                        // a re-entry. `property:monomorphic` spent 18% in
8782                        // `read_field_cached` and 21% in `push`, both across that boundary.
8783                        //
8784                        // The site is `pc + width`, which is exactly the `next` the slow arm
8785                        // passes — the two must agree or every fast lookup misses and
8786                        // re-records the same entry forever.
8787                        //
8788                        // A miss leaves the stack untouched (`fast_field_get` peeks) so the
8789                        // slow arm finds the receiver where it expects it.
8790                        // `name` resolved from the global-variable cache inside the loop.
8791                        //
8792                        // Same shape as `get_field` above and for the same reason: `get_var`
8793                        // was not in the fast loop, so reading a global — which `fib` does
8794                        // once per recursive call, for its own name — cost a `stop(pc)`, a
8795                        // return out of the loop, a `step` re-dispatch and a re-entry, before
8796                        // `get_global` even started its `scopes_are_plain` checks.
8797                        //
8798                        // Everything here is exactly `get_global`'s first branch: not lexical,
8799                        // no `eval` scope, cache hit. Anything else leaves the stack untouched
8800                        // and lets the slow arm decide.
8801                        Opcode::GetVar => {
8802                            let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
8803                                return Ok(self.stop(pc));
8804                            };
8805                            self.push(value);
8806                        }
8807                        Opcode::GetField | Opcode::GetField2 => {
8808                            let Some(value) =
8809                                self.fast_field_get(insn.a as usize, pc + insn.width())
8810                            else {
8811                                return Ok(self.stop(pc));
8812                            };
8813                            if insn.op == Opcode::GetField2 {
8814                                // `get_field2` keeps the receiver for the `call_method` that
8815                                // follows.
8816                                self.push(value);
8817                            } else {
8818                                // `get_field` replaces the receiver, so this is one store over
8819                                // the top slot rather than a `pop` and a `push`: the length
8820                                // never changes, so neither `Vec` arm has a capacity check or a
8821                                // drop to run beyond the one the overwrite itself does.
8822                                let frame = self.frame_mut();
8823                                match frame.stack.last_mut() {
8824                                    Some(slot) => *slot = value,
8825                                    None => return Ok(self.stop(pc)),
8826                                }
8827                            }
8828                        }
8829                        // -- constants ---------------------------------------------------
8830                        Opcode::PushMinus1
8831                        | Opcode::Push0
8832                        | Opcode::Push1
8833                        | Opcode::Push2
8834                        | Opcode::Push3
8835                        | Opcode::Push4
8836                        | Opcode::Push5
8837                        | Opcode::Push6
8838                        | Opcode::Push7
8839                        | Opcode::PushI8
8840                        | Opcode::PushI16
8841                        | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
8842                        // -- stack shuffling ---------------------------------------------
8843                        Opcode::Drop => {
8844                            self.pop();
8845                        }
8846                        // -- arithmetic on two integers ----------------------------------
8847                        //
8848                        // The operands are *looked at* before they are popped, so a non-integer
8849                        // pair leaves the stack exactly as the slow path expects to find it.
8850                        Opcode::Add if self.numeric_pair() => {
8851                            let right = self.pop();
8852                            let left = self.pop();
8853                            // Exactly [`add_numbers`], which is what the slow arm reaches.
8854                            let answer = match (&left, &right) {
8855                                (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
8856                                    Some(sum) => Value::Int(sum),
8857                                    None => Value::Float(*a as f64 + *b as f64),
8858                                },
8859                                _ => Value::Float(left.to_number() + right.to_number()),
8860                            };
8861                            self.push(answer);
8862                        }
8863                        Opcode::Sub
8864                        | Opcode::And
8865                        | Opcode::Or
8866                        | Opcode::Xor
8867                        | Opcode::Shl
8868                        | Opcode::Sar
8869                        | Opcode::Shr
8870                            if self.numeric_pair() =>
8871                        {
8872                            let right = self.pop();
8873                            let left = self.pop();
8874                            let answer =
8875                                arithmetic(insn.op, left, right).expect("numbers cannot throw");
8876                            self.push(answer);
8877                        }
8878                        Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
8879                            if self.numeric_pair() =>
8880                        {
8881                            let right = self.pop();
8882                            let left = self.pop();
8883                            let answer = self
8884                                .relational(insn.op, left, right)
8885                                .expect("numbers cannot throw");
8886                            self.push(answer);
8887                        }
8888                        // -- calls -------------------------------------------------------
8889                        //
8890                        // A plain call: `callee(arg0, …, argN) -> result`.
8891                        //
8892                        // This arm exists because of one measurement. `call:recursion` had
8893                        // **20.4% of its profile in `execute_instruction`** — the *slow*
8894                        // executor — and `fib`'s recursive call is the only thing in that
8895                        // function which is not a fast arm. Every call therefore left this
8896                        // loop via `stop()`, went through `step()`'s dispatch and
8897                        // `execute_instruction`'s match over every opcode, and came back here
8898                        // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
8899                        //
8900                        // Two things make it safe to do here rather than only in the slow path:
8901                        //
8902                        // * the caller's `pc` is stored *before* the call, which is what
8903                        //   `step` does too — so when the callee returns, the caller resumes
8904                        //   after the call and not at it;
8905                        // * `check_memory` runs, because `step` calls it once per instruction
8906                        //   and a call allocates a frame, its locals and its cells. Skipping
8907                        //   the checkpoint here would let a `--memory-limit` script overshoot
8908                        //   by one call per instruction.
8909                        Opcode::Call
8910                        | Opcode::Call0
8911                        | Opcode::Call1
8912                        | Opcode::Call2
8913                        | Opcode::Call3 => {
8914                            let argc = self.argc_operand(insn.op, insn.a);
8915                            let next = pc + insn.width();
8916                            {
8917                                let frame = self
8918                                    .frames
8919                                    .last_mut()
8920                                    .expect("run_fast() is only called with a live frame");
8921                                // `at` is what a stack trace reports for this frame, so a throw
8922                                // inside the callee has to see the call site and not whatever
8923                                // the last `stop()` left there.
8924                                frame.at = insn.offset as usize;
8925                                frame.pc = next;
8926                            }
8927                            self.check_memory()?;
8928                            self.check_interrupt()?;
8929                            let args = self.pop_n(argc);
8930                            let callee = self.pop();
8931                            // A plain call has no receiver; the callee decides what to do with
8932                            // `undefined` (a sloppy function substitutes the global object).
8933                            if let Some(result) =
8934                                self.call_or_push(callee, Value::Undefined, args)?
8935                            {
8936                                // Native, host, generator, async, bound — no frame was pushed,
8937                                // so this loop is still describing the right function. `pc`
8938                                // is advanced by the loop tail like every other arm; only the
8939                                // frame's copy had to be written here, and it already was.
8940                                self.push(result);
8941                            } else {
8942                                // A bytecode callee: its frame is on top now, and `insns` and
8943                                // `pc` both belong to the caller. Start over on the new frame.
8944                                continue 'outer;
8945                            }
8946                        }
8947                        // -- return ------------------------------------------------------
8948                        Opcode::Return => {
8949                            let value = self.pop();
8950                            self.frame_mut().pc = pc + insn.width();
8951                            return Ok(Some(value));
8952                        }
8953                        Opcode::ReturnUndef => {
8954                            self.frame_mut().pc = pc + insn.width();
8955                            return Ok(Some(Value::Undefined));
8956                        }
8957                        // Everything else needs the slow path.
8958                        _ => return Ok(self.stop(pc)),
8959                    },
8960                }
8961                pc += insn.width();
8962            }
8963        }
8964    }
8965
8966    /// Whether the top two operand-stack values are both numbers.
8967    ///
8968    /// The guard the fast loop uses before it takes an arithmetic record: two numbers
8969    /// cannot run script, so the arm may not throw and may not change frames.
8970    fn numeric_pair(&self) -> bool {
8971        is_number(&self.peek(0)) && is_number(&self.peek(1))
8972    }
8973
8974    /// `a[i]` for a dense array and an integer index, without the string round trip.
8975    ///
8976    /// The slow path answers this by turning `i` into a string (`propkey` →
8977    /// `number_to_string`) and then parsing it straight back (`read_field_key` →
8978    /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
8979    /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
8980    /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
8981    /// without even the cheap `Int` formatting.
8982    ///
8983    /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
8984    /// unambiguously the one the slow path would give:
8985    ///
8986    /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
8987    ///   `2^32-1` is the length, not an index),
8988    /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
8989    ///   typed array or an ordinary object, all of which have their own rules),
8990    /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
8991    ///   starts walking the prototype chain, and `a[i]` on a hole must find
8992    ///   `Array.prototype[i]` if it exists rather than `undefined`.
8993    ///
8994    /// The last condition is the one that makes this safe rather than merely fast: an own
8995    /// element always wins over the prototype, so a non-hole hit needs no further lookup.
8996    /// `get_var` answered from the global-variable cache, or `None`.
8997    ///
8998    /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
8999    /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
9000    /// records nothing — the slow arm is about to walk the chain and record it.
9001    fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
9002        let frame = self.frame();
9003        let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
9004        // "Lexical" is presence in the realm's table, not the closure var's flag: a
9005        // `GlobalRef` forwarded through a nested function has its flags cleared.
9006        if self.realm.globals.contains_key(name) {
9007            return None;
9008        }
9009        if !self.scopes_are_plain() {
9010            return None;
9011        }
9012        let object = &self.realm.global;
9013        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
9014        let cached = self.global_cache[site].as_ref()?;
9015        if !object.upgrades_to(&cached.object) {
9016            return None;
9017        }
9018        object.data_property_at(cached.index, name)
9019    }
9020
9021    /// `o.x` answered entirely from the inline cache, or `None`.
9022    ///
9023    /// Read-only on purpose: a miss must not record an entry, because the slow arm is
9024    /// about to do exactly that and recording it twice would rebuild the chain for every
9025    /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
9026    /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
9027    fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
9028        // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
9029        // an object receiver is a reference-count bump that the answer never needs.
9030        let frame = self.frame();
9031        let object = frame.stack.last()?;
9032        let Value::Object(target) = object else {
9033            return None;
9034        };
9035        // A proxy traps the lookup, so no cache entry ever describes it.
9036        if target.proxy_state().is_some() {
9037            return None;
9038        }
9039        let key = frame.code.atom_keys.get(atom)?;
9040        let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
9041        if cached.key != *key {
9042            return None;
9043        }
9044        Self::cached_hit(target, cached)
9045    }
9046
9047    fn fast_array_get(&self) -> Option<Value> {
9048        let Value::Int(index) = self.peek(0) else {
9049            return None;
9050        };
9051        // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
9052        // set for an `i32`.
9053        if index < 0 {
9054            return None;
9055        }
9056        let Value::Object(object) = self.peek(1) else {
9057            return None;
9058        };
9059        match object.array_get(index as usize) {
9060            Some(value) if !matches!(value, Value::Hole) => Some(value),
9061            _ => None,
9062        }
9063    }
9064
9065    /// `a[i] = v` on a dense array with an integer index, as one store.
9066    ///
9067    /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
9068    /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
9069    /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
9070    /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
9071    /// reference at the time it was measured (14.7x).
9072    ///
9073    /// Every condition here is one the slow path would also have to satisfy before
9074    /// storing into the element vector:
9075    ///
9076    /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
9077    ///   accepts as an index;
9078    /// * the target is an array whose elements are writable (`Object.freeze` clears it);
9079    /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
9080    ///   one inside a recorded descriptor, reports `false` and the caller stops.
9081    ///
9082    /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
9083    /// writes the own element too once `array_set` says it did.
9084    fn fast_array_set(&mut self) -> bool {
9085        // Every test runs *before* anything is popped: a refusal has to leave the stack
9086        // exactly as the slow path expects to find it. Popping first and reporting the
9087        // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
9088        // then ran the slow path with nothing to write.
9089        let Value::Int(index) = self.peek(1) else {
9090            return false;
9091        };
9092        // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
9093        if index < 0 {
9094            return false;
9095        }
9096        // Only a real array: a typed array's elements live in its buffer, a string-like
9097        // object has no element vector, and `array_set` on either does nothing.
9098        let Value::Object(object) = self.peek(2) else {
9099            return false;
9100        };
9101        if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
9102            return false;
9103        }
9104        // A non-extensible array reports `false` here, but the *slow* path has to decide
9105        // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
9106        // that with the key and the stack still intact.
9107        if !object.is_extensible() {
9108            return false;
9109        }
9110        // Inside the logical length, so the store cannot change `length`. Combined with
9111        // extensibility above, the only growth left for `array_set` is filling a hole in
9112        // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
9113        // shape this fast path exists for. A store past the length would grow the array,
9114        // and whether that is allowed is the slow path's question.
9115        if index as usize >= object.array_length().unwrap_or(0) {
9116            return false;
9117        }
9118        // The bound `array_set` refuses past. Checking it here keeps that arm from having
9119        // to report a failure after the operands are gone.
9120        if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
9121            return false;
9122        }
9123        let value = self.pop();
9124        self.pop();
9125        self.pop();
9126        object.array_store(self.heap, index as usize, value)
9127    }
9128
9129    /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
9130    fn stop(&mut self, pc: usize) -> Option<Value> {
9131        self.frame_mut().pc = pc;
9132        None
9133    }
9134
9135    fn push(&mut self, value: Value) {
9136        self.frame_mut().stack.push(value);
9137    }
9138
9139    fn pop(&mut self) -> Value {
9140        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
9141    }
9142
9143    fn pop_n(&mut self, count: usize) -> Vec<Value> {
9144        let frame = self.frame_mut();
9145        let start = frame.stack.len().saturating_sub(count);
9146        frame.stack.split_off(start)
9147    }
9148
9149    fn peek(&self, back: usize) -> Value {
9150        let frame = self.frame();
9151        frame
9152            .stack
9153            .get(frame.stack.len().wrapping_sub(1 + back))
9154            .cloned()
9155            .unwrap_or(Value::Undefined)
9156    }
9157
9158    #[allow(clippy::too_many_lines)]
9159    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
9160        use Opcode::*;
9161        match op {
9162            // -- constants and stack shuffling -----------------------------
9163            Nop => {}
9164            PushMinus1 => self.push(Value::Int(-1)),
9165            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
9166                let value = match op {
9167                    Push0 => 0,
9168                    Push1 => 1,
9169                    Push2 => 2,
9170                    Push3 => 3,
9171                    Push4 => 4,
9172                    Push5 => 5,
9173                    Push6 => 6,
9174                    _ => 7,
9175                };
9176                self.push(Value::Int(value));
9177            }
9178            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
9179            PushBigintI32 => {
9180                // The immediate form of a `BigInt` literal; the reference has the same
9181                // split between this and a constant-pool entry.
9182                let value = crate::bigint::BigInt::from_i64(a as i64);
9183                self.push(self.bigint(value));
9184            }
9185            PushTrue => self.push(Value::Bool(true)),
9186            PushFalse => self.push(Value::Bool(false)),
9187            PushEmptyString => self.push(self.string("")),
9188            Undefined => self.push(Value::Undefined),
9189            Null => self.push(Value::Null),
9190            Object => {
9191                let proto = self.realm.object_proto.clone();
9192                self.push(Value::Object(self.new_object(Some(proto))));
9193            }
9194            PushThis => {
9195                let this = self.frame().this.clone();
9196                self.push(this);
9197            }
9198            PushConst | PushConst8 => {
9199                let value = self.constant(a as usize)?;
9200                self.push(value);
9201            }
9202            PushAtomValue => {
9203                let text = self.atom_wtf8(a as usize);
9204                self.push(self.string_wtf8(text));
9205            }
9206            Dup => {
9207                let value = self.peek(0);
9208                self.push(value);
9209            }
9210            Dup2 => {
9211                // `a b -> a b a b`
9212                let b = self.peek(0);
9213                let a = self.peek(1);
9214                self.push(a);
9215                self.push(b);
9216            }
9217            Dup3 => {
9218                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
9219                // prototype and key while reading the current value through them.
9220                let c = self.peek(0);
9221                let b = self.peek(1);
9222                let a = self.peek(2);
9223                self.push(a);
9224                self.push(b);
9225                self.push(c);
9226            }
9227            Swap => {
9228                // `a b -> b a`
9229                let bottom = self.pop();
9230                let top = self.pop();
9231                self.push(bottom);
9232                self.push(top);
9233            }
9234            Perm3 => {
9235                // `a b c -> b a c`, the reference's reordering for a spread method
9236                // call: `obj func array` becomes the `func this array` that `apply`
9237                // takes.
9238                let c = self.pop();
9239                let b = self.pop();
9240                let a = self.pop();
9241                self.push(b);
9242                self.push(a);
9243                self.push(c);
9244            }
9245            Dup1 => {
9246                let value = self.peek(1);
9247                self.push(value);
9248            }
9249            Drop => {
9250                self.pop();
9251            }
9252            Nip => {
9253                // `a b -> b`
9254                let top = self.pop();
9255                self.pop();
9256                self.push(top);
9257            }
9258            Perm4 => {
9259                // `obj prop a b -> a obj prop b`, the reference's reordering for a
9260                // postfix update of a computed element: it puts the *old* value
9261                // underneath the receiver and key so `put_array_el` can consume them
9262                // and leave the old value as the expression's result.
9263                let d = self.pop();
9264                let c = self.pop();
9265                let b = self.pop();
9266                let a = self.pop();
9267                self.push(c);
9268                self.push(a);
9269                self.push(b);
9270                self.push(d);
9271            }
9272            Insert2 => {
9273                // `obj a -> a obj a`
9274                let value = self.pop();
9275                let object = self.pop();
9276                self.push(value.clone());
9277                self.push(object);
9278                self.push(value);
9279            }
9280            Insert3 => {
9281                // `obj prop a -> a obj prop a`
9282                let value = self.pop();
9283                let key = self.pop();
9284                let object = self.pop();
9285                self.push(value.clone());
9286                self.push(object);
9287                self.push(key);
9288                self.push(value);
9289            }
9290            Insert4 => {
9291                // `this obj prop a -> a this obj prop a`
9292                //
9293                // `put_super_value` consumes all four and yields nothing, so the copy
9294                // underneath is what leaves the assignment an expression value.
9295                let value = self.pop();
9296                let key = self.pop();
9297                let object = self.pop();
9298                let receiver = self.pop();
9299                self.push(value.clone());
9300                self.push(receiver);
9301                self.push(object);
9302                self.push(key);
9303                self.push(value);
9304            }
9305            Swap2 => {
9306                // `a b c d -> c d a b`
9307                let d = self.pop();
9308                let c = self.pop();
9309                let b = self.pop();
9310                let a = self.pop();
9311                self.push(c);
9312                self.push(d);
9313                self.push(a);
9314                self.push(b);
9315            }
9316            Rot3l => {
9317                // `x a b -> a b x`
9318                let b = self.pop();
9319                let a = self.pop();
9320                let x = self.pop();
9321                self.push(a);
9322                self.push(b);
9323                self.push(x);
9324            }
9325            Rot3r => {
9326                // `a b c -> c a b`
9327                let c = self.pop();
9328                let b = self.pop();
9329                let a_value = self.pop();
9330                self.push(c);
9331                self.push(a_value);
9332                self.push(b);
9333            }
9334
9335            Rest => {
9336                // `...rest` in a parameter list: the arguments from index `a` on, as a
9337                // real array. It takes nothing off the stack — the arguments are in the
9338                // frame, not on it.
9339                let frame = self.frame();
9340                let from = a as usize;
9341                let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
9342                let array = self.new_array(collected);
9343                self.push(Value::Object(array));
9344            }
9345
9346            // -- slots ------------------------------------------------------
9347            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
9348                let slot = self.slot_operand(op, a);
9349                let value = self.get_loc(slot);
9350                self.push(value);
9351            }
9352            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
9353                let slot = self.slot_operand(op, a);
9354                let value = self.pop();
9355                self.put_loc(slot, value);
9356            }
9357            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
9358                let slot = self.slot_operand(op, a);
9359                let value = self.pop();
9360                self.put_loc(slot, value.clone());
9361                self.push(value);
9362            }
9363            // The `_check` forms are the temporal dead zone: they throw when the
9364            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
9365            // *reads*, so only the two writes may pop — mishandling that quietly
9366            // consumes the value the caller pushed just before.
9367            GetLocCheck => {
9368                let slot = self.slot_operand(op, a);
9369                let value = self.get_loc(slot);
9370                if matches!(value, Value::Uninitialized) {
9371                    return Err(self.dead_zone(slot, VarSlot::Loc));
9372                }
9373                self.push(value);
9374            }
9375            PutLocCheck | SetLocCheck => {
9376                let slot = self.slot_operand(op, a);
9377                let value = self.pop();
9378                if matches!(value, Value::Uninitialized) {
9379                    return Err(self.dead_zone(slot, VarSlot::Loc));
9380                }
9381                // The initialiser goes through `put_loc`, not this, so any store that
9382                // reaches here is a later assignment — which a `const` refuses.
9383                if self.is_read_only(slot, VarSlot::Loc) {
9384                    return Err(self.read_only(slot, VarSlot::Loc));
9385                }
9386                if op == SetLocCheck {
9387                    self.put_loc(slot, value.clone());
9388                    self.push(value);
9389                } else {
9390                    self.put_loc(slot, value);
9391                }
9392            }
9393            PutLocCheckInit => {
9394                // The one store that *initialises* a lexical slot: `this` in a derived
9395                // constructor, which only exists after `super()` has run. A second
9396                // initialisation is the error the reference reports as
9397                // "'this' can be initialized only once".
9398                let slot = self.slot_operand(op, a);
9399                let value = self.pop();
9400                if !matches!(self.get_loc(slot), Value::Uninitialized) {
9401                    return Err(Signal::Throw(self.make_error(
9402                        "ReferenceError",
9403                        "'this' can be initialized only once",
9404                    )));
9405                }
9406                self.put_loc(slot, value);
9407            }
9408            CheckCtor => {
9409                // A class constructor may only run under `new`, which is what makes
9410                // `class A {}; A()` a TypeError.
9411                if matches!(self.frame().new_target, Value::Undefined) {
9412                    return Err(Signal::Throw(self.make_error(
9413                        "TypeError",
9414                        "class constructors must be invoked with 'new'",
9415                    )));
9416                }
9417            }
9418            InitCtor => {
9419                // The body a derived class gets when it declares no constructor:
9420                // forward every argument to the parent constructor, keeping `new.target`.
9421                if matches!(self.frame().new_target, Value::Undefined) {
9422                    return Err(Signal::Throw(self.make_error(
9423                        "TypeError",
9424                        "class constructors must be invoked with 'new'",
9425                    )));
9426                }
9427                let Some(callee) = self.current_callee() else {
9428                    return Err(Signal::Throw(
9429                        self.make_error("TypeError", "no constructor to inherit from"),
9430                    ));
9431                };
9432                let parent = callee.proto().map_or(Value::Null, Value::Object);
9433                let new_target = self.frame().new_target.clone();
9434                let args = self.frame().passed().to_vec();
9435                let result = self.construct(parent, new_target, args)?;
9436                self.push(result);
9437            }
9438            SetLocUninitialized => {
9439                let slot = self.slot_operand(op, a);
9440                self.put_loc(slot, Value::Uninitialized);
9441            }
9442            CloseLoc => {
9443                // "Close" a binding: give it a *fresh* cell holding the current
9444                // value. Closures created before this point keep the old cell and the
9445                // ones created after see the new one, which is what makes every
9446                // iteration of `for (let i ...)` capture its own `i`, and what freezes
9447                // a block-scoped binding when the block ends.
9448                //
9449                // Clearing the slot instead (which this used to do) broke both: a
9450                // closure over a captured block variable read `undefined`, and a loop
9451                // terminated after one iteration.
9452                let slot = self.slot_operand(op, a);
9453                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
9454                if index >= 0 {
9455                    let current = self.frame().cells[index as usize].get();
9456                    let fresh = self.new_cell(current);
9457                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
9458                        *cell = fresh;
9459                    }
9460                }
9461            }
9462            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
9463                let slot = self.slot_operand(op, a);
9464                let value = self.get_arg(slot);
9465                self.push(value);
9466            }
9467            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
9468                let slot = self.slot_operand(op, a);
9469                let value = self.pop();
9470                self.put_arg(slot, value);
9471            }
9472            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
9473                let slot = self.slot_operand(op, a);
9474                let value = self.pop();
9475                self.put_arg(slot, value.clone());
9476                self.push(value);
9477            }
9478
9479            // -- closure variables ------------------------------------------
9480            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
9481                let slot = self.slot_operand(op, a);
9482                // A name a direct `eval` created shadows the binding the compiler chose.
9483                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
9484                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
9485                // and only a runtime lookup can know that.
9486                if let Some(cell) = self.eval_created_local(slot) {
9487                    self.push(cell.get());
9488                    return self.step();
9489                }
9490                let value = self.cell_value(slot)?;
9491                self.push(value);
9492            }
9493            GetVarRefCheck => {
9494                let slot = self.slot_operand(op, a);
9495                let value = self.cell_value(slot)?;
9496                if matches!(value, Value::Uninitialized) {
9497                    return Err(self.dead_zone(slot, VarSlot::Closure));
9498                }
9499                self.push(value);
9500            }
9501            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
9502                let slot = self.slot_operand(op, a);
9503                let value = self.pop();
9504                if let Some(cell) = self.eval_created_local(slot) {
9505                    cell.set(value);
9506                    return self.step();
9507                }
9508                // Same rule as `PutLocCheck`: a checked store to a captured binding
9509                // refuses a `const` once its initialiser has run.
9510                if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
9511                    return Err(self.read_only(slot, VarSlot::Closure));
9512                }
9513                self.set_cell(slot, value)?;
9514            }
9515            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
9516                let slot = self.slot_operand(op, a);
9517                let value = self.pop();
9518                if let Some(cell) = self.eval_created_local(slot) {
9519                    cell.set(value.clone());
9520                    self.push(value);
9521                    return self.step();
9522                }
9523                self.set_cell(slot, value.clone())?;
9524                self.push(value);
9525            }
9526
9527            // -- globals ----------------------------------------------------
9528            GetVar => {
9529                let value = self.get_global(a as usize)?;
9530                self.push(value);
9531            }
9532            GetVarUndef => {
9533                let value = self
9534                    .get_global(a as usize)
9535                    .or_else(|_| Ok(Value::Undefined))?;
9536                self.push(value);
9537            }
9538            DeleteVar => {
9539                // `delete name` for a name that is not a declared binding. A lexical
9540                // global lives in the reference table and cannot be deleted; anything
9541                // reachable only as a property of the global object is *implicit* —
9542                // `x = 1` with no declaration — and goes away if it is configurable,
9543                // which is what `delete` on an implicit global answers.
9544                let name = self.atom_text(a as usize);
9545                let global = self.realm.global.clone();
9546                let deleted = if self.realm.globals.contains_key(&name) {
9547                    false
9548                } else if global.own_property(&name).is_some() {
9549                    self.delete_property(&global, &name)?
9550                } else {
9551                    true
9552                };
9553                self.push(Value::Bool(deleted));
9554            }
9555            PutVar => {
9556                let value = self.pop();
9557                self.put_global(a as usize, value)?;
9558            }
9559            PutVarInit => {
9560                let slot = a as usize;
9561                let value = self.pop();
9562                self.init_global(slot, value)?;
9563            }
9564
9565            // -- arithmetic -------------------------------------------------
9566            Add => self.binary_add()?,
9567            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
9568                let raw_right = self.pop();
9569                let raw_left = self.pop();
9570                // BigInt arithmetic is a separate path, and not only for the type of the
9571                // result: `ToNumber` of a bigint throws, so mixing the two must be an error
9572                // rather than a silent conversion.
9573                if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
9574                    let left = self.primitive_of(raw_left)?;
9575                    let right = self.primitive_of(raw_right)?;
9576                    let value = self.bigint_arithmetic(op, left, right)?;
9577                    self.push(value);
9578                } else {
9579                    let right = self.numeric(raw_right)?;
9580                    let left = self.numeric(raw_left)?;
9581                    self.push(arithmetic(op, left, right)?);
9582                }
9583            }
9584            Neg => {
9585                let raw = self.pop();
9586                match raw {
9587                    // A bigint negates exactly, however wide it is.
9588                    Value::BigInt(big) => {
9589                        let negated = big.negate();
9590                        self.push(self.bigint(negated));
9591                    }
9592                    other => {
9593                        let value = self.numeric(other)?;
9594                        self.push(negate(value));
9595                    }
9596                }
9597            }
9598            Plus => {
9599                let value = self.pop();
9600                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
9601                // unary plus is defined to produce a *number*, which a bigint cannot
9602                // become without loss. It used to fall through to `NaN`.
9603                if matches!(value, Value::BigInt(_)) {
9604                    return Err(self.type_error("cannot convert bigint to number"));
9605                }
9606                let numeric = self.numeric_of(value)?;
9607                self.push(numeric);
9608            }
9609            Inc => {
9610                let raw = self.pop();
9611                let (_, updated) = self.advance_numeric(raw, true)?;
9612                self.push(updated);
9613            }
9614            Dec => {
9615                let raw = self.pop();
9616                let (_, updated) = self.advance_numeric(raw, false)?;
9617                self.push(updated);
9618            }
9619            PostInc | PostDec => {
9620                // `x -> x x+1`: the *new* value ends up on top, so the store the
9621                // compiler emits right after (`put_var`) writes the incremented
9622                // one, while the old value stays underneath for the expression's
9623                // own result. Getting this backwards makes `i++` a no-op, which
9624                // turns `while (i < 3)` into an infinite loop.
9625                let raw = self.pop();
9626                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
9627                self.push(old);
9628                self.push(updated);
9629            }
9630            Not => {
9631                let raw = self.pop();
9632                match raw {
9633                    // `~x` on a bigint is `-x - 1`, exact at any width.
9634                    Value::BigInt(big) => {
9635                        let inverted = big.bitnot();
9636                        self.push(self.bigint(inverted));
9637                    }
9638                    other => {
9639                        let value = self.numeric(other)?;
9640                        self.push(Value::Int(!value.to_int32()));
9641                    }
9642                }
9643            }
9644            Lnot => {
9645                let value = self.pop();
9646                self.push(Value::Bool(!value.to_boolean()));
9647            }
9648
9649            // -- comparison -------------------------------------------------
9650            Lt | Lte | Gt | Gte => {
9651                let right = self.pop();
9652                let left = self.pop();
9653                let answer = self.relational(op, left, right)?;
9654                self.push(answer);
9655            }
9656            Eq | Neq => {
9657                let right = self.pop();
9658                let left = self.pop();
9659                let equal = self.abstract_equals(left, right)?;
9660                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
9661            }
9662            StrictEq => {
9663                let right = self.pop();
9664                let left = self.pop();
9665                self.push(Value::Bool(left.strict_equals(&right)));
9666            }
9667            StrictNeq => {
9668                let right = self.pop();
9669                let left = self.pop();
9670                self.push(Value::Bool(!left.strict_equals(&right)));
9671            }
9672            IsUndefined => {
9673                // `=== undefined`, which is what a destructuring default tests. It is
9674                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
9675                let value = self.pop();
9676                self.push(Value::Bool(matches!(value, Value::Undefined)));
9677            }
9678            IsUndefinedOrNull => {
9679                let value = self.pop();
9680                self.push(Value::Bool(value.is_nullish()));
9681            }
9682            Typeof => {
9683                let value = self.pop();
9684                self.push(self.string(value.type_of()));
9685            }
9686            ToObject => {
9687                // A destructuring *object* pattern starts here, which is why
9688                // `var {} = null` throws. Only `undefined` and `null` are refused; a
9689                // primitive is boxed.
9690                let value = self.pop();
9691                let object = self.object_from(&value)?;
9692                self.push(Value::Object(object));
9693            }
9694            Instanceof => {
9695                let constructor = self.pop();
9696                let object = self.pop();
9697                let answer = self.instance_of(&object, &constructor)?;
9698                self.push(Value::Bool(answer));
9699            }
9700            In => {
9701                let object = self.pop();
9702                let key = self.pop();
9703                let answer = self.has_property(&key, &object)?;
9704                self.push(Value::Bool(answer));
9705            }
9706
9707            // -- control flow -----------------------------------------------
9708            Goto | Goto8 | Goto16 => {
9709                self.frame_mut().pc = a as usize;
9710            }
9711            IfTrue | IfTrue8 => {
9712                let value = self.pop();
9713                if value.to_boolean() {
9714                    self.frame_mut().pc = a as usize;
9715                }
9716            }
9717            IfFalse | IfFalse8 => {
9718                let value = self.pop();
9719                if !value.to_boolean() {
9720                    self.frame_mut().pc = a as usize;
9721                }
9722            }
9723            Catch => {
9724                // Pushes the handler target onto the value stack; `unwind` finds it.
9725                self.push(Value::CatchOffset(a));
9726            }
9727            Gosub => {
9728                self.push(Value::ReturnAddress(next as u32));
9729                self.frame_mut().pc = a as usize;
9730            }
9731            Ret => {
9732                let value = self.pop();
9733                match value {
9734                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
9735                    _ => {
9736                        return Err(Signal::Throw(
9737                            self.make_error("InternalError", "invalid return address"),
9738                        ));
9739                    }
9740                }
9741            }
9742            NipCatch => {
9743                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
9744                // including the marker, keeping the top value.
9745                let top = self.pop();
9746                loop {
9747                    match self.pop() {
9748                        Value::CatchOffset(_) | Value::Undefined => break,
9749                        _ => {}
9750                    }
9751                    if self.frame().stack.is_empty() {
9752                        break;
9753                    }
9754                }
9755                self.push(top);
9756            }
9757            Throw => {
9758                let value = self.pop();
9759                return Err(Signal::Throw(value));
9760            }
9761            ThrowError => {
9762                let name = self.atom_text(a as usize);
9763                let (class, message) = match b {
9764                    0 => ("TypeError", format!("'{name}' is read-only")),
9765                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
9766                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
9767                    // `delete super.x` is a syntax-level mistake the reference reports
9768                    // with this wording, not a property-access failure.
9769                    3 => (
9770                        "ReferenceError",
9771                        "unsupported reference to 'super'".to_string(),
9772                    ),
9773                    4 => (
9774                        "TypeError",
9775                        "iterator does not have a throw method".to_string(),
9776                    ),
9777                    5 => (
9778                        "ReferenceError",
9779                        "invalid assignment left-hand side".to_string(),
9780                    ),
9781                    _ => ("TypeError", format!("invalid operation on '{name}'")),
9782                };
9783                return Err(Signal::Throw(self.make_error(class, &message)));
9784            }
9785            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
9786            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
9787            YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
9788            AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
9789            Await => return Ok(Step::Suspend(SuspendKind::Await)),
9790            ReturnAsync => {
9791                // The reference's `return_async` returns `undefined` and lets the resume
9792                // machinery pick the real value off `sp[-1]`, which is how it tells a
9793                // completion from a suspension. Carrying the value explicitly says the
9794                // same thing without the implicit stack slot.
9795                let value = self.pop();
9796                return Ok(Step::Return(value));
9797            }
9798            Return => {
9799                let value = self.pop();
9800                return Ok(Step::Return(value));
9801            }
9802            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
9803
9804            // -- calls ------------------------------------------------------
9805            Call | Call0 | Call1 | Call2 | Call3 => {
9806                let argc = self.argc_operand(op, a);
9807                let args = self.pop_n(argc);
9808                let callee = self.pop();
9809                // A plain call has no receiver; the callee decides what to do with
9810                // `undefined` (a sloppy function substitutes the global object).
9811                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
9812                    self.push(result);
9813                }
9814            }
9815            CallConstructor => {
9816                // `constructor this_obj args… -> object`. The duplicated
9817                // constructor is `new.target`; this milestone does not expose it,
9818                // so the extra copy is simply consumed here.
9819                let argc = a as usize;
9820                let args = self.pop_n(argc);
9821                let new_target = self.pop();
9822                let callee = self.pop();
9823                let result = self.construct(callee, new_target, args)?;
9824                self.push(result);
9825            }
9826            CallMethod => {
9827                let argc = a as usize;
9828                let args = self.pop_n(argc);
9829                let callee = self.pop();
9830                let this = self.pop();
9831                if let Some(result) = self.call_or_push(callee, this, args)? {
9832                    self.push(result);
9833                }
9834            }
9835            Apply => {
9836                // `func this array -> result`, the spread-call form: the compiler
9837                // builds one array of arguments, and all that is left here is to
9838                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
9839                let array = self.pop();
9840                let this = self.pop();
9841                let callee = self.pop();
9842                let args = self.array_like_to_args(&array)?;
9843                if a & 1 != 0 {
9844                    let result = self.construct(callee, this, args)?;
9845                    self.push(result);
9846                } else if let Some(result) = self.call_or_push(callee, this, args)? {
9847                    self.push(result);
9848                }
9849            }
9850            TailCall | TailCallMethod => {
9851                // `tail_call` is `call` whose result is returned immediately — the
9852                // reference jumps straight to `done` instead of storing the value and
9853                // running on. The callee still gets its own frame, so deep tail
9854                // recursion hits the stack limit exactly like plain recursion does;
9855                // marking this frame lets the return path unwind without needing
9856                // instructions after the call.
9857                let argc = if op == TailCallMethod {
9858                    a as usize
9859                } else {
9860                    self.argc_operand(op, a)
9861                };
9862                let args = self.pop_n(argc);
9863                let callee = self.pop();
9864                let this = if op == TailCallMethod {
9865                    self.pop()
9866                } else {
9867                    Value::Undefined
9868                };
9869                if let Value::Object(function) = &callee
9870                    && let Some((code, env)) = bytecode_of(function)
9871                {
9872                    // A generator or async body is not run here at all: calling it only
9873                    // *creates* the generator/coroutine, so it must not inherit this
9874                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
9875                    // onto `f`'s frame, and the first `yield`/`await` then reported
9876                    // "a generator body ran as an ordinary call".
9877                    if code.code.kind.is_generator() || code.code.kind.is_async() {
9878                        let value = self.call_value(callee, this, args)?;
9879                        return Ok(Step::Return(value));
9880                    }
9881                    self.frame_mut().tail = true;
9882                    self.push_frame(code, env, this, args, callee)?;
9883                    return Ok(Step::Continue);
9884                }
9885                // A native callee has no frame to reuse, so its value is simply
9886                // returned.
9887                let value = self.call_value(callee, this, args)?;
9888                return Ok(Step::Return(value));
9889            }
9890
9891            // -- objects ----------------------------------------------------
9892            SpecialObject => {
9893                let value = self.special_object(a)?;
9894                self.push(value);
9895            }
9896            PrivateSymbol => {
9897                // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
9898                // symbol each time it is evaluated, which is why the compiler evaluates it
9899                // once (at class definition) and stores it in a class-scope binding.
9900                let name = self.atom_text(a as usize);
9901                let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
9902                self.push(Value::Symbol(symbol));
9903            }
9904            GetPrivateField => {
9905                // `obj symbol -> value`. A missing private field is a TypeError, which is what
9906                // makes `#x` inaccessible on any object not built by this class.
9907                let symbol = self.pop();
9908                let object = self.pop();
9909                let value = self.read_private_field(&object, &symbol)?;
9910                self.push(value);
9911            }
9912            PutPrivateField => {
9913                // `obj value symbol ->`, and the store is a plain assignment to a property the
9914                // class already created, so there is no setter to consult.
9915                let symbol = self.pop();
9916                let value = self.pop();
9917                let object = self.pop();
9918                self.write_private_field(&object, &symbol, value)?;
9919            }
9920            DefinePrivateField => {
9921                // `obj symbol value -> obj`: a field initialiser creates the property, and
9922                // redefining one is a TypeError ("already exists").
9923                let value = self.pop();
9924                let symbol = self.pop();
9925                let object = self.pop();
9926                self.define_private_field(&object, &symbol, value)?;
9927                self.push(object);
9928            }
9929            PrivateIn => {
9930                // `obj key -> bool`: `#x in o`. The second operand decides which question is
9931                // being asked, which is the reference's `js_operator_private_in`: a *symbol*
9932                // is a field, so this is an own-property test; a *function* is a method or
9933                // accessor, so this is a brand check.
9934                let key = self.pop();
9935                let object = self.pop();
9936                let Some(target) = object.as_object() else {
9937                    return Err(Signal::Throw(
9938                        self.make_error("TypeError", "invalid 'in' operand"),
9939                    ));
9940                };
9941                let present = match &key {
9942                    Value::Object(_) => self.check_brand(target, &key)?,
9943                    _ => target.own_property_key(&self.private_key(&key)?).is_some(),
9944                };
9945                self.push(Value::Bool(present));
9946            }
9947            AddBrand => {
9948                // `obj home ->`: create the class brand on `home` if it has none, then give
9949                // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
9950                // class definition: only the prototype's copy of the symbol is wanted.
9951                let home = self.pop();
9952                let object = self.pop();
9953                self.add_brand(&object, &home)?;
9954            }
9955            CheckBrand => {
9956                // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
9957                // Both stay, because the caller needs them — `nip` halves a read into its
9958                // value and `call_method` uses the pair as receiver and callee.
9959                let function = self.peek(0);
9960                let object = self.peek(1);
9961                let Some(target) = object.as_object() else {
9962                    return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9963                };
9964                if !self.check_brand(target, &function)? {
9965                    return Err(Signal::Throw(
9966                        self.make_error("TypeError", "invalid brand on object"),
9967                    ));
9968                }
9969            }
9970            GetLength => {
9971                // `get_length` is the `.length` read; an array and a string answer
9972                // from their own length, anything else from the property.
9973                let target = self.pop();
9974                let value = match &target {
9975                    Value::Object(object) => match object.array_length() {
9976                        Some(length) => crate::object::length_value(length),
9977                        None => self.read_field(&target, "length")?,
9978                    },
9979                    Value::String(text) => Value::Int(text.utf16_len() as i32),
9980                    _ => self.read_field(&target, "length")?,
9981                };
9982                self.push(value);
9983            }
9984            GetField | GetField2 => {
9985                let object = self.pop();
9986                // Borrowed out of the code object, not cloned: `atom_key` returns an owned
9987                // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
9988                // just below is what lets the borrow outlive the `&mut self` the lookup
9989                // needs — one refcount bump instead of a key clone plus its drop, on the
9990                // hottest property path there is: every `o.x` and every `o.m()` receiver.
9991                let code = self.frame().code.clone();
9992                let key = &code.atom_keys[a as usize];
9993                let value = self.read_field_cached(&object, key, next)?;
9994                if op == GetField2 {
9995                    self.push(object);
9996                }
9997                self.push(value);
9998            }
9999            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
10000                let key = self.pop();
10001                let object = self.pop();
10002                let key = self.propkey(&key)?;
10003                let value = self.read_field_key(&object, &key)?;
10004                if matches!(op, GetArrayEl2 | GetArrayEl3) {
10005                    self.push(object);
10006                }
10007                if op == GetArrayEl3 {
10008                    // The key goes back in its *value* form, which the compiler stores
10009                    // into the target of a destructuring assignment.
10010                    self.push(match &key {
10011                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
10012                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
10013                    });
10014                }
10015                self.push(value);
10016            }
10017            PutField => {
10018                let value = self.pop();
10019                let object = self.pop();
10020                // Borrowed, like the `get_field` arm: `atom_key` would return an owned
10021                // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
10022                // only reads. `this.value = …` is the write half of the hottest loop in
10023                // `property:method-call`, and `own_property_key` was 4.8% of the case.
10024                let code = self.frame().code.clone();
10025                let key = &code.atom_keys[a as usize];
10026                self.write_field_key(&object, key, value)?;
10027            }
10028            PutArrayEl => {
10029                let value = self.pop();
10030                let key = self.pop();
10031                let object = self.pop();
10032                let key = self.propkey(&key)?;
10033                self.write_field_key(&object, &key, value)?;
10034            }
10035            DefineField => {
10036                let value = self.pop();
10037                let object = self.pop();
10038                // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
10039                // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
10040                // three U+FFFD — a property under a different name from the one
10041                // `o["\uD800"]` reads.
10042                let code = self.frame().code.clone();
10043                let key = code.atom_keys[a as usize].clone();
10044                // No naming here. `{m: function(){}}` is named by the *compiler*, which
10045                // emits `set_name` — and only where `NamedEvaluation` applies, so
10046                // `{m: (0, function(){})}` stays anonymous. Naming every function that
10047                // reaches a property definition got that case wrong, and the compiler is
10048                // the only place that can tell the two apart.
10049                if let Some(target) = object.as_object() {
10050                    // Only an *array* stores into the element vector. A numeric key
10051                    // on an ordinary object is an ordinary property, which is what
10052                    // makes `{1: 'a'}` iterate as a key rather than disappear.
10053                    let stored = target.is_array()
10054                        && key.as_str().and_then(array_index).is_some_and(|index| {
10055                            target.array_set(self.heap, index as usize, value.clone())
10056                        });
10057                    if !stored {
10058                        target.define_data_key(&key, value);
10059                    }
10060                }
10061                self.push(object);
10062            }
10063            DefineArrayEl => {
10064                // `obj key value -> obj key`. The *value* form of the key is what goes
10065                // back on the stack — the compiler stores it into the pattern's binding —
10066                // so the symbol is not stringified on the way through.
10067                let value = self.pop();
10068                let key_value = self.pop();
10069                let object = self.peek(0);
10070                let key = self.propkey(&key_value)?;
10071                self.write_field_key(&object, &key, value)?;
10072                self.push(key_value);
10073            }
10074            SetHomeObject => {
10075                // `obj func -> obj func`: records the object a method was defined on so
10076                // `super` inside it resolves against that object's prototype.
10077                let function = self.peek(0);
10078                let home = self.peek(1);
10079                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
10080                    function.set_home_object(Some(home.clone()));
10081                }
10082            }
10083            Regexp => {
10084                // `pattern flags -> regexp`. A literal compiles here rather than through the
10085                // constructor, which is both what the reference's dedicated opcode is for
10086                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
10087                let flags = self.pop();
10088                let pattern = self.pop();
10089                let pattern = self.to_js_string(&pattern)?;
10090                let flags = self.to_js_string(&flags)?;
10091                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
10092                self.push(Value::Object(object));
10093            }
10094            UsingDisposeInit => {
10095                // The error state a disposal accumulates into. Uninitialised means "no
10096                // failure yet"; anything else is the exception being propagated.
10097                self.push(Value::Uninitialized);
10098            }
10099            UsingCheck => {
10100                // `value -> value, method`: validate and snapshot the disposer now, so a
10101                // later change to `Symbol.dispose` cannot change what gets called, and so a
10102                // value that is not disposable fails before the body runs.
10103                let value = self.pop();
10104                let method = self.using_method_for(&value, a as u8 == 1)?;
10105                self.push(value);
10106                self.push(method);
10107            }
10108            UsingDispose => {
10109                // `error_state -> error_state'`: dispose the variable at `slot` — its value
10110                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
10111                // the pending error.
10112                let slot = self.slot_operand(op, a);
10113                let error_state = self.pop();
10114                let merged = self.using_dispose_once(slot, error_state)?;
10115                self.push(merged);
10116            }
10117            UsingDisposeMerge => {
10118                let new_error = self.pop();
10119                let error_state = self.pop();
10120                let merged = self.merge_dispose_error(new_error, error_state);
10121                self.push(merged);
10122            }
10123            UsingDisposeEnd => {
10124                // A disposal that failed replaces the block's normal completion, so the
10125                // error state becomes a real throw here rather than at the call site.
10126                let error_state = self.pop();
10127                if !matches!(error_state, Value::Uninitialized) {
10128                    return Err(Signal::Throw(error_state));
10129                }
10130            }
10131            UsingDisposeAsync => {
10132                // `await using` needs a promise to await and this runtime has no
10133                // `Promise` builtin, so the disposer is called synchronously and its result
10134                // discarded. That is correct for a disposer that returns nothing and is
10135                // reported as a gap rather than silently skipped.
10136                let slot = self.slot_operand(op, a);
10137                let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
10138                self.push(error_state);
10139            }
10140            GetSuper => {
10141                // `obj -> obj's prototype`: the starting point of a `super` lookup.
10142                let object = self.pop();
10143                let proto = match &object {
10144                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
10145                    _ => Value::Null,
10146                };
10147                self.push(proto);
10148            }
10149            GetSuperValue => {
10150                // `receiver proto key -> value`, searching from `proto` but reporting to
10151                // `receiver`, which is what `super.g` must do for a getter to see `this`.
10152                //
10153                // Three values in, one out: the receiver is *consumed*, not left under the
10154                // result. Leaving it there was invisible for `super.x` in `return` or
10155                // statement position (the result is what gets popped) and corrupted the
10156                // frame everywhere else — `print(super.x)` left the class where the call
10157                // opcode looks for the receiver and called the class itself.
10158                let key = self.pop();
10159                let proto = self.pop();
10160                let receiver = self.pop();
10161                let value = self.super_read(&receiver, &proto, &key)?;
10162                self.push(value);
10163            }
10164            PutSuperValue => {
10165                // `receiver proto key value ->`: a store that starts at `proto` but
10166                // assigns to `receiver`.
10167                let value = self.pop();
10168                let key = self.pop();
10169                let proto = self.pop();
10170                let receiver = self.pop();
10171                self.super_write(&receiver, &proto, &key, value)?;
10172            }
10173            DefineClass => {
10174                // `parent ctor -> ctor proto`: the constructor becomes the class and a
10175                // fresh prototype object lands on top for the methods to go on.
10176                let name = self.atom_text(a as usize);
10177                let (ctor, proto) = self.define_class(&name, b)?;
10178                self.push(ctor);
10179                self.push(Value::Object(proto));
10180            }
10181            DefineClassComputed => {
10182                // `parent ctor key -> ctor proto key`: the computed name stays put so
10183                // `define_field`-style consumers can still read it.
10184                let key = self.pop();
10185                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
10186                let (ctor, proto) = self.define_class(&name, b)?;
10187                self.push(ctor);
10188                self.push(Value::Object(proto));
10189                self.push(key);
10190            }
10191            DefineMethod => {
10192                let function = self.pop();
10193                let object = self.pop();
10194                // The exact key, like `define_field`: a quoted method key may hold an
10195                // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
10196                // that `o["\uD800"]` finds.
10197                let code = self.frame().code.clone();
10198                let key = code.atom_keys[a as usize].clone();
10199                // A method's `[[HomeObject]]` is the object it was defined on, which is
10200                // what `super` inside it resolves against.
10201                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
10202                    function.set_home_object(Some(object.clone()));
10203                }
10204                if let Some(text) = key.as_wtf8() {
10205                    self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
10206                } else {
10207                    self.set_function_name(
10208                        &function,
10209                        &key_with_accessor_prefix(&key.to_string(), b),
10210                    );
10211                }
10212                if let Some(array) = object.as_object() {
10213                    define_function_property(array, &key, function, b);
10214                }
10215                self.push(object);
10216            }
10217            DefineMethodComputed => {
10218                let function = self.pop();
10219                let key = self.pop();
10220                let object = self.pop();
10221                let key = self.propkey(&key)?;
10222                // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
10223                // the name: `super` inside a computed method resolves through it. Without
10224                // this, `class B extends A { [k]() { return super.m() } }` read the
10225                // home object as null and threw.
10226                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
10227                    function.set_home_object(Some(object.clone()));
10228                }
10229                match key.as_wtf8() {
10230                    Some(text) => {
10231                        let name = accessor_prefixed(text, a);
10232                        self.set_function_name_wtf8(&function, &name);
10233                    }
10234                    None => self.set_function_name(
10235                        &function,
10236                        &key_with_accessor_prefix(&key.to_string(), a),
10237                    ),
10238                }
10239                if let Some(array) = object.as_object() {
10240                    define_function_property(array, &key, function, a);
10241                }
10242                self.push(object);
10243            }
10244            SetProto => {
10245                let proto = self.pop();
10246                let object = self.pop();
10247                if let Some(target) = object.as_object() {
10248                    target.set_proto(proto.as_object().cloned());
10249                }
10250                self.push(object);
10251            }
10252            CopyDataProperties => {
10253                let exclusion = self.pop();
10254                let source = self.pop();
10255                let target = self.peek(0);
10256                self.copy_properties(&target, &source, &exclusion)?;
10257                self.push(source);
10258                self.push(exclusion);
10259            }
10260            ToPropkey => {
10261                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
10262                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
10263                // ordinary `"Symbol(b)"` property.
10264                let value = self.pop();
10265                let key = match self.propkey(&value)? {
10266                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
10267                    PropertyKey::String(text) => self.string_wtf8(text),
10268                };
10269                self.push(key);
10270            }
10271            SetName => {
10272                let function = self.peek(0);
10273                let name = self.atom_wtf8(a as usize);
10274                self.set_function_name_wtf8(&function, &name);
10275            }
10276            SetNameComputed => {
10277                let key = self.peek(1);
10278                let function = self.peek(0);
10279                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
10280                self.set_function_name(&function, &name);
10281            }
10282
10283            // -- arrays -----------------------------------------------------
10284            ArrayFrom => {
10285                let count = a as usize;
10286                let elements = self.pop_n(count);
10287                let array = self.new_array(elements);
10288                self.push(Value::Object(array));
10289            }
10290            Append => {
10291                // `array index iterable -> array new_index`
10292                let iterable = self.pop();
10293                self.pop();
10294                let array = self.peek(0);
10295                let added = self.append_enumerate(&array, &iterable)?;
10296                self.push(Value::Int(added));
10297            }
10298
10299            // -- iteration --------------------------------------------------
10300            ForInStart => {
10301                let value = self.pop();
10302                let record = self.for_in_record(&value)?;
10303                self.push(Value::Object(record));
10304            }
10305            ForInNext => {
10306                // `record -> record key done`. The flag is *done*, not "found":
10307                // the compiler tests it with `if_false` to jump back into the body,
10308                // so reporting `true` while keys remain would end the loop at once.
10309                let record = self.peek(0);
10310                match self.for_in_advance(&record)? {
10311                    Some(key) => {
10312                        let text = self.string(key);
10313                        self.push(text);
10314                        self.push(Value::Bool(false));
10315                    }
10316                    None => {
10317                        self.push(Value::Undefined);
10318                        self.push(Value::Bool(true));
10319                    }
10320                }
10321            }
10322            ForOfStart => {
10323                let value = self.pop();
10324                let iterator = self.get_iterator(&value)?;
10325                self.push(iterator.object);
10326                self.push(iterator.next);
10327                self.push(Value::CatchOffset(0));
10328            }
10329            ForOfNext => {
10330                // `iter next catch_offset -> iter next catch_offset value done`.
10331                //
10332                // The operand is how many values sit *above* the iterator triple: a
10333                // destructuring rest element keeps its target array and running index
10334                // there while draining the iterator, so the triple is not at the top.
10335                let extra = a as usize;
10336                let iterator_slot = 2 + extra;
10337                // An exhausted iterator is replaced by `undefined` (see below), so a
10338                // second step must not call `next` again — `Array.from` and a
10339                // destructuring pattern both keep stepping past the end.
10340                let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
10341                    (Value::Undefined, true)
10342                } else {
10343                    let iterator = Iterator {
10344                        object: self.peek(iterator_slot),
10345                        next: self.peek(1 + extra),
10346                    };
10347                    self.iterator_step(&iterator)?
10348                };
10349                if done {
10350                    // The result's `value` is meaningless once the iterator is done:
10351                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
10352                    // rather than binding the generator's return value.
10353                    let top = self.frame().stack.len() - 1 - iterator_slot;
10354                    self.frame_mut().stack[top] = Value::Undefined;
10355                    self.push(Value::Undefined);
10356                    self.push(Value::Bool(true));
10357                } else {
10358                    self.push(value);
10359                    self.push(Value::Bool(false));
10360                }
10361            }
10362            IteratorNext => {
10363                // `iter next catch val -> iter next catch val'`: replace the argument with
10364                // the result of `next(val)`. The triple below stays put, which is why the
10365                // three instructions of the `yield*` loop all address the stack the same way.
10366                let value = self.pop();
10367                let object = self.peek(2);
10368                let next = self.peek(1);
10369                let result = self.call_value(next, object, vec![value])?;
10370                self.push(result);
10371            }
10372            IteratorCall => {
10373                // `iter next catch val -> iter next catch val' flag`.
10374                //
10375                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
10376                // The flag is `true` when the method was missing, which is how the
10377                // caller learns that the inner iterator cannot take part in the
10378                // unwinding.
10379                let value = self.pop();
10380                let object = self.peek(2);
10381                let key = if a & 1 != 0 { "throw" } else { "return" };
10382                let method = self.read_field(&object, key)?;
10383                if matches!(method, Value::Undefined | Value::Null) {
10384                    self.push(value);
10385                    self.push(Value::Bool(true));
10386                } else {
10387                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
10388                    let result = self.call_value(method, object, argument)?;
10389                    self.push(result);
10390                    self.push(Value::Bool(false));
10391                }
10392            }
10393            IteratorCheckObject => {
10394                if !matches!(self.peek(0), Value::Object(_)) {
10395                    return Err(Signal::Throw(
10396                        self.make_error("TypeError", "iterator must return an object"),
10397                    ));
10398                }
10399            }
10400            IteratorClose => {
10401                // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
10402                // calling the iterator's `return` so it can release whatever it holds.
10403                //
10404                // The catch offset goes first, so an exception from `return` is not caught
10405                // by the loop being abandoned. This used to pop the three operands and call
10406                // nothing at all, which made `break` out of a `for of` invisible to an
10407                // iterator with a `return` method.
10408                self.pop();
10409                self.pop();
10410                let iterator = self.pop();
10411                if !matches!(iterator, Value::Undefined) {
10412                    let method = self.read_field(&iterator, "return")?;
10413                    if !matches!(method, Value::Undefined | Value::Null) {
10414                        let result = self.call_value(method, iterator.clone(), Vec::new())?;
10415                        // §7.4.6: a `return` that answers a non-object is a TypeError.
10416                        if !matches!(result, Value::Object(_)) {
10417                            return Err(Signal::Throw(
10418                                self.make_error("TypeError", "iterator must return an object"),
10419                            ));
10420                        }
10421                    }
10422                }
10423            }
10424            Import => {
10425                // `import(specifier)`: the options slot is on top and is not read yet.
10426                let _options = self.pop();
10427                let specifier = self.pop();
10428                let promise = self.dynamic_import(specifier)?;
10429                self.push(promise);
10430            }
10431            ForAwaitOfStart => {
10432                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
10433                // `Symbol.iterator` fallback.
10434                let value = self.pop();
10435                let iterator = self.get_async_iterator(&value)?;
10436                self.push(iterator.object);
10437                self.push(iterator.next);
10438                self.push(Value::CatchOffset(0));
10439            }
10440            ForAwaitOfNext => {
10441                // `for await` steps the iterator and leaves the *result* wrapped in a
10442                // promise, so the `await` the compiler emits right after this can suspend
10443                // on it. Unwrapping happens in `iterator_get_value_done`.
10444                let extra = a as usize;
10445                let iterator_slot = 2 + extra;
10446                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
10447                    Value::Undefined
10448                } else {
10449                    let iterator = Iterator {
10450                        object: self.peek(iterator_slot),
10451                        next: self.peek(1 + extra),
10452                    };
10453                    let next = iterator.next.clone();
10454                    self.call_value(next, iterator.object, Vec::new())?
10455                };
10456                let promise = self.promise_resolve_value(result)?;
10457                self.push(promise);
10458            }
10459            IteratorGetValueDone => {
10460                // `result -> value done`. A missing result object means the iterator was
10461                // already exhausted, which the loop treats as `done`.
10462                let result = self.pop();
10463                let done = match &result {
10464                    Value::Object(object) => self
10465                        .get_property(object, "done")?
10466                        .is_some_and(|value| value.to_boolean()),
10467                    _ => true,
10468                };
10469                if done {
10470                    // Clear the iterator object so the `iterator_close` the loop emits on
10471                    // its way out has nothing to close: `AsyncIteratorClose` must *not* run
10472                    // on normal completion, and this is where a normal completion is
10473                    // recognised — the same trick `for_of_next` uses, which also replaces
10474                    // the slot with `undefined`.
10475                    //
10476                    // The layout is fixed because only `for await` emits this opcode:
10477                    // `iter next catch [result]`, so the iterator is three below the top.
10478                    let depth = self.frame().stack.len();
10479                    if depth >= 3 {
10480                        self.frame_mut().stack[depth - 3] = Value::Undefined;
10481                    }
10482                    self.push(Value::Undefined);
10483                    self.push(Value::Bool(true));
10484                } else {
10485                    let Value::Object(object) = &result else {
10486                        self.push(Value::Undefined);
10487                        self.push(Value::Bool(true));
10488                        return Ok(Step::Continue);
10489                    };
10490                    let value = self
10491                        .get_property(object, "value")?
10492                        .unwrap_or(Value::Undefined);
10493                    self.push(value);
10494                    self.push(Value::Bool(false));
10495                }
10496            }
10497
10498            Delete => {
10499                // `delete obj[key]`, where the key was just pushed. Deleting an array
10500                // index leaves a *hole* rather than closing the gap, and a
10501                // non-configurable property answers `false` and stays.
10502                let key = self.pop();
10503                let target = self.pop();
10504                let key = self.propkey(&key)?;
10505                let text_label = key.as_str().unwrap_or("").to_string();
10506                let deleted = match &target {
10507                    Value::Object(object) => {
10508                        let object = object.clone();
10509                        self.delete_property_key(&object, &key)?
10510                    }
10511                    // A string's `length` and its index properties are
10512                    // non-configurable, so deleting one answers `false`.
10513                    Value::String(text) => {
10514                        !(text_label == "length"
10515                            || array_index(&text_label)
10516                                .is_some_and(|index| (index as usize) < text.utf16_len()))
10517                    }
10518                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
10519                    // object to delete from, and only a *boxable* primitive has one.
10520                    Value::Undefined | Value::Null => {
10521                        return Err(Signal::Throw(
10522                            self.make_error("TypeError", "cannot convert to object"),
10523                        ));
10524                    }
10525                    // Any other primitive has no own properties; deleting nothing
10526                    // succeeds.
10527                    _ => true,
10528                };
10529                // §13.5.1.2: in strict mode a `delete` that answers `false` is a
10530                // `TypeError` rather than a `false` result. Sloppy mode silently reports
10531                // the refusal, which is why the same statement throws here but not there.
10532                if !deleted && self.current_strict() {
10533                    return Err(Signal::Throw(
10534                        self.make_error("TypeError", "cannot delete property"),
10535                    ));
10536                }
10537                self.push(Value::Bool(deleted));
10538            }
10539
10540            // -- exceptions and bookkeeping ---------------------------------
10541            Fclosure | Fclosure8 => {
10542                let value = self.closure(a as usize)?;
10543                self.push(value);
10544            }
10545
10546            other => {
10547                let name = other.info().name;
10548                return Err(Signal::Throw(self.make_error(
10549                    "InternalError",
10550                    &format!("{name} is not implemented yet"),
10551                )));
10552            }
10553        }
10554        Ok(Step::Continue)
10555    }
10556
10557    // -- operand helpers ----------------------------------------------------
10558
10559    /// The slot index an operand names, taking short forms into account.
10560    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
10561        use Opcode::*;
10562        match op {
10563            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
10564            | SetVarRef0 => 0,
10565            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
10566            | SetVarRef1 => 1,
10567            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
10568            | SetVarRef2 => 2,
10569            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
10570            | SetVarRef3 => 3,
10571            _ => a as usize,
10572        }
10573    }
10574
10575    /// The argument count of a call, taking `call0`…`call3` into account.
10576    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
10577        use Opcode::*;
10578        match op {
10579            Call0 => 0,
10580            Call1 => 1,
10581            Call2 => 2,
10582            Call3 => 3,
10583            _ => a as usize,
10584        }
10585    }
10586
10587    /// The atom's name as a property key.
10588    ///
10589    /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
10590    /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
10591    /// `String::clone` was a heap allocation and a copy — per property access.
10592    /// The atom at `index`, as a property key.
10593    ///
10594    /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
10595    /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
10596    /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
10597    /// 5.3% of `property:monomorphic`.
10598    /// The atom's text, exactly — including an unpaired surrogate.
10599    ///
10600    /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
10601    /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
10602    /// `atom_text` below is for the other kind of use, where the atom is a key in the
10603    /// engine's own tables.
10604    fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
10605        self.frame()
10606            .code
10607            .code
10608            .atoms
10609            .get(index)
10610            .map(|atom| match atom {
10611                Atom::Str(text) => text.clone(),
10612                Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
10613                // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
10614                Atom::Null => crate::value::Wtf8::new(String::new()),
10615            })
10616            .unwrap_or_default()
10617    }
10618
10619    fn atom_text(&self, index: usize) -> String {
10620        self.frame()
10621            .code
10622            .code
10623            .atoms
10624            .get(index)
10625            .map(|atom| match atom {
10626                // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
10627                // compare it to an identifier, and a surrogate-bearing name is reachable
10628                // through `atom_wtf8` where it matters.
10629                Atom::Str(text) => text.to_string_lossy().into_owned(),
10630                Atom::Index(value) => value.to_string(),
10631                // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
10632                // `throw_error`, `delete super.x`) never read it.
10633                Atom::Null => String::new(),
10634            })
10635            .unwrap_or_default()
10636    }
10637
10638    fn constant(&mut self, index: usize) -> JsResult<Value> {
10639        let constant = self.frame().code.code.cpool.get(index).cloned();
10640        Ok(match &constant {
10641            Some(Constant::Number(number)) => Value::Float(*number),
10642            Some(Constant::String(text)) => self.string_wtf8(text.clone()),
10643            Some(Constant::BigInt { digits, radix }) => {
10644                match crate::bigint::BigInt::from_radix(digits, *radix) {
10645                    Some(big) => self.bigint(big),
10646                    // A literal the parser accepted is always parseable; a failure here
10647                    // would be a compiler bug, so it reads as an `InternalError`.
10648                    None => {
10649                        return Err(Signal::Throw(
10650                            self.make_error("InternalError", "unparseable bigint literal"),
10651                        ));
10652                    }
10653                }
10654            }
10655            Some(Constant::Function(_)) => {
10656                return Err(Signal::Throw(
10657                    self.make_error("InternalError", "a bare function constant"),
10658                ));
10659            }
10660            // A tagged template's call site: a frozen array of the cooked chunks with a
10661            // frozen `raw` array beside it, which is what `String.raw` reads back.
10662            Some(Constant::Template { cooked, raw }) => {
10663                let cooked_values: Vec<Value> = cooked
10664                    .iter()
10665                    .map(|chunk| match chunk {
10666                        Some(text) => self.string_wtf8(text.clone()),
10667                        None => Value::Undefined,
10668                    })
10669                    .collect();
10670                let raw_values: Vec<Value> =
10671                    raw.iter().map(|text| self.string(text.clone())).collect();
10672                let raw_array = self.new_array(raw_values);
10673                raw_array.set_extensible(false);
10674                let template = self.new_array(cooked_values);
10675                template.define(
10676                    "raw",
10677                    Property::with_attributes(Value::Object(raw_array), false, false),
10678                );
10679                template.set_extensible(false);
10680                Value::Object(template)
10681            }
10682            _ => Value::Undefined,
10683        })
10684    }
10685
10686    /// The reference cell a closure-variable slot names.
10687    ///
10688    /// Two kinds of binding share this addressing: a genuine closure variable
10689    /// (captured from an enclosing function) lives in this frame's environment,
10690    /// while a *declared global* lives in the realm so that a script, a function
10691    /// declaration and their uses all see one binding. A plain `Global` — an
10692    /// undeclared name that may be satisfied by the global object — has no cell at
10693    /// all, which is how `typeof x` still works for a name that does not exist.
10694    /// The reference cell a closure-variable slot names.
10695    ///
10696    /// The environment is resolved once, when the closure is built, and this is
10697    /// just the lookup afterwards. A *declared global* is in there too, pointing at
10698    /// the realm's cell, so a script, a hoisted function declaration and their uses
10699    /// all share one binding. A plain `Global` — a name the script never declared —
10700    /// is read and written through `get_var`/`put_var` by name instead, which is
10701    /// what lets the global object satisfy it.
10702    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
10703        self.frame().env.cells.get(slot).cloned()
10704    }
10705
10706    /// Whether `slot` refers to a global binding through the reference table.
10707    ///
10708    /// A global's cell in the closure environment only exists so the slot has
10709    /// something to point at; the binding itself lives on the global object (a `var`)
10710    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
10711    /// be routed, not performed on the placeholder.
10712    fn is_global_slot(&self, slot: usize) -> bool {
10713        self.frame()
10714            .code
10715            .code
10716            .closure_vars
10717            .get(slot)
10718            .is_some_and(|c| {
10719                // A module's declarations and imports are *not* globals: their cells are
10720                // the module environment's, filled by the host, so the placeholder routing
10721                // must not apply to them.
10722                matches!(
10723                    c.closure_type,
10724                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
10725                )
10726            })
10727    }
10728
10729    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
10730        if self.is_global_slot(slot) {
10731            return self.get_global(slot);
10732        }
10733        Ok(self
10734            .var_ref_cell(slot)
10735            .map(|cell| cell.get())
10736            .unwrap_or(Value::Undefined))
10737    }
10738
10739    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
10740        // A function declaration is hoisted by storing into a global reference before
10741        // the body runs, so this path is also what puts it on the global object.
10742        if self.is_global_slot(slot) {
10743            return self.put_global(slot, value);
10744        }
10745        if let Some(cell) = self.var_ref_cell(slot) {
10746            cell.set(value);
10747        }
10748        Ok(())
10749    }
10750
10751    // -- closures -----------------------------------------------------------
10752
10753    /// Build the closure for the function constant `index`.
10754    ///
10755    /// Every entry in the child's closure table names where its binding lives in
10756    /// *this* frame: a local or argument slot that was marked captured, or a cell
10757    /// this frame is itself holding. That is how a variable three functions deep
10758    /// stays one binding.
10759    fn closure(&mut self, index: usize) -> JsResult<Value> {
10760        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
10761        else {
10762            return Err(Signal::Throw(
10763                self.make_error("InternalError", "fclosure of a non-function"),
10764            ));
10765        };
10766        let mut cells = Vec::with_capacity(function.closure_vars.len());
10767        for closure_var in &function.closure_vars {
10768            let cell = match closure_var.closure_type {
10769                ClosureType::Arg => {
10770                    let slot = closure_var.var_idx as usize;
10771                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
10772                }
10773                ClosureType::Local => {
10774                    let slot = closure_var.var_idx as usize;
10775                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
10776                }
10777                ClosureType::Ref | ClosureType::GlobalRef => {
10778                    // A `Ref` names a cell in this frame's own closure table; a
10779                    // `GlobalRef` also starts there, then resolves by name below.
10780                    let slot = closure_var.var_idx as usize;
10781                    if let Some(cell) = self.frame().env.cells.get(slot) {
10782                        cells.push(cell.clone());
10783                        continue;
10784                    }
10785                    -1
10786                }
10787                _ => -1,
10788            };
10789            if cell >= 0 {
10790                let cell = self.frame().cells[cell as usize].clone();
10791                cells.push(cell);
10792                continue;
10793            }
10794            // A global: the cell is created on demand and shared through the realm,
10795            // so every function sees one binding.
10796            let name = closure_var.name.clone();
10797            let cell = match self.realm.globals.get(&name) {
10798                Some(cell) => cell.clone(),
10799                None => {
10800                    let cell = self.new_cell(Value::Undefined);
10801                    self.realm.globals.insert(name.clone(), cell.clone());
10802                    cell
10803                }
10804            };
10805            cells.push(cell);
10806        }
10807        let name = function.name.clone();
10808        // `.length` is the arity before any default or rest parameter, not the number
10809        // of slots a pattern parameter needs.
10810        let length = function.defined_args;
10811        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
10812        // function and an arrow function do not. A *method* also does not, but that is not
10813        // known here — the method is marked when the `[[HomeObject]]` is attached (see
10814        // `set_home_object`), which is the moment it becomes a method.
10815        let function_kind = function.kind;
10816        let constructible =
10817            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
10818        let code = Gc::new(self.heap, CompiledCode::new(*function));
10819        // A closure built inside an `eval` inherits the eval's view of the enclosing
10820        // bindings, so it can still read them once the eval has returned.
10821        let eval_scope = self
10822            .active_eval_scope
10823            .clone()
10824            .or_else(|| self.frame().env.eval_scope.clone());
10825        // A closure sees the variables a direct `eval` declared in the frame it was
10826        // created in — the ones declared before *and after* it, so the same object is
10827        // shared; only the phase bounds which of them are visible.
10828        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
10829        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
10830        let env = Gc::new(
10831            self.heap,
10832            ClosureEnv {
10833                cells,
10834                eval_scope,
10835                local_vars,
10836                local_phase,
10837            },
10838        );
10839        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
10840        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
10841        // the only thing that carries `Symbol.toStringTag`, so without it
10842        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
10843        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
10844        let proto = match function_kind {
10845            js_compile::bytecode::FunctionKind::AsyncGenerator => self
10846                .realm
10847                .async_generator_function_proto
10848                .clone()
10849                .or_else(|| self.realm.function_proto.clone().into()),
10850            js_compile::bytecode::FunctionKind::Generator => self
10851                .realm
10852                .generator_function_proto
10853                .clone()
10854                .or_else(|| self.realm.function_proto.clone().into()),
10855            js_compile::bytecode::FunctionKind::Async => self
10856                .realm
10857                .async_function_proto
10858                .clone()
10859                .or_else(|| self.realm.function_proto.clone().into()),
10860            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
10861        };
10862        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
10863        object.set_constructible(constructible);
10864        object.define(
10865            "length",
10866            Property::name_or_length(Value::Int(length as i32)),
10867        );
10868        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
10869        // that checks the own-property descriptor fails if the property is missing.
10870        object.define("name", Property::name_or_length(self.string(name)));
10871        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
10872        // when `[[Construct]]` is created, so a generator, an async function and an arrow
10873        // function have none of their own. Installing it unconditionally gave
10874        // `Array.fromAsync` (an async function) an own `prototype` property, which
10875        // `builtin.js` checks for absence.
10876        if constructible {
10877            self.install_function_prototype(&object);
10878        }
10879        Ok(Value::Object(object))
10880    }
10881
10882    // -- conversions used by the operators ----------------------------------
10883
10884    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
10885        // `+x` is `ToNumber`, which for a string parses it and for an object runs
10886        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
10887        // string, which then behaves differently in every later comparison.
10888        match value {
10889            Value::Int(_) | Value::Float(_) => Ok(value),
10890            other => Ok(Value::Float(self.to_js_number(&other)?)),
10891        }
10892    }
10893
10894    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
10895    ///
10896    /// Returns the *converted* old value and the new one, because the two callers need
10897    /// different halves: `++x` yields the new value, while `x++` yields the old one and
10898    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
10899    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
10900    /// boolean.
10901    ///
10902    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
10903    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
10904    /// a bigint algorithm then ran exactly once.
10905    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
10906        if let Value::BigInt(big) = &value {
10907            let one = crate::bigint::BigInt::from_i64(1);
10908            let next = if up { big.add(&one) } else { big.sub(&one) };
10909            return Ok((value, self.bigint(next)));
10910        }
10911        let old = self.numeric(value)?;
10912        let new = if up {
10913            increment(old.clone())
10914        } else {
10915            decrement(old.clone())
10916        };
10917        Ok((old, new))
10918    }
10919
10920    fn numeric(&mut self, value: Value) -> JsResult<Value> {
10921        // `ToNumber` on an object runs `ToPrimitive` first, which is how
10922        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
10923        // heard at all. Reading the object's own tag instead (`other.to_number()`)
10924        // turned the whole operand into `NaN` and swallowed the exception.
10925        match value {
10926            Value::Int(_) | Value::Float(_) => Ok(value),
10927            other => Ok(Value::Float(self.to_js_number(&other)?)),
10928        }
10929    }
10930
10931    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
10932    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
10933        match value {
10934            Value::BigInt(big) => Ok((**big).clone()),
10935            // The reference words this the same way for every operator, so a failing
10936            // script reads identically; the operator itself adds nothing a caller can use.
10937            _ => Err(Signal::Throw(
10938                self.make_error("TypeError", "cannot convert bigint to number"),
10939            )),
10940        }
10941    }
10942
10943    /// Arithmetic where at least one operand is a `BigInt`.
10944    ///
10945    /// The two numeric types never mix, so a bigint paired with anything else is an error
10946    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
10947    /// that the relational operators handle it separately.
10948    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10949        use Opcode::*;
10950        let a = self.bigint_operand(&left)?;
10951        let b = self.bigint_operand(&right)?;
10952        let result = match op {
10953            Add => a.add(&b),
10954            Sub => a.sub(&b),
10955            Mul => a.mul(&b),
10956            Div | Mod => {
10957                let Some((quotient, remainder)) = a.div_rem(&b) else {
10958                    return Err(Signal::Throw(
10959                        self.make_error("RangeError", "division by zero"),
10960                    ));
10961                };
10962                if op == Div { quotient } else { remainder }
10963            }
10964            Pow => {
10965                let Some(value) = a.pow(&b) else {
10966                    return Err(Signal::Throw(self.make_error(
10967                        "RangeError",
10968                        "BigInt exponent must be non-negative and not absurdly large",
10969                    )));
10970                };
10971                value
10972            }
10973            And => a.bitand(&b),
10974            Or => a.bitor(&b),
10975            Xor => a.bitxor(&b),
10976            Shl | Sar => {
10977                // A shift count is a `BigInt` here, and both directions are exact; a
10978                // negative count would be the other direction, which the spec forbids.
10979                let Some(count) = b.to_i64() else {
10980                    return Err(Signal::Throw(
10981                        self.make_error("RangeError", "BigInt shift count is too large"),
10982                    ));
10983                };
10984                if count < 0 {
10985                    return Err(Signal::Throw(self.make_error(
10986                        "RangeError",
10987                        "BigInt shift count must be non-negative",
10988                    )));
10989                }
10990                if op == Shl {
10991                    a.shl(count as u64)
10992                } else {
10993                    a.shr(count as u64)
10994                }
10995            }
10996            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
10997            _ => {
10998                return Err(Signal::Throw(self.make_error(
10999                    "TypeError",
11000                    "BigInts have no unsigned right shift, use >> instead",
11001                )));
11002            }
11003        };
11004        Ok(self.bigint(result))
11005    }
11006
11007    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
11008    ///
11009    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
11010    /// is on the mathematical values, and nothing is rounded first.
11011    /// `<`, `<=`, `>`, `>=`.
11012    ///
11013    /// Both operands go through `ToPrimitive` **before** the comparison, which is what
11014    /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
11015    /// It is a `?`-returning function for exactly that reason: an object operand can run
11016    /// script, and script can throw. The old version compared `to_number` of the raw
11017    /// values, which answered `false` for every object instead of calling `valueOf` —
11018    /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
11019    /// never ran.
11020    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
11021        // The hot arm first: `i < n` with both sides already integers. No conversion, no
11022        // call, nothing that can throw.
11023        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
11024            let ordering = Some(left.cmp(right));
11025            return Ok(ordering_answer(op, ordering));
11026        }
11027        // Anything that can run script has to be converted first, in this order.
11028        let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
11029        {
11030            (
11031                self.to_primitive(left, Hint::Number)?,
11032                self.to_primitive(right, Hint::Number)?,
11033            )
11034        } else {
11035            (left, right)
11036        };
11037        let ordering = match (&left, &right) {
11038            // The loop condition `i < n` is integer against integer, and it runs once
11039            // per iteration of every loop in every program. Without this arm it took the
11040            // `to_number` path twice, which is a `match` plus a conversion each.
11041            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
11042            (Value::String(a), Value::String(b)) => {
11043                Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
11044            }
11045            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
11046            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
11047            // is true even though `2.5` has no bigint form.
11048            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
11049                let b = other.to_number();
11050                if b.is_nan() {
11051                    None
11052                } else {
11053                    compare_bigint_and_f64(a, b)
11054                }
11055            }
11056            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
11057                let a = other.to_number();
11058                if a.is_nan() {
11059                    None
11060                } else {
11061                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
11062                }
11063            }
11064            _ => left.to_number().partial_cmp(&right.to_number()),
11065        };
11066        Ok(ordering_answer(op, ordering))
11067    }
11068
11069    fn binary_add(&mut self) -> JsResult<()> {
11070        let right = self.pop();
11071        let left = self.pop();
11072        // Two integers add without any of the machinery below: no `ToPrimitive` (an
11073        // `Int` is already primitive), no string check, no bigint check, no allocation.
11074        // `x += 1` in a loop is the single most common instruction sequence in real
11075        // script, and it used to walk every one of those checks before reaching the
11076        // same `checked_add`.
11077        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
11078            self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
11079            return Ok(());
11080        }
11081        let left = self.primitive_of(left)?;
11082        let right = self.primitive_of(right)?;
11083        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
11084        // that check comes before the bigint one: `"" + 1n` is a string, not a
11085        // mixed-type error.
11086        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
11087            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
11088            // `TypeError`, the one place a symbol and a string do not mix.
11089            // Keep the operands as strings rather than as bytes: `JsString::concat` decides
11090            // between a copy and a rope from their lengths, and a rope is what turns
11091            // `text += "abc"` in a loop from quadratic into linear.
11092            if let (Value::String(left), Value::String(right)) = (&left, &right) {
11093                // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
11094                // reports as `InternalError: string too long`.
11095                let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
11096                    return Err(Signal::Throw(
11097                        self.make_error("InternalError", "string too long"),
11098                    ));
11099                };
11100                self.push(Value::String(Gc::new(self.heap, joined)));
11101                return Ok(());
11102            }
11103            // At least one operand was not a string, so `ToString` it. This rejects a
11104            // symbol, which is the one place a symbol and a string do not mix.
11105            let left = self.checked_to_wtf8(&left)?;
11106            let right = self.checked_to_wtf8(&right)?;
11107            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
11108            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
11109            let text = left.concat(&right);
11110            self.push(self.string_wtf8(text));
11111            return Ok(());
11112        }
11113        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
11114        // not a conversion.
11115        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
11116            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
11117            self.push(value);
11118            return Ok(());
11119        }
11120        let left = self.numeric(left)?;
11121        let right = self.numeric(right)?;
11122        self.push(add_numbers(left, right));
11123        Ok(())
11124    }
11125
11126    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
11127        self.to_primitive(value, Hint::Default)
11128    }
11129
11130    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
11131    ///
11132    /// The order depends on the hint: the "number" order tries `valueOf` first and
11133    /// `toString` second, the "string" order the other way round, and the default
11134    /// hint uses the number order. A result that is still an object is a `TypeError`,
11135    /// because no built-in `valueOf`/`toString` returns one.
11136    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
11137        let Value::Object(object) = &value else {
11138            return Ok(value);
11139        };
11140        // A Date overrides the default hint to mean "string", which is what
11141        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
11142        // this, `"" + new Date()` would print the milliseconds, not the date.
11143        let hint = if hint == Hint::Default && is_date_object(self, object) {
11144            Hint::String
11145        } else {
11146            hint
11147        };
11148        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
11149        // handed the hint as a string. This is the hook a Date uses for its default hint
11150        // and a script uses to take over conversion entirely.
11151        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
11152        if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
11153            if !function.is_callable() {
11154                return Err(self.type_error("Symbol.toPrimitive is not a function"));
11155            }
11156            let hint = match hint {
11157                Hint::String => "string",
11158                Hint::Number => "number",
11159                Hint::Default => "default",
11160            };
11161            let hint = self.string(hint);
11162            let result = self.call_value(
11163                Value::Object(function),
11164                Value::Object(object.clone()),
11165                vec![hint],
11166            )?;
11167            if matches!(result, Value::Object(_)) {
11168                return Err(self.type_error("cannot convert object to primitive value"));
11169            }
11170            return Ok(result);
11171        }
11172        let order: [&str; 2] = match hint {
11173            Hint::String => ["toString", "valueOf"],
11174            Hint::Number | Hint::Default => ["valueOf", "toString"],
11175        };
11176        let receiver = object.clone();
11177        for method in order {
11178            if let Some(function) = self.get_property(&receiver, method)?
11179                && matches!(&function, Value::Object(object) if object.is_callable())
11180            {
11181                let result =
11182                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
11183                if !matches!(result, Value::Object(_)) {
11184                    return Ok(result);
11185                }
11186            }
11187        }
11188        Err(self.type_error("cannot convert object to primitive value"))
11189    }
11190
11191    /// `ToString` with the object case going through `ToPrimitive`.
11192    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
11193        if matches!(value, Value::Object(_)) {
11194            let primitive = self.to_primitive(value.clone(), Hint::String)?;
11195            return Ok(primitive.to_js_string());
11196        }
11197        Ok(value.to_js_string())
11198    }
11199
11200    /// `ToString` that keeps the string's code units instead of flattening them.
11201    ///
11202    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
11203    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
11204    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
11205        if matches!(value, Value::Symbol(_)) {
11206            return Err(Signal::Throw(
11207                self.make_error("TypeError", "cannot convert symbol to string"),
11208            ));
11209        }
11210        // An object runs `ToPrimitive` first, which may itself produce a symbol.
11211        let value = self.to_primitive(value.clone(), Hint::String)?;
11212        match value {
11213            Value::Symbol(_) => Err(Signal::Throw(
11214                self.make_error("TypeError", "cannot convert symbol to string"),
11215            )),
11216            Value::String(text) => Ok(text.wtf8().clone()),
11217            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
11218        }
11219    }
11220
11221    /// `ToNumber` with the object case going through `ToPrimitive`.
11222    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
11223        let value = if matches!(value, Value::Object(_)) {
11224            self.to_primitive(value.clone(), Hint::Number)?
11225        } else {
11226            value.clone()
11227        };
11228        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
11229        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
11230        // `NaN` to stay total, and the operators check for the bigint themselves — but
11231        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
11232        // refuse, and answering `NaN` made them silently wrong instead.
11233        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
11234        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
11235        match value {
11236            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
11237            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
11238            other => Ok(other.to_number()),
11239        }
11240    }
11241
11242    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
11243    /// [`ElementType::write`].
11244    ///
11245    /// This is separated from the write because both conversions are observable script —
11246    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
11247    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
11248    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
11249    /// setters, and a plain `a[i] = v`.
11250    pub(crate) fn element_value(
11251        &mut self,
11252        element: crate::builtins::typedarray::ElementType,
11253        value: Value,
11254    ) -> JsResult<Value> {
11255        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
11256        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
11257        let primitive = match &value {
11258            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
11259            _ => value,
11260        };
11261        if element.is_bigint() {
11262            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
11263            Ok(Value::BigInt(Gc::new(self.heap, big)))
11264        } else {
11265            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
11266            Ok(Value::Float(self.to_js_number(&primitive)?))
11267        }
11268    }
11269
11270    /// `ToPropertyKey`: what a computed member access uses as its key.
11271    ///
11272    /// A symbol is returned as itself, never stringified — that is what keeps
11273    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
11274    pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
11275        match value {
11276            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
11277            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
11278            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
11279            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
11280            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
11281                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
11282                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
11283                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
11284                    other.to_js_string(),
11285                ))),
11286            },
11287            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
11288        }
11289    }
11290
11291    /// `ToPropertyKey` for the callers that can only use a string key.
11292    ///
11293    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
11294    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
11295    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
11296    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
11297    /// program continues with a value nobody asked for.
11298    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
11299        use crate::value::Wtf8;
11300        Ok(match value {
11301            // A string key keeps its code units. Going through a lossy `String` would make
11302            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
11303            Value::String(text) => text.wtf8().clone(),
11304            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
11305            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
11306            // falling back to its `ToString` would print `[object Object]`.
11307            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
11308                Value::String(text) => text.wtf8().clone(),
11309                other => Wtf8::new(other.to_js_string()),
11310            },
11311            other => Wtf8::new(other.to_js_string()),
11312        })
11313    }
11314
11315    // -- object operations used by instructions -----------------------------
11316
11317    /// Read `object[key]`, returning `undefined` when the property is missing.
11318    ///
11319    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
11320    /// primitive (looking through its prototype) as well as an object — which is what
11321    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
11322    /// argument needs too.
11323    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
11324        self.read_field_key(object, &PropertyKey::from(key))
11325    }
11326
11327    /// [`Interp::read_field`] with a key that may be a symbol.
11328    ///
11329    /// A symbol key never reaches the string shortcuts: a string's `length` and its
11330    /// indices are string properties, and a symbol named `length` is a different
11331    /// property that a string primitive cannot have.
11332    /// [`Interp::read_field_key`], with an inline cache in front of it.
11333    ///
11334    /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
11335    /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
11336    /// without this the engine walked the chain and compared ~40 property names on each
11337    /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
11338    ///
11339    /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
11340    /// missing property. Those answers depend on running code or on state the guard below
11341    /// does not cover, and a wrong answer here is far more expensive than a lookup.
11342    ///
11343    /// A hit is re-validated against the *whole* walked chain, not just the level that
11344    /// answered: the receiver and every prototype down to that level must still be the same
11345    /// object (weakly, so a collected and reallocated object is a miss) with unchanged
11346    /// property-table *lengths* — which is what catches a property appearing on an
11347    /// intermediate prototype and shadowing the cached one.
11348    pub fn read_field_cached(
11349        &mut self,
11350        object: &Value,
11351        key: &PropertyKey,
11352        slot: usize,
11353    ) -> JsResult<Value> {
11354        let index = Self::field_cache_slot(object, key, slot);
11355        let Value::Object(target) = object else {
11356            return self.read_field_key(object, key);
11357        };
11358        if target.proxy_state().is_some() {
11359            return self.read_field_key(object, key);
11360        }
11361        if let Some(cached) = &self.field_cache[index]
11362            && cached.key == *key
11363            && let Some(value) = Self::cached_hit(target, cached)
11364        {
11365            return Ok(value);
11366        }
11367        let value = self.read_field_key(object, key)?;
11368        self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
11369        Ok(value)
11370    }
11371
11372    /// Whether a cache entry still describes this lookup, and if so the value.
11373    ///
11374    /// The guard is the whole point of the entry: identity plus property-table length for
11375    /// every level walked. Re-checked per level rather than once at the receiving end,
11376    /// because a shadowing property can appear anywhere along the chain.
11377    fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
11378        // Level 0 — the receiver itself answered — without the `Gc` clone this loop
11379        // starts with: a clone is a reference-count bump and a drop, and for
11380        // `property:monomorphic` every single hit takes only this arm.
11381        let (weak, len) = cached.chain[0].as_ref()?;
11382        if !target.upgrades_to(weak) {
11383            return None;
11384        }
11385        if cached.level == 0 {
11386            // Length and key and accessor-ness in one borrow: see `cached_property_at`.
11387            return target.cached_property_at(cached.index, &cached.key, *len);
11388        }
11389        if target.props_len() != *len {
11390            return None;
11391        }
11392        let mut level = 1;
11393        let mut current = target.proto()?;
11394        loop {
11395            let (weak, len) = cached.chain[level].as_ref()?;
11396            if !current.upgrades_to(weak) || current.props_len() != *len {
11397                return None;
11398            }
11399            if level == cached.level as usize {
11400                // The level that answered: the value is only reusable while the key is
11401                // still there and still a plain data property.
11402                return current.cached_data_property(cached.index, &cached.key);
11403            }
11404            current = current.proto()?;
11405            level += 1;
11406        }
11407    }
11408
11409    /// Build a cache entry for a lookup that just went through the slow path.
11410    ///
11411    /// Records the chain only when the answer came from a plain data property at a level
11412    /// the fixed-size array can hold; everything else simply leaves the slot empty, which
11413    /// costs the next lookup the walk it would have cost anyway.
11414    fn record_field_lookup(
11415        target: &Gc<JsObject>,
11416        key: &PropertyKey,
11417        _value: Value,
11418    ) -> Option<FieldCache> {
11419        let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
11420            [None, None, None];
11421        let mut current = target.clone();
11422        for level in 0..MAX_CACHED_CHAIN {
11423            chain[level] = Some((current.downgrade(), current.props_len()));
11424            if let Some((found, _)) = current.own_property_index(key) {
11425                // `own_property_index` declines an accessor and a hole, which is exactly
11426                // the set that must not be cached.
11427                return Some(FieldCache {
11428                    key: key.clone(),
11429                    index: found,
11430                    level: level as u8,
11431                    chain,
11432                });
11433            }
11434            current = current.proto()?;
11435        }
11436        None
11437    }
11438
11439    /// Which cache slot a lookup uses.
11440    ///
11441    /// Mixes the object's address, the name and the site, so that two properties of one
11442    /// object, and one property of two objects, land in different slots — which is what lets
11443    /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
11444    /// other iteration.
11445    fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
11446        let mut hash = match object {
11447            Value::Object(object) => object.address(),
11448            _ => 0,
11449        };
11450        hash = hash
11451            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
11452            .rotate_left(17)
11453            .wrapping_add(key.hash_code());
11454        hash = hash.wrapping_add(site.wrapping_mul(31));
11455        // The table is a power of two, so the low bits are the slot.
11456        hash & (FIELD_CACHE_SLOTS - 1)
11457    }
11458
11459    /// Read `key` from `object`, without the inline cache.
11460    ///
11461    /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
11462    /// prototype chain, while the cached form answers an own data property from memory.
11463    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
11464        let text = key.as_str().unwrap_or("");
11465        let Value::Object(object) = object else {
11466            // Reading a property of `undefined`/`null` is the classic TypeError.
11467            if object.is_nullish() {
11468                return Err(Signal::Throw(self.make_error(
11469                    "TypeError",
11470                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
11471                )));
11472            }
11473            // A string has `length` and index access without being boxed.
11474            if let Value::String(value) = object {
11475                if text == "length" {
11476                    return Ok(Value::Int(value.utf16_len() as i32));
11477                }
11478                if let Some(index) = array_index(text) {
11479                    return Ok(match value.wtf8().unit_at(index as usize) {
11480                        Some(unit) => self.string_wtf8(unit),
11481                        None => Value::Undefined,
11482                    });
11483                }
11484            }
11485            // A property of a primitive is looked up on its prototype: this is what
11486            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
11487            let prototype = match object {
11488                Value::String(_) => self.realm.string_proto.clone(),
11489                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11490                Value::Bool(_) => self.realm.boolean_proto.clone(),
11491                // A symbol's methods live on `Symbol.prototype`, reached the same way —
11492                // `sym.description` reads through the prototype, not off the symbol.
11493                Value::Symbol(_) => self.realm.symbol_proto.clone(),
11494                // …and a bigint's on `BigInt.prototype`, which is how
11495                // `(255n).toString(16)` reaches its method.
11496                Value::BigInt(_) => self.realm.bigint_proto.clone(),
11497                _ => None,
11498            };
11499            if let Some(prototype) = prototype
11500                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
11501            {
11502                return Ok(value);
11503            }
11504            return Ok(Value::Undefined);
11505        };
11506        Ok(self
11507            .get_property_key(object, key)?
11508            .unwrap_or(Value::Undefined))
11509    }
11510
11511    /// The `#name` a private symbol stands for, for error messages.
11512    ///
11513    /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
11514    /// was made from.
11515    fn private_name(symbol: &Value) -> Option<String> {
11516        match symbol {
11517            Value::Symbol(symbol) if symbol.is_private() => Some(
11518                symbol
11519                    .description()
11520                    .map(|text| text.to_string())
11521                    .unwrap_or_default(),
11522            ),
11523            _ => None,
11524        }
11525    }
11526
11527    /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
11528    ///
11529    /// Every private-field opcode takes the symbol the class stored in its own scope; a
11530    /// non-symbol here would be a compiler bug, and the reference guards it with
11531    /// `JS_ThrowTypeErrorNotASymbol`.
11532    fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
11533        match symbol {
11534            Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
11535            _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
11536        }
11537    }
11538
11539    /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
11540    ///
11541    /// Three early errors, all from the reference: a non-object receiver, a non-extensible
11542    /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
11543    /// would hit if the parser did not reject it first.
11544    fn define_private_field(
11545        &mut self,
11546        object: &Value,
11547        symbol: &Value,
11548        value: Value,
11549    ) -> JsResult<()> {
11550        let key = self.private_key(symbol)?;
11551        let Some(target) = object.as_object() else {
11552            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11553        };
11554        if !target.is_extensible() {
11555            return Err(Signal::Throw(
11556                self.make_error("TypeError", "object is not extensible"),
11557            ));
11558        }
11559        if target.own_property_key(&key).is_some() {
11560            let name = Self::private_name(symbol).unwrap_or_default();
11561            return Err(Signal::Throw(self.make_error(
11562                "TypeError",
11563                &format!("private class field '{name}' already exists"),
11564            )));
11565        }
11566        target.define_data_key(&key, value);
11567        Ok(())
11568    }
11569
11570    /// `JS_GetPrivateField`: only an own property, never the prototype chain.
11571    fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
11572        let key = self.private_key(symbol)?;
11573        let Some(target) = object.as_object() else {
11574            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11575        };
11576        match target.own_property_key(&key) {
11577            Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
11578            None => {
11579                let name = Self::private_name(symbol).unwrap_or_default();
11580                Err(Signal::Throw(self.make_error(
11581                    "TypeError",
11582                    &format!("private class field '{name}' does not exist"),
11583                )))
11584            }
11585        }
11586    }
11587
11588    /// `JS_SetPrivateField`: the store half of the same rule.
11589    fn write_private_field(
11590        &mut self,
11591        object: &Value,
11592        symbol: &Value,
11593        value: Value,
11594    ) -> JsResult<()> {
11595        let key = self.private_key(symbol)?;
11596        let Some(target) = object.as_object() else {
11597            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11598        };
11599        if target.write_value_key(&key, value) {
11600            return Ok(());
11601        }
11602        let name = Self::private_name(symbol).unwrap_or_default();
11603        Err(Signal::Throw(self.make_error(
11604            "TypeError",
11605            &format!("private class field '{name}' does not exist"),
11606        )))
11607    }
11608
11609    /// The `in` half: does `object` have this private field?
11610    /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
11611    ///
11612    /// The symbol is created once per class — the first `add_brand` on a given home object
11613    /// makes it, every later one reuses it, which is what ties the prototype, the constructor
11614    /// and each instance to one identity. `obj` being `null` is not an error: the class-level
11615    /// emit for the *instance* brand passes null because all it wants is the symbol.
11616    fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
11617        let Some(home_object) = home.as_object() else {
11618            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11619        };
11620        let symbol = match home_object.private_brand() {
11621            Some(symbol) => symbol,
11622            None => {
11623                let symbol = Gc::new(
11624                    self.heap,
11625                    crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
11626                );
11627                home_object.set_private_brand(symbol.clone());
11628                symbol
11629            }
11630        };
11631        let Some(target) = object.as_object() else {
11632            // Not an object: nothing to brand. The reference does the same, and `undefined`
11633            // here would otherwise turn a field initialiser into a TypeError.
11634            return Ok(());
11635        };
11636        if !target.is_extensible() {
11637            return Err(Signal::Throw(
11638                self.make_error("TypeError", "object is not extensible"),
11639            ));
11640        }
11641        if target.carries_brand(&symbol) {
11642            return Err(Signal::Throw(
11643                self.make_error("TypeError", "private method is already present"),
11644            ));
11645        }
11646        target.add_brand(symbol);
11647        Ok(())
11648    }
11649
11650    /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
11651    ///
11652    /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
11653    /// decides whether to throw.
11654    fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
11655        let Some(function) = function.as_object() else {
11656            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11657        };
11658        let Some(home) = function.home_object() else {
11659            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11660        };
11661        let Some(brand) = home.private_brand() else {
11662            return Err(Signal::Throw(
11663                self.make_error("TypeError", "expecting <brand> private field"),
11664            ));
11665        };
11666        Ok(object.carries_brand(&brand))
11667    }
11668
11669    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
11670        let Value::Object(object) = object else {
11671            return Err(Signal::Throw(self.make_error(
11672                "TypeError",
11673                &format!("cannot set property '{key}' of {}", object.to_js_string()),
11674            )));
11675        };
11676        // The write half of the property inline cache, in effect: an own, writable,
11677        // non-accessor data property already holds this key, so `[[Set]]` has nothing to
11678        // decide — no prototype walk (an own property shadows the chain before a setter
11679        // there could matter), no extensibility check (the object already has the key),
11680        // and no `[[DefineOwnProperty]]`.
11681        //
11682        // `this.value = …` inside a method is the whole write side of
11683        // `property:method-call`, and it was reaching `set_property_with_key` with its
11684        // proxy test, its typed-array test, its array-index test and finally a linear
11685        // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
11686        //
11687        // Every disqualifier is checked here: a proxy traps the set, an array index and
11688        // `length` live outside the property table, and a typed array's element is stored
11689        // through its view's element type.
11690        if object.proxy_state().is_none()
11691            && !object.is_array()
11692            && object.typed_array_element_type().is_none()
11693            && object.write_value_key(key, value.clone())
11694        {
11695            return Ok(());
11696        }
11697        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
11698        let on_failure = if self.frame().code.code.strict {
11699            DeleteFailure::Throw
11700        } else {
11701            DeleteFailure::Ignore
11702        };
11703        self.set_property_with_key(object, key, value, on_failure)
11704    }
11705
11706    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
11707    ///
11708    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
11709    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
11710    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
11711    /// `Number.parseInt(sym)` — so those callers use this instead.
11712    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
11713        if matches!(value, Value::Symbol(_)) {
11714            return Err(Signal::Throw(
11715                self.make_error("TypeError", "cannot convert symbol to string"),
11716            ));
11717        }
11718        // An object runs `ToPrimitive` first, which may itself produce a symbol —
11719        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
11720        let value = self.to_primitive(value.clone(), Hint::String)?;
11721        if matches!(value, Value::Symbol(_)) {
11722            return Err(Signal::Throw(
11723                self.make_error("TypeError", "cannot convert symbol to string"),
11724            ));
11725        }
11726        Ok(value.to_js_string())
11727    }
11728
11729    /// `ToPropertyKey` for a builtin that takes a key argument.
11730    ///
11731    /// Fallible: a key whose `toString` throws has to propagate that error, both for
11732    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
11733    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
11734    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
11735    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
11736        self.propkey(value)
11737    }
11738
11739    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
11740    ///
11741    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
11742    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
11743    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
11744    /// `RangeError` — and why this cannot be a plain `ToNumber`.
11745    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
11746        let number = match value {
11747            Value::Int(number) => *number as f64,
11748            Value::Float(number) => *number,
11749            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
11750            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
11751            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
11752            // reference answers 0.
11753            Value::Null | Value::Bool(_) => value.to_number(),
11754            _ => {
11755                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
11756                match primitive {
11757                    Value::Int(number) => number as f64,
11758                    Value::Float(number) => number,
11759                    other => {
11760                        // `ToString` then `ToNumber`, so a string length goes through the
11761                        // full numeric-literal grammar: `"0x00B"` is 11 and `"  5  "` is 5.
11762                        // `Value::to_number` on the string already implements exactly that.
11763                        let text = self.to_js_string(&other)?;
11764                        crate::value::string_to_number(&text)
11765                    }
11766                }
11767            }
11768        };
11769        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
11770        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
11771        // is a `RangeError`, not `0`.
11772        if !number.is_finite()
11773            || number.fract() != 0.0
11774            || !(0.0..=u32::MAX as f64).contains(&number)
11775        {
11776            return Err(self.range_error("invalid array length"));
11777        }
11778        Ok(number as u32)
11779    }
11780
11781    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
11782    /// `Object.getOwnPropertySymbols` put in their result array.
11783    pub fn key_value(&self, key: &PropertyKey) -> Value {
11784        match key {
11785            PropertyKey::String(text) => self.string_wtf8(text.clone()),
11786            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11787        }
11788    }
11789
11790    /// Fill in a String exotic object: `_value`, `length` and the index properties.
11791    ///
11792    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
11793    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
11794    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
11795    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
11796    /// the two paths had drifted; this is the one both now use.
11797    ///
11798    /// The indices are *code units*, so an astral character occupies two of them — the
11799    /// same rule `s.length` and `s[i]` follow.
11800    /// Give an already-created object the internal slot that makes it a wrapper of
11801    /// `value`, so the primitive's prototype methods work on it.
11802    ///
11803    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
11804    /// which are wrappers of their own type holding the empty value.
11805    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
11806        self.internal_set(object, "_value", value);
11807    }
11808
11809    pub(crate) fn init_string_wrapper(
11810        &mut self,
11811        object: &Gc<JsObject>,
11812        text: &Gc<crate::value::JsString>,
11813    ) {
11814        object.define(
11815            "length",
11816            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
11817        );
11818        for index in 0..text.utf16_len() {
11819            if let Some(unit) = text.wtf8().unit_at(index) {
11820                object.define(
11821                    &index.to_string(),
11822                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
11823                    Property::with_attributes(self.string_wtf8(unit), false, true),
11824                );
11825            }
11826        }
11827        object.define_key(
11828            &self.internal_slot("_value"),
11829            Property::with_attributes(Value::String(text.clone()), false, false),
11830        );
11831    }
11832
11833    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
11834    ///
11835    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
11836    /// throws. The wrapper carries its primitive in `_value` — the same slot
11837    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
11838    /// on a boxed value no constructor ever built.
11839    pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
11840        let (prototype, primitive) = match value {
11841            Value::Object(object) => return Ok(object.clone()),
11842            Value::String(text) => {
11843                let object = self.new_object(self.realm.string_proto.clone());
11844                self.init_string_wrapper(&object, text);
11845                return Ok(object);
11846            }
11847            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
11848            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
11849            // A symbol and a bigint box into wrappers whose methods live on
11850            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
11851            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
11852            // branch below instead produced an object with *no* prototype, so those
11853            // methods were unreachable on a box.
11854            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
11855            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
11856            Value::Undefined | Value::Null => {
11857                return Err(Signal::Throw(self.make_error(
11858                    "TypeError",
11859                    &format!("cannot convert {} to object", value.to_js_string()),
11860                )));
11861            }
11862            _ => (None, value.clone()),
11863        };
11864        let object = self.new_object(prototype);
11865        self.internal_set(&object, "_value", primitive);
11866        Ok(object)
11867    }
11868
11869    /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
11870    ///
11871    /// Split out for a reader that has to create the object *before* it knows what it wraps:
11872    /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
11873    /// written before its primitive, so the placeholder has to exist first and be filled in
11874    /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
11875    /// than a second in the deserialiser.
11876    pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
11877        let prototype = match value {
11878            Value::String(_) => self.realm.string_proto.clone(),
11879            Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11880            Value::Bool(_) => self.realm.boolean_proto.clone(),
11881            Value::Symbol(_) => self.realm.symbol_proto.clone(),
11882            Value::BigInt(_) => self.realm.bigint_proto.clone(),
11883            _ => {
11884                return Err(Signal::Throw(self.make_error(
11885                    "TypeError",
11886                    &format!("cannot box {}", value.to_js_string()),
11887                )));
11888            }
11889        };
11890        object.set_proto(prototype);
11891        if let Value::String(text) = value {
11892            self.init_string_wrapper(object, text);
11893            return Ok(());
11894        }
11895        self.internal_set(object, "_value", value.clone());
11896        Ok(())
11897    }
11898
11899    /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
11900    ///
11901    /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
11902    /// through the `Symbol` function object, so the registry is reachable as a method rather
11903    /// than only from `builtins::symbol`.
11904    pub fn symbol_for(&mut self, key: &str) -> Value {
11905        if let Some(existing) = self.realm.symbol_registry.get(key) {
11906            return existing.clone();
11907        }
11908        let symbol = crate::builtins::symbol::symbol_value(
11909            self,
11910            crate::value::JsSymbol::registered(key.to_string()),
11911        );
11912        self.realm
11913            .symbol_registry
11914            .insert(key.to_string(), symbol.clone());
11915        symbol
11916    }
11917
11918    /// `a == b`, the coercing comparison.
11919    ///
11920    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
11921    /// which is what makes `[] == ""` true: `[]` becomes `""` via
11922    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
11923    /// because the conversion is allowed to call script code, so the two primitive
11924    /// operands are handed back to it.
11925    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
11926        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
11927            return Ok(left.loose_equals(&right));
11928        }
11929        // `null == undefined` holds even though neither is an object.
11930        if matches!(left, Value::Undefined | Value::Null)
11931            && matches!(right, Value::Undefined | Value::Null)
11932        {
11933            return Ok(true);
11934        }
11935        if matches!(left, Value::Undefined | Value::Null)
11936            || matches!(right, Value::Undefined | Value::Null)
11937        {
11938            return Ok(false);
11939        }
11940        // Two objects compare by identity. Only an object *against a primitive* is
11941        // converted, which is why `{} == {}` is false while `[] == ""` is true.
11942        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
11943            return Ok(a.ptr_eq(b));
11944        }
11945        let left = self.to_primitive(left, Hint::Default)?;
11946        let right = self.to_primitive(right, Hint::Default)?;
11947        Ok(left.loose_equals(&right))
11948    }
11949
11950    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
11951        let Value::Object(object) = object else {
11952            return Err(Signal::Throw(
11953                self.make_error("TypeError", "cannot use 'in' on a non-object"),
11954            ));
11955        };
11956        let key = self.propkey(key)?;
11957        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
11958        // trap. One implementation, so an array's derived `length` and its inherited holes
11959        // cannot be right in one caller and wrong in another.
11960        self.has_own_or_inherited(object, &key)
11961    }
11962
11963    /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
11964    ///
11965    /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
11966    /// whole reason the operator is a hook rather than a prototype walk.
11967    pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11968        if let Value::Object(function) = constructor {
11969            let key = self.realm.well_known_key(WellKnown::HasInstance);
11970            let method = self.get_property_key(function, &key)?;
11971            if let Some(method) = method
11972                && !matches!(method, Value::Undefined)
11973            {
11974                let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
11975                return Ok(answer.to_boolean());
11976            }
11977        }
11978        self.instance_of(object, constructor)
11979    }
11980
11981    /// `OrdinaryHasInstance`: the prototype walk on its own.
11982    pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11983        self.instance_of(object, constructor)
11984    }
11985
11986    /// `IsArray`: an array, or a proxy whose target is one.
11987    ///
11988    /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
11989    /// makes `Array.isArray(new Proxy([], {}))` true.
11990    pub fn is_array_value(&self, value: &Value) -> bool {
11991        match value {
11992            Value::Object(object) => {
11993                if let Some(state) = object.proxy_state() {
11994                    return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
11995                }
11996                object.is_array()
11997            }
11998            _ => false,
11999        }
12000    }
12001
12002    /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
12003    ///
12004    /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
12005    /// in a Rust closure would hide GC values from the collector. A host-supplied job is
12006    /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
12007    /// see [`Interp::enqueue_job_function`].
12008    pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
12009        // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
12010        // the handler is reported rather than lost — the same reason a `then` reaction needs a
12011        // promise to settle.
12012        let promise = self.new_promise();
12013        self.fulfill_promise(&promise, Value::Undefined);
12014        self.jobs.push_back(Job::Reaction {
12015            handler: Some(function),
12016            argument: Value::Undefined,
12017            rejected: false,
12018            promise,
12019        });
12020        Ok(())
12021    }
12022
12023    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
12024        let Value::Object(target) = object else {
12025            return Ok(false);
12026        };
12027        let Value::Object(function) = constructor else {
12028            return Err(Signal::Throw(self.make_error(
12029                "TypeError",
12030                "right-hand side of 'instanceof' is not callable",
12031            )));
12032        };
12033        let prototype = self.get_property(function, "prototype")?;
12034        let Some(Value::Object(prototype)) = prototype else {
12035            return Ok(false);
12036        };
12037        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
12038        // which is also what makes `proxyOfInstance instanceof C` work.
12039        let mut current = Some(target.clone());
12040        while let Some(object) = current {
12041            if object.ptr_eq(&prototype) {
12042                return Ok(true);
12043            }
12044            current = self.object_prototype_of(&object)?;
12045        }
12046        Ok(false)
12047    }
12048
12049    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
12050    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
12051        if let Some(proto) = self.proxy_get_prototype_of(object)? {
12052            return Ok(proto);
12053        }
12054        if let Some(exotic) = object.exotic()
12055            && let Some(proto) = exotic.get_prototype(self, object)?
12056        {
12057            return Ok(proto);
12058        }
12059        Ok(object.proto())
12060    }
12061
12062    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
12063    pub fn object_set_prototype_of(
12064        &mut self,
12065        object: &Gc<JsObject>,
12066        proto: Option<Gc<JsObject>>,
12067    ) -> JsResult<bool> {
12068        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
12069            return Ok(answer);
12070        }
12071        if let Some(exotic) = object.exotic()
12072            && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
12073        {
12074            return Ok(answer);
12075        }
12076        // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
12077        // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
12078        // inheriting from itself, which every later prototype walk then had to defend
12079        // against — and `Reflect.setPrototypeOf` reported success for an operation the
12080        // language says is impossible.
12081        if let Some(proto) = &proto {
12082            let mut current = Some(proto.clone());
12083            let mut guard = 0;
12084            while let Some(node) = current {
12085                if node.ptr_eq(object) {
12086                    return Err(Signal::Throw(
12087                        self.make_error("TypeError", "circular prototype chain"),
12088                    ));
12089                }
12090                guard += 1;
12091                if guard > 1000 {
12092                    break;
12093                }
12094                current = node.proto();
12095            }
12096        }
12097        object.set_proto(proto);
12098        Ok(true)
12099    }
12100
12101    /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
12102    ///
12103    /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
12104    /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
12105    /// already one.
12106    pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
12107        // An integer-indexed exotic object answers from `IsValidIntegerIndex` alone
12108        // (§10.4.5.4 step 1.b.i) — the prototype chain is *not* consulted for a canonical
12109        // numeric index. That is observable: a view that has been resized out of bounds
12110        // has no indices, and `2 in view` must then be `false` even when
12111        // `Object.getPrototypeOf(view)[2]` exists. Falling through to the chain answered
12112        // `true`, which is what `TypedArray/out-of-bounds-behaves-like-detached` catches.
12113        // A proxy is excluded because it has no `[[ViewedArrayBuffer]]` slot of its own.
12114        if object.typed_array_parts().is_some()
12115            && object.proxy_state().is_none()
12116            && let Some(index) = key.as_str().and_then(array_index)
12117        {
12118            return Ok(object
12119                .typed_array_length()
12120                .is_some_and(|length| (index as usize) < length));
12121        }
12122        let mut current = Some(object.clone());
12123        // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
12124        let mut guard = 0;
12125        while let Some(node) = current {
12126            guard += 1;
12127            if guard > 1000 {
12128                return Ok(false);
12129            }
12130            let own = self.object_get_own_property(&node, key)?;
12131            if own.is_some() {
12132                return Ok(true);
12133            }
12134            current = self.object_prototype_of(&node)?;
12135        }
12136        Ok(false)
12137    }
12138
12139    /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
12140    ///
12141    /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
12142    /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
12143    /// boolean as well, and it needs the receiver to be the one the caller named.
12144    pub fn set_property_with_key_receiver(
12145        &mut self,
12146        object: &Gc<JsObject>,
12147        key: &PropertyKey,
12148        value: Value,
12149        receiver: Option<&Value>,
12150        on_failure: DeleteFailure,
12151    ) -> JsResult<bool> {
12152        let receiver = receiver
12153            .cloned()
12154            .unwrap_or_else(|| Value::Object(object.clone()));
12155        if object.proxy_state().is_some() {
12156            return match self.proxy_set(object, key, value, &receiver)? {
12157                Some(accepted) => Ok(accepted),
12158                None => Ok(true),
12159            };
12160        }
12161        // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
12162        // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
12163        // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
12164        // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
12165        if object.typed_array_element_type().is_some()
12166            && key.as_str().and_then(array_index).is_some()
12167        {
12168            let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
12169            self.set_property_with_key_receiver_aware(object, key, value, on_failure, same)?;
12170            return Ok(true);
12171        }
12172        // An own accessor, or one found up the chain, receives the call with `receiver` as
12173        // `this` — which is the whole reason this variant exists.
12174        if let Some(setter) = self.lookup_setter(object, key)? {
12175            self.call_value(setter, receiver, vec![value])?;
12176            return Ok(true);
12177        }
12178        // Otherwise it is an ordinary create-or-write, which the plain path already does —
12179        // carrying the receiver comparison, which a typed array's element store can see.
12180        let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
12181        self.set_property_with_key_receiver_aware(object, key, value, on_failure, same)?;
12182        Ok(true)
12183    }
12184
12185    /// The setter `key` resolves to, if it resolves to an accessor.
12186    fn lookup_setter(
12187        &mut self,
12188        object: &Gc<JsObject>,
12189        key: &PropertyKey,
12190    ) -> JsResult<Option<Value>> {
12191        let mut current = Some(object.clone());
12192        let mut guard = 0;
12193        while let Some(node) = current {
12194            guard += 1;
12195            if guard > 1000 {
12196                return Ok(None);
12197            }
12198            if let Some(property) = self.object_get_own_property(&node, key)? {
12199                if property.is_accessor() {
12200                    return Ok(property.setter);
12201                }
12202                // A data property stops the walk: the store writes here, not further up.
12203                return Ok(None);
12204            }
12205            current = self.object_prototype_of(&node)?;
12206        }
12207        Ok(None)
12208    }
12209
12210    /// `[[IsExtensible]]`, with the proxy trap when there is one.
12211    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
12212        if let Some(answer) = self.proxy_is_extensible(object)? {
12213            return Ok(answer);
12214        }
12215        if let Some(exotic) = object.exotic()
12216            && let Some(answer) = exotic.is_extensible(self, object)?
12217        {
12218            return Ok(answer);
12219        }
12220        Ok(object.is_extensible())
12221    }
12222
12223    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
12224    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
12225        if let Some(answer) = self.proxy_prevent_extensions(object)? {
12226            return Ok(answer);
12227        }
12228        if let Some(exotic) = object.exotic()
12229            && let Some(answer) = exotic.prevent_extensions(self, object)?
12230        {
12231            return Ok(answer);
12232        }
12233        object.set_extensible(false);
12234        Ok(true)
12235    }
12236
12237    fn copy_properties(
12238        &mut self,
12239        target: &Value,
12240        source: &Value,
12241        exclusion: &Value,
12242    ) -> JsResult<()> {
12243        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
12244        // does contribute: its index properties are own, enumerable and writable, which
12245        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
12246        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
12247        // is a no-op.
12248        let Some(target) = target.as_object() else {
12249            return Ok(());
12250        };
12251        let source_object = match source {
12252            Value::Object(object) => object.clone(),
12253            Value::String(text) => {
12254                // Untaken keys are the string's indices, which are code units.
12255                for index in 0..text.utf16_len() {
12256                    if let Some(unit) = text.wtf8().unit_at(index) {
12257                        target.define_data(&index.to_string(), self.string_wtf8(unit));
12258                    }
12259                }
12260                return Ok(());
12261            }
12262            _ => return Ok(()),
12263        };
12264        // An object *rest* element passes the keys already taken by the literal part as
12265        // an array of strings; a spread passes `null`, which excludes nothing. Only the
12266        // string keys of the exclusion array are meaningful, so an array is read by its
12267        // elements rather than by its own property names.
12268        let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
12269        if let Value::Object(list) = exclusion
12270            && let Some(length) = list.array_length()
12271        {
12272            for index in 0..length {
12273                if let Some(value) = list.array_get(index) {
12274                    excluded.push(self.propkey_of(&value)?);
12275                }
12276            }
12277        }
12278        let source = &source_object;
12279        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
12280        // Reading the property table directly made every spread of a proxy empty.
12281        let keys = self.object_own_property_keys(source)?;
12282        for as_key in keys {
12283            if as_key.is_symbol() {
12284                // A spread copies string-keyed properties only.
12285                continue;
12286            }
12287            if excluded.contains(&crate::value::Wtf8::new(
12288                as_key.as_str().unwrap_or_default(),
12289            )) {
12290                continue;
12291            }
12292            let enumerable = self
12293                .object_get_own_property(source, &as_key)?
12294                .is_some_and(|property| property.enumerable);
12295            if !enumerable {
12296                continue;
12297            }
12298            let value = self
12299                .get_property_key(source, &as_key)?
12300                .unwrap_or(Value::Undefined);
12301            target.define_data_key(&as_key, value);
12302        }
12303        Ok(())
12304    }
12305
12306    // -- iteration ---------------------------------------------------------
12307
12308    /// One object's own keys in enumeration order: array indices ascending, then the
12309    /// rest in insertion order.
12310    ///
12311    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
12312    /// whether the key is enumerable, which the caller resolves per key because an
12313    /// array's elements are not in the same store as its named properties.
12314    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
12315        // An index can arrive twice, once from the array's element store and once from
12316        // its property map, so the numeric keys go through a map that keeps the
12317        // enumerable answer if either source gave one.
12318        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
12319        for (key, enumerable) in &own {
12320            if let Some(index) = key.as_str().and_then(array_index) {
12321                let entry = numeric.entry(index).or_insert(false);
12322                *entry = *entry || *enumerable;
12323            }
12324        }
12325        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
12326            .into_iter()
12327            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
12328            .collect();
12329        ordered.extend(
12330            own.into_iter()
12331                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
12332        );
12333        ordered
12334    }
12335
12336    /// Build the key list a `for-in` loop walks.
12337    ///
12338    /// The order is the specification's: own properties before inherited ones, and
12339    /// within one object the integer-like keys in ascending numeric order ahead of the
12340    /// string keys in insertion order. A shadowed key only appears once, and a key that
12341    /// is a non-enumerable own property anywhere nearer is skipped entirely.
12342    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12343        let record = self.new_object(None);
12344        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
12345        // A proxy supplies its own key list, and — the reason this is not just another
12346        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
12347        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
12348        // descriptor there.
12349        if let Value::Object(object) = value
12350            && object.proxy_state().is_some()
12351        {
12352            let own = self
12353                .proxy_own_keys(object)?
12354                .unwrap_or_else(|| object.own_property_keys());
12355            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
12356            let mut numeric: Vec<u32> = Vec::new();
12357            let mut rest: Vec<PropertyKey> = Vec::new();
12358            for key in own {
12359                match key.as_str().and_then(array_index) {
12360                    Some(index) => numeric.push(index),
12361                    None => rest.push(key),
12362                }
12363            }
12364            numeric.sort_unstable();
12365            ordered.extend(
12366                numeric
12367                    .into_iter()
12368                    .map(|index| PropertyKey::from(index.to_string())),
12369            );
12370            ordered.extend(rest);
12371            for (index, key) in ordered.into_iter().enumerate() {
12372                record.define_data(&index.to_string(), self.key_value(&key));
12373            }
12374            record.define_data("__index", Value::Int(0));
12375            // The mark that makes `for_in_advance` re-ask the proxy per key.
12376            record.define_data("__proxy", Value::Object(object.clone()));
12377            return Ok(record);
12378        }
12379        if let Value::Object(object) = value {
12380            let mut chain = vec![object.clone()];
12381            chain.extend(object.chain());
12382            // Every own string key the walk has seen, enumerable or not. A
12383            // non-enumerable own property still hides a same-named enumerable one
12384            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
12385            // keeps `x` out of the loop even when the prototype has one.
12386            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
12387            for object in chain {
12388                let mut own: Vec<(crate::value::Wtf8, bool)> = object
12389                    .own_property_keys()
12390                    .iter()
12391                    .filter_map(|key| key.as_wtf8().cloned())
12392                    .map(|key| {
12393                        let enumerable = object
12394                            .own_property(&key.to_string_lossy())
12395                            .map(|property| property.enumerable)
12396                            .unwrap_or(false);
12397                        (key, enumerable)
12398                    })
12399                    .collect();
12400                if let Some(length) = object.array_length() {
12401                    own.retain(|(key, _)| key.as_str() != Some("length"));
12402                    for index in 0..length {
12403                        if object.array_get(index).is_some() {
12404                            own.push((crate::value::Wtf8::new(index.to_string()), true));
12405                        }
12406                    }
12407                }
12408                // Integer-like keys come first in ascending order, then the rest in
12409                // insertion order — and the ordering is *per object*, not for the chain
12410                // as a whole: one pass over every collected key lifted a prototype's
12411                // `"4"` above the target's own `x`/`y`, which is not the order
12412                // `for…in` reports.
12413                for (key, enumerable) in Self::order_own_keys(own) {
12414                    if visited.contains(&key) {
12415                        continue;
12416                    }
12417                    visited.push(key.clone());
12418                    if enumerable {
12419                        keys.push(key);
12420                    }
12421                }
12422            }
12423        }
12424        for (index, key) in keys.into_iter().enumerate() {
12425            record.define_data(&index.to_string(), self.string_wtf8(key));
12426        }
12427        record.define_data("__index", Value::Int(0));
12428        Ok(record)
12429    }
12430
12431    /// The next key of a `for…in` record, `None` when the loop is done.
12432    ///
12433    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
12434    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
12435    /// the loop reaches it, so a handler that stops reporting a key partway through drops
12436    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
12437    /// key the handler had already withdrawn.
12438    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
12439        let Value::Object(record) = record else {
12440            return Ok(None);
12441        };
12442        let proxy = record
12443            .own_property("__proxy")
12444            .and_then(|property| property.value);
12445        loop {
12446            let index = record
12447                .own_property("__index")
12448                .and_then(|property| property.value)
12449                .map(|value| value.to_int32())
12450                .unwrap_or(0);
12451            let Some(candidate) = record
12452                .own_property(&index.to_string())
12453                .and_then(|property| property.value)
12454            else {
12455                return Ok(None);
12456            };
12457            record.define_data("__index", Value::Int(index + 1));
12458            let text = candidate.to_js_string();
12459            let Some(Value::Object(proxy)) = &proxy else {
12460                return Ok(Some(text));
12461            };
12462            // The candidate is already a key string here, so the lookup does not need a
12463            // second `ToPropertyKey` conversion.
12464            let key = PropertyKey::from(text.as_str());
12465            let live = match self.proxy_get_own_property(proxy, &key)? {
12466                Some(descriptor) => descriptor,
12467                // Not a proxy after all, or it lost its state: fall back to the target.
12468                None => proxy.own_property_key(&key),
12469            };
12470            if live.is_some_and(|property| property.enumerable) {
12471                return Ok(Some(text));
12472            }
12473            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
12474            // next one.
12475        }
12476    }
12477
12478    /// The iterator for `for-of`: the object and its `next` method.
12479    ///
12480    /// An object that already carries a `next` method is used as it is — that is what
12481    /// `arr.values()` returns — and only arrays and strings get the built-in
12482    /// sequence iterator.
12483    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
12484    ///
12485    /// Callers that must choose between the iterable and the array-like protocol — the
12486    /// typed-array constructor is the main one — need to ask *before* committing to one.
12487    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
12488        let key = self.realm.well_known_key(WellKnown::Iterator);
12489        let method = self.read_field_key(value, &key)?;
12490        if matches!(method, Value::Undefined | Value::Null) {
12491            return Ok(false);
12492        }
12493        if !matches!(&method, Value::Object(object) if object.is_callable()) {
12494            return Err(Signal::Throw(
12495                self.make_error("TypeError", "Symbol.iterator is not callable"),
12496            ));
12497        }
12498        Ok(true)
12499    }
12500
12501    /// Collect everything an iterable yields.
12502    ///
12503    /// The cap is a guard against a generator that never ends: an unbounded collect would
12504    /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
12505    /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
12506    /// `MAX_ARRAY_LIKE` in the `Array` builtins.
12507    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
12508        const MAX_ITEMS: usize = 1 << 24;
12509        let iterator = self.get_iterator(value)?;
12510        let mut out = Vec::new();
12511        loop {
12512            let (element, done) = self.iterator_step(&iterator)?;
12513            if done {
12514                return Ok(out);
12515            }
12516            out.push(element);
12517            if out.len() > MAX_ITEMS {
12518                // Close before refusing: the walk is being abandoned, so the iterator's
12519                // `return` has to run (§7.4.6). Leaving it open left a `finally` block
12520                // unrun and a locked resource unreleased.
12521                self.close_iterator_after_throw(&iterator)?;
12522                return Err(self.range_error("iterable is too long to collect"));
12523            }
12524        }
12525    }
12526
12527    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
12528    ///
12529    /// A native constructor calls this once it has validated its arguments, which is the
12530    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
12531    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
12532    /// never reached. The prototype comes from `new.target` when it is an object, and from
12533    /// `default_proto` otherwise.
12534    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12535        let proto = self.ctor_prototype(default_proto)?;
12536        Ok(self.new_object(Some(proto)))
12537    }
12538
12539    /// An **array** whose prototype comes from `new.target`.
12540    ///
12541    /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
12542    /// instance from `new.target.prototype`, and building a plain array instead made every
12543    /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
12544    pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
12545        let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
12546        Ok(JsObject::array(self.heap, Some(proto), 0))
12547    }
12548
12549    /// `new.target.prototype` when this is a construction, or `None` for a plain call.
12550    ///
12551    /// The `Option` form is for the constructors that build their instance in a helper which
12552    /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
12553    /// from `await`'s internal promise, and only the first has a `new.target`.
12554    fn ctor_prototype_opt(
12555        &mut self,
12556        default_proto: Option<Gc<JsObject>>,
12557    ) -> JsResult<Option<Gc<JsObject>>> {
12558        let Some(target) = self.pending_new_target.clone() else {
12559            return Ok(default_proto);
12560        };
12561        let Some(target) = target.as_object().cloned() else {
12562            return Ok(default_proto);
12563        };
12564        match self.get_property(&target, "prototype")? {
12565            Some(Value::Object(proto)) => Ok(Some(proto)),
12566            _ => Ok(default_proto),
12567        }
12568    }
12569
12570    /// `new.target.prototype`, or `default_proto` when this is a plain call.
12571    fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12572        let Some(target) = self.pending_new_target.clone() else {
12573            return Ok(default_proto);
12574        };
12575        let Some(target) = target.as_object().cloned() else {
12576            return Ok(default_proto);
12577        };
12578        match self.get_property(&target, "prototype")? {
12579            Some(Value::Object(proto)) => Ok(proto),
12580            _ => Ok(default_proto),
12581        }
12582    }
12583
12584    /// `CreateDataPropertyOrThrow(O, key, value)`.
12585    ///
12586    /// A *definition*, not an assignment. The difference is visible the moment the target
12587    /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
12588    /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
12589    /// replaces the descriptor. It is a `TypeError` only when the definition itself is
12590    /// refused (`configurable: false`).
12591    ///
12592    /// The fast path exists because this is called once per element by `map`, `filter`,
12593    /// `slice` and friends: a plain array with no custom element descriptors and a writable
12594    /// `length` can store straight into its element vector.
12595    pub fn create_data_property_or_throw(
12596        &mut self,
12597        object: &Gc<JsObject>,
12598        index: usize,
12599        value: Value,
12600    ) -> JsResult<()> {
12601        if object.is_array()
12602            && object.elements_writable()
12603            && !object.has_element_descriptors()
12604            && object.is_extensible()
12605            && object.array_set(self.heap, index, value.clone())
12606        {
12607            return Ok(());
12608        }
12609        let key = PropertyKey::from(index.to_string());
12610        let property = Property {
12611            value: Some(value),
12612            writable: true,
12613            enumerable: true,
12614            configurable: true,
12615            ..Property::default()
12616        };
12617        // `CreateDataProperty` always asks for the default attributes, so it can only ever
12618        // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
12619        // the rest. Checking here rather than inside `object_define_own_property` is
12620        // deliberate: that function receives a fully-populated `Property` and cannot tell
12621        // an omitted attribute from an explicit `false`, so the generic check it would need
12622        // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
12623        // writable property (that cost eight `Object/defineProperty` tests).
12624        if let Some(existing) = self.object_get_own_property(object, &key)?
12625            && !existing.configurable
12626        {
12627            return Err(self.type_error("cannot create the property"));
12628        }
12629        if self.object_define_own_property(object, &key, property)? {
12630            return Ok(());
12631        }
12632        Err(self.type_error("cannot create the property"))
12633    }
12634
12635    /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
12636    ///
12637    /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
12638    /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
12639    /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
12640    /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
12641    /// run user code and both can throw.
12642    pub fn species_constructor(
12643        &mut self,
12644        object: &Gc<JsObject>,
12645        default: Value,
12646    ) -> JsResult<Value> {
12647        let Some(constructor) = self.get_property(object, "constructor")? else {
12648            return Ok(default);
12649        };
12650        let constructor = match constructor {
12651            Value::Undefined => return Ok(default),
12652            Value::Object(constructor) => constructor,
12653            _ => return Err(self.type_error("constructor is not an object")),
12654        };
12655        let key = self.realm.well_known_key(WellKnown::Species);
12656        let species = self.get_property_key(&constructor, &key)?;
12657        match species {
12658            None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
12659            Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
12660            Some(_) => Err(self.type_error("species is not a constructor")),
12661        }
12662    }
12663
12664    /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
12665    ///
12666    /// The result is an array of `length` holes whose prototype comes from
12667    /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
12668    /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
12669    /// is why the `IsArray` check is the first step and not an optimisation.
12670    pub fn array_species_create(
12671        &mut self,
12672        original: &Value,
12673        length: usize,
12674    ) -> JsResult<Gc<JsObject>> {
12675        let Some(object) = original.as_object().cloned() else {
12676            return Ok(self.new_array_of_length(length));
12677        };
12678        if !object.is_array() {
12679            return Ok(self.new_array_of_length(length));
12680        }
12681        // A `constructor` that *is* this realm's `Array` means "the default", and skipping
12682        // it here is what keeps `Array.prototype.map` from calling `Array` at all.
12683        let Some(constructor) = self.get_property(&object, "constructor")? else {
12684            return Ok(self.new_array_of_length(length));
12685        };
12686        let species = match constructor {
12687            Value::Undefined => return Ok(self.new_array_of_length(length)),
12688            Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
12689                return Ok(self.new_array_of_length(length));
12690            }
12691            Value::Object(constructor) => {
12692                let key = self.realm.well_known_key(WellKnown::Species);
12693                match self.get_property_key(&constructor, &key)? {
12694                    None | Some(Value::Undefined) | Some(Value::Null) => {
12695                        return Ok(self.new_array_of_length(length));
12696                    }
12697                    Some(species) => species,
12698                }
12699            }
12700            _ => return Ok(self.new_array_of_length(length)),
12701        };
12702        // `IsConstructor(species)` decides whether step 7 may construct at all; a species
12703        // that is merely callable is the `create-species-non-ctor` case.
12704        if !matches!(&species, Value::Object(object) if object.is_constructor()) {
12705            return Err(self.type_error("species is not a constructor"));
12706        }
12707        let created = self.construct(species.clone(), species, vec![Value::Int(length as i32)])?;
12708        let Some(created) = created.as_object().cloned() else {
12709            return Err(self.type_error("species constructor did not answer an object"));
12710        };
12711        // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
12712        // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
12713        // object, and `create-species-with-non-writable-property` asserts exactly that.
12714        // The length is set for the array case; the generic case is the caller's
12715        // `Set(A, "length", …)`.
12716        if created.is_array() {
12717            created.array_set_length(self.heap, length);
12718        }
12719        Ok(created)
12720    }
12721
12722    /// Whether `object` is this realm's `%Array%`.
12723    fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
12724        self.realm
12725            .array_constructor
12726            .as_ref()
12727            .is_some_and(|array| array.ptr_eq(object))
12728    }
12729
12730    /// A fresh `length`-hole array with the intrinsic prototype.
12731    pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
12732        let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
12733        array.array_set_length(self.heap, length);
12734        array
12735    }
12736
12737    /// Whether this call is a construction, i.e. `new.target` is defined.
12738    ///
12739    /// A native constructor receives `this = undefined` (it builds its own instance), so it
12740    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
12741    /// The native function currently executing, if any.
12742    pub fn current_native(&self) -> Option<Gc<JsObject>> {
12743        self.current_native.clone()
12744    }
12745
12746    /// Whether this call is a construction, i.e. `new.target` is defined.
12747    pub fn is_constructing(&self) -> bool {
12748        self.pending_new_target.is_some()
12749    }
12750
12751    /// The `TypeError` a constructor too primitive to have a wrapper raises.
12752    ///
12753    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
12754    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
12755    /// happens inside the native function, which is why the trace carries an
12756    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
12757    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
12758    /// constructor`, and an unnamed one reports the leading space of `" is not a
12759    /// constructor"` because the reference formats the empty name as it is.
12760    ///
12761    /// It is also the answer for a `new.target` that cannot be named at all — not a
12762    /// function, or a throwing `name` getter — where the reference falls back to the bare
12763    /// `not a constructor`.
12764    pub fn not_a_constructor_error(&mut self) -> Signal {
12765        let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
12766        self.not_a_constructor_error_for(target)
12767    }
12768
12769    /// The same `TypeError` for an explicit target, for the callers that check
12770    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
12771    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
12772        let target = match target {
12773            Value::Object(target) if target.is_callable() => target,
12774            _ => return self.type_error("not a constructor"),
12775        };
12776        let name = match self.get_property(&target, "name") {
12777            Ok(Some(value)) => value.to_js_string(),
12778            _ => return self.type_error("not a constructor"),
12779        };
12780        self.type_error(format!("{name} is not a constructor"))
12781    }
12782
12783    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
12784    ///
12785    /// True whenever `new.target` is not the callee itself, or when it has no usable
12786    /// `prototype` — the cases where reading the property is observable at all.
12787    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
12788        match &self.pending_new_target {
12789            Some(Value::Object(target)) => !target.ptr_eq(callee),
12790            Some(_) => true,
12791            None => false,
12792        }
12793    }
12794
12795    /// The symbol key for one of the engine's own hidden slots.
12796    ///
12797    /// Cached on the realm, so every object of a kind shares one key and a slot can be
12798    /// read back by name.
12799    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
12800        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
12801            return PropertyKey::Symbol(symbol.clone());
12802        }
12803        let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
12804        self.realm
12805            .internal_slots
12806            .borrow_mut()
12807            .insert(name, Value::Symbol(symbol.clone()));
12808        PropertyKey::Symbol(symbol)
12809    }
12810
12811    /// Read a hidden slot, or `None` when the object has none of that name.
12812    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
12813        let slots = self.realm.internal_slots.borrow();
12814        let Value::Symbol(symbol) = slots.get(name)? else {
12815            return None;
12816        };
12817        object
12818            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
12819            .and_then(|property| property.value)
12820    }
12821
12822    /// Define a hidden slot.
12823    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
12824        let key = self.internal_slot(name);
12825        object.define_key(&key, Property::with_attributes(value, false, false));
12826    }
12827
12828    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
12829    ///
12830    /// The method is looked up on the value (through its prototype), called with no
12831    /// arguments, and its result becomes the iterator. A generator gets here through
12832    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
12833    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
12834    ///
12835    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
12836    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
12837    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
12838    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
12839    /// does, and a user-defined iterable works without a special case.
12840    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
12841    /// `Symbol.iterator`.
12842    ///
12843    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
12844    /// iterable is legal there, and each value it produces is simply already settled by
12845    /// the time the `await` around it runs.
12846    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12847        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
12848        let method = self.read_field_key(value, &async_key)?;
12849        // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
12850        // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
12851        // is *present but not callable* is a TypeError — it does not mean "try the other
12852        // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
12853        // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
12854        // guard is there to catch.
12855        let absent = matches!(method, Value::Undefined | Value::Null);
12856        if !absent {
12857            let Value::Object(object) = &method else {
12858                return Err(Signal::Throw(
12859                    self.make_error("TypeError", "value is not iterable"),
12860                ));
12861            };
12862            if !object.is_callable() {
12863                return Err(Signal::Throw(
12864                    self.make_error("TypeError", "value is not iterable"),
12865                ));
12866            }
12867        }
12868        if absent {
12869            return self.get_iterator(value);
12870        }
12871        let iterator = self.call_value(method, value.clone(), Vec::new())?;
12872        if !matches!(iterator, Value::Object(_)) {
12873            return Err(Signal::Throw(
12874                self.make_error("TypeError", "iterator is not an object"),
12875            ));
12876        }
12877        let next = self.read_field(&iterator, "next")?;
12878        Ok(Iterator {
12879            object: iterator,
12880            next,
12881        })
12882    }
12883
12884    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12885        let key = self.realm.well_known_key(WellKnown::Iterator);
12886        let method = self.read_field_key(value, &key)?;
12887        let Value::Object(function) = &method else {
12888            return Err(Signal::Throw(self.make_error(
12889                "TypeError",
12890                &format!("{} is not iterable", value.to_js_string()),
12891            )));
12892        };
12893        if !function.is_callable() {
12894            return Err(Signal::Throw(self.make_error(
12895                "TypeError",
12896                &format!("{} is not iterable", value.to_js_string()),
12897            )));
12898        }
12899        let iterator = self.call_value(method, value.clone(), Vec::new())?;
12900        // The spec requires an object here; a primitive iterator has no `next` to call
12901        // and would fail one step later with a confusing message.
12902        if !matches!(iterator, Value::Object(_)) {
12903            return Err(Signal::Throw(
12904                self.make_error("TypeError", "iterator is not an object"),
12905            ));
12906        }
12907        let next = self.read_field(&iterator, "next")?;
12908        Ok(Iterator {
12909            object: iterator,
12910            next,
12911        })
12912    }
12913
12914    /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
12915    /// cannot replace it.
12916    fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
12917        let method = self.read_field(&iterator.object, "return")?;
12918        if matches!(method, Value::Undefined | Value::Null) {
12919            return Ok(());
12920        }
12921        if !matches!(&method, Value::Object(object) if object.is_callable()) {
12922            return Err(self.type_error("iterator return is not a function"));
12923        }
12924        self.call_value(method, iterator.object.clone(), Vec::new())?;
12925        Ok(())
12926    }
12927
12928    /// One step of an internal iterator: the value and whether it is exhausted.
12929    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
12930        // A real iterator (`next` is a function) answers with a result object.
12931        if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
12932            let result =
12933                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
12934            let Some(result) = result.as_object().cloned() else {
12935                return Err(self.type_error("iterator result is not an object"));
12936            };
12937            let done = self
12938                .get_property(&result, "done")?
12939                .is_some_and(|value| value.to_boolean());
12940            // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
12941            // `done` is false. Reading it unconditionally ran a throwing `value` getter on
12942            // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
12943            // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
12944            // made an unrelated `value` getter observable after the loop was over.
12945            if done {
12946                return Ok((Value::Undefined, true));
12947            }
12948            let value = self
12949                .get_property(&result, "value")?
12950                .unwrap_or(Value::Undefined);
12951            return Ok((value, false));
12952        }
12953        // An iterator whose `next` is not callable is treated as exhausted, which is
12954        // what `for (x of {})` relies on: `for_of_start` has already refused the ones
12955        // that are not iterable at all.
12956        Ok((Value::Undefined, true))
12957    }
12958
12959    /// `[...iterable]`: append everything the iterator yields, and answer the next
12960    /// index.
12961    ///
12962    /// This goes through the same iterator machinery `for-of` uses rather than copying
12963    /// an array's elements, because a spread source is any iterable: a string spreads
12964    /// into its characters and an array iterator spreads into its results. Handling
12965    /// only arrays made `[..."ab"]` come out empty with no error at all.
12966    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
12967        let Some(target) = array.as_object().cloned() else {
12968            return Ok(0);
12969        };
12970        let start = target.array_length().unwrap_or(0);
12971        let mut added = 0;
12972        let iterator = self.get_iterator(iterable)?;
12973        loop {
12974            let (value, done) = self.iterator_step(&iterator)?;
12975            if done {
12976                break;
12977            }
12978            target.array_set(self.heap, start + added, value);
12979            added += 1;
12980        }
12981        Ok((start + added) as i32)
12982    }
12983
12984    /// How an uncaught exception is reported.
12985    ///
12986    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
12987    /// with `ToString` — `js_std_dump_error` is three lines that end in
12988    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
12989    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
12990    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
12991    ///
12992    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
12993    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
12994    /// `toString`"; it does call it, but only for objects of a class it does not know how
12995    /// to walk, and never for errors, arrays or plain objects.
12996    ///
12997    /// A printer that fails must not take the reporter down with it, so that case falls
12998    /// back to the `ToString` rendering.
12999    pub fn describe_exception(&mut self, value: &Value) -> String {
13000        match crate::print::sprint(self, value) {
13001            Ok(text) => text,
13002            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
13003        }
13004    }
13005
13006    /// The file name of whatever is running, innermost frame first.
13007    ///
13008    /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
13009    /// innermost frame's file name, without distinguishing a module body from a plain
13010    /// script. `import()` uses it as the base for a relative specifier, which is why
13011    /// `import('./x.js')` inside a script resolves next to the script and not next to the
13012    /// process's working directory.
13013    pub fn script_or_module_name(&self) -> Option<String> {
13014        self.script_or_module_name_at(0)
13015    }
13016
13017    /// [`Interp::script_or_module_name`] `level` frames further out.
13018    ///
13019    /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
13020    /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
13021    /// frame without a file name is skipped rather than counted, because a native call
13022    /// pushes no frame of its own and so cannot be a level.
13023    pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
13024        self.frames
13025            .iter()
13026            .rev()
13027            .filter_map(|frame| frame.code.code.filename.clone())
13028            .nth(level)
13029    }
13030
13031    /// The current call stack, formatted the way `qjs` prints `error.stack`.
13032    ///
13033    /// One `    at name (file:line:col)` line per active frame, innermost first. The
13034    /// position is the one recorded for the instruction each frame is stopped on, which
13035    /// is why the compiler builds a pc-to-position table per function: without it a
13036    /// trace could only name the function, not the line inside it.
13037    ///
13038    /// A frame whose code has no positions prints just `(file)`, matching the
13039    /// reference's output for stripped bytecode.
13040    pub fn stack_trace(&self) -> String {
13041        self.stack_trace_skipping(0)
13042    }
13043
13044    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
13045    fn stack_trace_skipping(&self, skip: usize) -> String {
13046        // One ordered list, innermost first, so `skip` counts the same thing whether the
13047        // frames it leaves out are native or bytecode. Indices rather than references: a
13048        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
13049        let depth = self.frames.len();
13050        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
13051        // A native entered while `at` bytecode frames were live was called *from* the
13052        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
13053        // entered at the current depth are therefore innermost of all.
13054        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
13055            for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
13056                if *at == wanted {
13057                    order.push((true, index));
13058                }
13059            }
13060        };
13061        push_natives(&mut order, depth);
13062        for index in (0..depth).rev() {
13063            order.push((false, index));
13064            push_natives(&mut order, index);
13065        }
13066        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
13067        // barrier. Natives entered at exactly the barrier depth are the eval entry point
13068        // itself (`evalScript (native)`), and the reference leaves those out too.
13069        if let Some(barrier) = self.trace_barriers.last().copied() {
13070            order.retain(|(is_native, index)| match is_native {
13071                true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
13072                false => *index >= barrier,
13073            });
13074        }
13075
13076        let mut out = String::new();
13077        for (is_native, index) in order.into_iter().skip(skip) {
13078            match is_native {
13079                true => {
13080                    out.push_str("    at ");
13081                    let (native, _) = &self.native_frames[index];
13082                    let name = native
13083                        .own_property("name")
13084                        .and_then(|property| property.value)
13085                        .map(|value| value.to_js_string())
13086                        .unwrap_or_default();
13087                    out.push_str(&name);
13088                    out.push_str(" (native)\n");
13089                }
13090                false => {
13091                    let frame = &self.frames[index];
13092                    let code = &frame.code.code;
13093                    let file = code.filename.as_deref().unwrap_or("<input>");
13094                    // The name comes from the function *object*, not from the compiled code:
13095                    // an anonymous function expression is named by the property it is stored
13096                    // in (`{valueOf: function(){}}`), which only the object knows.
13097                    let bound_name = match &frame.callee {
13098                        Value::Object(object) => {
13099                            object
13100                                .own_property("name")
13101                                .and_then(|property| match property.value {
13102                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
13103                                        Some(text.to_string_lossy().into_owned())
13104                                    }
13105                                    _ => None,
13106                                })
13107                        }
13108                        _ => None,
13109                    };
13110                    // No callee object means the body was entered by the host, so the
13111                    // name has to come from the compiled code. Two cases differ:
13112                    //
13113                    // * an *unnamed* function of any kind — the reference reads the
13114                    //   `name` property, finds it empty, and prints `<anonymous>`;
13115                    // * a *module* body, which has no `name` property at all: the
13116                    //   reference builds that function object with `js_closure2` and
13117                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
13118                    //   so a trace reaching it also prints `<anonymous>` — while a
13119                    //   *script* body prints `<eval>`, its `name`.
13120                    let unnamed = code.name.is_empty() || code.module.is_some();
13121                    out.push_str("    at ");
13122                    match bound_name.as_deref() {
13123                        Some(name) => out.push_str(name),
13124                        None if unnamed => out.push_str("<anonymous>"),
13125                        None => out.push_str(&code.name),
13126                    }
13127                    match code.position_at(frame.at as u32) {
13128                        Some((line, column)) => {
13129                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
13130                        }
13131                        None => out.push_str(&format!(" ({file})\n")),
13132                    }
13133                }
13134            }
13135        }
13136        out
13137    }
13138
13139    /// Give an anonymous function the name of the property it is stored in.
13140    ///
13141    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
13142    /// enumerable and not configurable, and a function that already has a real name
13143    /// keeps it.
13144    ///
13145    /// "Already named" means a *non-empty* name: every function object is created with
13146    /// a `name` of `""` so the property exists on all of them, and treating that empty
13147    /// string as a name left every anonymous function nameless — which is how a stack
13148    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
13149    /// `SetFunctionName`, for a name that came from source text.
13150    fn set_function_name(&mut self, function: &Value, name: &str) {
13151        self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
13152    }
13153
13154    /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
13155    /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
13156    fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
13157        let Value::Object(object) = function else {
13158            return;
13159        };
13160        // `SetFunctionName` applies to *functions* and classes only, and only when they are
13161        // anonymous. Without the callability guard, `{value: someObject}` renamed
13162        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
13163        // on the right-hand side of a property. That is how a `zipKeyed` result object
13164        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
13165        // has no `NamedEvaluation` at all.
13166        if !object.is_callable() {
13167            return;
13168        }
13169        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
13170            && !existing.wtf8().is_empty()
13171        {
13172            return;
13173        }
13174        let text = self.string_wtf8(name.clone());
13175        object.define("name", Property::name_or_length(text));
13176    }
13177
13178    // -- global declarations -----------------------------------------------
13179
13180    /// Declare a global binding, creating its reference cell.
13181    /// Declare a `var` or function global, whose home is the global object.
13182    ///
13183    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
13184    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
13185    /// such as `print`, or a redeclaration — is left alone.
13186    pub fn declare_var_global(&mut self, name: &str) {
13187        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
13188        // global object is exactly the leak `typeof my_var === "undefined"` after
13189        // `eval("var my_var=2")` rules out.
13190        if let Some(scope) = self.eval_scope.as_mut() {
13191            scope.entry(name.to_string()).or_insert(Value::Undefined);
13192            return;
13193        }
13194        // A sloppy direct eval declares into its *caller's* variable environment. Doing
13195        // this on the global object instead made `eval("var c = 1")` inside a parameter
13196        // list overwrite a global `c`, and made two calls to the same function share one
13197        // binding.
13198        if let Some(cell) = self.declare_eval_local(name) {
13199            cell.set(Value::Undefined);
13200            return;
13201        }
13202        let global = self.realm.global.clone();
13203        if global.own_property(name).is_some() {
13204            return;
13205        }
13206        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
13207        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
13208        // whole point of that trick and what lets `Object.defineProperty` reshape it
13209        // afterwards. `eval_scope` is `Some` while an eval is running.
13210        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
13211        global.define(
13212            name,
13213            Property {
13214                value: Some(Value::Undefined),
13215                writable: true,
13216                enumerable: true,
13217                configurable: from_eval,
13218                ..Property::default()
13219            },
13220        );
13221    }
13222
13223    /// Declare a *lexical* global binding, which starts in its dead zone.
13224    ///
13225    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
13226    /// global object and is created when its initialiser runs.
13227    pub fn declare_global(&mut self, name: &str, is_const: bool) {
13228        if is_const {
13229            self.realm.lexical_consts.insert(name.to_string());
13230        }
13231        if !self.realm.globals.contains_key(name) {
13232            // `Uninitialized` rather than `Undefined`: the binding exists but is not
13233            // readable until its initialiser runs, and that is what `let x` before
13234            // `x = 1` has to observe.
13235            let cell = self.new_cell(Value::Uninitialized);
13236            self.realm.globals.insert(name.to_string(), cell);
13237            self.realm.declared.push(name.to_string());
13238        }
13239    }
13240}
13241
13242/// The bytecode and environment of a function object, if it is a bytecode function.
13243///
13244/// Extracted before a call so no borrow of the object is held across it.
13245fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
13246    function.with(|data| match &data.kind {
13247        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
13248        _ => None,
13249    })
13250}
13251
13252/// A native call target, extracted before the call so no borrow is held.
13253enum NativeCall {
13254    Native(NativeFn),
13255    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
13256    /// not hold that object's `RefCell` borrow.
13257    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
13258    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
13259    Bound {
13260        target: Value,
13261        this: Value,
13262        leading: Vec<Value>,
13263    },
13264    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
13265    Revoker(crate::object::ProxyRef),
13266    /// A promise's `resolve`.
13267    PromiseResolve(Gc<JsObject>),
13268    /// A promise's `reject`.
13269    PromiseReject(Gc<JsObject>),
13270    /// The executor `NewPromiseCapability(C)` hands a user constructor.
13271    CapabilityExecutor {
13272        state: Gc<JsObject>,
13273    },
13274    /// One leg of a `then` that settles through a user capability.
13275    ThenShim {
13276        handler: Option<Value>,
13277        resolve: Value,
13278        reject: Value,
13279        fulfilled: bool,
13280    },
13281    /// One continuation of an `await`.
13282    AwaitResume {
13283        coroutine: Gc<JsObject>,
13284        promise: Gc<JsObject>,
13285        kind: ResumeKind,
13286    },
13287    /// One element of a `Promise` combinator settling.
13288    CombinatorSettle {
13289        state: Gc<JsObject>,
13290        index: usize,
13291        fulfilled: bool,
13292    },
13293    /// One of `Promise.prototype.finally`'s two shims.
13294    FinallyShim {
13295        callback: Option<Value>,
13296        fulfilled: bool,
13297        constructor: Value,
13298    },
13299    /// Settle a promise with a fixed outcome.
13300    SettlePromise {
13301        promise: Gc<JsObject>,
13302        value: Value,
13303        rejected: bool,
13304    },
13305    /// Continue an async generator after its `await` settled.
13306    GeneratorResume {
13307        generator: Gc<JsObject>,
13308        promise: Gc<JsObject>,
13309        kind: ResumeKind,
13310    },
13311    /// Read a module namespace's binding out of its cell.
13312    ModuleBinding(Gc<Cell>),
13313    /// Finish a completed async generator's `return(v)` once `v` has settled.
13314    CompletedReturn {
13315        generator: Gc<JsObject>,
13316        promise: Gc<JsObject>,
13317        rejected: bool,
13318    },
13319    /// Answer a pending async-generator method with `{value, done}`.
13320    YieldResult {
13321        generator: Gc<JsObject>,
13322        promise: Gc<JsObject>,
13323        done: bool,
13324    },
13325    /// One step of `AsyncDisposableStack.disposeAsync`.
13326    DisposeStep {
13327        remaining: Gc<JsObject>,
13328        promise: Gc<JsObject>,
13329        error: Value,
13330        rejected: bool,
13331    },
13332}
13333
13334/// What a store does when the object refuses the write.
13335#[derive(Clone, Copy, PartialEq, Eq)]
13336pub enum DeleteFailure {
13337    /// Raise a `TypeError`, which is what strict mode and every built-in does.
13338    Throw,
13339    /// Ignore the write, which is what a sloppy-mode assignment does.
13340    Ignore,
13341}
13342
13343/// Whether `object` is a `Date` instance, by the class tag it carries.
13344///
13345/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
13346/// builtins module depending on the interpreter's conversion order.
13347fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
13348    interp
13349        .internal_get(object, "_class")
13350        .is_some_and(|value| value.to_js_string() == "Date")
13351}
13352
13353/// Which type `ToPrimitive` prefers when it converts an object.
13354#[derive(Clone, Copy, PartialEq, Eq)]
13355pub enum Hint {
13356    /// The default hint, which behaves like [`Hint::Number`].
13357    Default,
13358    /// `Number(obj)` and the arithmetic operators.
13359    Number,
13360    /// `String(obj)` and `ToPropertyKey`.
13361    String,
13362}
13363
13364/// Which table a binding slot indexes, for the messages that name it.
13365#[derive(Clone, Copy)]
13366enum VarSlot {
13367    Loc,
13368    Closure,
13369}
13370
13371/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
13372fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
13373    Ok(this)
13374}
13375
13376/// An internal iterator: the sequence plus a cursor.
13377pub(crate) struct Iterator {
13378    pub(crate) object: Value,
13379    pub(crate) next: Value,
13380}
13381
13382/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
13383/// and plain `a` for a method.
13384///
13385/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
13386/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
13387/// reads `at get a (file:1:2)`.
13388/// The same prefixing, for a name that may hold an unpaired surrogate.
13389fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
13390    let prefix = match flags & 3 {
13391        1 => "get ",
13392        2 => "set ",
13393        _ => return key.clone(),
13394    };
13395    let mut units: Vec<u16> = prefix.encode_utf16().collect();
13396    units.extend_from_slice(&key.to_units());
13397    crate::value::Wtf8::from_units(&units)
13398}
13399
13400fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
13401    match flags & 3 {
13402        1 => format!("get {key}"),
13403        2 => format!("set {key}"),
13404        _ => key.to_string(),
13405    }
13406}
13407
13408/// Define a method or accessor property, per the `define_method` flag byte.
13409///
13410/// The low two bits pick value/getter/setter and bit 2 marks the property
13411/// enumerable.
13412///
13413/// A getter and a setter arrive as two separate `define_method` instructions, and the
13414/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
13415/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
13416/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
13417/// `JS_DefineProperty`, which leaves the other half alone.
13418fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
13419    let enumerable = flags & 4 != 0;
13420    let kind = flags & 3;
13421    let existing = object.own_property_key(key);
13422    let property = match kind {
13423        1 => Property {
13424            getter: Some(function),
13425            // The setter half, if this literal already defined one.
13426            setter: existing
13427                .filter(Property::is_accessor)
13428                .and_then(|p| p.setter),
13429            enumerable,
13430            configurable: true,
13431            ..Property::default()
13432        },
13433        2 => Property {
13434            getter: existing
13435                .filter(Property::is_accessor)
13436                .and_then(|p| p.getter),
13437            setter: Some(function),
13438            enumerable,
13439            configurable: true,
13440            ..Property::default()
13441        },
13442        _ => Property {
13443            value: Some(function),
13444            writable: true,
13445            enumerable,
13446            configurable: true,
13447            ..Property::default()
13448        },
13449    };
13450    object.define_key(key, property);
13451}
13452
13453// ---------------------------------------------------------------------------
13454// Operand decoding
13455// ---------------------------------------------------------------------------
13456
13457/// How `print` renders a value: the reference's `JS_PrintValue`.
13458///
13459/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
13460/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
13461/// The format is reproduced closely because the test suite compares output text:
13462///
13463/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
13464/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
13465/// * a cycle prints `[circular N]` with `N` the stack index of the object;
13466/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
13467///   end print as `<N empty item(s)>`;
13468/// * a string is quoted inside a container but raw at the top level, which is why
13469///   `print("x")` and `print(["x"])` differ.
13470pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
13471    // A string argument is printed raw: `js_print` converts it with `ToString`
13472    // instead of dumping it, and the quoting only appears inside a container.
13473    if let Value::String(text) = value {
13474        return text.to_string_lossy().into_owned();
13475    }
13476    let mut printer = Printer {
13477        interp,
13478        out: String::new(),
13479        stack: Vec::new(),
13480    };
13481    printer.value(value, 0);
13482    printer.out
13483}
13484
13485/// The internal class name an object carries, when it has one.
13486fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
13487    interp
13488        .internal_get(object, "_class")
13489        .map(|value| value.to_js_string())
13490}
13491
13492/// A string property, looked up the way `GetProperty` does: own first, then the
13493/// prototype chain. Needed because the print formatter holds the interpreter
13494/// immutably and so cannot run getters.
13495fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
13496    let mut current = Some(object.clone());
13497    // Bounded, because a prototype cycle would otherwise loop forever.
13498    for _ in 0..100 {
13499        let node = current?;
13500        if let Some(property) = node.own_property(name)
13501            && let Some(value) = property.value
13502        {
13503            return Some(value.to_js_string());
13504        }
13505        current = node.with(|data| data.proto.clone());
13506    }
13507    None
13508}
13509
13510/// The `JS_PrintValue` state: output, and the objects currently being printed.
13511struct Printer<'a, 'rt> {
13512    /// Kept for the class-name lookups that typed arrays and `Date` will need.
13513    #[allow(dead_code)]
13514    interp: &'a Interp<'rt>,
13515    out: String,
13516    stack: Vec<Gc<JsObject>>,
13517}
13518
13519impl Printer<'_, '_> {
13520    /// Depth past which a container is summarised by its class name.
13521    const MAX_DEPTH: usize = 2;
13522
13523    fn value(&mut self, value: &Value, level: usize) {
13524        match value {
13525            Value::Undefined
13526            | Value::Uninitialized
13527            | Value::Hole
13528            | Value::CatchOffset(_)
13529            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
13530            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
13531            // The printer writes a bigint the way the language spells one, so a dump is
13532            // unambiguous about which kind of number it is showing.
13533            Value::BigInt(big) => {
13534                self.out.push_str(&big.to_decimal_string());
13535                self.out.push('n');
13536            }
13537            Value::Null => self.out.push_str("null"),
13538            Value::Bool(true) => self.out.push_str("true"),
13539            Value::Bool(false) => self.out.push_str("false"),
13540            Value::Int(number) => self.out.push_str(&number.to_string()),
13541            Value::Float(number) => {
13542                self.out
13543                    .push_str(&crate::value::number_to_string_for_print(*number));
13544            }
13545            Value::String(text) => self.print_string(&text.to_string_lossy()),
13546            Value::Object(object) => self.object(object, level),
13547        }
13548    }
13549
13550    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
13551        // A cycle is reported rather than followed; the index is where the object
13552        // already sits in the print stack, which is what the reference shows.
13553        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
13554            self.out.push_str(&format!("[circular {index}]"));
13555            return;
13556        }
13557        if object.is_callable() {
13558            let name = object
13559                .own_property("name")
13560                .and_then(|property| property.value)
13561                .map(|value| value.to_js_string())
13562                .unwrap_or_default();
13563            if name.is_empty() {
13564                self.out.push_str("[Function (anonymous)]");
13565            } else {
13566                self.out.push_str(&format!("[Function {name}]"));
13567            }
13568            return;
13569        }
13570        if level >= Self::MAX_DEPTH {
13571            let class = if object.is_array() { "Array" } else { "Object" };
13572            self.out.push_str(&format!("[{class}]"));
13573            return;
13574        }
13575        // `Date` and `Error` print as themselves rather than as bags of properties:
13576        // the ISO string, and `Name: message` followed by the trace.
13577        if let Some(class) = class_of(self.interp, object) {
13578            if class == "Date" {
13579                self.date(object);
13580                return;
13581            }
13582            if class == "Error" {
13583                self.error(object);
13584                return;
13585            }
13586        }
13587        self.stack.push(object.clone());
13588        if object.is_array() {
13589            self.array(object, level);
13590        } else {
13591            self.plain_object(object, level);
13592        }
13593        self.stack.pop();
13594    }
13595
13596    /// A Date prints as its ISO string; an invalid one falls through to the plain
13597    /// object form, the way the reference falls back when `toISOString` throws.
13598    fn date(&mut self, object: &Gc<JsObject>) {
13599        let value = self
13600            .interp
13601            .internal_get(object, "_date_value")
13602            .map(|value| value.to_number());
13603        match value.and_then(crate::builtins::date::iso_string) {
13604            Some(text) => self.out.push_str(&text),
13605            None => self.plain_object(object, 0),
13606        }
13607    }
13608
13609    /// `Name: message`, then the trace with its trailing newline removed.
13610    fn error(&mut self, object: &Gc<JsObject>) {
13611        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
13612        self.out.push_str(&name);
13613        if let Some(message) = inherited(object, "message")
13614            && !message.is_empty()
13615        {
13616            self.out.push_str(": ");
13617            self.out.push_str(&message);
13618        }
13619        if let Some(stack) = inherited(object, "stack") {
13620            self.out.push('\n');
13621            self.out.push_str(stack.trim_end_matches('\n'));
13622        }
13623    }
13624
13625    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
13626        let elements = object.array_elements().unwrap_or_default();
13627        self.out.push_str("[ ");
13628        // An interior hole means the array is "sparse": the reference prints those
13629        // as `index: value` pairs and says nothing about the holes themselves, while
13630        // a hole run at the end becomes a single `<N empty items>` note.
13631        let last_present = elements
13632            .iter()
13633            .rposition(|value| !matches!(value, Value::Hole));
13634        let has_interior_hole = match last_present {
13635            Some(last) => elements[..last]
13636                .iter()
13637                .any(|value| matches!(value, Value::Hole)),
13638            None => false,
13639        };
13640        let mut first = true;
13641        if has_interior_hole {
13642            let mut index = 0;
13643            while index < elements.len() {
13644                let value = &elements[index];
13645                if matches!(value, Value::Hole) {
13646                    index += 1;
13647                    continue;
13648                }
13649                if !first {
13650                    self.out.push_str(", ");
13651                }
13652                first = false;
13653                self.out.push_str(&format!("{index}: "));
13654                self.value(value, level + 1);
13655                index += 1;
13656            }
13657        } else {
13658            for (index, value) in elements.iter().enumerate() {
13659                if matches!(value, Value::Hole) {
13660                    continue;
13661                }
13662                if !first {
13663                    self.out.push_str(", ");
13664                }
13665                first = false;
13666                let _ = index;
13667                self.value(value, level + 1);
13668            }
13669            if let Some(last) = last_present {
13670                let trailing = elements.len() - last - 1;
13671                if trailing > 0 {
13672                    if !first {
13673                        self.out.push_str(", ");
13674                    }
13675                    self.out.push_str(&format!(
13676                        "<{trailing} empty item{}>",
13677                        if trailing > 1 { "s" } else { "" }
13678                    ));
13679                }
13680            } else if !elements.is_empty() {
13681                let count = elements.len();
13682                self.out.push_str(&format!(
13683                    "<{count} empty item{}>",
13684                    if count > 1 { "s" } else { "" }
13685                ));
13686            }
13687        }
13688        self.out.push_str(" ]");
13689    }
13690
13691    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
13692        self.out.push_str("{ ");
13693        let mut first = true;
13694        for key in object.own_keys() {
13695            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
13696                continue;
13697            };
13698            if !property.enumerable {
13699                continue;
13700            }
13701            if !first {
13702                self.out.push_str(", ");
13703            }
13704            first = false;
13705            self.out
13706                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
13707                    &key.to_string_lossy(),
13708                )));
13709            self.out.push_str(": ");
13710            // An accessor has no value to dump; the reference names the half that
13711            // exists instead of calling it.
13712            if property.is_accessor() {
13713                let text = match (property.getter.is_some(), property.setter.is_some()) {
13714                    (true, true) => "[Getter/Setter]",
13715                    (false, true) => "[Setter]",
13716                    _ => "[Getter]",
13717                };
13718                self.out.push_str(text);
13719            } else {
13720                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
13721            }
13722        }
13723        self.out.push_str(" }");
13724    }
13725
13726    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
13727    fn print_string(&mut self, text: &str) {
13728        self.out.push('"');
13729        for character in text.chars() {
13730            match character {
13731                '"' => self.out.push_str("\\\""),
13732                '\\' => self.out.push_str("\\\\"),
13733                '\n' => self.out.push_str("\\n"),
13734                '\r' => self.out.push_str("\\r"),
13735                '\t' => self.out.push_str("\\t"),
13736                c if (c as u32) < 0x20 => {
13737                    self.out.push_str(&format!("\\u{:04x}", c as u32));
13738                }
13739                c => self.out.push(c),
13740            }
13741        }
13742        self.out.push('"');
13743    }
13744}
13745
13746/// How `print` renders a value.
13747///
13748/// `ToString`, except that negative zero keeps its sign — the reference's host
13749/// printer does that while `String(-0)` is `"0"`.
13750pub fn display(value: &Value) -> String {
13751    match value {
13752        Value::Float(number) => crate::value::number_to_string_for_print(*number),
13753        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
13754            "undefined".to_string()
13755        }
13756        other => other.to_js_string(),
13757    }
13758}
13759
13760// ---------------------------------------------------------------------------
13761// Numeric operators
13762// ---------------------------------------------------------------------------
13763
13764/// `a + b` keeping the `Int` representation when it fits.
13765fn add_numbers(left: Value, right: Value) -> Value {
13766    match (&left, &right) {
13767        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
13768            Some(sum) => Value::Int(sum),
13769            None => Value::Float(*a as f64 + *b as f64),
13770        },
13771        _ => Value::Float(left.to_number() + right.to_number()),
13772    }
13773}
13774
13775/// The arithmetic operators other than `+`, which needs string concatenation.
13776fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13777    use Opcode::*;
13778    // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
13779    // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
13780    // *before* the match, so even the arms that never needed `a` or `b` paid for it.
13781    if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
13782        return Ok(match op {
13783            And => Value::Int(x & y),
13784            Or => Value::Int(x | y),
13785            Xor => Value::Int(x ^ y),
13786            Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
13787            Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
13788            Shr => match (*x as u32) >> ((*y as u32) & 31) {
13789                shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
13790                shifted => Value::Float(shifted as f64),
13791            },
13792            Sub => match x.checked_sub(*y) {
13793                Some(value) => Value::Int(value),
13794                None => Value::Float(*x as f64 - *y as f64),
13795            },
13796            _ => return arithmetic_slow(op, left, right),
13797        });
13798    }
13799    arithmetic_slow(op, left, right)
13800}
13801
13802/// [`arithmetic`] for everything the integer fast path above does not take.
13803fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13804    use Opcode::*;
13805    let (a, b) = (left.to_number(), right.to_number());
13806    Ok(match op {
13807        Sub => match (&left, &right) {
13808            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
13809                Some(value) => Value::Int(value),
13810                None => Value::Float(a - b),
13811            },
13812            _ => Value::Float(a - b),
13813        },
13814        Mul => Value::Float(a * b),
13815        Div => Value::Float(a / b),
13816        Mod => Value::Float(js_mod(a, b)),
13817        Pow => Value::Float(a.powf(b)),
13818        And => Value::Int(left.to_int32() & right.to_int32()),
13819        Or => Value::Int(left.to_int32() | right.to_int32()),
13820        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
13821        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
13822        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
13823        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
13824        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
13825        // fits the small-integer representation stays an `Int`; the rest become a
13826        // float, which is how the reference keeps `n >>> 0` non-negative.
13827        Shr => {
13828            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
13829            match i32::try_from(shifted) {
13830                Ok(value) => Value::Int(value),
13831                Err(_) => Value::Float(shifted as f64),
13832            }
13833        }
13834        _ => Value::Float(a),
13835    })
13836}
13837
13838/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
13839///
13840/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
13841/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
13842/// slow path where the rules live.
13843fn is_number(value: &Value) -> bool {
13844    matches!(value, Value::Int(_) | Value::Float(_))
13845}
13846
13847/// The `Value::Bool` a comparison operator answers for `ordering`.
13848///
13849/// `None` is the unordered case — a `NaN` on either side — and every operator answers
13850/// false for it, including `<=` and `>=`.
13851fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
13852    use Opcode::*;
13853    let answer = match (op, ordering) {
13854        (_, None) => false,
13855        (Lt, Some(ordering)) => ordering.is_lt(),
13856        (Lte, Some(ordering)) => ordering.is_le(),
13857        (Gt, Some(ordering)) => ordering.is_gt(),
13858        (Gte, Some(ordering)) => ordering.is_ge(),
13859        _ => false,
13860    };
13861    Value::Bool(answer)
13862}
13863
13864/// `%`, which follows the sign of the dividend rather than Rust's.
13865fn js_mod(left: f64, right: f64) -> f64 {
13866    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
13867        return f64::NAN;
13868    }
13869    if right.is_infinite() {
13870        return left;
13871    }
13872    let remainder = left % right;
13873    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
13874    // the spec makes the sign match the dividend.
13875    if remainder == 0.0 {
13876        0.0f64.copysign(left)
13877    } else {
13878        remainder
13879    }
13880}
13881
13882fn negate(value: Value) -> Value {
13883    match value {
13884        Value::Int(0) => Value::Float(-0.0),
13885        Value::Int(i) => Value::Int(-i),
13886        other => Value::Float(-other.to_number()),
13887    }
13888}
13889
13890fn increment(value: Value) -> Value {
13891    match value {
13892        Value::Int(i) => match i.checked_add(1) {
13893            Some(next) => Value::Int(next),
13894            None => Value::Float(i as f64 + 1.0),
13895        },
13896        other => Value::Float(other.to_number() + 1.0),
13897    }
13898}
13899
13900fn decrement(value: Value) -> Value {
13901    match value {
13902        Value::Int(i) => match i.checked_sub(1) {
13903            Some(next) => Value::Int(next),
13904            None => Value::Float(i as f64 - 1.0),
13905        },
13906        other => Value::Float(other.to_number() - 1.0),
13907    }
13908}
13909
13910/// Compare a `BigInt` with an `f64` on their mathematical values.
13911///
13912/// Neither side is rounded to the other's precision: the number is split into its integer
13913/// part (compared as an exact bigint) and its fraction, which is what decides the answer
13914/// when the integer parts are equal. An infinite value is larger than every bigint.
13915fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
13916    use std::cmp::Ordering;
13917    if number.is_nan() {
13918        return None;
13919    }
13920    if number.is_infinite() {
13921        return Some(if number > 0.0 {
13922            Ordering::Less
13923        } else {
13924            Ordering::Greater
13925        });
13926    }
13927    let truncated = number.trunc();
13928    // A number wider than `i128` still has an exact integer part, but no bigint form we can
13929    // build cheaply; the sign of the difference is all that is needed, so compare against
13930    // the bigint's own magnitude instead.
13931    if truncated.abs() >= 1.7e38 {
13932        let big_as_f64 = big.to_f64();
13933        return big_as_f64.partial_cmp(&number);
13934    }
13935    let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
13936    match big.cmp(&integer) {
13937        Ordering::Equal => {
13938            // Same integer part: the fraction decides, and a negative number's fraction is
13939            // below the integer (`-1.5` truncates to `-1`).
13940            if number > truncated {
13941                Some(Ordering::Less)
13942            } else if number < truncated {
13943                Some(Ordering::Greater)
13944            } else {
13945                Some(Ordering::Equal)
13946            }
13947        }
13948        other => Some(other),
13949    }
13950}