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        // A typed array's indices are bytes in its buffer, so a descriptor for one has to
2833        // be synthesized too — and every one of them is a plain writable, enumerable,
2834        // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
2835        // `undefined` before this, which made `key-is-numericindex` fail on its own
2836        // side effect check.
2837        //
2838        // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
2839        // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
2840        // likewise not elements however numeric they look.
2841        if object.typed_array_element_type().is_some()
2842            && let Some(numeric) = canonical_numeric_index(key)
2843            && numeric.is_finite()
2844            && numeric.fract() == 0.0
2845            && !(numeric == 0.0 && numeric.is_sign_negative())
2846            && numeric >= 0.0
2847            && (numeric as usize) < object.typed_array_length().unwrap_or(0)
2848        {
2849            let value = object.typed_array_element(numeric as usize)?;
2850            return Some(Property::data(value));
2851        }
2852        // An array's elements live in their own vector rather than the property table, so
2853        // a descriptor for one has to be synthesized — with the attributes an element has.
2854        if let Some(index) = key.as_str().and_then(array_index)
2855            && let Some(value) = object.array_get(index as usize)
2856            && !matches!(value, Value::Hole)
2857        {
2858            return Some(Property::data(value));
2859        }
2860        // `length` is an own property of an array that is not in its property table
2861        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2862        // and non-enumerable.
2863        if key.as_str() == Some("length")
2864            && let Some(length) = object.array_length()
2865        {
2866            return Some(Property {
2867                value: Some(crate::object::length_value(length)),
2868                writable: object.length_writable(),
2869                enumerable: false,
2870                configurable: false,
2871                getter: None,
2872                setter: None,
2873            });
2874        }
2875        None
2876    }
2877
2878    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2879    pub fn object_get_own_property(
2880        &mut self,
2881        object: &Gc<JsObject>,
2882        key: &PropertyKey,
2883    ) -> JsResult<Option<Property>> {
2884        if let Some(answer) = self.proxy_get_own_property(object, key)? {
2885            return Ok(answer);
2886        }
2887        if let Some(exotic) = object.exotic()
2888            && let Some(answer) = exotic.get_own_property(self, object, key)?
2889        {
2890            return Ok(answer);
2891        }
2892        // A mapped `arguments` index is a data property as far as script can see: the
2893        // accessor pair that aliases the parameter is plumbing, and exposing it would
2894        // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
2895        // report a `get` where the spec has a `[[Value]]`.
2896        if let Some(index) = key.as_str().and_then(crate::object::array_index)
2897            && let Some(cell) = object.mapped_argument_cell(index as usize)
2898        {
2899            // Non-configurable is *not* the default: an ordinary mapped index is
2900            // configurable, and only becomes non-configurable once something
2901            // redefines it. Preserve whatever the property table currently says.
2902            // The attributes come from whatever the property table holds, because they
2903            // can be changed independently of the mapping; only the *value* and the
2904            // data-property *kind* are the accessor's secret.
2905            let flags = Self::ordinary_own_property(object, key);
2906            if let Some(existing) = &flags
2907                && !existing.is_accessor()
2908            {
2909                // Already demapped: the table entry is the answer, not the cell.
2910                return Ok(flags);
2911            }
2912            return Ok(Some(Property {
2913                value: Some(cell.get()),
2914                writable: true,
2915                enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
2916                configurable: flags.as_ref().is_some_and(|p| p.configurable),
2917                ..Property::default()
2918            }));
2919        }
2920        Ok(Self::ordinary_own_property(object, key))
2921    }
2922
2923    /// §7.3.40 `SetterThatIgnoresPrototypeProperties(thisValue, home, propertyKey, value)`.
2924    ///
2925    /// Written for `Error.prototype.stack`'s setter and the exact mechanism
2926    /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
2927    /// abstract operation here rather than a private helper in `error.rs`.
2928    ///
2929    /// The name is the whole point: the setter must behave as if the prototype were not
2930    /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
2931    /// the accessor for every error object in the realm. Everything below follows from that:
2932    ///
2933    /// 1. `thisValue` must be an object — otherwise `TypeError`.
2934    /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
2935    ///    accessor's own home an error rather than a self-shadow.
2936    /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
2937    ///    either has a string or has made a mistake.
2938    /// 4. An existing *own* property decides the path — an own setter is called, an own
2939    ///    non-writable data property is a `TypeError` — and only a missing own property
2940    ///    falls through to defining one.
2941    /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
2942    ///    traps and a non-extensible receiver is a `TypeError`.
2943    ///
2944    /// The installed shape is writable + configurable, not enumerable.
2945    pub fn setter_that_ignores_prototype_properties(
2946        &mut self,
2947        this_value: Value,
2948        home: &Gc<JsObject>,
2949        property_key: &str,
2950        args: &[Value],
2951    ) -> JsResult<Value> {
2952        let Some(receiver) = this_value.as_object().cloned() else {
2953            return Err(self.type_error("setter called on a non-object"));
2954        };
2955        if Gc::ptr_eq(&receiver, home) {
2956            return Err(self.type_error("cannot assign to the accessor's own home object"));
2957        }
2958        // No type check here: §7.3.40 takes an arbitrary `v`, and
2959        // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
2960        // insists on a String is `Error.prototype.stack`'s setter, which does its own check
2961        // before calling this.
2962        let value = args.first().cloned().unwrap_or(Value::Undefined);
2963        let key = PropertyKey::from(property_key);
2964        // Step 4: an own property on the receiver changes what happens, and there are three
2965        // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
2966        // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
2967        // `Set` with `throw = true`, and a test exists for each.
2968        if let Some(existing) = self.object_get_own_property(&receiver, &key)? {
2969            if existing.is_accessor() && existing.setter.is_none() {
2970                // A getter-only own accessor cannot be written through.
2971                return Err(self.type_error("no setter for the own property"));
2972            }
2973            // Everything else — an own data property, or an own accessor *with* a setter —
2974            // takes the `Set` path with `throw = true`. That is what routes a proxy's own
2975            // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
2976            // an own user setter receives the value (`setter-own-accessor`), because
2977            // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
2978            // setter directly is the difference between one code path and two that can
2979            // disagree.
2980            self.set_property(&receiver, property_key, value.clone())?;
2981            return Ok(Value::Undefined);
2982        }
2983        let property = Property {
2984            value: Some(value.clone()),
2985            writable: true,
2986            // Enumerable, despite the accessor it shadows not being. The reference installs
2987            // it that way and six cases check it (`setter-creates-own-property` and friends).
2988            enumerable: true,
2989            configurable: true,
2990            ..Property::default()
2991        };
2992        if !self.object_define_own_property(&receiver, &key, property)? {
2993            return Err(self.type_error("the receiver refused the definition"));
2994        }
2995        Ok(Value::Undefined)
2996    }
2997
2998    /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
2999    ///
3000    /// The indices of a typed array are not properties at all — they are bytes in the
3001    /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3002    /// fly. That makes their descriptor shape fixed: every valid index is writable,
3003    /// enumerable and configurable, so a definition can only ever change the *value*, and
3004    /// every other descriptor is refused rather than applied.
3005    ///
3006    /// The order of the checks is the spec's, and two of them are load-bearing:
3007    ///
3008    /// * the index is validated **before** the value is converted, because the conversion
3009    ///   itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3010    ///   detaches from a `valueOf` and still expects `true` with no store, which only
3011    ///   happens when the index was valid on the way in;
3012    /// * the store is attempted even when the index has gone out of bounds by the time the
3013    ///   conversion finishes, because the store is a silent no-op rather than a failure —
3014    ///   the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3015    ///   the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3016    ///
3017    /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3018    /// the existing element, which is harmless here: every valid index is already
3019    /// writable, enumerable and configurable, so a `false` in the merged property can only
3020    /// have come from the descriptor having named `false`.
3021    fn integer_indexed_define_own_property(
3022        &mut self,
3023        object: &Gc<JsObject>,
3024        numeric: f64,
3025        property: &Property,
3026    ) -> JsResult<bool> {
3027        // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3028        // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3029        if !typed_array_index_is_valid(object, numeric) {
3030            return Ok(false);
3031        }
3032        // Step 6: the indices are data properties, so an accessor descriptor is refused
3033        // rather than converted. `Object.defineProperty` turns the `false` into a
3034        // `TypeError`; `Reflect.defineProperty` reports it.
3035        if property.is_accessor() {
3036            return Ok(false);
3037        }
3038        // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3039        // definition that asks for anything else cannot be honoured.
3040        if !property.writable || !property.enumerable || !property.configurable {
3041            return Ok(false);
3042        }
3043        // Step 10: only a descriptor that names a value stores anything.
3044        let Some(value) = property.value.clone() else {
3045            return Ok(true);
3046        };
3047        let Some(element) = object.typed_array_element_type() else {
3048            return Ok(false);
3049        };
3050        let stored = self.element_value(element, value)?;
3051        if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3052            return Err(self.type_error(reason));
3053        }
3054        Ok(true)
3055    }
3056
3057    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3058    pub fn object_define_own_property(
3059        &mut self,
3060        object: &Gc<JsObject>,
3061        key: &PropertyKey,
3062        property: Property,
3063    ) -> JsResult<bool> {
3064        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3065            return Ok(accepted);
3066        }
3067        // A proxy always answers above — with `Some` from its trap, or with `None` when
3068        // the trap is absent, and then the definition belongs to the **target**
3069        // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3070        // when there is no trap). Falling through to the ordinary path here defined the
3071        // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3072        // property the target never saw.
3073        if object.proxy_state().is_some() {
3074            let Some((target, _handler)) = self.proxy_parts(object)? else {
3075                return Err(self.type_error("cannot use a proxy that has been revoked"));
3076            };
3077            return self.object_define_own_property(&target, key, property);
3078        }
3079        // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3080        // they accept exactly one descriptor shape. This has to happen before the
3081        // ordinary path, which would happily store a data property next to the buffer —
3082        // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3083        // and `TypedArray/prototype/set` are about this section.
3084        if object.typed_array_element_type().is_some()
3085            && let Some(index) = canonical_numeric_index(key)
3086        {
3087            return self.integer_indexed_define_own_property(object, index, &property);
3088        }
3089        // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3090        // non-extensible object. The check lives here rather than in the callers because
3091        // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3092        // `Array.prototype.filter` uses to store its result, and a species object made
3093        // non-extensible by its own constructor must make that a `TypeError`
3094        // (`target-array-non-extensible`).
3095        if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3096            return Ok(false);
3097        }
3098        // A host class that intercepts definitions owns the attributes of the properties it
3099        // defines: `_class`-style storage on the native side is the usual reason.
3100        if let Some(exotic) = object.exotic()
3101            && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3102        {
3103            return Ok(accepted);
3104        }
3105        // An array index is stored in the element vector, which can hold a plain value and
3106        // nothing else. An accessor — or a data property with non-default attributes —
3107        // therefore has to live in the property table, and the element slot is blanked so
3108        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3109        // {get})` stored the accessor where no read ever looked, and the array kept
3110        // answering its old value.
3111        // An array's `length` is not stored in the property table, so defining it has to
3112        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3113        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3114        // {value: 1})` reported success and changed nothing.
3115        if key.as_str() == Some("length") && object.is_array() {
3116            // `{writable: false}` on `length` does not change the length, but it does make
3117            // it read-only — after which neither a later `{writable: true}` nor a store
3118            // past the end may succeed.
3119            if property.value.is_none() {
3120                if !object.length_writable() && property.writable {
3121                    return Ok(false);
3122                }
3123                object.set_length_writable(property.writable);
3124                return Ok(true);
3125            }
3126            if !object.length_writable() {
3127                return Ok(false);
3128            }
3129        }
3130        if key.as_str() == Some("length")
3131            && object.is_array()
3132            && let Some(value) = property.value.clone()
3133        {
3134            let requested = value.to_number();
3135            let valid = requested.is_finite()
3136                && requested >= 0.0
3137                && requested.fract() == 0.0
3138                && requested <= u32::MAX as f64;
3139            if !valid {
3140                return Err(self.range_error("invalid array length"));
3141            }
3142            // Truncating deletes the elements above the new length, and a non-configurable
3143            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3144            // makes `a.length = 2` fail rather than quietly drop it.
3145            let current = object.array_length().unwrap_or(0);
3146            let requested = requested as usize;
3147            if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3148                return Ok(false);
3149            }
3150            object.array_set_length(self.heap, requested);
3151            return Ok(true);
3152        }
3153        let plain = property.writable
3154            && property.enumerable
3155            && property.configurable
3156            && !property.is_accessor();
3157        if let Some(index) = key.as_str().and_then(array_index)
3158            && object.is_array()
3159        {
3160            // Growing the array needs a writable `length`: after
3161            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3162            // be added.
3163            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3164                return Ok(false);
3165            }
3166            if plain && property.value.is_some() {
3167                // An ordinary element: the vector is where a read looks first, so it has
3168                // to be the vector that changes — unless the index is too far out to be
3169                // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3170                // one property, because past its own limit it stores the index as an
3171                // ordinary key. Falling through to `define_key` below is the same choice,
3172                // and the alternative was worse: the store used to be *dropped* and the
3173                // length left at 0, which is a silent wrong answer.
3174                let value = property.value.clone().unwrap_or(Value::Undefined);
3175                object.delete_key(key);
3176                if object.array_set(self.heap, index as usize, value) {
3177                    return Ok(true);
3178                }
3179                // Past the dense limit the element lives in the table like any property.
3180                object.note_element_descriptor();
3181                object.define_key(key, property);
3182                // A sparse store past the dense limit still extends `length`, which is what
3183                // `a[a.length] = v` relies on — but only extends: shortening would delete
3184                // the sparse properties above the index, including this one.
3185                if index as usize + 1 > object.array_length().unwrap_or(0) {
3186                    object.array_set_length(self.heap, index as usize + 1);
3187                }
3188                return Ok(true);
3189            }
3190            // A non-plain element — an accessor, or an attribute that is not the default —
3191            // lives in the table while the slot becomes a hole. Recording it keeps every
3192            // later `a[i] = v` off the dense path, where the write would have shadowed the
3193            // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3194            // replace the accessor with a plain data property.
3195            object.note_element_descriptor();
3196            object.define_key(key, property);
3197            // The slot stays, so `length` does not shrink; a hole is not an element, so
3198            // the table entry is now what a read finds.
3199            object.array_set(self.heap, index as usize, Value::Hole);
3200            return Ok(true);
3201        }
3202        object.define_key(key, property);
3203        Ok(true)
3204    }
3205
3206    /// Build a proxy object over `target`, with its traps read from `handler`.
3207    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3208        JsObject::proxy(self.heap, target, handler)
3209    }
3210
3211    /// The `revoke` function for a proxy's slots.
3212    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3213        JsObject::function(
3214            self.heap,
3215            Some(self.realm.function_proto.clone()),
3216            Callable::Revoker(slots),
3217        )
3218    }
3219
3220    /// A new array.
3221    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3222        let array = JsObject::array(
3223            self.heap,
3224            Some(self.realm.array_proto.clone()),
3225            elements.len(),
3226        );
3227        for (index, element) in elements.into_iter().enumerate() {
3228            array.array_set(self.heap, index, element);
3229        }
3230        array
3231    }
3232
3233    /// A new native function object.
3234    ///
3235    /// The observable `name` and `length` are installed as properties here, which is
3236    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3237    /// so `f.name = "x"` behaves like the writable property it is.
3238    /// A native constructor that builds its own instance after validating its arguments.
3239    ///
3240    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3241    /// check runs before `new.target.prototype` is read.
3242    pub fn new_native_ctor(
3243        &self,
3244        name: impl Into<String>,
3245        length: u32,
3246        func: NativeFn,
3247    ) -> Gc<JsObject> {
3248        let function = JsObject::function(
3249            self.heap,
3250            Some(self.realm.function_proto.clone()),
3251            Callable::Native {
3252                func,
3253                own_instance: true,
3254            },
3255        );
3256        function.set_constructible(true);
3257        function.define(
3258            "length",
3259            Property::name_or_length(Value::Int(length as i32)),
3260        );
3261        function.define("name", Property::name_or_length(self.string(name)));
3262        function
3263    }
3264
3265    /// A native constructor that lets `new` build the instance first.
3266    ///
3267    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3268    /// validation that must precede reading `new.target.prototype`, so the object can be
3269    /// created before the implementation runs. Distinct from [`Interp::new_native`],
3270    /// which makes a *method* and therefore not a constructor at all.
3271    pub fn new_native_constructor(
3272        &self,
3273        name: impl Into<String>,
3274        length: u32,
3275        func: NativeFn,
3276    ) -> Gc<JsObject> {
3277        let function = self.new_native(name, length, func);
3278        function.set_constructible(true);
3279        function
3280    }
3281
3282    /// A new host function object: a native closure that carries its own state.
3283    ///
3284    /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3285    /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3286    /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3287    /// this safe: the closure must not capture a `Gc`.
3288    pub fn new_host_function(
3289        &self,
3290        name: impl Into<String>,
3291        length: u32,
3292        func: crate::object::HostFn,
3293    ) -> Gc<JsObject> {
3294        self.new_host_inner(name.into(), length, func, false)
3295    }
3296
3297    /// A host constructor: `new` hands it `this = undefined`, so it validates its
3298    /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3299    pub fn new_host_ctor(
3300        &self,
3301        name: impl Into<String>,
3302        length: u32,
3303        func: crate::object::HostFn,
3304    ) -> Gc<JsObject> {
3305        let function = self.new_host_inner(name.into(), length, func, true);
3306        function.set_constructible(true);
3307        // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3308        // installs its own methods on it, so it starts as a plain object.
3309        let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3310        function.define(
3311            "prototype",
3312            Property {
3313                value: Some(Value::Object(proto)),
3314                writable: true,
3315                enumerable: false,
3316                configurable: false,
3317                ..Property::default()
3318            },
3319        );
3320        function
3321    }
3322
3323    fn new_host_inner(
3324        &self,
3325        name: String,
3326        length: u32,
3327        func: crate::object::HostFn,
3328        own_instance: bool,
3329    ) -> Gc<JsObject> {
3330        let function = JsObject::function(
3331            self.heap,
3332            Some(self.realm.function_proto.clone()),
3333            Callable::Host {
3334                func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3335                own_instance,
3336            },
3337        );
3338        function.define(
3339            "length",
3340            Property::name_or_length(Value::Int(length as i32)),
3341        );
3342        function.define("name", Property::name_or_length(self.string(name)));
3343        function
3344    }
3345
3346    /// A callable object with the `length`/`name` a built-in function has, in that order.
3347    ///
3348    /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3349    /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3350    /// [`JsObject::function`] defines neither, which is why every capability helper built
3351    /// with it reported no own `length` and no own `name` at all.
3352    ///
3353    /// The attributes are the spec's for a built-in: not writable, not enumerable,
3354    /// configurable.
3355    pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3356        let function =
3357            JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3358        function.define(
3359            "length",
3360            Property::name_or_length(Value::Int(length as i32)),
3361        );
3362        function.define("name", Property::name_or_length(self.string(name)));
3363        function
3364    }
3365
3366    /// A new native function object.
3367    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3368        let function = JsObject::function(
3369            self.heap,
3370            Some(self.realm.function_proto.clone()),
3371            Callable::Native {
3372                func,
3373                own_instance: false,
3374            },
3375        );
3376        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3377        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3378        // `length,name` and this listed `name,length`. A bytecode function already gets it
3379        // the right way round; only native ones were built backwards.
3380        function.define(
3381            "length",
3382            Property::name_or_length(Value::Int(length as i32)),
3383        );
3384        function.define("name", Property::name_or_length(self.string(name)));
3385        function
3386    }
3387
3388    /// A new bound function.
3389    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3390        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3391        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3392        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3393        let constructible = target
3394            .as_object()
3395            .is_some_and(|target| target.is_constructor());
3396        let bound = JsObject::function(
3397            self.heap,
3398            Some(self.realm.function_proto.clone()),
3399            Callable::Bound { target, this, args },
3400        );
3401        bound.set_constructible(constructible);
3402        bound
3403    }
3404
3405    /// A new reference cell.
3406    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3407        Gc::new(self.heap, Cell::new(value))
3408    }
3409
3410    // -- running ------------------------------------------------------------
3411
3412    /// Evaluate `code` as a script body and return its completion value.
3413    /// Compile and run `source` for the engine's own use, returning its completion value.
3414    ///
3415    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3416    /// needs to be a real async function, and the engine already runs those as coroutines,
3417    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3418    ///
3419    /// Differences from [`Self::eval_in_global`], both deliberate:
3420    ///
3421    /// * It does **not** drain the microtask queue. Install runs while the realm is still
3422    ///   being built, and the source is an IIFE that only constructs a closure, so there
3423    ///   is nothing to drain — and draining here would run script-queued jobs in the
3424    ///   middle of `install`.
3425    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3426    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3427    ///   and it should not look like the user wrote something wrong.
3428    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3429        let program = match js_parse::parse_script(source) {
3430            Ok(program) => program,
3431            Err(error) => {
3432                let message = format!("builtin source does not parse: {error}");
3433                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3434            }
3435        };
3436        let mut code = match js_compile::compile_script_with_source(&program, source) {
3437            Ok(code) => code,
3438            Err(error) => {
3439                let message = format!("builtin source does not compile: {}", error.message);
3440                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3441            }
3442        };
3443        // The frame has to name something, and `<builtin>` is what a stack trace through
3444        // this code should say.
3445        code.set_filename("<builtin>");
3446        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3447        let closure_vars = compiled.code.closure_vars.clone();
3448        let env = self.global_env(&closure_vars);
3449        let this = Value::Object(self.realm.global.clone());
3450        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3451    }
3452
3453    /// Run an already-parsed script and drain the microtasks it queued.
3454    ///
3455    /// The drain is what lets an `async` function's body advance past its first `await`
3456    /// before the host sees the result: nothing else pumps the job queue.
3457    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3458        let this = Value::Object(self.realm.global.clone());
3459        self.run_script_with_this(code, this)
3460    }
3461
3462    /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3463    ///
3464    /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3465    /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3466    /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3467    /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3468    /// state the next script evaluation tripped over.
3469    pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3470        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3471        let closure_vars = compiled.code.closure_vars.clone();
3472        let env = self.global_env(&closure_vars);
3473        let callee = Value::Undefined;
3474        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3475        // The script is done, so the microtasks it queued run before the host sees the
3476        // result. Without this an `async` function's body would never advance past its
3477        // first `await`, because nothing else drains the queue.
3478        self.drain_jobs()?;
3479        Ok(result)
3480    }
3481
3482    /// Compile and run `source` in global scope, returning its completion value.
3483    ///
3484    /// This is what `eval` and `new Function` use. Running it as a script means it
3485    /// sees the global object and nothing else, which is right for `eval("1+1")` and
3486    /// for a `Function` body; a *direct* eval that reads a local variable would need
3487    /// the compiler to hand its variable environment over, which is not implemented.
3488    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3489        self.eval_in_global_named(source, EVAL_FILE, false)
3490    }
3491
3492    /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3493    ///
3494    /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3495    /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3496    /// through the code, so they cannot share one constant.
3497    pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3498        self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3499    }
3500
3501    /// Evaluate `source` as a global script, reported under `file`.
3502    ///
3503    /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3504    /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3505    /// from inside a C callback, where the interpreter is the running one rather than a
3506    /// context's own.
3507    pub fn eval_in_global_named(
3508        &mut self,
3509        source: &str,
3510        file: &str,
3511        barrier: bool,
3512    ) -> JsResult<Value> {
3513        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3514        // eval-created global binding — configurable, unlike a script's own `var`.
3515        self.eval_depth += 1;
3516        if barrier {
3517            let depth = self.frames.len();
3518            self.trace_barriers.push(depth);
3519        }
3520        let result = self.eval_in_global_inner(source, file);
3521        if barrier {
3522            self.trace_barriers.pop();
3523        }
3524        self.eval_depth -= 1;
3525        result
3526    }
3527
3528    fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3529        let compiled = self.compile_global_script(source, file, false)?;
3530        let strict = compiled.strict;
3531        self.run_eval_script(compiled, strict)
3532    }
3533
3534    /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3535    ///
3536    /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3537    /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3538    /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3539    /// direct eval's is.
3540    pub fn eval_script_with_this(
3541        &mut self,
3542        source: &str,
3543        file: &str,
3544        this: Value,
3545    ) -> JsResult<Value> {
3546        let program = match js_parse::parse_script(source) {
3547            Ok(program) => program,
3548            Err(error) => {
3549                return Err(Signal::Throw(self.syntax_error_at(
3550                    file,
3551                    error.span.start.line,
3552                    error.span.start.column,
3553                    &error.message,
3554                )));
3555            }
3556        };
3557        let mut compiled = match js_compile::compile_script(&program) {
3558            Ok(compiled) => compiled,
3559            Err(error) => {
3560                return Err(Signal::Throw(self.syntax_error_at(
3561                    file,
3562                    error.span.start.line,
3563                    error.span.start.column,
3564                    &error.message,
3565                )));
3566            }
3567        };
3568        compiled.set_filename(file);
3569        self.run_script_with_this(compiled, this)
3570    }
3571
3572    /// Parse and compile `source` as a global script, without running it.
3573    ///
3574    /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3575    /// before a promise exists to reject — while still evaluating in the same eval context
3576    /// (direct-eval strictness, `new.target`, `super`).
3577    fn compile_global_script(
3578        &mut self,
3579        source: &str,
3580        file: &str,
3581        async_body: bool,
3582    ) -> JsResult<CompiledFunction> {
3583        // A *direct* eval inherits the strictness of the code that called it, which is
3584        // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3585        // implicit global. The caller's frame is the innermost one here, because a
3586        // native function does not push a frame of its own.
3587        let strict = self.current_strict();
3588        // `eval` runs in the caller's function context, so `new.target` is legal here
3589        // even though the source is a bare script — and so is `super.x` when the caller
3590        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3591        // caller's, which is what `special_object 4` already does.
3592        let context = js_parse::EvalContext {
3593            in_method: self.enclosing_home_object().is_some(),
3594            // `super()` belongs to a derived constructor, and an eval'd body is not a
3595            // constructor at all: the caller frame's `this` is already built.
3596            in_derived_constructor: false,
3597        };
3598        // A *global* eval is not a function body: `new.target` and `super` are out of
3599        // reach there. Its `{async: true}` form differs in the other direction — the body
3600        // may `await` — so the two flags are independent and the reference sets both from
3601        // the eval type rather than from the caller.
3602        let parsed = if async_body {
3603            js_parse::parse_suspensible_global_eval(source, strict)
3604        } else {
3605            js_parse::parse_eval_script_in(source, strict, context)
3606        };
3607        let program = match parsed {
3608            Ok(program) => program,
3609            Err(error) => {
3610                // The message is bare: the position lives in `fileName`,
3611                // `lineNumber`, `columnNumber` and the stack frame above, which is where
3612                // the reference puts it. An `invalid source: L:C: ` prefix made
3613                // `e.message` differ from the reference while the stack already agreed.
3614                return Err(Signal::Throw(self.syntax_error_at(
3615                    file,
3616                    error.span.start.line,
3617                    error.span.start.column,
3618                    &error.message,
3619                )));
3620            }
3621        };
3622        let mut compiled = match if async_body {
3623            js_compile::compile_script_suspensible(&program)
3624        } else {
3625            js_compile::compile_script(&program)
3626        } {
3627            Ok(compiled) => compiled,
3628            // A construct the compiler does not handle yet is reported the same way a
3629            // parse error is: it happens before anything runs, so the trace is the
3630            // position in the source followed by the caller.
3631            Err(error) => {
3632                return Err(Signal::Throw(self.syntax_error_at(
3633                    file,
3634                    error.span.start.line,
3635                    error.span.start.column,
3636                    &error.message,
3637                )));
3638            }
3639        };
3640        compiled.set_filename(file);
3641        Ok(compiled)
3642    }
3643
3644    /// Run an `eval`'d script in the caller's scope.
3645    ///
3646    /// Three things have to come from the calling frame, because the eval'd code is a
3647    /// script and would otherwise see only the global object:
3648    ///
3649    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3650    /// * `arguments`, exposed as a binding of the eval's own scope, so
3651    ///   `f("arguments.length", 1)` sees the caller's arguments;
3652    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3653    ///   `eval("var v = 1")` into the global object.
3654    ///
3655    /// Locals of the calling function are *not* reachable: that needs the compiler to
3656    /// hand its variable environment over, which this milestone does not do.
3657    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3658        // `this` and `arguments` come from the innermost frame only — those are not
3659        // lexical — while the name bindings come from the whole chain of frames, part
3660        // of it being ordinary scope resolution.
3661        // An arrow has no `this` of its own, so an `eval` inside one inherits the
3662        // enclosing function's receiver — the lexical `this` the arrow was compiled to
3663        // read from its closure.
3664        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3665        // variable environment is the innermost frame of all: an arrow's own body is where
3666        // `var`s declared by an `eval` inside it belong.
3667        let caller_index = self
3668            .frames
3669            .iter()
3670            .rposition(|frame| !frame.code.code.is_arrow)
3671            .or_else(|| self.frames.len().checked_sub(1));
3672        let env_index = self.frames.len().checked_sub(1);
3673        let caller = caller_index.and_then(|index| self.frames.get(index));
3674        let (this, passed) = match caller {
3675            Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3676            // No frame at all: the eval is running at the top level, so there is
3677            // nothing to inherit and the global receiver is right.
3678            None => (Value::Object(self.realm.global.clone()), Vec::new()),
3679        };
3680        // Innermost frame first, so the first binding found for a name is the one that
3681        // shadows the rest. A script frame (`<eval>`) contributes nothing.
3682        let mut bindings: Vec<EvalBinding> = Vec::new();
3683        // The calling function's own bindings, resolved by the compiler at the call
3684        // site. That table is the only reliable answer when a name is declared twice in
3685        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3686        // body means, and guessing by declaration order picks the wrong one as soon as
3687        // two loops in a row use the same name.
3688        // Only a *direct* eval sees the caller's scope. The compiler records a site for
3689        // every direct call — a bare `eval(...)` callee — so finding one at the current
3690        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3691        // callee to a value first and leave no site behind.
3692        let mut direct = false;
3693        let mut resolved_here = false;
3694        if let Some(frame) = self.frames.last() {
3695            let (line, column) = frame
3696                .code
3697                .code
3698                .position_at(frame.at as u32)
3699                .unwrap_or_default();
3700            // The nearest site at or before the current position, not an exact match:
3701            // the recorded position of the `call` instruction is the callee's, which
3702            // sits a few columns inside the call expression the compiler recorded. A
3703            // site is unique per call, so "the closest one behind us" identifies it.
3704            if let Some(site) = frame
3705                .code
3706                .code
3707                .eval_sites
3708                .iter()
3709                .filter(|site| (site.line, site.column) <= (line, column))
3710                .max_by_key(|site| (site.line, site.column))
3711            {
3712                direct = true;
3713                resolved_here = true;
3714                for binding in &site.bindings {
3715                    // An enclosing function's frame sits `owner` levels below the one
3716                    // running the call.
3717                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3718                    else {
3719                        continue;
3720                    };
3721                    bindings.push(EvalBinding {
3722                        name: binding.name.clone(),
3723                        frame,
3724                        slot: if binding.is_arg {
3725                            EvalSlot::Arg
3726                        } else {
3727                            EvalSlot::Local
3728                        },
3729                        index: binding.index as usize,
3730                    });
3731                }
3732            }
3733        }
3734        for frame_index in (0..self.frames.len()).rev() {
3735            // Skip the innermost frame's flat scan when the compiler already answered
3736            // for it; an enclosing frame still needs one, because the eval resolves
3737            // those names dynamically.
3738            if resolved_here && frame_index == self.frames.len() - 1 {
3739                continue;
3740            }
3741            let frame = &self.frames[frame_index];
3742            for (index, arg) in frame.code.code.args.iter().enumerate() {
3743                bindings.push(EvalBinding {
3744                    name: arg.name.clone(),
3745                    frame: frame_index,
3746                    slot: EvalSlot::Arg,
3747                    index,
3748                });
3749            }
3750            for (index, local) in frame.code.code.vars.iter().enumerate() {
3751                bindings.push(EvalBinding {
3752                    name: local.name.clone(),
3753                    frame: frame_index,
3754                    slot: EvalSlot::Local,
3755                    index,
3756                });
3757            }
3758        }
3759        let mut seen = BTreeSet::new();
3760        bindings.retain(|binding| seen.insert(binding.name.clone()));
3761
3762        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
3763        // elements is all the spec's ordinary uses need.
3764        //
3765        // Known divergence: this is bound for a *global* eval too, where there is no
3766        // caller and the reference throws `'arguments' is not defined`. Deciding properly
3767        // needs "does the calling frame have an `arguments` of its own", which is not
3768        // recorded anywhere the runtime can see — the caller of a direct eval has one, a
3769        // script or eval body does not, and `eval(b)` passes the callee as a value so even
3770        // the call-site detection does not answer it. Modelled as a binding in the caller's
3771        // variable environment, this would fall out; that is a larger change than the one
3772        // this comment is attached to.
3773        let arguments = Value::Object(self.new_array(passed));
3774
3775        // Only a *strict* eval gets a variable environment of its own. A sloppy one
3776        // declares its `var`s in the caller's — which for a top-level eval is the global
3777        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
3778        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
3779        // vanish into a scope nobody reads back from.
3780        let previous_scope = if code_strict {
3781            self.eval_scope.replace(BTreeMap::new())
3782        } else {
3783            None
3784        };
3785        let previous_arguments = self.eval_arguments.replace(arguments);
3786        let previous_with = self.eval_with.replace(self.with_objects());
3787        let inherited_new_target = self
3788            .frames
3789            .iter()
3790            .rev()
3791            .find(|frame| !frame.code.code.is_arrow)
3792            .map(|frame| frame.new_target.clone());
3793        let previous_new_target = self
3794            .eval_new_target
3795            .replace(inherited_new_target.unwrap_or(Value::Undefined));
3796        let eval_cells = self.eval_cells_for(&bindings);
3797        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
3798        // A sloppy direct eval declares its `var`s in the caller's variable environment;
3799        // `declare_eval_local` needs to know which frame that is.
3800        // An indirect eval gets the global environment, so nothing of the caller's is
3801        // recorded as the place its `var`s belong.
3802        let previous_caller = self
3803            .eval_caller
3804            .replace(if direct { env_index } else { None });
3805        // The cell-based view of the same bindings, which is what a closure created
3806        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3807        // whose compiler did not put a binding in a cell simply does not appear here —
3808        // reads and writes still work through `eval_bindings`, they just cannot outlive
3809        // the eval.
3810        let previous_eval_scope = self
3811            .active_eval_scope
3812            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3813        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3814        let closure_vars = compiled.code.closure_vars.clone();
3815        let env = self.global_env(&closure_vars);
3816        let callee = Value::Undefined;
3817        // An async body does not run here: it becomes a coroutine and answers a promise,
3818        // which is what makes `await` legal in it. `this` still has to be the caller's
3819        // (for a global eval, the global object), because `this` is not part of `await`.
3820        let result = if compiled.code.kind.is_async() {
3821            self.run_async_body(compiled, env, this)
3822        } else {
3823            self.execute(compiled, env, this, Vec::new(), callee)
3824        };
3825        self.eval_scope = previous_scope;
3826        self.eval_arguments = previous_arguments;
3827        self.eval_with = previous_with;
3828        self.eval_new_target = previous_new_target;
3829        self.eval_bindings = previous_bindings;
3830        self.eval_caller = previous_caller;
3831        self.active_eval_scope = previous_eval_scope;
3832        result
3833    }
3834
3835    /// The cell-backed subset of `bindings`, in the same priority order.
3836    ///
3837    /// Both lookup routes have to agree — the eval's own reads go through
3838    /// [`Interp::eval_binding_value`] and the closures it builds go through
3839    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
3840    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
3841    /// is not in a cell simply does not appear: reads and writes still work, they just
3842    /// cannot be handed to a closure that outlives the eval.
3843    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
3844        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
3845        for binding in bindings {
3846            let Some(frame) = self.frames.get(binding.frame) else {
3847                continue;
3848            };
3849            let cell = match binding.slot {
3850                EvalSlot::Arg => frame
3851                    .code
3852                    .arg_cell
3853                    .get(binding.index)
3854                    .copied()
3855                    .unwrap_or(-1),
3856                EvalSlot::Local => frame
3857                    .code
3858                    .loc_cell
3859                    .get(binding.index)
3860                    .copied()
3861                    .unwrap_or(-1),
3862            };
3863            if cell < 0 {
3864                continue;
3865            }
3866            if let Some(cell) = frame.cells.get(cell as usize) {
3867                names.push((binding.name.clone(), cell.clone()));
3868            }
3869        }
3870        names
3871    }
3872
3873    /// A `SyntaxError` that reports where in the source it happened.
3874    ///
3875    /// Compile-time failures never run, so they have no frame of their own; the
3876    /// reference still puts the position first in the trace, with no function name and
3877    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
3878    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
3879    /// reference borrows), which is how a script reads the position without parsing
3880    /// the trace.
3881    /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
3882    ///
3883    /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
3884    /// `columnNumber`, which is how the reference prints one. A positionless error
3885    /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
3886    /// the reference raises it from `js_resolve_module`, where there is no position.
3887    pub(crate) fn syntax_error_plain(
3888        &mut self,
3889        error: &js_parse::SyntaxError,
3890        file: &str,
3891    ) -> Value {
3892        if error.positionless {
3893            return self.make_error("SyntaxError", &error.message);
3894        }
3895        self.syntax_error_at(
3896            file,
3897            error.span.start.line,
3898            error.span.start.column,
3899            &error.message,
3900        )
3901    }
3902
3903    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
3904        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
3905        let value = self.make_error("SyntaxError", message);
3906        if let Value::Object(object) = &value {
3907            let text = self.string(blamed);
3908            // `stack` is an own data property, and the reference keeps it
3909            // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
3910            object.define("stack", Property::with_attributes(text, true, false));
3911            let name = self.string(file);
3912            object.define("fileName", Property::with_attributes(name, true, true));
3913            object.define(
3914                "lineNumber",
3915                Property::with_attributes(Value::Int(line as i32), true, true),
3916            );
3917            object.define(
3918                "columnNumber",
3919                Property::with_attributes(Value::Int(column as i32), true, true),
3920            );
3921        }
3922        value
3923    }
3924
3925    /// Run a compiled script whose completion value is a function, returning it.
3926    ///
3927    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
3928    /// get the closure out, which keeps the constant-pool plumbing in one place.
3929    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
3930        self.run_script(code)
3931    }
3932
3933    /// The environment of a script or of any function compiled at global scope:
3934    /// every entry is a global binding, so each one resolves to the realm's cell.
3935    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
3936        let mut cells = Vec::with_capacity(closure_vars.len());
3937        for closure_var in closure_vars {
3938            let cell = match closure_var.closure_type {
3939                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
3940                    if closure_var.is_lexical =>
3941                {
3942                    // A lexical declaration: the cell is created here holding the
3943                    // dead-zone marker, which is what makes the binding exist and
3944                    // unreadable before its initialiser runs.
3945                    self.declare_global(&closure_var.name, closure_var.is_const);
3946                    self.realm.globals[&closure_var.name].clone()
3947                }
3948                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
3949                    // A `var` or function declaration becomes a property of the global
3950                    // object, and it exists from here on — which is why
3951                    // `print(v); var v = 1` prints `undefined` instead of raising.
3952                    // Declaring it at instantiation time (rather than at the
3953                    // initialiser) is also what makes it non-configurable: the store
3954                    // then lands on an existing property instead of creating one.
3955                    self.declare_var_global(&closure_var.name);
3956                    // The cell is a placeholder that nothing indexes; it cannot be
3957                    // omitted because the slot has to hold something.
3958                    self.new_cell(Value::Undefined)
3959                }
3960                _ => {
3961                    // An undeclared global is read by name; the cell is a
3962                    // placeholder that nothing indexes.
3963                    self.new_cell(Value::Undefined)
3964                }
3965            };
3966            cells.push(cell);
3967        }
3968        Gc::new(
3969            self.heap,
3970            ClosureEnv {
3971                cells,
3972                eval_scope: None,
3973                local_vars: None,
3974                local_phase: 1,
3975            },
3976        )
3977    }
3978
3979    /// Push a frame and run until it returns.
3980    pub(crate) fn execute(
3981        &mut self,
3982        code: Gc<CompiledCode>,
3983        env: Gc<ClosureEnv>,
3984        this: Value,
3985        args: Vec<Value>,
3986        callee: Value,
3987    ) -> JsResult<Value> {
3988        let depth = self.frames.len();
3989        if depth == 0 {
3990            // A throw that reached the host ends the *active* mode: the next one is catchable
3991            // again. The standing request (`uncatchable_next`) is deliberately untouched — a
3992            // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
3993            // for the throw that evaluation will raise.
3994            self.uncatchable = false;
3995        }
3996        self.push_frame(code, env, this, args, callee)?;
3997        loop {
3998            // The fast loop first: it runs whole runs of records with `pc` in a register.
3999            //
4000            // `step`'s `pc` lives in the frame, so every instruction writes it back and
4001            // reads it again — a store, a load and two bounds checks that a loop body does
4002            // not need, because nothing outside the loop can run in between. This is the
4003            // classic split: advance a register, and only spill it when leaving.
4004            //
4005            // `Some(value)` means the function ended by running off the end of its
4006            // instruction array, which is a normal return.
4007            let step = match self.run_fast() {
4008                Ok(Some(value)) => Ok(Step::Return(value)),
4009                Ok(None) => self.step(),
4010                Err(signal) => Err(signal),
4011            };
4012            match step {
4013                Ok(Step::Continue) => {}
4014                Ok(Step::Return(value)) => {
4015                    self.pop_frame();
4016                    // A frame that ended in a `tail_call` hands its value straight to
4017                    // its caller: nothing after the call can run, so every frame above
4018                    // the callee unwinds with the same value. See [`Frame::tail`] —
4019                    // the reference does not reuse frames either, so recursion depth
4020                    // and the stack-overflow limit behave the same way.
4021                    while self.frames.len() > depth && self.frame().tail {
4022                        self.pop_frame();
4023                    }
4024                    if self.frames.len() == depth {
4025                        return Ok(value);
4026                    }
4027                    // The caller resumes with the value on its stack.
4028                    self.frames
4029                        .last_mut()
4030                        .expect("a caller is live")
4031                        .stack
4032                        .push(value);
4033                }
4034                Err(Signal::Throw(value)) => {
4035                    // The host's standing request becomes the active mode for this unwind,
4036                    // and is consumed here so it does not leak into the next throw.
4037                    if self.uncatchable_next {
4038                        self.uncatchable_next = false;
4039                        self.uncatchable = true;
4040                    }
4041                    // An uncatchable throw walks past every `catch` on the way out. The
4042                    // frames are still popped, because the values they hold have to be
4043                    // dropped — only the search for a handler is skipped.
4044                    if self.uncatchable {
4045                        while self.frames.len() > depth {
4046                            self.frames.pop();
4047                        }
4048                        return Err(Signal::Throw(value));
4049                    }
4050                    // A handler lives on the stack of the frame that is throwing —
4051                    // `catch` pushed it there — so this frame gets the first chance
4052                    // to catch before it is popped.
4053                    let value = value;
4054                    loop {
4055                        if self.frames.len() <= depth {
4056                            return Err(Signal::Throw(value));
4057                        }
4058                        if self.catch_here(value.clone()).is_some() {
4059                            break;
4060                        }
4061                        self.frames.pop();
4062                    }
4063                }
4064                // A `yield` in a frame that `execute` is running directly means a
4065                // generator body was entered as an ordinary call, which only happens if
4066                // the generator check in `call_or_push` was bypassed.
4067                Ok(Step::Suspend(_)) => {
4068                    return Err(Signal::Throw(self.make_error(
4069                        "InternalError",
4070                        "a generator body ran as an ordinary call",
4071                    )));
4072                }
4073                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4074            }
4075        }
4076    }
4077
4078    /// Install a handler for `value` if this frame has one, resuming at it.
4079    ///
4080    /// The scan is the reference's: walk the frame's stack downwards looking for the
4081    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
4082    /// `0` is an enumerator marker rather than a handler — it exists so that a
4083    /// `break` out of a `for-of` can find and close the iterator — so it is skipped
4084    /// here and the unwinding continues.
4085    fn catch_here(&mut self, value: Value) -> Option<()> {
4086        let frame = self.frames.last_mut()?;
4087        while let Some(top) = frame.stack.pop() {
4088            if let Value::CatchOffset(offset) = top {
4089                if offset == 0 {
4090                    continue;
4091                }
4092                frame.stack.push(value);
4093                frame.pc = offset as usize;
4094                return Some(());
4095            }
4096        }
4097        None
4098    }
4099
4100    fn push_frame(
4101        &mut self,
4102        code: Gc<CompiledCode>,
4103        env: Gc<ClosureEnv>,
4104        this: Value,
4105        mut args: Vec<Value>,
4106        callee: Value,
4107    ) -> JsResult<()> {
4108        // Two bounds, and the byte budget is the one that decides in practice. The
4109        // reference's message is `stack overflow` on an `InternalError`, not V8's
4110        // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4111        // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4112        let frame_cost = Self::frame_cost(&code);
4113        let stack_base = self.stack_used();
4114        if self.frames.len() >= self.max_frames
4115            || stack_base.saturating_add(frame_cost) > self.stack_limit
4116        {
4117            return Err(Signal::Throw(
4118                self.make_error("InternalError", "stack overflow"),
4119            ));
4120        }
4121        let arg_count = code.code.args.len();
4122        // How many were actually passed, which `arguments.length` reports and
4123        // `assert(x)` depends on: a call with one argument must not look like a call
4124        // with one argument and an explicit `undefined`.
4125        let passed = args.len();
4126        // Missing arguments are `undefined` in their slots; extra ones are dropped
4127        // from the slots but still reachable through `arguments`.
4128        //
4129        // A call that passes no more than the declared parameters needs **no** copy:
4130        // after the resize below, `args[..passed]` *is* the passed values. Only the
4131        // extra ones — which `truncate` is about to drop — have to be kept, and they are
4132        // the rare case. This used to copy every call: one `Value` clone per argument
4133        // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4134        let passed_overflow = (passed > arg_count).then(|| {
4135            let mut values = self.take_values(passed, Value::Undefined);
4136            values[..passed].clone_from_slice(&args[..passed]);
4137            values
4138        });
4139        // Only when the counts differ, which for the overwhelmingly common call — as many
4140        // arguments as parameters — is never. `resize` followed by `truncate` on equal
4141        // lengths is two length compares and nothing else, but this is the hottest few
4142        // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4143        if passed != arg_count {
4144            args.resize(arg_count, Value::Undefined);
4145            args.truncate(arg_count);
4146        }
4147        let cell_count = code.code.var_ref_count as usize;
4148        let mut cells = Vec::with_capacity(cell_count);
4149        for _ in 0..cell_count {
4150            cells.push(self.new_cell(Value::Undefined));
4151        }
4152        let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4153        // A captured argument lives in its cell, not in the argument slot, so the
4154        // incoming value has to be moved there before the body runs.
4155        for (slot, cell) in code.arg_cell.iter().enumerate() {
4156            if *cell >= 0
4157                && let Some(value) = args.get(slot).cloned()
4158            {
4159                cells[*cell as usize].set(value);
4160            }
4161        }
4162        // Sloppy mode substitutes the global object for a missing receiver and boxes a
4163        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4164        // reports `object`. Strict mode passes the value through untouched.
4165        let this = if code.code.strict {
4166            this
4167        } else if this.is_nullish() {
4168            Value::Object(self.realm.global.clone())
4169        } else if matches!(this, Value::Object(_)) {
4170            this
4171        } else {
4172            match crate::builtins::this_object(self, &this) {
4173                Ok(boxed) => Value::Object(boxed),
4174                Err(_) => this,
4175            }
4176        };
4177        let stack_depth = code.code.stack_size as usize + 1;
4178        // Taken before the `push` borrows `self.frames`, because the operand stack comes
4179        // out of the same recycle pool the locals did.
4180        let stack = self.take_values(stack_depth, Value::Undefined);
4181        self.frames.push(Frame {
4182            code,
4183            env,
4184            this,
4185            args,
4186            passed_count: passed,
4187            passed_overflow: passed_overflow.map(Box::new),
4188            locals,
4189            cells,
4190            local_vars: None,
4191            // Exactly the depth the compiler computed, so the operand stack never
4192            // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4193            // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4194            // the buffer between calls, so "exactly" costs nothing after the first one.
4195            stack,
4196            pc: 0,
4197            at: 0,
4198            callee,
4199            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4200            cost: frame_cost,
4201            stack_base,
4202            tail: false,
4203        });
4204        Ok(())
4205    }
4206
4207    /// A value buffer of `len` slots, from the recycle pool when there is one.
4208    ///
4209    /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4210    fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4211        // A frame with no locals asks for nothing, and that is most frames: taking a
4212        // buffer out of the pool, clearing it and resizing it to zero is four operations
4213        // and a pool pop for an empty `Vec`, which is free to construct.
4214        if len == 0 {
4215            return Vec::new();
4216        }
4217        let mut buffer = self.free_values.pop().unwrap_or_default();
4218        buffer.clear();
4219        buffer.resize(len, fill);
4220        buffer
4221    }
4222
4223    /// Return a finished frame's value buffers for the next call to reuse.
4224    fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4225        for mut buffer in [
4226            std::mem::take(&mut frame.locals),
4227            frame
4228                .passed_overflow
4229                .take()
4230                .map(|buffer| *buffer)
4231                .unwrap_or_default(),
4232            std::mem::take(&mut frame.stack),
4233        ] {
4234            // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4235            // GC root: it kept every value the frame held reachable, which is invisible
4236            // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4237            // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4238            // exactly that within one run — the target `{}` of a finished IIFE was still
4239            // in its operand stack, in the pool.
4240            buffer.clear();
4241            // A buffer with no capacity is what `Vec::new` is; putting it back would just
4242            // fill the pool with nothing to offer.
4243            if free_values.len() < RECYCLE_SLOTS
4244                && buffer.capacity() > 0
4245                && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4246            {
4247                free_values.push(buffer);
4248            }
4249        }
4250    }
4251
4252    /// Pop a finished frame and keep its buffers.
4253    ///
4254    /// Every place that drops a frame goes through here: a recycled buffer is also where
4255    /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4256    /// nothing but the reuse.
4257    fn pop_frame(&mut self) -> Option<()> {
4258        // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4259        // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4260        let last = self.frames.len().checked_sub(1)?;
4261        Self::recycle(&mut self.free_values, &mut self.frames[last]);
4262        self.frames.truncate(last);
4263        Some(())
4264    }
4265
4266    /// Poll the host's interrupt handler, if one is installed.
4267    ///
4268    /// The counter is what keeps this off the hot path when nobody asked: the early return is
4269    /// one `Option` test, and with no handler installed the whole function is that test —
4270    /// `check_memory` next door already costs more, so this cannot be what shows up in a
4271    /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4272    #[inline]
4273    fn check_interrupt(&mut self) -> JsResult<()> {
4274        if self.interrupt.is_none() {
4275            return Ok(());
4276        }
4277        if self.interrupt_counter > 0 {
4278            self.interrupt_counter -= 1;
4279            return Ok(());
4280        }
4281        self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4282        // The closure is taken out for the duration so that a handler which re-enters the
4283        // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4284        let mut handler = self.interrupt.take().expect("checked above");
4285        let abort = handler();
4286        self.interrupt = Some(handler);
4287        if abort {
4288            // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4289            // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4290            // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4291            // documentation says.
4292            self.uncatchable = true;
4293            return Err(Signal::Throw(
4294                self.make_error("InternalError", "interrupted"),
4295            ));
4296        }
4297        Ok(())
4298    }
4299
4300    /// A memory checkpoint: does the heap still fit under its limit?
4301    ///
4302    /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4303    /// a `Cell` read and a predictable branch, and the point of asking that often is that
4304    /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4305    /// only at calls would let it run until the machine died, which is the exact failure
4306    /// `--memory-limit` exists to prevent.
4307    ///
4308    /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4309    /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4310    /// script that catches it, drops the reference and carries on is legitimate: measured
4311    /// on `qjs --memory-limit 1M`, the engine recovers.
4312    fn check_memory(&mut self) -> JsResult<()> {
4313        // One `Cell` read and a predictable branch when no limit is set, and an integer
4314        // compare when one is. Containers report their own growth as it happens
4315        // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4316        // walking it here was the first version and it was O(live) per 256 instructions,
4317        // which turned a 100k-element push loop into a five-minute one.
4318        let Some(limit) = self.heap.memory_limit() else {
4319            return Ok(());
4320        };
4321        let used = self.heap.used_bytes();
4322        if used <= limit {
4323            // Back under the limit — a collection or a dropped reference did it. The next
4324            // time it goes over is a new failure, not a repeat of this one.
4325            self.oom_reported_at = 0;
4326            return Ok(());
4327        }
4328        // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4329        // block runs normally after `out of memory` — it allocates nothing, so nothing
4330        // fails. A check that re-fired on every instruction made the handler itself throw,
4331        // which is a dead end: the error became unobservable from script.
4332        //
4333        // Comparing against the total at the last report gives the same behaviour: the
4334        // handler runs while the total is unchanged, and the very next allocation over the
4335        // limit fails.
4336        if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4337        {
4338            return Ok(());
4339        }
4340        self.oom_reported_at = used;
4341        Err(Signal::Throw(
4342            self.make_error("InternalError", "out of memory"),
4343        ))
4344    }
4345
4346    /// Fail before allocating `payload` bytes, if they would not fit.
4347    ///
4348    /// For the allocations whose size comes from script data — `new Array(n)`,
4349    /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4350    /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4351    /// answering NULL for the one big request.
4352    pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4353        if self.heap.fits(payload) {
4354            return Ok(());
4355        }
4356        Err(Signal::Throw(
4357            self.make_error("InternalError", "out of memory"),
4358        ))
4359    }
4360
4361    /// Bytes of frame state the live call chain accounts for.
4362    pub fn stack_used(&self) -> usize {
4363        match self.frames.last() {
4364            Some(frame) => frame.stack_base + frame.cost,
4365            None => 0,
4366        }
4367    }
4368
4369    /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4370    ///
4371    /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4372    /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4373    /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4374    /// instead. That is the whole difference between the two models: it rations C stack, we
4375    /// ration frame state, and both quantities are dominated by the value slots — which is
4376    /// why the two depths come out comparable rather than merely proportional.
4377    fn frame_cost(code: &CompiledCode) -> usize {
4378        let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4379        std::mem::size_of::<Frame>()
4380            + std::mem::size_of::<Value>() * slots
4381            + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4382    }
4383
4384    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4385    ///
4386    /// Only names the eval created are here: a name the frame already declared statically
4387    /// is written through to its own slot instead, so this cannot shadow a real local.
4388    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4389        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4390        let (local_vars, phase) = self.visible_local_vars()?;
4391        if !local_vars.contains(name) {
4392            return None;
4393        }
4394        local_vars.get(name, phase)
4395    }
4396
4397    /// The variables a direct `eval` declared, as the code currently running sees them.
4398    ///
4399    /// Inside an eval that is the *caller's* set — the eval's own variable environment
4400    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4401    /// else it is the current frame's, falling back to the frame the closure was created
4402    /// in.
4403    /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4404    ///
4405    /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4406    /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4407    /// refcount operations (the clone out of the frame, the drop at the end of the match)
4408    /// just to be asked `is_none`.
4409    fn has_visible_local_vars(&self) -> bool {
4410        let index = match self.eval_caller.flatten() {
4411            Some(caller) => caller,
4412            None => match self.frames.len().checked_sub(1) {
4413                Some(top) => top,
4414                None => return false,
4415            },
4416        };
4417        match self.frames.get(index) {
4418            Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4419            None => false,
4420        }
4421    }
4422
4423    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4424        // While an `eval` runs, its own frame is on top but its variable environment is
4425        // the *caller's* — so the caller is what the lookup has to start from.
4426        let (index, phase) = match self.eval_caller.flatten() {
4427            Some(caller) => (
4428                caller,
4429                if self.in_parameter_list_at(caller) {
4430                    0
4431                } else {
4432                    1
4433                },
4434            ),
4435            None => (
4436                self.frames.len().checked_sub(1)?,
4437                if self.in_parameter_list() { 0 } else { 1 },
4438            ),
4439        };
4440        let frame = self.frames.get(index)?;
4441        // The frame's own variables, or — for an arrow, which has no variable environment
4442        // of its own — the one it was created in, which `ClosureEnv` carries.
4443        if let Some(local_vars) = frame.local_vars.clone() {
4444            return Some((local_vars, phase));
4445        }
4446        frame
4447            .env
4448            .local_vars
4449            .clone()
4450            .map(|local_vars| (local_vars, frame.env.local_phase))
4451    }
4452
4453    /// Whether the innermost frame is still evaluating its parameter list.
4454    ///
4455    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4456    /// and a closure created there may only see that much of [`LocalVars`].
4457    fn in_parameter_list(&self) -> bool {
4458        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4459    }
4460
4461    /// [`Interp::in_parameter_list`] for a specific frame.
4462    fn in_parameter_list_at(&self, frame: usize) -> bool {
4463        let Some(frame) = self.frames.get(frame) else {
4464            return false;
4465        };
4466        let code = &frame.code.code;
4467        if !code.has_parameter_expressions {
4468            return false;
4469        }
4470        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4471        // function as its body and let a direct `eval` act accordingly.
4472        if code.body_start == (0, 0) {
4473            return false;
4474        }
4475        match code.position_at(frame.at as u32) {
4476            Some(position) => position < code.body_start,
4477            None => false,
4478        }
4479    }
4480
4481    fn frame(&self) -> &Frame {
4482        self.frames.last().expect("a frame is live")
4483    }
4484
4485    fn frame_mut(&mut self) -> &mut Frame {
4486        self.frames.last_mut().expect("a frame is live")
4487    }
4488
4489    // -- slot access --------------------------------------------------------
4490
4491    /// Move a local's value out, leaving `undefined` in the slot.
4492    ///
4493    /// `None` for a captured slot: its value lives in a cell shared with every closure
4494    /// that closed over it, so it can never be exclusively ours and must not be taken.
4495    ///
4496    /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4497    /// for every read and fatal for this one — a clone is exactly the second handle that
4498    /// rules out growing the string in place.
4499    fn take_loc(&mut self, slot: usize) -> Option<Value> {
4500        let frame = self.frames.last_mut()?;
4501        if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4502            return None;
4503        }
4504        frame
4505            .locals
4506            .get_mut(slot)
4507            .map(|value| std::mem::replace(value, Value::Undefined))
4508    }
4509
4510    /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4511    /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4512    ///
4513    /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4514    /// it** — the value is put back before the general path runs — so a `valueOf` that
4515    /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4516    /// error as it would have without the fusion. This is why the in-place attempt is a
4517    /// `take` and not a `get`: an optimisation that changes what an exception observes is
4518    /// a wrong answer with a good excuse.
4519    fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4520        // The take is `matches!`-guarded on the *right* operand only, and the taken value
4521        // is put back on every path that does not append. An earlier version wrote the two
4522        // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4523        // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4524        // through with its value already taken and dropped: the general path below then
4525        // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4526        // A wrong answer, from an optimisation, with every test green.
4527        if matches!(right, Value::String(_))
4528            && let Some(taken) = self.take_loc(slot)
4529        {
4530            if let Value::String(mut left) = taken {
4531                let appended = match left.get_mut() {
4532                    Some(string) => string.append_in_place(
4533                        // The pattern is the one `matches!` just checked.
4534                        match &right {
4535                            Value::String(text) => text,
4536                            _ => unreachable!("guarded above"),
4537                        },
4538                    ),
4539                    None => None,
4540                };
4541                self.put_loc(slot, Value::String(left));
4542                if let Some(added) = appended {
4543                    // The buffer grew where it stood, so the heap's running total has to
4544                    // be told: `measure_used` would report the new length, and the two must
4545                    // agree or the subtraction at free time leaves the counter wrong.
4546                    self.heap.adjust_payload(added as isize);
4547                    return Ok(());
4548                }
4549            } else {
4550                self.put_loc(slot, taken);
4551            }
4552        }
4553        // The two-number case, without an operand stack round trip. Everything below
4554        // this point is the *general* path: push both, call `binary_add`, pop the answer,
4555        // store it — five operations and two `Value` clones for what is one integer add.
4556        // `AddImmLoc` already answers this shape that way; the fusion above it was written
4557        // for string append and never got the numeric half, so `t += i` — a counting loop
4558        // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4559        let left = self.get_loc(slot);
4560        if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4561            self.put_loc(
4562                slot,
4563                match a.checked_add(*b) {
4564                    Some(sum) => Value::Int(sum),
4565                    None => Value::Float(*a as f64 + *b as f64),
4566                },
4567            );
4568            return Ok(());
4569        }
4570        self.push(left);
4571        self.push(right);
4572        self.binary_add()?;
4573        let value = self.pop();
4574        self.put_loc(slot, value);
4575        Ok(())
4576    }
4577
4578    fn get_arg(&self, slot: usize) -> Value {
4579        self.frame().read_arg(slot)
4580    }
4581
4582    fn put_arg(&mut self, slot: usize, value: Value) {
4583        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4584        if cell == -1 {
4585            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4586                *slot = value;
4587            }
4588        } else {
4589            self.frame().cells[cell as usize].set(value);
4590        }
4591    }
4592
4593    fn get_loc(&self, slot: usize) -> Value {
4594        // The cell mapping is `-1` for every slot that was not captured — which is all of
4595        // them in a function that creates no closure. `Frame::read_loc` tests that first,
4596        // so the common case is one array read and a clone: 20% of every loop iteration
4597        // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4598        // sample of `dispatch:arith`).
4599        self.frame().read_loc(slot)
4600    }
4601
4602    fn put_loc(&mut self, slot: usize, value: Value) {
4603        // One borrow instead of three, and the cell check on the frame we already hold.
4604        let frame = self.frames.last_mut().expect("a frame is live");
4605        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4606        if cell < 0 {
4607            if let Some(slot) = frame.locals.get_mut(slot) {
4608                *slot = value;
4609            }
4610        } else if let Some(cell) = frame.cells.get(cell as usize) {
4611            cell.set(value);
4612        }
4613    }
4614
4615    // -- globals ------------------------------------------------------------
4616
4617    /// The name a global-slot operand refers to.
4618    fn global_name(&self, slot: usize) -> String {
4619        self.frame()
4620            .code
4621            .code
4622            .closure_vars
4623            .get(slot)
4624            .map(|c| c.name.clone())
4625            .unwrap_or_default()
4626    }
4627
4628    /// The facts about a global binding that decide where it lives.
4629    ///
4630    /// A script's globals split in two, and the split is observable: `var` and
4631    /// function declarations become properties of the global object (`globalThis.v`
4632    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4633    /// declarations live in the global *lexical* environment and are invisible there
4634    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4635    /// `is_lexical` flag means the answer is already in the bytecode.
4636    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4637        let name = self.global_name(slot);
4638        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4639        // while forwarding a reference through a nested function is built with the
4640        // flags cleared, so `const c` would look like an ordinary `var` from inside a
4641        // closure. Presence in the realm's lexical table is the same fact, recorded
4642        // once, and every slot sees it.
4643        let lexical = self.realm.globals.contains_key(&name);
4644        let is_const = self.realm.lexical_consts.contains(&name);
4645        (name, lexical, is_const)
4646    }
4647
4648    /// The value of `name` in the innermost active `with` object, if any.
4649    ///
4650    /// The active objects are the [`VarKind::With`] locals of every frame still running,
4651    /// innermost frame first and innermost block first within one. Walking frames rather
4652    /// than keeping a separate stack is what makes a closure called from inside a `with`
4653    /// see it, and what keeps the object alive only as long as the block is.
4654    /// The innermost active `with` object that has `name`, if any.
4655    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4656        let objects = self.eval_with.clone().unwrap_or_default();
4657        for object in objects {
4658            let key = self.string(name.to_string());
4659            if self
4660                .has_property(&key, &Value::Object(object.clone()))
4661                .ok()?
4662            {
4663                return Some(object);
4664            }
4665        }
4666        None
4667    }
4668
4669    /// Every active `with` object, innermost first.
4670    fn with_objects(&self) -> Vec<Gc<JsObject>> {
4671        let mut objects = Vec::new();
4672        for frame in self.frames.iter().rev() {
4673            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4674                if var.kind != js_compile::VarKind::With {
4675                    continue;
4676                }
4677                // A captured binding lives in its cell and not in the slot list, so the
4678                // cell is consulted first — a closure created inside the block is exactly
4679                // what makes the object captured. Before the store runs the slot still
4680                // holds `undefined`, and a `with` object is always boxed, so a non-object
4681                // entry is simply not in scope yet.
4682                let value = frame
4683                    .code
4684                    .loc_cell
4685                    .get(index)
4686                    .copied()
4687                    .filter(|cell| *cell >= 0)
4688                    .and_then(|cell| frame.cells.get(cell as usize))
4689                    .map(|cell| cell.get())
4690                    .or_else(|| frame.locals.get(index).cloned());
4691                if let Some(Value::Object(object)) = value {
4692                    objects.push(object);
4693                }
4694            }
4695        }
4696        objects
4697    }
4698
4699    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4700        for object in self.eval_with.clone().unwrap_or_default() {
4701            let key = self.string(name.to_string());
4702            if self.has_property(&key, &Value::Object(object.clone()))? {
4703                return Ok(Some(self.read_field(&Value::Object(object), name)?));
4704            }
4705        }
4706        Ok(None)
4707    }
4708
4709    /// Whether every scope between here and the global object is an ordinary one.
4710    ///
4711    /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4712    /// bytecode resolved; when any is live the general path has to run in full order. When
4713    /// none is — every ordinary program — a global read is a property read and nothing
4714    /// else, and that is worth caching.
4715    fn scopes_are_plain(&self) -> bool {
4716        self.eval_caller.is_none()
4717            && self.eval_with.is_none()
4718            && self.eval_arguments.is_none()
4719            && self.eval_bindings.is_empty()
4720            && self.eval_scope.is_none()
4721            // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4722            // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4723            // its `ClosureEnv`, so the test has to be the same one the general path makes.
4724            // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4725            // upstream corpus caught and no unit test did.
4726            && !self.has_visible_local_vars()
4727            && self.frame().env.eval_scope.is_none()
4728    }
4729
4730    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4731        // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4732        // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4733        // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4734        // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4735        // borrow outlive the `&mut self` the lookup needs.
4736        //
4737        // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4738        // forwarded through a nested function has its flags cleared, so the flag cannot
4739        // be believed.
4740        let code = self.frame().code.clone();
4741        let name = code
4742            .code
4743            .closure_vars
4744            .get(slot)
4745            .map(|c| c.name.as_str())
4746            .unwrap_or_default();
4747        let lexical = self.realm.globals.contains_key(name);
4748        // The common case, first: an ordinary global `var`, with a cache in front of the
4749        // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4750        // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4751        // cache hit and return without touching any of it.
4752        if !lexical && self.scopes_are_plain() {
4753            return self.get_plain_global(name, slot);
4754        }
4755        if name == "arguments"
4756            && let Some(arguments) = &self.eval_arguments
4757        {
4758            return Ok(arguments.clone());
4759        }
4760        // A `with` block around the *call site* is part of the scope an `eval` sees, so
4761        // the objects live when the eval started are consulted before anything else. The
4762        // snapshot is taken at entry rather than scanning the frames on every read: a
4763        // block that has already finished still leaves its object in the slot, and a
4764        // bytecode read outside the block must not see it.
4765        if let Some(value) = self.with_lookup(name)? {
4766            return Ok(value);
4767        }
4768        // A variable a direct `eval` declared shadows everything the compiler resolved,
4769        // including an enclosing function's binding: the eval put it in the caller's own
4770        // variable environment, which is nearer than any captured scope.
4771        if let Some((local_vars, phase)) = self.visible_local_vars()
4772            && let Some(cell) = local_vars.get(name, phase)
4773        {
4774            return Ok(cell.get());
4775        }
4776        // The frame that called `eval` is the innermost scope the eval'd code sees, so
4777        // its local `a` wins over a global `a`.
4778        if let Some(value) = self.eval_binding_value(name) {
4779            return Ok(value);
4780        }
4781        // A closure created by an `eval` resolves its free names against the bindings
4782        // that eval saw, even after the eval (and its frames) are gone.
4783        if let Some(cell) = self
4784            .frame()
4785            .env
4786            .eval_scope
4787            .as_ref()
4788            .and_then(|scope| scope.get(name))
4789        {
4790            let value = cell.get();
4791            if matches!(value, Value::Uninitialized) {
4792                return Err(self.throw_reference(name));
4793            }
4794            return Ok(value);
4795        }
4796        // A binding declared by the strict `eval` currently running shadows anything
4797        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
4798        if let Some(scope) = &self.eval_scope
4799            && let Some(value) = scope.get(name)
4800        {
4801            return Ok(value.clone());
4802        }
4803        if lexical {
4804            // A lexical global is a binding in a side table, so the dead zone is
4805            // visible and it is nowhere on the global object.
4806            if let Some(cell) = self.realm.globals.get(name) {
4807                let value = cell.get();
4808                if matches!(value, Value::Uninitialized) {
4809                    return Err(self.throw_reference(name));
4810                }
4811                return Ok(value);
4812            }
4813            return Err(self.throw_reference(name));
4814        }
4815        // A `var` global is an ordinary property, so the prototype chain and the
4816        // global object's own builtins are all reachable through it.
4817        match self.get_property(&self.realm.global.clone(), name)? {
4818            Some(value) => Ok(value),
4819            None => Err(self.throw_reference(name)),
4820        }
4821    }
4822
4823    /// Read a plain global `var`: a cached own data property, or the full lookup.
4824    ///
4825    /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
4826    /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
4827    fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
4828        let object = self.realm.global.clone();
4829        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4830        if let Some(cached) = &self.global_cache[site]
4831            && object.upgrades_to(&cached.object)
4832            && let Some(value) = object.data_property_at(cached.index, name)
4833        {
4834            return Ok(value);
4835        }
4836        // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
4837        // chain exactly as before, then remember the answer if it is worth remembering.
4838        let Some(value) = self.get_property(&object, name)? else {
4839            return Err(self.throw_reference(name));
4840        };
4841        if let Some(index) = object.own_data_index(name) {
4842            self.global_cache[site] = Some(GlobalCache {
4843                object: object.downgrade(),
4844                index,
4845            });
4846        }
4847        Ok(value)
4848    }
4849
4850    /// Store to a global binding.
4851    ///
4852    /// Returns a signal when the store is refused: a `const` global may only be
4853    /// written by its initialiser, and a non-configurable `var` global may not be
4854    /// deleted but is always writable.
4855    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4856        let (name, lexical, is_const) = self.global_binding(slot);
4857
4858        // An assignment inside a `with` writes through to the object that supplies the
4859        // name, which for an `eval` means consulting the same chain `get_global` does.
4860        if let Some(owner) = self.with_owner(&name) {
4861            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
4862            return Ok(());
4863        }
4864        // A variable the running eval *declared* takes the write before any caller
4865        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
4866        // environment even when an enclosing function has a `var c` of its own.
4867        if self.eval_caller.flatten().is_some()
4868            && let Some((local_vars, phase)) = self.visible_local_vars()
4869            && local_vars.contains(&name)
4870            && let Some(cell) = local_vars.get(&name, phase)
4871        {
4872            cell.set(value);
4873            return Ok(());
4874        }
4875        // A binding of the frame that called `eval` takes the write, which is what
4876        // makes `f("a = 3")` change the caller's `a`.
4877        if self.set_eval_binding(&name, &value)? {
4878            return Ok(());
4879        }
4880        // A closure that outlived its `eval` writes through to the same cell it reads.
4881        if let Some(cell) = self
4882            .frame()
4883            .env
4884            .eval_scope
4885            .as_ref()
4886            .and_then(|scope| scope.get(&name))
4887            .cloned()
4888        {
4889            cell.set(value);
4890            return Ok(());
4891        }
4892        // Inside a strict `eval`, a name it declared itself is stored there. An
4893        // *assignment* to a name nobody declared is not a declaration, so it falls
4894        // through: strict mode raises `ReferenceError` for it, which is what
4895        // `eval("1 + (@not_def = 1)")` has to do.
4896        if let Some(scope) = self.eval_scope.as_mut()
4897            && scope.contains_key(&name)
4898        {
4899            scope.insert(name, value);
4900            return Ok(());
4901        }
4902        if lexical {
4903            if let Some(cell) = self.realm.globals.get(&name).cloned() {
4904                if is_const && !matches!(cell.get(), Value::Uninitialized) {
4905                    return Err(self.read_only_global(&name));
4906                }
4907                cell.set(value);
4908                return Ok(());
4909            }
4910            // Writing an undeclared lexical global is a `ReferenceError` in strict
4911            // mode and a silent global creation otherwise; creating the cell here
4912            // keeps both paths from losing the value.
4913            let cell = self.new_cell(value);
4914            self.realm.globals.insert(name, cell);
4915            return Ok(());
4916        }
4917        // A variable a direct `eval` declared in this call shadows the global object, even
4918        // when the global already has a property of that name — `var c = "global"` at the
4919        // top level must not capture `eval("var c = 1")` inside a function.
4920        if let Some((local_vars, phase)) = self.visible_local_vars()
4921            && local_vars.contains(&name)
4922            && let Some(cell) = local_vars.get(&name, phase)
4923        {
4924            cell.set(value);
4925            return Ok(());
4926        }
4927        // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
4928        // remembered a global's slot index since M12b, but the *store* side never did: it
4929        // converted the name to a `PropertyKey` (two allocations) and then scanned the
4930        // global object's whole table — which holds every builtin — on every assignment to
4931        // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
4932        // full global lookup per iteration; measured with a counter, `s` as a global made
4933        // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
4934        //
4935        // Re-validated exactly like the read: same object, same index, still the name, and
4936        // — the one extra check a store needs — still writable. A global that is an
4937        // accessor, non-writable, or inherited fails here and falls through to the full
4938        // path below, which reports the failure the way it always did.
4939        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4940        let global = self.realm.global.clone();
4941        if let Some(cached) = &self.global_cache[site]
4942            && global.upgrades_to(&cached.object)
4943            && global.write_data_at(cached.index, &name, value.clone())
4944        {
4945            return Ok(());
4946        }
4947        match global.own_property(&name) {
4948            // A `var` global is writable, so the store goes straight through — but
4949            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
4950            // store (a non-writable or accessor-without-setter global) is a silent
4951            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
4952            // split every other assignment has.
4953            Some(_) => {
4954                let on_failure = if self.current_strict() {
4955                    DeleteFailure::Throw
4956                } else {
4957                    DeleteFailure::Ignore
4958                };
4959                let result = self.set_property_with(&global, &name, value, on_failure);
4960                // Teach the cache the slot for a plain writable own data property, which is
4961                // what a declared `var` is. Without this the fast path above could never
4962                // fire for a global that is only ever *written* — its entry would have to
4963                // be put there by a read of the same slot, and a write-only loop has none.
4964                if result.is_ok()
4965                    && let Some(index) = global.own_data_index(&name)
4966                {
4967                    self.global_cache[site] = Some(GlobalCache {
4968                        object: global.downgrade(),
4969                        index,
4970                    });
4971                }
4972                result
4973            }
4974            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
4975            // declaration creates a *configurable* property, which is what makes it
4976            // deletable and is the one way a global differs from a declared `var`.
4977            // In strict mode the same store is a `ReferenceError` instead: that is the
4978            // whole point of strict mode, and creating the global silently meant
4979            // `"use strict"; x = 1` looked like it worked.
4980            None => {
4981                if self.current_strict() {
4982                    return Err(self.throw_reference(&name));
4983                }
4984                // A direct eval declares here rather than on the global object: its
4985                // `var`s belong to the caller's variable environment. `declare_eval_local`
4986                // also covers a plain assignment to a variable an earlier eval made.
4987                if let Some(cell) = self.declare_eval_local(&name) {
4988                    cell.set(value);
4989                    return Ok(());
4990                }
4991                global.define_data(&name, value);
4992                Ok(())
4993            }
4994        }
4995    }
4996
4997    /// The value of a binding of the frame that called `eval`, if there is one.
4998    fn eval_binding_value(&self, name: &str) -> Option<Value> {
4999        let binding = self
5000            .eval_bindings
5001            .iter()
5002            .find(|binding| binding.name == name)?;
5003        let owner = self.frames.get(binding.frame)?;
5004        let (slot, index) = (binding.slot, binding.index);
5005        Some(match slot {
5006            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5007                cell if cell >= 0 => owner
5008                    .cells
5009                    .get(cell as usize)
5010                    .map(|cell| cell.get())
5011                    .unwrap_or(Value::Undefined),
5012                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5013            },
5014            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5015                cell if cell >= 0 => owner
5016                    .cells
5017                    .get(cell as usize)
5018                    .map(|cell| cell.get())
5019                    .unwrap_or(Value::Undefined),
5020                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5021            },
5022        })
5023    }
5024
5025    /// Write to a binding of the frame that called `eval`.
5026    ///
5027    /// `Ok(false)` means no binding matched and the caller should keep looking. A
5028    /// matched binding can still refuse the store, which is why this is fallible: a
5029    /// `const` is read-only everywhere, and a named function expression's own name is
5030    /// read-only in strict mode.
5031    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5032        let Some(binding) = self
5033            .eval_bindings
5034            .iter()
5035            .find(|binding| binding.name == name)
5036        else {
5037            return Ok(false);
5038        };
5039        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5040        let strict = self.current_strict();
5041        let Some(owner) = self.frames.get_mut(frame) else {
5042            return Ok(false);
5043        };
5044        match slot {
5045            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5046                cell if cell >= 0 => {
5047                    if let Some(cell) = owner.cells.get(cell as usize) {
5048                        cell.set(value.clone());
5049                    }
5050                }
5051                _ => {
5052                    if let Some(slot) = owner.args.get_mut(index) {
5053                        *slot = value.clone();
5054                    }
5055                }
5056            },
5057            EvalSlot::Local => {
5058                let declared = owner.code.code.vars.get(index);
5059                // A `const` is read-only even through `eval`. The realm records this for
5060                // globals (see `lexical_consts`), but a local's `const`-ness is only in
5061                // the bytecode, so this is where it has to be enforced.
5062                if declared.is_some_and(|var| var.is_const) {
5063                    return Err(self.read_only_local(name));
5064                }
5065                // The name of a named function expression is read-only too, but only
5066                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5067                // such a name is ignored, the same as a direct store would be.
5068                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5069                    return if strict {
5070                        Err(self.read_only_local(name))
5071                    } else {
5072                        Ok(true)
5073                    };
5074                }
5075                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5076                    cell if cell >= 0 => {
5077                        if let Some(cell) = owner.cells.get(cell as usize) {
5078                            cell.set(value.clone());
5079                        }
5080                    }
5081                    _ => {
5082                        if let Some(slot) = owner.locals.get_mut(index) {
5083                            *slot = value.clone();
5084                        }
5085                    }
5086                }
5087            }
5088        }
5089        Ok(true)
5090    }
5091
5092    /// The `TypeError` an assignment to a read-only binding raises.
5093    fn read_only_local(&self, name: &str) -> Signal {
5094        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5095    }
5096
5097    /// Declare `name` as a variable of the frame that called the running `eval`.
5098    ///
5099    /// `None` when there is no direct eval in progress, or it was called from the top
5100    /// level — then the caller's variable environment *is* the global one and the
5101    /// existing path is right.
5102    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5103        let caller = self.eval_caller.flatten()?;
5104        // The bottom frame is the top-level script, whose variable environment *is* the
5105        // global one — so `eval("var x = 1")` at the top level still creates a global.
5106        if caller == 0 {
5107            return None;
5108        }
5109        // A name the eval's *own* variable environment already binds is not a new
5110        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5111        // `arguments`, and creating a second binding would leave the first — the one
5112        // closures read — untouched. A binding of an *outer* frame does not count: a
5113        // declaration shadows it rather than writing through.
5114        if self
5115            .eval_bindings
5116            .iter()
5117            .any(|binding| binding.name == name && binding.frame == caller)
5118        {
5119            return None;
5120        }
5121        let phase = if self.in_parameter_list_at(caller) {
5122            0
5123        } else {
5124            1
5125        };
5126        self.frame_local_vars(caller)?;
5127        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5128        if let Some(cell) = local_vars.get(name, 1) {
5129            return Some(cell);
5130        }
5131        let cell = self.new_cell(Value::Undefined);
5132        Some(local_vars.declare(name, phase, cell))
5133    }
5134
5135    /// Make sure `frame` has a `LocalVars`, creating it on demand.
5136    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5137        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5138            return Some(local_vars.clone());
5139        }
5140        let local_vars = Gc::new(self.heap, LocalVars::new());
5141        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5142        Some(local_vars)
5143    }
5144
5145    /// Whether the realm already has a binding for `name`, lexically or as an *own*
5146    /// property of the global object. Used to decide whether a store inside an
5147    /// `eval` writes through to the realm or declares a binding of its own.
5148    ///
5149    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5150    /// write to `Object.prototype.toString`, and must not shadow it either.
5151    fn global_knows(&mut self, name: &str) -> bool {
5152        if self.realm.globals.contains_key(name) {
5153            return true;
5154        }
5155        self.realm.global.own_property(name).is_some()
5156    }
5157
5158    /// Whether the code currently running is strict.
5159    ///
5160    /// Read off the frame's function, which is where the parser's answer ended up; a
5161    /// native function never runs strict-only checks, and there is no frame at all
5162    /// before the first script.
5163    pub fn current_strict(&self) -> bool {
5164        self.frames
5165            .last()
5166            .is_some_and(|frame| frame.code.code.strict)
5167    }
5168
5169    /// Initialise a declared global, which is what ends its dead zone.
5170    ///
5171    /// A `var` global becomes a property of the global object: writable, so a later
5172    /// assignment goes through, and non-configurable, so `delete` refuses.
5173    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5174        let (name, lexical, _) = self.global_binding(slot);
5175        // A `var` declared by the strict `eval` currently running belongs to the
5176        // eval's scope, not to the global object: `eval("var v = 1")` must not make
5177        // `typeof v` answer `"number"` afterwards. A name the realm already has is
5178        // initialised in place, which is what a re-declaration inside eval does.
5179        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5180            self.eval_scope
5181                .as_mut()
5182                .expect("checked above")
5183                .insert(name, value);
5184            return Ok(());
5185        }
5186        if let Some(scope) = self.eval_scope.as_mut()
5187            && scope.contains_key(&name)
5188        {
5189            scope.insert(name, value);
5190            return Ok(());
5191        }
5192        if lexical {
5193            // The cell exists (created at declaration time) holding the dead-zone
5194            // marker; storing the value is what makes the binding readable.
5195            if let Some(cell) = self.realm.globals.get(&name).cloned() {
5196                cell.set(value);
5197                return Ok(());
5198            }
5199            let cell = self.new_cell(value);
5200            self.realm.globals.insert(name, cell);
5201            return Ok(());
5202        }
5203        let global = self.realm.global.clone();
5204        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5205        // to answer `false` and leave the binding in place. `with_attributes` ties
5206        // `configurable` to `writable`, so the property is built field by field.
5207        global.define(
5208            &name,
5209            Property {
5210                value: Some(value),
5211                writable: true,
5212                enumerable: true,
5213                configurable: false,
5214                ..Property::default()
5215            },
5216        );
5217        Ok(())
5218    }
5219
5220    /// The `TypeError` a store to a `const` global raises.
5221    fn read_only_global(&self, name: &str) -> Signal {
5222        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5223    }
5224
5225    // -- properties ---------------------------------------------------------
5226
5227    /// Read `object[key]`, following the prototype chain.
5228    ///
5229    /// An inherited accessor runs with the *receiver* as `this`, which is why the
5230    /// lookup returns the owner rather than just the value.
5231    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5232        self.get_property_key(object, &PropertyKey::from(key))
5233    }
5234
5235    /// [`Interp::get_property`] with a key that may be a symbol.
5236    pub fn get_property_key(
5237        &mut self,
5238        object: &Gc<JsObject>,
5239        key: &PropertyKey,
5240    ) -> JsResult<Option<Value>> {
5241        self.get_property_key_for(object, None, key)
5242    }
5243
5244    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5245    ///
5246    /// The receiver matters when the property is found on a *prototype*: a getter has to
5247    /// see the object the read started from. For a primitive that is the primitive
5248    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5249    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5250    /// the owner.
5251    pub fn get_property_key_for(
5252        &mut self,
5253        object: &Gc<JsObject>,
5254        receiver: Option<&Value>,
5255        key: &PropertyKey,
5256    ) -> JsResult<Option<Value>> {
5257        // A proxy answers for itself, before any of the shortcuts below: `new
5258        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5259        // have.
5260        if object.proxy_state().is_some() {
5261            let receiver = receiver
5262                .cloned()
5263                .unwrap_or_else(|| Value::Object(object.clone()));
5264            return self.proxy_get(object, &receiver, key);
5265        }
5266        // A host class's `get_property` trap replaces the whole read, prototype walk
5267        // included — that is what makes a native accessor free rather than a JavaScript
5268        // getter call.
5269        if let Some(exotic) = object.exotic() {
5270            let receiver_value = receiver
5271                .cloned()
5272                .unwrap_or_else(|| Value::Object(object.clone()));
5273            if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5274                return Ok(Some(value));
5275            }
5276            // With no `get_property` trap, a `get_own_property` trap still answers for the
5277            // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5278            // and the hook lives exactly there. A key the trap reports as absent is still
5279            // looked for on the prototype, which is why the search resumes *above*.
5280            if let Some(property) = exotic.get_own_property(self, object, key)? {
5281                return match property {
5282                    Some(property) => self.read_property(property, object, receiver),
5283                    None => match lookup_key_above(object, key) {
5284                        Some((_, property)) => self.read_property(property, object, receiver),
5285                        None => Ok(None),
5286                    },
5287                };
5288            }
5289        }
5290        // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
5291        // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
5292        // The `[[Get]]` short-circuit therefore belongs to this one arm.
5293        //
5294        // Constructibility is exactly the split the reference makes: `function f(){}` and
5295        // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
5296        // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
5297        // function" — it *is* the predicate, which is why no extra marker is needed.
5298        if let Some(text) = key.as_str()
5299            && (text == "caller" || text == "arguments")
5300            && object.is_constructor()
5301            && object.is_callable()
5302            && !object.is_bound_function()
5303            && object.own_property(text).is_none()
5304        {
5305            return Ok(Some(Value::Undefined));
5306        }
5307        // The element-vector and `length` shortcuts are string-only: an array index
5308        // has no symbol spelling.
5309        if let Some(text) = key.as_str() {
5310            if let Some(value) = self.own_element(object, text) {
5311                return Ok(Some(value));
5312            }
5313            // `length` is not stored as a property: an array's length is its element
5314            // count, and keeping one copy of it is what makes `push`/`pop` and
5315            // `a.length = n` agree.
5316            if let Some(length) = object.array_length()
5317                && text == "length"
5318            {
5319                // Not `Value::Int(length as i32)`: see [`length_value`].
5320                return Ok(Some(crate::object::length_value(length)));
5321            }
5322        }
5323        match lookup_key(object, key) {
5324            Some((_, property)) => self.read_property(property, object, receiver),
5325            None => Ok(None),
5326        }
5327    }
5328
5329    /// The value a property read answers.
5330    ///
5331    /// One place rather than three, because an accessor has to run with the *receiver* as
5332    /// `this` whether the descriptor came from the property table, an exotic
5333    /// `get_own_property` trap, or a prototype above one.
5334    fn read_property(
5335        &mut self,
5336        property: Property,
5337        object: &Gc<JsObject>,
5338        receiver: Option<&Value>,
5339    ) -> JsResult<Option<Value>> {
5340        if property.is_accessor() {
5341            match &property.getter {
5342                Some(getter) if !matches!(getter, Value::Undefined) => {
5343                    let receiver = receiver
5344                        .cloned()
5345                        .unwrap_or_else(|| Value::Object(object.clone()));
5346                    self.call_value(getter.clone(), receiver, Vec::new())
5347                        .map(Some)
5348                }
5349                // An accessor with no getter reads as `undefined`.
5350                _ => Ok(Some(Value::Undefined)),
5351            }
5352        } else {
5353            Ok(property.value)
5354        }
5355    }
5356
5357    /// `super.key` — start the search at `proto`, but report to `receiver`.
5358    ///
5359    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5360    /// found on the prototype of a class has to see the *instance* as `this`, and a
5361    /// plain property read off `proto` would lose that.
5362    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5363        let start = self.require_object(proto)?;
5364        let key = self.propkey(key)?;
5365        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5366        if matches!(proto, Value::Null) {
5367            return Ok(Value::Undefined);
5368        }
5369        match lookup_key(&start, &key) {
5370            Some((_, property)) if property.is_accessor() => match &property.getter {
5371                Some(getter) if !matches!(getter, Value::Undefined) => {
5372                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
5373                }
5374                _ => Ok(Value::Undefined),
5375            },
5376            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5377            None => Ok(Value::Undefined),
5378        }
5379    }
5380
5381    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5382    ///
5383    /// A setter found on the prototype runs with `receiver` as `this`; a data property
5384    /// is shadowed by a new own property on the receiver, the same rule an ordinary
5385    /// assignment follows.
5386    fn super_write(
5387        &mut self,
5388        receiver: &Value,
5389        proto: &Value,
5390        key: &Value,
5391        value: Value,
5392    ) -> JsResult<()> {
5393        let target = self.require_object(receiver)?;
5394        let key = self.propkey(key)?;
5395        if !matches!(proto, Value::Null)
5396            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5397        {
5398            if property.is_accessor() {
5399                if let Some(setter) = &property.setter
5400                    && !matches!(setter, Value::Undefined)
5401                {
5402                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5403                }
5404                return Ok(());
5405            }
5406            // A data property on the prototype is writable or not; reading `owner` at
5407            // all is only for the attribute check.
5408            if !property.writable {
5409                return Err(self.type_error(format!("'{key}' is read-only")));
5410            }
5411            let _ = owner;
5412        }
5413        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5414    }
5415
5416    /// The object a `super` operation needs, or the `TypeError` the spec raises.
5417    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5418        match value.as_object() {
5419            Some(object) => Ok(object.clone()),
5420            None => Err(Signal::Throw(
5421                self.make_error("TypeError", "value is not an object"),
5422            )),
5423        }
5424    }
5425
5426    /// Build the class object `define_class` produces.
5427    ///
5428    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5429    /// whose prototype property is a fresh object inheriting from the parent's
5430    /// prototype, and whose own prototype is the parent constructor — which is what makes
5431    /// a static method inherited too.
5432    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5433        let ctor = self.pop();
5434        let parent = self.pop();
5435        let Value::Object(function) = &ctor else {
5436            return Err(Signal::Throw(
5437                self.make_error("TypeError", "class constructor must be a function"),
5438            ));
5439        };
5440        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5441        // but gives the instances no prototype at all.
5442        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5443            match &parent {
5444                Value::Null => (Some(self.realm.function_proto.clone()), None),
5445                Value::Object(parent_class) => {
5446                    if !parent_class.is_callable() {
5447                        return Err(Signal::Throw(
5448                            self.make_error("TypeError", "parent class must be constructor"),
5449                        ));
5450                    }
5451                    let proto = self.get_property(parent_class, "prototype")?;
5452                    match proto {
5453                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5454                        Some(Value::Null) => (Some(parent_class.clone()), None),
5455                        _ => {
5456                            return Err(Signal::Throw(self.make_error(
5457                                "TypeError",
5458                                "parent prototype must be an object or null",
5459                            )));
5460                        }
5461                    }
5462                }
5463                _ => {
5464                    return Err(Signal::Throw(
5465                        self.make_error("TypeError", "parent class must be constructor"),
5466                    ));
5467                }
5468            }
5469        } else {
5470            (
5471                Some(self.realm.function_proto.clone()),
5472                Some(self.realm.object_proto.clone()),
5473            )
5474        };
5475        let proto = self.new_object(parent_proto);
5476        function.set_proto(parent_ctor);
5477        // A class is not callable without `new`, and its `prototype` is not writable —
5478        // both follow from being a class and are what `class A {}; A()` throws on.
5479        function.set_class_constructor(true);
5480        function.set_home_object(None);
5481        self.set_function_name(&ctor, name);
5482        self.define_class_properties(function, &ctor, &proto)?;
5483        Ok((ctor, proto))
5484    }
5485
5486    /// Give the constructor its `prototype` and `length`, and the prototype its
5487    /// `constructor` back-pointer.
5488    fn define_class_properties(
5489        &mut self,
5490        function: &Gc<JsObject>,
5491        ctor: &Value,
5492        proto: &Gc<JsObject>,
5493    ) -> JsResult<()> {
5494        proto.define(
5495            "constructor",
5496            Property::with_attributes(ctor.clone(), true, false),
5497        );
5498        function.define(
5499            "prototype",
5500            Property::prototype_of(Value::Object(proto.clone()), false),
5501        );
5502        if let Some((code, _)) = bytecode_of(function) {
5503            let length = code.code.defined_args;
5504            function.define(
5505                "length",
5506                Property::name_or_length(Value::Int(length as i32)),
5507            );
5508        }
5509        Ok(())
5510    }
5511
5512    /// The own array element `key` names, if this object has one.
5513    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5514        // A typed array's elements live in its buffer, not in a property list: reading one
5515        // goes through the view's element type so a bounds check and a detached buffer are
5516        // both handled there.
5517        //
5518        // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
5519        // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
5520        // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
5521        // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
5522        // consulted. Testing with `array_index` rejected all three, which let a throwing
5523        // getter installed on `TypedArray.prototype["-1"]` run.
5524        if object.typed_array_parts().is_some() {
5525            let property_key = PropertyKey::from(key);
5526            let numeric = canonical_numeric_index(&property_key)?;
5527            if typed_array_index_is_valid(object, numeric) {
5528                return object.typed_array_element(numeric as usize);
5529            }
5530            // Canonical, but not a valid index: `undefined`, and *final*.
5531            return Some(Value::Undefined);
5532        }
5533        let index = array_index(key)?;
5534        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5535        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5536        // search early, which is why `Array.prototype[1] = 9` could not be seen through
5537        // `[1,,3][1]`.
5538        match object.array_get(index as usize) {
5539            Some(Value::Hole) | None => None,
5540            other => other,
5541        }
5542    }
5543
5544    /// Store `object[key] = value`, honouring setters and inherited properties.
5545    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5546        self.set_property_with(object, key, value, DeleteFailure::Throw)
5547    }
5548
5549    /// Store a property, choosing what to do when the object refuses.
5550    ///
5551    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5552    /// mode, which is the one place assignment differs by mode. Native code (the array
5553    /// methods, `JSON`) always asks for the throw.
5554    pub fn set_property_with(
5555        &mut self,
5556        object: &Gc<JsObject>,
5557        key: &str,
5558        value: Value,
5559        on_failure: DeleteFailure,
5560    ) -> JsResult<()> {
5561        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5562    }
5563
5564    /// [`Interp::set_property_with`] with a key that may be a symbol.
5565    pub fn set_property_with_key(
5566        &mut self,
5567        object: &Gc<JsObject>,
5568        key: &PropertyKey,
5569        value: Value,
5570        on_failure: DeleteFailure,
5571    ) -> JsResult<()> {
5572        self.set_property_with_key_receiver_aware(object, key, value, on_failure)
5573    }
5574
5575    /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
5576    ///
5577    /// The receiver split lives one level up, in
5578    /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
5579    /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
5580    /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
5581    /// stores into `object` itself, which is why the element branch below converts `V`
5582    /// before asking whether the index is valid: `V` may put it back in bounds
5583    /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
5584    fn set_property_with_key_receiver_aware(
5585        &mut self,
5586        object: &Gc<JsObject>,
5587        key: &PropertyKey,
5588        value: Value,
5589        on_failure: DeleteFailure,
5590    ) -> JsResult<()> {
5591        // A proxy's `set` trap decides, and its `false` means the same thing an
5592        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5593        if object.proxy_state().is_some() {
5594            let receiver = Value::Object(object.clone());
5595            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5596                return match (accepted, on_failure) {
5597                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5598                    (false, DeleteFailure::Throw) => {
5599                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5600                    }
5601                };
5602            }
5603        }
5604        // A host class's `set_property` trap decides for itself. `Some(false)` is a
5605        // refusal and means exactly what a proxy's `false` means.
5606        if let Some(exotic) = object.exotic() {
5607            let receiver = Value::Object(object.clone());
5608            if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5609                return match (accepted, on_failure) {
5610                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5611                    (false, DeleteFailure::Throw) => {
5612                        Err(self.type_error(format!("property '{key}' is read-only")))
5613                    }
5614                };
5615            }
5616        }
5617        // The element and `length` shortcuts only exist for string keys: an array
5618        // index has no symbol spelling, and a symbol named `length` is an ordinary
5619        // property.
5620        let text = key.as_str();
5621        // A typed array's elements are a window onto its buffer: the store has to go
5622        // through the view's element type so the value is wrapped (or clamped) and so an
5623        // out-of-range or detached write is a silent no-op, as the spec says.
5624        //
5625        // The key test is `CanonicalNumericIndexString`, like every other index operation
5626        // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
5627        // does not exist, so they do nothing and leave no own property behind
5628        // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
5629        // path, which created a property named `"-0"`.
5630        //
5631        // The conversion comes **first**, before the index is checked at all, and that
5632        // order is observable twice over:
5633        //
5634        // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
5635        //   has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
5636        //   then store the converted value;
5637        // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
5638        //   `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
5639        //   run and its exception to escape.
5640        //
5641        // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
5642        // validity check, not a validity check that skips the conversion. The store itself
5643        // is a no-op when the index is invalid by then, which is why no extra guard is
5644        // needed around `typed_array_set`.
5645        if let Some(element) = object.typed_array_element_type()
5646            && let Some(numeric) = canonical_numeric_index(key)
5647        {
5648            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5649            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5650            // in `Interp`, because it is script-observable and the storage borrow inside
5651            // `typed_array_set` must not be held across it.
5652            let stored = self.element_value(element, value)?;
5653            if typed_array_index_is_valid(object, numeric)
5654                && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
5655            {
5656                return Err(self.type_error(reason));
5657            }
5658            return Ok(());
5659        }
5660        if let Some(text) = text
5661            && let Some(index) = array_index(text)
5662            && object.is_array()
5663        {
5664            // An accessor defined on an index lives in the property table while the
5665            // element slot is a hole, so the store has to go through the property first.
5666            // Writing the vector directly skipped the setter entirely.
5667            if let Some(existing) = object.own_property_key(key) {
5668                if existing.is_accessor() {
5669                    return match existing.setter.clone() {
5670                        Some(setter) if !matches!(setter, Value::Undefined) => {
5671                            let receiver = Value::Object(object.clone());
5672                            self.call_value(setter, receiver, vec![value]).map(|_| ())
5673                        }
5674                        _ => match on_failure {
5675                            DeleteFailure::Throw => Err(self.type_error(format!(
5676                                "cannot set property '{text}', it has only a getter"
5677                            ))),
5678                            DeleteFailure::Ignore => Ok(()),
5679                        },
5680                    };
5681                }
5682                if !existing.writable {
5683                    return match on_failure {
5684                        DeleteFailure::Throw => {
5685                            Err(self.type_error(format!("'{text}' is read-only")))
5686                        }
5687                        DeleteFailure::Ignore => Ok(()),
5688                    };
5689                }
5690            }
5691            {
5692                // Growing the array needs a writable `length`.
5693                if (index as usize) >= object.array_length().unwrap_or(0)
5694                    && !object.length_writable()
5695                {
5696                    return match on_failure {
5697                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5698                        DeleteFailure::Ignore => Ok(()),
5699                    };
5700                }
5701                // Adding an index past the end makes the array longer, which a
5702                // non-extensible array refuses.
5703                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5704                    return match on_failure {
5705                        DeleteFailure::Throw => Err(self.type_error(format!(
5706                            "cannot add property '{key}', object is not extensible"
5707                        ))),
5708                        DeleteFailure::Ignore => Ok(()),
5709                    };
5710                }
5711                if object.element_is_locked(index) {
5712                    return match on_failure {
5713                        DeleteFailure::Throw => {
5714                            Err(self.type_error(format!("'{key}' is read-only")))
5715                        }
5716                        DeleteFailure::Ignore => Ok(()),
5717                    };
5718                }
5719                // The element vector is only half of `[[Set]]` for an index: the
5720                // prototype chain is consulted first, and a setter there answers instead
5721                // of the element store. This branch used to write the element directly, so
5722                // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5723                // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5724                // the reference calls the setter and the array keeps no own index.
5725                //
5726                // An *exotic* prototype has no entry to find, because its indices live
5727                // outside the property table — `Object.setPrototypeOf([], typedArray)`
5728                // then looked like "nothing on the chain" and the store created the
5729                // element, where the view's `[[Set]]` answers `true` and does nothing for
5730                // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
5731                // checks the array's `length` stays 0). So the dispatch comes first.
5732                if !object.has_own_key(key)
5733                    && let Some(proto) = object.proto()
5734                    && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
5735                {
5736                    let receiver = Value::Object(object.clone());
5737                    let accepted =
5738                        self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
5739                    return if accepted {
5740                        Ok(())
5741                    } else {
5742                        match on_failure {
5743                            DeleteFailure::Throw => {
5744                                Err(self.type_error(format!("'{key}' is read-only")))
5745                            }
5746                            DeleteFailure::Ignore => Ok(()),
5747                        }
5748                    };
5749                }
5750                if let Some((owner, property)) = lookup_key(object, key)
5751                    && !owner.ptr_eq(object)
5752                {
5753                    match &property {
5754                        property if property.is_accessor() => {
5755                            match &property.setter {
5756                                Some(setter) if !matches!(setter, Value::Undefined) => {
5757                                    let receiver = Value::Object(object.clone());
5758                                    self.call_value(setter.clone(), receiver, vec![value])?;
5759                                }
5760                                _ => {
5761                                    return match on_failure {
5762                                        DeleteFailure::Throw => Err(self.type_error(format!(
5763                                            "cannot set property '{text}', it has only a getter"
5764                                        ))),
5765                                        DeleteFailure::Ignore => Ok(()),
5766                                    };
5767                                }
5768                            }
5769                            return Ok(());
5770                        }
5771                        property if !property.writable => {
5772                            return match on_failure {
5773                                DeleteFailure::Throw => {
5774                                    Err(self.type_error(format!("'{text}' is read-only")))
5775                                }
5776                                DeleteFailure::Ignore => Ok(()),
5777                            };
5778                        }
5779                        _ => {}
5780                    }
5781                }
5782                if object.array_set(self.heap, index as usize, value.clone()) {
5783                    return Ok(());
5784                }
5785                // Past the dense limit the slot is too far out to be worth one `Value`
5786                // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
5787                // constant time by keeping the index as an ordinary property. The store
5788                // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
5789                // to a legal program.
5790                object.define_key(key, Property::with_attributes(value, true, true));
5791                // Extend, never shorten: the index may be *inside* the current length (a
5792                // huge `length` with a sparse store), and shortening would delete the
5793                // sparse properties above it — including the one just stored.
5794                if index as usize + 1 > object.array_length().unwrap_or(0) {
5795                    object.array_set_length(self.heap, index as usize + 1);
5796                }
5797                return Ok(());
5798            }
5799        }
5800        if text == Some("length") && object.is_array() {
5801            if !object.length_writable() {
5802                return match on_failure {
5803                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5804                    DeleteFailure::Ignore => Ok(()),
5805                };
5806            }
5807            // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
5808            // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
5809            // answered `NaN`, which left the assignment silently ignored
5810            // (`S15.4.5.2_A3_T2`).
5811            let length = self.to_js_number(&value)?;
5812            // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
5813            // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
5814            // `RangeError`s; the old code only tested "finite and non-negative" and then
5815            // truncated, so `[].length = 4294967297` quietly produced a length no array can
5816            // hold (`Array/length/S15.4.5.1_A1.1_T1`).
5817            let valid = length.is_finite()
5818                && length >= 0.0
5819                && length.fract() == 0.0
5820                && length <= u32::MAX as f64;
5821            if !valid {
5822                return Err(self.range_error("invalid array length"));
5823            }
5824            {
5825                let length = length as usize;
5826                // `a.length = n` with `n` below a non-configurable element cannot
5827                // drop that element, so the whole assignment fails. The spec makes
5828                // this a `TypeError` rather than a silent no-op, in any mode.
5829                if let Some(blocked) = object.first_undeletable_at_or_above(length) {
5830                    // Sloppy mode stops the truncation at the blocking element
5831                    // instead of failing; strict mode raises.
5832                    // Both modes stop at the blocking element; they differ in
5833                    // whether that is reported. The reference truncates *then*
5834                    // throws, so the array is left in the shortened state.
5835                    object.array_truncate(self.heap, blocked + 1);
5836                    return match on_failure {
5837                        DeleteFailure::Throw => {
5838                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
5839                        }
5840                        DeleteFailure::Ignore => Ok(()),
5841                    };
5842                }
5843                object.array_set_length(self.heap, length);
5844                return Ok(());
5845            }
5846        }
5847        // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
5848        // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
5849        // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
5850        //
5851        // The prototype step is a dispatch, not a lookup. Walking the chain here and
5852        // applying whatever came back is the same thing for an ordinary prototype and
5853        // completely different for an exotic one: `var p = new Uint8Array(1); var o =
5854        // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
5855        // answers "not mine, the receiver is not me" without touching the buffer. This
5856        // code used to find nothing owned by `o`, find no property on the view either,
5857        // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
5858        // object and never converted (`key-is-valid-index-prototype-chain-set`,
5859        // `key-is-canonical-invalid-index-prototype-chain-set`).
5860        //
5861        // The read-only and accessor rules of step 1 are what make
5862        // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
5863        // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
5864        let own = match self.lookup_for_write(object, key)? {
5865            Some((owner, property)) if owner.ptr_eq(object) => Some(property),
5866            _ => None,
5867        };
5868        if let Some(property) = own {
5869            if property.is_accessor() {
5870                return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
5871                    Some(setter) => {
5872                        let receiver = Value::Object(object.clone());
5873                        self.call_value(setter, receiver, vec![value])?;
5874                        Ok(())
5875                    }
5876                    // §10.1.9.2 step 3: an accessor with no setter refuses the write.
5877                    // Sloppy code swallows that refusal, strict code raises — the same
5878                    // rule the read-only *data* property below follows, and skipping it
5879                    // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
5880                    // return silently. The reference answers `TypeError: 'x' is
5881                    // read-only`.
5882                    None => match on_failure {
5883                        DeleteFailure::Throw => {
5884                            Err(self.type_error(format!("'{key}' is read-only")))
5885                        }
5886                        DeleteFailure::Ignore => Ok(()),
5887                    },
5888                };
5889            }
5890            // An own non-writable data property stops here: nothing may change it.
5891            if !property.writable {
5892                return match on_failure {
5893                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
5894                    DeleteFailure::Ignore => Ok(()),
5895                };
5896            }
5897            // An existing writable own property keeps its attributes: only the value
5898            // moves. Redefining instead would reset them, which is how a
5899            // non-configurable global `var` used to become deletable.
5900            if object.write_value_key(key, value.clone()) {
5901                return Ok(());
5902            }
5903        }
5904        // Step 2: hand the store to the prototype, with `object` as the receiver.
5905        if let Some(proto) = object.proto() {
5906            let receiver = Value::Object(object.clone());
5907            let accepted =
5908                self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
5909            return if accepted {
5910                Ok(())
5911            } else {
5912                match on_failure {
5913                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
5914                    DeleteFailure::Ignore => Ok(()),
5915                }
5916            };
5917        }
5918        // Step 3: create one, and a non-extensible object cannot.
5919        if !object.is_extensible() {
5920            return match on_failure {
5921                DeleteFailure::Throw => Err(self.type_error(format!(
5922                    "cannot add property {key}, object is not extensible"
5923                ))),
5924                DeleteFailure::Ignore => Ok(()),
5925            };
5926        }
5927        object.define_data_key(key, value);
5928        Ok(())
5929    }
5930
5931    /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
5932    ///
5933    /// The distinction the fast path above does not need: it is called with the store's
5934    /// receiver already being the object it writes to. Here `object` is the one whose
5935    /// **own descriptor** decides what happens, and `receiver` is the one that ends up
5936    /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
5937    /// and not a write to `object`.
5938    ///
5939    /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
5940    /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
5941    /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
5942    /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
5943    /// descriptor on the prototype refuses instead, which is the same rule that keeps
5944    /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
5945    ///
5946    /// Answers `false` where the spec says `false`; the caller turns that into the
5947    /// strict-mode `TypeError` or the sloppy-mode silence.
5948    fn ordinary_set_with_receiver(
5949        &mut self,
5950        object: &Gc<JsObject>,
5951        receiver: &Value,
5952        key: &PropertyKey,
5953        value: Value,
5954        on_failure: DeleteFailure,
5955    ) -> JsResult<bool> {
5956        // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
5957        if object.proxy_state().is_some() {
5958            return Ok(self
5959                .proxy_set(object, key, value, receiver)?
5960                .unwrap_or(true));
5961        }
5962        // A host class decides for itself, with the receiver the caller named.
5963        if let Some(exotic) = object.exotic()
5964            && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
5965        {
5966            return Ok(accepted);
5967        }
5968        // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
5969        // rather than the receiver, but the receiver may still *be* the view:
5970        // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
5971        // itself as receiver, and then the first half applies — convert `V` once, store
5972        // if the index is valid, answer `true` either way. The conversion is the observable
5973        // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
5974        //
5975        // Only the second half, a view that is *not* the receiver, skips the conversion
5976        // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
5977        // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
5978        // below with the value still unconverted.
5979        if object.typed_array_element_type().is_some()
5980            && let Some(numeric) = canonical_numeric_index(key)
5981        {
5982            if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
5983                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
5984                return Ok(true);
5985            }
5986            if !typed_array_index_is_valid(object, numeric) {
5987                return Ok(true);
5988            }
5989        }
5990        let own = self.object_get_own_property(object, key)?;
5991        if let Some(own) = own {
5992            if own.is_accessor() {
5993                return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
5994                    Some(setter) => {
5995                        self.call_value(setter, receiver.clone(), vec![value])?;
5996                        Ok(true)
5997                    }
5998                    None => Ok(false),
5999                };
6000            }
6001            // A non-writable data descriptor refuses, own or inherited. Either way the
6002            // receiver must not gain a shadowing property.
6003            if !own.writable {
6004                return Ok(false);
6005            }
6006            // Step 1.d: the *receiver's* own descriptor decides whether it can be
6007            // created or written, and it is created as an ordinary data property.
6008            let Some(receiver_object) = receiver.as_object().cloned() else {
6009                return Ok(false);
6010            };
6011            return match self.object_get_own_property(&receiver_object, key)? {
6012                Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6013                Some(existing) => self.object_define_own_property(
6014                    &receiver_object,
6015                    key,
6016                    Property {
6017                        value: Some(value),
6018                        ..existing
6019                    },
6020                ),
6021                None => {
6022                    self.object_define_own_property(&receiver_object, key, Property::data(value))
6023                }
6024            };
6025        }
6026        // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6027        if let Some(proto) = object.proto() {
6028            return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6029        }
6030        // Step 3: nowhere to inherit from, so create on the receiver — if it will take it.
6031        let Some(receiver_object) = receiver.as_object().cloned() else {
6032            return Ok(false);
6033        };
6034        if !self.object_is_extensible(&receiver_object)? {
6035            return Ok(false);
6036        }
6037        self.object_define_own_property(&receiver_object, key, Property::data(value))
6038    }
6039
6040    /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6041    ///
6042    /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6043    /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6044    /// a virtual accessor gets its setter run without implementing `set_property` at all.
6045    /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6046    /// the prototype, so the walk resumes above the object.
6047    fn lookup_for_write(
6048        &mut self,
6049        object: &Gc<JsObject>,
6050        key: &PropertyKey,
6051    ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6052        let Some(exotic) = object.exotic() else {
6053            return Ok(lookup_key(object, key));
6054        };
6055        Ok(match exotic.get_own_property(self, object, key)? {
6056            Some(Some(property)) => Some((object.clone(), property)),
6057            Some(None) => lookup_key_above(object, key),
6058            None => lookup_key(object, key),
6059        })
6060    }
6061
6062    /// Delete `object[key]`.
6063    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6064        self.delete_property_key(object, &PropertyKey::from(key))
6065    }
6066
6067    /// [`Interp::delete_property`] with a key that may be a symbol.
6068    pub fn delete_property_key(
6069        &mut self,
6070        object: &Gc<JsObject>,
6071        key: &PropertyKey,
6072    ) -> JsResult<bool> {
6073        // A proxy decides for itself, and may even throw; the invariant checks live in
6074        // `proxy_delete`.
6075        if let Some(answer) = self.proxy_delete(object, key)? {
6076            return Ok(answer);
6077        }
6078        // A host class's `delete_property` trap decides; `false` is a refusal, which the
6079        // caller reports as a failed delete.
6080        if let Some(exotic) = object.exotic()
6081            && let Some(answer) = exotic.delete_property(self, object, key)?
6082        {
6083            return Ok(answer);
6084        }
6085        // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6086        // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6087        // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6088        // one answers `false` because the elements are non-configurable. The prototype
6089        // chain is not consulted either, which is what makes a throwing getter on
6090        // `TypedArray.prototype["-1"]` stay unrun.
6091        if object.typed_array_parts().is_some()
6092            && object.proxy_state().is_none()
6093            && let Some(numeric) = canonical_numeric_index(key)
6094        {
6095            return Ok(!typed_array_index_is_valid(object, numeric));
6096        }
6097        let mapped_index = key.as_str().and_then(array_index);
6098        if let Some(index) = mapped_index
6099            && let Some(length) = object.array_length()
6100            && (index as usize) < length
6101        {
6102            // An accessor defined on an index lives in the property table rather than the
6103            // element vector, so both have to be cleared: `delete` after
6104            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6105            object.delete_key(key);
6106            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6107            // index stops answering `in`.
6108            if object.element_is_undeletable(index) {
6109                return Ok(false);
6110            }
6111            // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6112            // so a later `defineProperty(arguments, "0", {value})` writes to the object
6113            // and no longer through to the parameter. A refused delete leaves the
6114            // mapping alone.
6115            object.drop_mapped_argument(index as usize);
6116            object.array_set(self.heap, index as usize, Value::Hole);
6117            return Ok(true);
6118        }
6119        // The same for an object that is not an array: only a delete that actually
6120        // removed the property ends the alias.
6121        let deleted = object.delete_key(key);
6122        if deleted && let Some(index) = mapped_index {
6123            object.drop_mapped_argument(index as usize);
6124        }
6125        Ok(deleted)
6126    }
6127
6128    // -- proxy traps --------------------------------------------------------
6129    //
6130    // A proxy's internal methods all look the same: ask the handler for the trap, call it
6131    // with the target and the operation's own arguments, then check the answer against
6132    // the target. The checks are not decoration — they are what stops a proxy from
6133    // reporting a `non-configurable` property as missing, which would let a frozen object
6134    // be rewritten by standing in front of it.
6135
6136    /// The target and handler of `object`, or `None` when it is not a proxy.
6137    ///
6138    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6139    /// one has to fail: the slots the traps would have been read from are gone.
6140    fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6141        let Some(state) = object.proxy_state() else {
6142            return Ok(None);
6143        };
6144        let state = state.borrow();
6145        match (&state.target, &state.handler) {
6146            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
6147            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
6148        }
6149    }
6150
6151    /// Call `handler[name]`, or answer `None` when the trap is absent.
6152    ///
6153    /// A trap that is present but not callable is a `TypeError` rather than "no trap":
6154    /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
6155    /// back to the target.
6156    fn proxy_trap(
6157        &mut self,
6158        handler: &Value,
6159        name: &str,
6160        args: Vec<Value>,
6161    ) -> JsResult<Option<Value>> {
6162        let Value::Object(table) = handler else {
6163            return Err(self.type_error("proxy handler is not an object"));
6164        };
6165        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
6166        match trap {
6167            Value::Undefined => Ok(None),
6168            Value::Object(function) if function.is_callable() => {
6169                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
6170                Ok(Some(answer))
6171            }
6172            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
6173        }
6174    }
6175
6176    /// Whether `object`'s own property `key` is one the target refuses to lose.
6177    ///
6178    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
6179    /// its value behind the target's back. This goes through
6180    /// [`Self::ordinary_own_property`] rather than the property table so that an array's
6181    /// elements and its `length` — both fixed, both outside the table — are covered.
6182    fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
6183        Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
6184    }
6185
6186    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
6187    fn proxy_get(
6188        &mut self,
6189        object: &Gc<JsObject>,
6190        receiver: &Value,
6191        key: &PropertyKey,
6192    ) -> JsResult<Option<Value>> {
6193        let Some((target, handler)) = self.proxy_parts(object)? else {
6194            return Ok(None);
6195        };
6196        let key_value = self.key_value(key);
6197        let Some(result) = self.proxy_trap(
6198            &handler,
6199            "get",
6200            vec![Value::Object(target.clone()), key_value, receiver.clone()],
6201        )?
6202        else {
6203            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
6204            // inherited getter still sees the proxy.
6205            return Ok(Some(
6206                self.get_property_key_for(&target, Some(receiver), key)?
6207                    .unwrap_or(Value::Undefined),
6208            ));
6209        };
6210        if let Some(fixed) = Self::is_fixed_property(&target, key) {
6211            if fixed.is_accessor() {
6212                // A fixed accessor with no getter must read as `undefined`.
6213                let has_getter = fixed
6214                    .getter
6215                    .as_ref()
6216                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
6217                if !has_getter && !matches!(result, Value::Undefined) {
6218                    return Err(self.type_error(format!(
6219                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
6220                    )));
6221                }
6222            } else if !fixed.writable {
6223                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6224                if !fixed_value.same_value(&result) {
6225                    return Err(self.type_error(format!(
6226                        "proxy 'get' disagrees with the non-configurable property '{key}'"
6227                    )));
6228                }
6229            }
6230        }
6231        Ok(Some(result))
6232    }
6233
6234    /// `[[Set]]` on a proxy.
6235    ///
6236    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
6237    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
6238    /// read-only store has.
6239    fn proxy_set(
6240        &mut self,
6241        object: &Gc<JsObject>,
6242        key: &PropertyKey,
6243        value: Value,
6244        receiver: &Value,
6245    ) -> JsResult<Option<bool>> {
6246        let Some((target, handler)) = self.proxy_parts(object)? else {
6247            return Ok(None);
6248        };
6249        let key_value = self.key_value(key);
6250        let Some(result) = self.proxy_trap(
6251            &handler,
6252            "set",
6253            vec![
6254                Value::Object(target.clone()),
6255                key_value,
6256                value.clone(),
6257                receiver.clone(),
6258            ],
6259        )?
6260        else {
6261            // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
6262            // given — not the target. `OrdinarySet` step 3 is
6263            // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
6264            // object whose prototype is a typed array has to reach the proxy's own
6265            // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
6266            // calls and expects exactly one. Storing on the target instead put the value
6267            // in the target and never consulted the trap.
6268            let accepted = self.ordinary_set_with_receiver(
6269                &target,
6270                receiver,
6271                key,
6272                value,
6273                DeleteFailure::Ignore,
6274            )?;
6275            return Ok(Some(accepted));
6276        };
6277        if !result.to_boolean() {
6278            return Ok(Some(false));
6279        }
6280        if let Some(fixed) = Self::is_fixed_property(&target, key) {
6281            if fixed.is_accessor() {
6282                let has_setter = fixed
6283                    .setter
6284                    .as_ref()
6285                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
6286                if !has_setter {
6287                    return Err(self.type_error(format!(
6288                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
6289                    )));
6290                }
6291            } else if !fixed.writable {
6292                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6293                if !fixed_value.same_value(&value) {
6294                    return Err(self.type_error(format!(
6295                        "proxy 'set' changed the non-configurable property '{key}'"
6296                    )));
6297                }
6298            }
6299        }
6300        // A new property cannot appear on a target that refuses new properties.
6301        if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
6302            return Err(self.type_error(format!(
6303                "proxy 'set' added '{key}' to a non-extensible target"
6304            )));
6305        }
6306        Ok(Some(true))
6307    }
6308
6309    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
6310    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6311        let Some((target, handler)) = self.proxy_parts(object)? else {
6312            return Ok(None);
6313        };
6314        let key_value = self.key_value(key);
6315        let Some(result) = self.proxy_trap(
6316            &handler,
6317            "has",
6318            vec![Value::Object(target.clone()), key_value],
6319        )?
6320        else {
6321            return Ok(Some(self.has_own_or_inherited(&target, key)?));
6322        };
6323        if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
6324            return Err(self.type_error(format!(
6325                "proxy 'has' denied the non-configurable property '{key}'"
6326            )));
6327        }
6328        // A non-extensible target cannot grow, so every own property it *has* is fixed.
6329        if !result.to_boolean()
6330            && !target.is_extensible()
6331            && Self::ordinary_own_property(&target, key).is_some()
6332        {
6333            return Err(self.type_error(format!(
6334                "proxy 'has' denied the own property '{key}' of a non-extensible target"
6335            )));
6336        }
6337        Ok(Some(result.to_boolean()))
6338    }
6339
6340    /// `[[Delete]]` on a proxy.
6341    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6342        let Some((target, handler)) = self.proxy_parts(object)? else {
6343            return Ok(None);
6344        };
6345        let key_value = self.key_value(key);
6346        let Some(result) = self.proxy_trap(
6347            &handler,
6348            "deleteProperty",
6349            vec![Value::Object(target.clone()), key_value],
6350        )?
6351        else {
6352            return Ok(Some(self.delete_property_key(&target, key)?));
6353        };
6354        if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
6355            return Err(self.type_error(format!(
6356                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
6357            )));
6358        }
6359        if result.to_boolean()
6360            && !target.is_extensible()
6361            && Self::ordinary_own_property(&target, key).is_some()
6362        {
6363            return Err(self.type_error(format!(
6364                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
6365            )));
6366        }
6367        Ok(Some(result.to_boolean()))
6368    }
6369
6370    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
6371    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
6372        let Some((target, handler)) = self.proxy_parts(object)? else {
6373            return Ok(None);
6374        };
6375        let Some(result) =
6376            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
6377        else {
6378            // No trap: the target's own keys, already in the order an object reports.
6379            return Ok(Some(self.object_own_property_keys(&target)?));
6380        };
6381        // `CreateListFromArrayLike` with the string-or-symbol restriction.
6382        let list = self.list_from_array_like(&result, true)?;
6383        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
6384        for value in list {
6385            let key = self.propkey(&value)?;
6386            if keys.contains(&key) {
6387                return Err(self.type_error(format!(
6388                    "proxy 'ownKeys' returned the duplicate key '{key}'"
6389                )));
6390            }
6391            keys.push(key);
6392        }
6393        for (key, property) in target.property_entries() {
6394            if !property.configurable && !keys.contains(&key) {
6395                return Err(self.type_error(format!(
6396                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
6397                )));
6398            }
6399            if !target.is_extensible() && !keys.contains(&key) {
6400                return Err(self.type_error(format!(
6401                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
6402                )));
6403            }
6404        }
6405        if !target.is_extensible() {
6406            let own = target.property_entries().len();
6407            if keys.len() != own {
6408                return Err(
6409                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
6410                );
6411            }
6412        }
6413        Ok(Some(keys))
6414    }
6415
6416    /// `[[GetOwnProperty]]` on a proxy.
6417    fn proxy_get_own_property(
6418        &mut self,
6419        object: &Gc<JsObject>,
6420        key: &PropertyKey,
6421    ) -> JsResult<Option<Option<Property>>> {
6422        let Some((target, handler)) = self.proxy_parts(object)? else {
6423            return Ok(None);
6424        };
6425        let key_value = self.key_value(key);
6426        let Some(result) = self.proxy_trap(
6427            &handler,
6428            "getOwnPropertyDescriptor",
6429            vec![Value::Object(target.clone()), key_value],
6430        )?
6431        else {
6432            // No trap: the target's own descriptor is the answer. This has to go through
6433            // the same synthesis an ordinary object gets, because a proxy's own property
6434            // table is empty by design — reading it directly reported `undefined` for
6435            // every key, including an array's indices and `length`.
6436            return Ok(Some(Self::ordinary_own_property(&target, key)));
6437        };
6438        let answer = if matches!(result, Value::Undefined) {
6439            None
6440        } else {
6441            Some(self.property_from_descriptor(&result)?)
6442        };
6443        let fixed = Self::is_fixed_property(&target, key);
6444        match (&answer, &fixed) {
6445            // A non-configurable property cannot be reported as absent.
6446            (None, Some(_)) => {
6447                return Err(self.type_error(format!(
6448                    "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
6449                )));
6450            }
6451            (Some(descriptor), Some(fixed)) => {
6452                if descriptor.configurable {
6453                    return Err(self.type_error(format!(
6454                        "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
6455                    )));
6456                }
6457                if fixed.is_accessor() != descriptor.is_accessor() {
6458                    return Err(self.type_error(format!(
6459                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6460                    )));
6461                }
6462                if !fixed.is_accessor() && !fixed.writable {
6463                    let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
6464                    let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
6465                    if !fixed_value.same_value(&reported) {
6466                        return Err(self.type_error(format!(
6467                            "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
6468                        )));
6469                    }
6470                }
6471            }
6472            _ => {}
6473        }
6474        Ok(Some(answer))
6475    }
6476
6477    /// `[[DefineOwnProperty]]` on a proxy.
6478    fn proxy_define_property(
6479        &mut self,
6480        object: &Gc<JsObject>,
6481        key: &PropertyKey,
6482        property: Property,
6483    ) -> JsResult<Option<bool>> {
6484        let Some((target, handler)) = self.proxy_parts(object)? else {
6485            return Ok(None);
6486        };
6487        let key_value = self.key_value(key);
6488        let descriptor = self.descriptor_from_property(&property);
6489        let Some(result) = self.proxy_trap(
6490            &handler,
6491            "defineProperty",
6492            vec![Value::Object(target.clone()), key_value, descriptor],
6493        )?
6494        else {
6495            return Ok(None);
6496        };
6497        if !result.to_boolean() {
6498            return Ok(Some(false));
6499        }
6500        let fixed = Self::is_fixed_property(&target, key);
6501        let creating = Self::ordinary_own_property(&target, key).is_none();
6502        if creating && !target.is_extensible() {
6503            return Err(self.type_error(format!(
6504                "proxy 'defineProperty' added '{key}' to a non-extensible target"
6505            )));
6506        }
6507        if let Some(fixed) = fixed {
6508            if property.configurable {
6509                return Err(self.type_error(format!(
6510                    "proxy 'defineProperty' made the non-configurable '{key}' configurable"
6511                )));
6512            }
6513            if !fixed.writable && property.writable && !fixed.is_accessor() {
6514                return Err(self.type_error(format!(
6515                    "proxy 'defineProperty' made the read-only '{key}' writable"
6516                )));
6517            }
6518        }
6519        Ok(Some(true))
6520    }
6521
6522    /// `[[GetPrototypeOf]]` on a proxy.
6523    fn proxy_get_prototype_of(
6524        &mut self,
6525        object: &Gc<JsObject>,
6526    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
6527        let Some((target, handler)) = self.proxy_parts(object)? else {
6528            return Ok(None);
6529        };
6530        let Some(result) = self.proxy_trap(
6531            &handler,
6532            "getPrototypeOf",
6533            vec![Value::Object(target.clone())],
6534        )?
6535        else {
6536            return Ok(Some(target.proto()));
6537        };
6538        let proto = match &result {
6539            Value::Null => None,
6540            Value::Object(proto) => Some(proto.clone()),
6541            _ => {
6542                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
6543            }
6544        };
6545        if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
6546            return Err(self.type_error(
6547                "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
6548            ));
6549        }
6550        Ok(Some(proto))
6551    }
6552
6553    /// `[[SetPrototypeOf]]` on a proxy.
6554    fn proxy_set_prototype_of(
6555        &mut self,
6556        object: &Gc<JsObject>,
6557        proto: Option<Gc<JsObject>>,
6558    ) -> JsResult<Option<bool>> {
6559        let Some((target, handler)) = self.proxy_parts(object)? else {
6560            return Ok(None);
6561        };
6562        let proto_value = match &proto {
6563            Some(proto) => Value::Object(proto.clone()),
6564            None => Value::Null,
6565        };
6566        let Some(result) = self.proxy_trap(
6567            &handler,
6568            "setPrototypeOf",
6569            vec![Value::Object(target.clone()), proto_value],
6570        )?
6571        else {
6572            target.set_proto(proto);
6573            return Ok(Some(true));
6574        };
6575        if result.to_boolean()
6576            && !target.is_extensible()
6577            && !same_proto(proto.as_ref(), target.proto().as_ref())
6578        {
6579            return Err(self.type_error(
6580                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
6581            ));
6582        }
6583        Ok(Some(result.to_boolean()))
6584    }
6585
6586    /// `[[IsExtensible]]` on a proxy.
6587    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6588        let Some((target, handler)) = self.proxy_parts(object)? else {
6589            return Ok(None);
6590        };
6591        let Some(result) = self.proxy_trap(
6592            &handler,
6593            "isExtensible",
6594            vec![Value::Object(target.clone())],
6595        )?
6596        else {
6597            return Ok(Some(target.is_extensible()));
6598        };
6599        // The answer is not the proxy's to invent: it must agree with the target, or a
6600        // script could learn `false` while the target keeps accepting new properties.
6601        if result.to_boolean() != target.is_extensible() {
6602            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
6603        }
6604        Ok(Some(result.to_boolean()))
6605    }
6606
6607    /// `[[PreventExtensions]]` on a proxy.
6608    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6609        let Some((target, handler)) = self.proxy_parts(object)? else {
6610            return Ok(None);
6611        };
6612        let Some(result) = self.proxy_trap(
6613            &handler,
6614            "preventExtensions",
6615            vec![Value::Object(target.clone())],
6616        )?
6617        else {
6618            target.set_extensible(false);
6619            return Ok(Some(true));
6620        };
6621        if result.to_boolean() && target.is_extensible() {
6622            return Err(self.type_error(
6623                "proxy 'preventExtensions' reported success but the target is still extensible",
6624            ));
6625        }
6626        Ok(Some(result.to_boolean()))
6627    }
6628
6629    /// `[[Call]]` on a proxy, through the `apply` trap.
6630    fn proxy_apply(
6631        &mut self,
6632        object: &Gc<JsObject>,
6633        this: Value,
6634        args: Vec<Value>,
6635    ) -> JsResult<Option<Value>> {
6636        let Some((target, handler)) = self.proxy_parts(object)? else {
6637            return Ok(None);
6638        };
6639        // The trap gets the arguments as one array, which is the shape the spec passes
6640        // and the shape `apply` traps are written against (`args[0]` is the first one).
6641        let arguments = self.new_array(args.clone());
6642        let this_for_trap = this.clone();
6643        let Some(result) = self.proxy_trap(
6644            &handler,
6645            "apply",
6646            vec![
6647                Value::Object(target.clone()),
6648                this_for_trap,
6649                Value::Object(arguments),
6650            ],
6651        )?
6652        else {
6653            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
6654        };
6655        Ok(Some(result))
6656    }
6657
6658    /// `[[Construct]]` on a proxy, through the `construct` trap.
6659    fn proxy_construct(
6660        &mut self,
6661        object: &Gc<JsObject>,
6662        args: Vec<Value>,
6663        new_target: &Value,
6664    ) -> JsResult<Option<Value>> {
6665        let Some((target, handler)) = self.proxy_parts(object)? else {
6666            return Ok(None);
6667        };
6668        if !target.is_callable() {
6669            return Err(self.type_error("proxy target is not a constructor"));
6670        }
6671        let arguments = self.new_array(args.clone());
6672        let Some(result) = self.proxy_trap(
6673            &handler,
6674            "construct",
6675            vec![
6676                Value::Object(target.clone()),
6677                Value::Object(arguments),
6678                new_target.clone(),
6679            ],
6680        )?
6681        else {
6682            return Ok(Some(self.construct(
6683                Value::Object(target),
6684                new_target.clone(),
6685                args,
6686            )?));
6687        };
6688        if !matches!(result, Value::Object(_)) {
6689            return Err(self.type_error("proxy 'construct' must return an object"));
6690        }
6691        Ok(Some(result))
6692    }
6693
6694    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
6695    pub(crate) fn has_own_or_inherited(
6696        &mut self,
6697        object: &Gc<JsObject>,
6698        key: &PropertyKey,
6699    ) -> JsResult<bool> {
6700        // The object itself first: it may be a proxy, and then the answer is its trap's.
6701        if let Some(answer) = self.proxy_has(object, key)? {
6702            return Ok(answer);
6703        }
6704        // An integer-indexed exotic object answers a canonical numeric index from
6705        // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
6706        // prototype chain. That is observable twice: a view the buffer has been resized
6707        // away from has no indices, so `2 in view` is `false` even when
6708        // `Object.getPrototypeOf(view)[2]` exists (what
6709        // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
6710        // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
6711        // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
6712        // goes through here, which is why the same rule is repeated in `has_property_key`
6713        // rather than living only there.
6714        if object.typed_array_parts().is_some()
6715            && let Some(numeric) = canonical_numeric_index(key)
6716        {
6717            return Ok(typed_array_index_is_valid(object, numeric));
6718        }
6719        // A host class answers `in` for its own keys, which may live nowhere in a property
6720        // table — `"x" in point` is true because the class says so, not because a property
6721        // exists.
6722        if let Some(exotic) = object.exotic()
6723            && let Some(answer) = exotic.has_property(self, object, key)?
6724        {
6725            return Ok(answer);
6726        }
6727        // `has_own` rather than `own_property_key`: an array's elements and its derived
6728        // `length` are invisible to the property table, and `Array.prototype` is an array.
6729        // A host class's `get_own_property` counts too, because the reference's
6730        // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
6731        // lives — a class with only `get_own_property` answers `in` through it.
6732        if self.exotic_has_own(object, key)? {
6733            return Ok(true);
6734        }
6735        // A hole is *not* the end of the search: the chain may still have the key, which
6736        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
6737        for ancestor in object.chain() {
6738            // A proxy further up the chain answers for itself.
6739            if let Some(answer) = self.proxy_has(&ancestor, key)? {
6740                return Ok(answer);
6741            }
6742            // Same for a host class: a prototype may be one, and `in` reaches it.
6743            if let Some(exotic) = ancestor.exotic()
6744                && let Some(answer) = exotic.has_property(self, &ancestor, key)?
6745            {
6746                return Ok(answer);
6747            }
6748            if self.exotic_has_own(&ancestor, key)? {
6749                return Ok(true);
6750            }
6751        }
6752        Ok(false)
6753    }
6754
6755    /// Whether `object` reports `key` as an own property, its class's `get_own_property`
6756    /// trap included.
6757    ///
6758    /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
6759    /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
6760    fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
6761        if let Some(exotic) = object.exotic()
6762            && let Some(answer) = exotic.get_own_property(self, object, key)?
6763        {
6764            return Ok(answer.is_some());
6765        }
6766        Ok(has_own(object, key))
6767    }
6768
6769    /// `CreateListFromArrayLike`, optionally restricted to property keys.
6770    ///
6771    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
6772    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
6773    /// `TypeError` instead of a property named `"1.5"`.
6774    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
6775        let object = self.object_from(value)?;
6776        let length = self
6777            .get_property(&object, "length")?
6778            .map(|value| value.to_number())
6779            .unwrap_or(0.0);
6780        if !length.is_finite() || length < 0.0 {
6781            return Err(self.type_error("invalid array-like length"));
6782        }
6783        let length = length as usize;
6784        let mut items = Vec::with_capacity(length.min(1024));
6785        for index in 0..length {
6786            let item = self
6787                .get_property(&object, &index.to_string())?
6788                .unwrap_or(Value::Undefined);
6789            if keys_only && matches!(&item, Value::Symbol(_)) {
6790                items.push(item);
6791                continue;
6792            }
6793            if keys_only && !matches!(&item, Value::String(_)) {
6794                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
6795            }
6796            items.push(item);
6797        }
6798        Ok(items)
6799    }
6800
6801    /// A `Property` from the descriptor object a trap returned.
6802    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
6803        let object = self.object_from(value)?;
6804        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
6805            interp.get_property(&object, name)
6806        };
6807        let getter = field(self, "get")?;
6808        let setter = field(self, "set")?;
6809        let accessor = getter.is_some() || setter.is_some();
6810        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
6811            Ok(interp
6812                .get_property(&object, name)?
6813                .is_some_and(|value| value.to_boolean()))
6814        };
6815        let enumerable = boolean(self, "enumerable")?;
6816        let configurable = boolean(self, "configurable")?;
6817        if accessor {
6818            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
6819                return Err(
6820                    self.type_error("a descriptor cannot be both a data property and an accessor")
6821                );
6822            }
6823            Ok(Property {
6824                getter: getter.or(Some(Value::Undefined)),
6825                setter: setter.or(Some(Value::Undefined)),
6826                enumerable,
6827                configurable,
6828                writable: false,
6829                value: None,
6830            })
6831        } else {
6832            Ok(Property {
6833                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
6834                writable: boolean(self, "writable")?,
6835                enumerable,
6836                configurable,
6837                getter: None,
6838                setter: None,
6839            })
6840        }
6841    }
6842
6843    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
6844    fn descriptor_from_property(&mut self, property: &Property) -> Value {
6845        let object = self.new_object(None);
6846        if property.is_accessor() {
6847            let getter = property.getter.clone().unwrap_or(Value::Undefined);
6848            let setter = property.setter.clone().unwrap_or(Value::Undefined);
6849            object.define_data("get", getter);
6850            object.define_data("set", setter);
6851        } else {
6852            let value = property.value.clone().unwrap_or(Value::Undefined);
6853            object.define_data("value", value);
6854            object.define_data("writable", Value::Bool(property.writable));
6855        }
6856        object.define_data("enumerable", Value::Bool(property.enumerable));
6857        object.define_data("configurable", Value::Bool(property.configurable));
6858        Value::Object(object)
6859    }
6860
6861    // -- calling ------------------------------------------------------------
6862
6863    /// Call `callee` with `this` and `args`.
6864    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
6865        let Value::Object(function) = &callee else {
6866            // `typeof x === "function"` is not enough to make `x()` legal: only a
6867            // callable object is. `null` and `undefined` need no special wording
6868            // here — their `ToString` already reads the way the reference's does.
6869            let what = format!("{} is not a function", callee.to_js_string());
6870            return Err(Signal::Throw(self.make_error("TypeError", &what)));
6871        };
6872        // A proxy of a function is called through its `apply` trap. It has no
6873        // `ObjectKind::Function` of its own, so this has to come before the dispatch
6874        // below, and a proxy of a non-function has nothing to forward to.
6875        if function.proxy_state().is_some() {
6876            return match self.proxy_apply(function, this, args)? {
6877                Some(result) => Ok(result),
6878                None => Err(Signal::Throw(
6879                    self.make_error("TypeError", "proxy target is not callable"),
6880                )),
6881            };
6882        }
6883        let callable = function.with(|data| match &data.kind {
6884            ObjectKind::Function(callable) => match callable {
6885                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
6886                // The `Rc` is cloned out so the borrow of this object's data is released
6887                // before the closure runs: the closure may touch the same object.
6888                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
6889                Callable::Bound {
6890                    target,
6891                    this,
6892                    args: leading,
6893                } => Some(NativeCall::Bound {
6894                    target: target.clone(),
6895                    this: this.clone(),
6896                    leading: leading.clone(),
6897                }),
6898                Callable::Bytecode { code, env } => {
6899                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
6900                }
6901                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
6902                Callable::PromiseResolve(promise) => {
6903                    Some(NativeCall::PromiseResolve(promise.clone()))
6904                }
6905                Callable::PromiseReject(promise) => {
6906                    Some(NativeCall::PromiseReject(promise.clone()))
6907                }
6908                Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
6909                    state: state.clone(),
6910                }),
6911                Callable::ThenShim {
6912                    handler,
6913                    resolve,
6914                    reject,
6915                    fulfilled,
6916                } => Some(NativeCall::ThenShim {
6917                    handler: handler.clone(),
6918                    resolve: resolve.clone(),
6919                    reject: reject.clone(),
6920                    fulfilled: *fulfilled,
6921                }),
6922                Callable::AwaitResume {
6923                    coroutine,
6924                    promise,
6925                    kind,
6926                } => Some(NativeCall::AwaitResume {
6927                    coroutine: coroutine.clone(),
6928                    promise: promise.clone(),
6929                    kind: *kind,
6930                }),
6931                Callable::CombinatorSettle {
6932                    state,
6933                    index,
6934                    fulfilled,
6935                } => Some(NativeCall::CombinatorSettle {
6936                    state: state.clone(),
6937                    index: *index,
6938                    fulfilled: *fulfilled,
6939                }),
6940                Callable::FinallyShim {
6941                    callback,
6942                    fulfilled,
6943                    constructor,
6944                } => Some(NativeCall::FinallyShim {
6945                    callback: callback.clone(),
6946                    fulfilled: *fulfilled,
6947                    constructor: constructor.clone(),
6948                }),
6949                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
6950                Callable::CompletedReturn {
6951                    generator,
6952                    promise,
6953                    rejected,
6954                } => Some(NativeCall::CompletedReturn {
6955                    generator: generator.clone(),
6956                    promise: promise.clone(),
6957                    rejected: *rejected,
6958                }),
6959                Callable::YieldResult {
6960                    generator,
6961                    promise,
6962                    done,
6963                } => Some(NativeCall::YieldResult {
6964                    generator: generator.clone(),
6965                    promise: promise.clone(),
6966                    done: *done,
6967                }),
6968                Callable::DisposeStep {
6969                    remaining,
6970                    promise,
6971                    error,
6972                    rejected,
6973                } => Some(NativeCall::DisposeStep {
6974                    remaining: remaining.clone(),
6975                    promise: promise.clone(),
6976                    error: error.clone(),
6977                    rejected: *rejected,
6978                }),
6979                Callable::GeneratorResume {
6980                    generator,
6981                    promise,
6982                    kind,
6983                } => Some(NativeCall::GeneratorResume {
6984                    generator: generator.clone(),
6985                    promise: promise.clone(),
6986                    kind: *kind,
6987                }),
6988                Callable::SettlePromise {
6989                    promise,
6990                    value,
6991                    rejected,
6992                } => Some(NativeCall::SettlePromise {
6993                    promise: promise.clone(),
6994                    value: value.clone(),
6995                    rejected: *rejected,
6996                }),
6997            },
6998            _ => None,
6999        });
7000        match callable {
7001            Some(NativeCall::Host(func)) => {
7002                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
7003                // function by name rather than stopping at the caller.
7004                let frame_less = function
7005                    .own_property("_frame_less")
7006                    .and_then(|property| property.value)
7007                    .is_some_and(|value| value.to_boolean());
7008                let outer = if frame_less {
7009                    None
7010                } else {
7011                    self.native_frames
7012                        .push((function.clone(), self.frames.len()));
7013                    Some(self.current_native.replace(function.clone()))
7014                };
7015                let result = {
7016                    let mut body = func.borrow_mut();
7017                    body(self, this, &args)
7018                };
7019                if !frame_less {
7020                    self.native_frames.pop();
7021                    self.current_native = outer.flatten();
7022                }
7023                result
7024            }
7025            Some(NativeCall::Native(func)) => {
7026                // A function marked `_frame_less` is one the reference implements
7027                // without a call frame — `eval` is the only one so far.
7028                let frame_less = function
7029                    .own_property("_frame_less")
7030                    .and_then(|property| property.value)
7031                    .is_some_and(|value| value.to_boolean());
7032                let outer = if frame_less {
7033                    None
7034                } else {
7035                    self.native_frames
7036                        .push((function.clone(), self.frames.len()));
7037                    Some(self.current_native.replace(function.clone()))
7038                };
7039                let result = func(self, this, &args);
7040                if !frame_less {
7041                    self.native_frames.pop();
7042                    self.current_native = outer.flatten();
7043                }
7044                result
7045            }
7046            Some(NativeCall::Revoker(slots)) => {
7047                // Idempotent: revoking twice answers `undefined` again rather than
7048                // complaining, which is what the spec says and what a `finally` block
7049                // relies on.
7050                let mut state = slots.borrow_mut();
7051                state.target = None;
7052                state.handler = None;
7053                Ok(Value::Undefined)
7054            }
7055            Some(NativeCall::PromiseResolve(promise)) => {
7056                // One-shot: a second call is silently ignored, which
7057                // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
7058                let value = args.first().cloned().unwrap_or(Value::Undefined);
7059                self.resolve_promise_with(&promise, value)?;
7060                Ok(Value::Undefined)
7061            }
7062            Some(NativeCall::PromiseReject(promise)) => {
7063                let reason = args.first().cloned().unwrap_or(Value::Undefined);
7064                self.reject_promise(&promise, reason);
7065                Ok(Value::Undefined)
7066            }
7067            Some(NativeCall::ThenShim {
7068                handler,
7069                resolve,
7070                reject,
7071                fulfilled,
7072            }) => {
7073                // `PerformPromiseThen` with a capability: run the handler, then settle
7074                // through the capability's own pair. A throw from the handler is the
7075                // rejection, and a throw from the capability's `resolve` is not caught —
7076                // exactly the spec's `?`.
7077                let value = args.first().cloned().unwrap_or(Value::Undefined);
7078                match handler {
7079                    Some(handler) => {
7080                        match self.call_value(handler, Value::Undefined, vec![value]) {
7081                            Ok(result) => {
7082                                self.call_value(resolve, Value::Undefined, vec![result])?;
7083                            }
7084                            Err(Signal::Throw(reason)) => {
7085                                self.call_value(reject, Value::Undefined, vec![reason])?;
7086                            }
7087                            Err(signal) => return Err(signal),
7088                        }
7089                    }
7090                    None => {
7091                        let handler = if fulfilled { resolve } else { reject };
7092                        self.call_value(handler, Value::Undefined, vec![value])?;
7093                    }
7094                }
7095                Ok(Value::Undefined)
7096            }
7097            Some(NativeCall::CapabilityExecutor { state }) => {
7098                // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
7099                // slot holds a value yet. The test is on the *values*, not on a call count —
7100                // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
7101                // called-twice`'s first case does exactly that), while a second call after a
7102                // real pair is the `TypeError`.
7103                let defined = |name: &str| {
7104                    state
7105                        .own_property(name)
7106                        .and_then(|property| property.value)
7107                        .is_some_and(|value| !matches!(value, Value::Undefined))
7108                };
7109                if defined("resolve") || defined("reject") {
7110                    return Err(self.type_error("promise capability executor called twice"));
7111                }
7112                let resolve = args.first().cloned().unwrap_or(Value::Undefined);
7113                let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
7114                state.define_data("resolve", resolve);
7115                state.define_data("reject", reject);
7116                Ok(Value::Undefined)
7117            }
7118            Some(NativeCall::CombinatorSettle {
7119                state,
7120                index,
7121                fulfilled,
7122            }) => {
7123                let value = args.first().cloned().unwrap_or(Value::Undefined);
7124                self.settle_combinator(&state, index, fulfilled, value)?;
7125                Ok(Value::Undefined)
7126            }
7127            Some(NativeCall::AwaitResume {
7128                coroutine,
7129                promise,
7130                kind,
7131            }) => {
7132                // Resume *inline*, in the reaction that delivered the value. Deferring it
7133                // by another job inserts a tick between every `await` and its
7134                // continuation, which reorders `await` against unrelated `then` chains —
7135                // `f().then(g)` then runs before `f`'s own next statement.
7136                self.drive_async(
7137                    &coroutine,
7138                    &promise,
7139                    kind,
7140                    args.first().cloned().unwrap_or(Value::Undefined),
7141                )
7142                .map(|()| Value::Undefined)
7143            }
7144            Some(NativeCall::FinallyShim {
7145                callback,
7146                fulfilled,
7147                constructor,
7148            }) => {
7149                // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
7150                // that settles with the *original* outcome once the callback's result has
7151                // settled. The callback's own value is discarded — that is the whole
7152                // difference between `finally` and `then`.
7153                let original = args.first().cloned().unwrap_or(Value::Undefined);
7154                let result = match &callback {
7155                    Some(callback) => {
7156                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
7157                    }
7158                    None => Value::Undefined,
7159                };
7160                // `PromiseResolve(C, result)`, not the intrinsic: a `result` that is
7161                // already a promise of this constructor is reused rather than rewrapped.
7162                let resolved = self.promise_resolve_for(&constructor, result)?;
7163                let Value::Object(resolved) = resolved else {
7164                    return Ok(original);
7165                };
7166                // The wait is a chained promise rather than a bare return, so a callback
7167                // that returns a slow promise really does delay the continuation.
7168                let waiting = self.new_promise();
7169                let pass = JsObject::function(
7170                    self.heap,
7171                    Some(self.realm.function_proto.clone()),
7172                    Callable::SettlePromise {
7173                        promise: waiting.clone(),
7174                        value: original,
7175                        rejected: !fulfilled,
7176                    },
7177                );
7178                let pass = Value::Object(pass);
7179                // Whichever way the callback's promise settles, the original outcome wins.
7180                self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
7181                Ok(Value::Object(waiting))
7182            }
7183            Some(NativeCall::DisposeStep {
7184                remaining,
7185                promise,
7186                error,
7187                rejected,
7188            }) => {
7189                let error = if rejected {
7190                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
7191                    self.merge_dispose_error(reason, error)
7192                } else {
7193                    error
7194                };
7195                self.dispose_step(&remaining, &promise, error)?;
7196                Ok(Value::Undefined)
7197            }
7198            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
7199            Some(NativeCall::CompletedReturn {
7200                generator,
7201                promise,
7202                rejected,
7203            }) => {
7204                let value = args.first().cloned().unwrap_or(Value::Undefined);
7205                let outcome = if rejected {
7206                    AsyncOutcome::Error(value)
7207                } else {
7208                    AsyncOutcome::Value(self.iterator_result(value, true)?)
7209                };
7210                self.settle_async_request(&generator, &promise, outcome)?;
7211                Ok(Value::Undefined)
7212            }
7213            Some(NativeCall::YieldResult {
7214                generator,
7215                promise,
7216                done,
7217            }) => {
7218                let value = args.first().cloned().unwrap_or(Value::Undefined);
7219                let result = self.iterator_result(value, done)?;
7220                self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
7221                Ok(Value::Undefined)
7222            }
7223            Some(NativeCall::GeneratorResume {
7224                generator,
7225                promise,
7226                kind,
7227            }) => {
7228                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
7229                // tick and reorders the generator against other chains.
7230                self.step_async_generator(
7231                    &generator,
7232                    &promise,
7233                    kind,
7234                    args.first().cloned().unwrap_or(Value::Undefined),
7235                )
7236                .map(|()| Value::Undefined)
7237            }
7238            Some(NativeCall::SettlePromise {
7239                promise,
7240                value,
7241                rejected,
7242            }) => {
7243                if rejected {
7244                    self.reject_promise(&promise, value);
7245                } else {
7246                    self.fulfill_promise(&promise, value);
7247                }
7248                Ok(Value::Undefined)
7249            }
7250            Some(NativeCall::Bound {
7251                target,
7252                this: bound_this,
7253                leading,
7254            }) => {
7255                let mut all = leading;
7256                all.extend(args);
7257                self.call_value(target, bound_this, all)
7258            }
7259            Some(NativeCall::Bytecode(code, env)) => {
7260                if code.code.kind.is_generator() {
7261                    return self.new_generator(callee, this, args);
7262                }
7263                if code.code.kind.is_async() {
7264                    // Same coroutine machinery as a generator; the difference is only in
7265                    // what the completion does — see `new_async_function`.
7266                    return self.new_async_function(callee, this, args);
7267                }
7268                self.execute(code, env, this, args, callee)
7269            }
7270            None => Err(Signal::Throw(
7271                self.make_error("TypeError", "not a function"),
7272            )),
7273        }
7274    }
7275
7276    /// Give a freshly built function its own `prototype` object.
7277    ///
7278    /// Every function that can be used with `new` carries one, and its
7279    /// `constructor` points back at the function — a reference cycle, which is
7280    /// exactly what the collector's cycle pass exists to reclaim.
7281    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
7282        let prototype = self.new_object(Some(self.realm.object_proto.clone()));
7283        let constructor = Value::Object(function.clone());
7284        prototype.define(
7285            "constructor",
7286            Property::with_attributes(constructor, true, false),
7287        );
7288        let value = Value::Object(prototype);
7289        function.define("prototype", Property::prototype_of(value, true));
7290    }
7291
7292    /// A getter or setter that reads or writes the reference cell behind a mapped
7293    /// `arguments` index.
7294    ///
7295    /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
7296    /// count — which is what the collector treats as "a reference from outside the
7297    /// heap". The closure therefore keeps the cell alive for exactly as long as the
7298    /// accessor is reachable, which is the same lifetime the arguments object has.
7299    ///
7300    /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
7301    /// borrow would not be reclaimed; that is acceptable here because the cell holds a
7302    /// parameter value and the arguments object reaches the closure, never the other
7303    /// way round. Nothing the collector has to see is hidden.
7304    fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
7305        let name = if is_setter { "set" } else { "get" };
7306        let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
7307            if is_setter {
7308                cell.set(args.first().cloned().unwrap_or(Value::Undefined));
7309                Ok(Value::Undefined)
7310            } else {
7311                Ok(cell.get())
7312            }
7313        };
7314        self.new_host_function(name, 1, Box::new(func))
7315    }
7316
7317    /// The object `special_object` builds.
7318    ///
7319    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
7320    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
7321    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
7322    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
7323    /// write through `arguments` does not reach the parameter.
7324    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
7325        match magic {
7326            0 | 1 => {
7327                let args = self.frame().passed().to_vec();
7328                let proto = self.realm.object_proto.clone();
7329                let object = self.new_object(Some(proto));
7330                // The marker `Object.prototype.toString` needs: an arguments object is an
7331                // ordinary object apart from reporting `[object Arguments]`, and that has
7332                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
7333                // show up ahead of them in a key listing anyway — it is non-enumerable.
7334                self.internal_set(&object, "_class", self.string("Arguments"));
7335                // `length` is writable and configurable but neither enumerable nor a
7336                // plain data property: `Object.keys(arguments)` lists the indices only,
7337                // which is how `{...arguments}` copies them without the length.
7338                object.define(
7339                    "length",
7340                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
7341                );
7342                // `magic == 1` is sloppy mode, where each index is *mapped* to the
7343                // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
7344                // change `a`, and assigning `a` has to change `arguments[0]`.
7345                //
7346                // The shared storage is the parameter's reference cell. The compiler
7347                // gives every parameter of such a function one (see
7348                // `provide_body_arguments`), and the cell outlives the frame, so this
7349                // keeps working after the arguments object escapes.
7350                //
7351                // The index becomes an accessor rather than a data property. A mapped
7352                // index reports as a plain writable/enumerable data property through
7353                // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
7354                // the getter/setter pair is only the plumbing underneath.
7355                let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
7356                    let frame = self.frame();
7357                    frame
7358                        .code
7359                        .arg_cell
7360                        .iter()
7361                        .map(|cell| {
7362                            (*cell >= 0)
7363                                .then(|| frame.cells.get(*cell as usize).cloned())
7364                                .flatten()
7365                        })
7366                        .collect()
7367                } else {
7368                    Vec::new()
7369                };
7370                // Tell the object which indices are mapped, so
7371                // `Object.getOwnPropertyDescriptor` can report them as the data
7372                // properties the spec describes instead of the accessors that
7373                // implement the aliasing.
7374                if magic == 1 {
7375                    let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
7376                    for cell in &mapped_cells {
7377                        table.push(cell.clone());
7378                    }
7379                    object.set_mapped_arguments(table);
7380                }
7381                for (index, value) in args.into_iter().enumerate() {
7382                    match mapped_cells.get(index).cloned().flatten() {
7383                        Some(cell) => {
7384                            let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
7385                            let setter = self.new_mapped_arguments_accessor(cell, true);
7386                            object.define(
7387                                &index.to_string(),
7388                                Property::accessor_with(
7389                                    Some(Value::Object(getter)),
7390                                    Some(Value::Object(setter)),
7391                                    true,
7392                                ),
7393                            );
7394                        }
7395                        None => object.define_data(&index.to_string(), value),
7396                    }
7397                }
7398                // §10.4.4: a *mapped* arguments object carries `callee` as a writable,
7399                // non-enumerable, configurable data property holding the function being
7400                // called. A strict (unmapped) one gets no such property at all; the
7401                // spec's poison-pill accessor for it is unreachable in this engine
7402                // because a strict `arguments.callee` is already a compile-time error.
7403                //
7404                // The legacy `S10.6_*` tests predate that restriction and ask only that
7405                // `arguments.hasOwnProperty("callee")` be true in sloppy mode.
7406                if magic == 1 {
7407                    let callee = self.frame().callee.clone();
7408                    // `{ DontEnum }`: `for (var x in arguments)` must not list it.
7409                    object.define("callee", Property::with_attributes(callee, true, false));
7410                }
7411                // An arguments object is iterable: `[...arguments]` and
7412                // `for (const a of arguments)` both work, through the *array* iterator
7413                // because the object is array-like. Without this the whole spread form
7414                // reported "not iterable".
7415                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
7416                let values = self
7417                    .realm
7418                    .array_proto
7419                    .own_property("values")
7420                    .and_then(|property| property.value);
7421                if let Some(values) = values {
7422                    object.define_key(
7423                        &iterator_key,
7424                        Property::with_attributes(values, true, false),
7425                    );
7426                }
7427                Ok(Value::Object(object))
7428            }
7429            // `this.active_func`: the constructor `super()` resolves against.
7430            //
7431            // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
7432            // own, so it inherits this from the function it was written in along with `this`
7433            // — and that is a lexical relationship, not a stack one: an arrow that escaped
7434            // the constructor and is called back later (`iter.return = () => super()`) has
7435            // the constructor nowhere on the stack. The compiler therefore reads it out of
7436            // a closure variable of the enclosing function, exactly as the reference does
7437            // with its `this_active_func` local.
7438            2 => Ok(self
7439                .current_callee()
7440                .map_or(Value::Undefined, Value::Object)),
7441            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
7442            // inherited from the caller inside an `eval`. An arrow has no `new.target` of
7443            // its own either, so the lookup walks out to the nearest non-arrow frame for
7444            // the same reason as `this.active_func` above — without that, `super()` inside
7445            // an arrow passed `undefined` as the new target and the parent constructor was
7446            // then rejected for being invoked without `new`.
7447            3 => Ok(self
7448                .eval_new_target
7449                .clone()
7450                .unwrap_or_else(|| self.frame().new_target.clone())),
7451            // `[[HomeObject]]` of the function being run: what `super` is relative to.
7452            // An arrow has none of its own, so the lookup walks out to the enclosing
7453            // method — which is why `super` works inside an arrow inside a method.
7454            4 => Ok(self
7455                .frames
7456                .iter()
7457                .rev()
7458                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
7459                .map_or(Value::Undefined, Value::Object)),
7460            // `import.meta`: the innermost module body's meta object. Outside a module
7461            // the compiler never emits this, so an empty fallback is unreachable rather
7462            // than permissive.
7463            6 => {
7464                let name = self.module_stack.last().cloned();
7465                let meta = name
7466                    .and_then(|name| self.modules.get(&name).cloned())
7467                    .and_then(|module| module.with(|r| r.import_meta.clone()));
7468                Ok(meta.map_or(Value::Undefined, Value::Object))
7469            }
7470            other => Err(Signal::Throw(self.make_error(
7471                "InternalError",
7472                &format!("special_object {other} is not implemented yet"),
7473            ))),
7474        }
7475    }
7476
7477    /// `[[HomeObject]]` of the innermost function that has one, if any.
7478    ///
7479    /// An arrow has none, so the search walks out to the enclosing method — the same
7480    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
7481    /// inside a method.
7482    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
7483        self.frames
7484            .iter()
7485            .rev()
7486            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
7487    }
7488
7489    /// The dispose method a `using` declaration should snapshot, or an error.
7490    ///
7491    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
7492    /// is what makes a resource that only knows the synchronous protocol usable in both
7493    /// forms.
7494    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
7495        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
7496        if value.is_nullish() {
7497            return Ok(Value::Undefined);
7498        }
7499        let Some(object) = value.as_object() else {
7500            return Err(self.type_error("not an object"));
7501        };
7502        let mut method = if await_form {
7503            let found = self.get_property_key(
7504                object,
7505                &self.realm.well_known_key(WellKnown::AsyncDisposable),
7506            )?;
7507            match found {
7508                Some(found) if !found.is_nullish() => Some(found),
7509                _ => self
7510                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
7511            }
7512        } else {
7513            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
7514        };
7515        let Some(found) = method.take() else {
7516            return Err(self.type_error("value is not disposable"));
7517        };
7518        if found.is_nullish() {
7519            return Err(self.type_error("value is not disposable"));
7520        }
7521        let callable = found.as_object().is_some_and(|object| object.is_callable());
7522        if !callable {
7523            return Err(self.type_error("dispose method is not a function"));
7524        }
7525        Ok(found)
7526    }
7527
7528    /// Call one resource's disposer, folding a failure into `error_state`.
7529    ///
7530    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
7531    /// because a captured `using` binding lives in its reference cell and the local slot is
7532    /// stale — a closure over the resource is legal and must not change what is disposed.
7533    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
7534        let value = self.get_loc(slot);
7535        let method = self.get_loc(slot + 1);
7536        // A resource that was never initialised — its declaration threw — or that is
7537        // `null`/`undefined` has nothing to dispose.
7538        if value.is_nullish() || matches!(value, Value::Uninitialized) {
7539            return Ok(error_state);
7540        }
7541        if matches!(method, Value::Undefined | Value::Uninitialized) {
7542            return Ok(error_state);
7543        }
7544        match self.call_value(method, value, Vec::new()) {
7545            Ok(_) => Ok(error_state),
7546            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
7547            Err(other) => Err(other),
7548        }
7549    }
7550
7551    /// Combine a disposal failure with whatever was already going wrong.
7552    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
7553        if matches!(error_state, Value::Uninitialized) {
7554            return new_error;
7555        }
7556        self.new_suppressed_error(new_error, error_state)
7557    }
7558
7559    /// A `SuppressedError` instance built straight from its prototype.
7560    ///
7561    /// Not through the constructor: a script that rewrites
7562    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
7563    /// error wrapping.
7564    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
7565        let proto = self
7566            .realm
7567            .suppressed_error_proto
7568            .clone()
7569            .unwrap_or_else(|| self.realm.error_proto.clone());
7570        let object = self.new_object(Some(proto));
7571        object.define("error", Property::with_attributes(error, true, true));
7572        object.define(
7573            "suppressed",
7574            Property::with_attributes(suppressed, true, true),
7575        );
7576        object.define(
7577            "message",
7578            Property::with_attributes(self.string("SuppressedError"), true, true),
7579        );
7580        self.internal_set(&object, "_class", self.string("Error"));
7581        self.add_stack(&object);
7582        Value::Object(object)
7583    }
7584
7585    /// Call `callee`, or push its frame and let the main loop run it.
7586    ///
7587    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
7588    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
7589    /// continues, so `function f(){ return f() }` costs heap and stops at
7590    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
7591    /// is entered directly, and natives do not re-enter JavaScript in this
7592    /// milestone.
7593    ///
7594    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
7595    /// because the returning frame will.
7596    /// The elements of an array-like value, as a call argument list.
7597    ///
7598    /// `apply` accepts any array-like, not only a real array: the reference reads
7599    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
7600    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
7601        let Some(object) = value.as_object().cloned() else {
7602            if value.is_nullish() {
7603                // `f.apply(this, null)` passes no arguments at all.
7604                return Ok(Vec::new());
7605            }
7606            return Err(self.type_error("createListFromArrayLike called on non-object"));
7607        };
7608        let length = match self.get_property(&object, "length")? {
7609            Some(length) => length.to_number(),
7610            None => 0.0,
7611        };
7612        if !length.is_finite() || length <= 0.0 {
7613            return Ok(Vec::new());
7614        }
7615        let length = (length as usize).min(1_000_000);
7616        let mut args = Vec::with_capacity(length);
7617        for index in 0..length {
7618            let element = self.get_property(&object, &index.to_string())?;
7619            args.push(element.unwrap_or(Value::Undefined));
7620        }
7621        Ok(args)
7622    }
7623
7624    /// Turn a call to a generator function into a generator object.
7625    ///
7626    /// The frame is built exactly as an ordinary call would build it, then detached and
7627    /// stored in the generator before any body instruction runs — which is what makes
7628    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
7629    /// is `initial_yield`, the first instruction of every suspending body.
7630    pub fn new_generator(
7631        &mut self,
7632        function: Value,
7633        this: Value,
7634        args: Vec<Value>,
7635    ) -> JsResult<Value> {
7636        let Some(object) = function.as_object().cloned() else {
7637            return Err(self.type_error("not a generator function"));
7638        };
7639        let Some((code, env)) = bytecode_of(&object) else {
7640            return Err(self.type_error("not a generator function"));
7641        };
7642        let is_async = code.code.kind.is_async();
7643        self.push_frame(code, env, this, args, function)?;
7644        let frame = self.frames.pop().expect("push_frame just pushed it");
7645        // A fresh generator is *suspended at start*: the body has not run, so a
7646        // `return`/`throw` on it finishes without executing anything.
7647        let mut state = GeneratorState {
7648            frame: Some(frame),
7649            phase: GeneratorPhase::SuspendedStart,
7650            parked_on_await: false,
7651            parked_on_yield_star: false,
7652            requests: std::collections::VecDeque::new(),
7653            async_busy: false,
7654        };
7655        // Run to the first suspension. For a generator that is `initial_yield`, so no
7656        // body code runs; for a malformed body it would be the first `yield`.
7657        // An `async function*` answers an async generator: same coroutine, but its
7658        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
7659        let proto = if is_async {
7660            self.realm
7661                .async_generator_proto
7662                .clone()
7663                .unwrap_or_else(|| self.realm.generator_proto.clone())
7664        } else {
7665            self.realm.generator_proto.clone()
7666        };
7667        let generator = self.new_object(Some(proto));
7668        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
7669            Ok(_) => {}
7670            Err(error) => return Err(error),
7671        }
7672        generator.with_mut(|data| {
7673            data.kind = ObjectKind::Generator(Box::new(state));
7674        });
7675        Ok(Value::Object(generator))
7676    }
7677
7678    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7679    ///
7680    /// Returns the `{value, done}` object itself rather than the pair, because a
7681    /// `yield*` suspension already has one — the inner iterator's own result — and the
7682    /// protocol says to hand that straight through rather than nest it.
7683    /// Advance a generator and report *why* it parked.
7684    ///
7685    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
7686    /// "hand this value to the caller" — but an async generator does: an `await` has to
7687    /// settle before it can answer, while a `yield` is the answer.
7688    fn resume_generator_detailed(
7689        &mut self,
7690        generator: &Gc<JsObject>,
7691        kind: ResumeKind,
7692        value: Value,
7693    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7694        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
7695            ObjectKind::Generator(state) => Some(std::mem::replace(
7696                state.as_mut(),
7697                GeneratorState {
7698                    frame: None,
7699                    phase: GeneratorPhase::Executing,
7700                    parked_on_await: false,
7701                    parked_on_yield_star: false,
7702                    requests: std::collections::VecDeque::new(),
7703                    async_busy: false,
7704                },
7705            )),
7706            _ => None,
7707        }) else {
7708            return Err(self.type_error("not a generator"));
7709        };
7710        let result = self.step_generator(&mut state, kind, value);
7711        generator.with_mut(|data| {
7712            data.kind = ObjectKind::Generator(Box::new(state));
7713        });
7714        result
7715    }
7716
7717    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7718    ///
7719    /// Returns the `{value, done}` object itself rather than the pair, because a
7720    /// `yield*` suspension already has one — the inner iterator's own result — and the
7721    /// protocol says to hand that straight through rather than nest it.
7722    pub fn resume_generator(
7723        &mut self,
7724        generator: &Gc<JsObject>,
7725        kind: ResumeKind,
7726        value: Value,
7727    ) -> JsResult<Value> {
7728        let (value, done, ready, _reason) =
7729            self.resume_generator_detailed(generator, kind, value)?;
7730        if ready {
7731            return Ok(value);
7732        }
7733        self.iterator_result(value, done)
7734    }
7735
7736    /// `next`/`return`/`throw` on an async generator, which answer a promise.
7737    ///
7738    /// The body is the same coroutine a sync generator runs; what changes is that an
7739    /// `await` inside it has to settle before the method can answer, so the step is
7740    /// driven off the job queue rather than returning inline.
7741    pub fn resume_async_generator(
7742        &mut self,
7743        generator: &Gc<JsObject>,
7744        kind: ResumeKind,
7745        value: Value,
7746    ) -> JsResult<Value> {
7747        let promise = self.new_promise();
7748        // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
7749        // that order, and the second value must reach the *second* `yield`.
7750        let idle = generator.with_mut(|data| match &mut data.kind {
7751            ObjectKind::Generator(state) => {
7752                state.requests.push_back(AsyncRequest {
7753                    kind,
7754                    value,
7755                    promise: promise.clone(),
7756                });
7757                !state.async_busy
7758            }
7759            _ => false,
7760        });
7761        if idle {
7762            self.next_async_request(generator)?;
7763        }
7764        Ok(Value::Object(promise))
7765    }
7766
7767    /// Serve the front queued request, if the generator is free to run one.
7768    ///
7769    /// A finished generator answers from the queue without running anything:
7770    /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
7771    /// first, and `throw(e)` rejects.
7772    fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
7773        enum Front {
7774            Idle,
7775            Run(ResumeKind, Value, Gc<JsObject>),
7776            Finished(ResumeKind, Value, Gc<JsObject>),
7777        }
7778        let front = generator.with_mut(|data| match &mut data.kind {
7779            ObjectKind::Generator(state) => {
7780                let Some(request) = state.requests.front() else {
7781                    return Front::Idle;
7782                };
7783                // Busy means a request is still in flight — awaiting inside the body, not
7784                // finished. Serving another now would interleave two requests.
7785                if state.async_busy && state.phase != GeneratorPhase::Completed {
7786                    return Front::Idle;
7787                }
7788                let kind = request.kind;
7789                let value = request.value.clone();
7790                let promise = request.promise.clone();
7791                state.async_busy = true;
7792                if state.phase == GeneratorPhase::Completed {
7793                    Front::Finished(kind, value, promise)
7794                } else {
7795                    Front::Run(kind, value, promise)
7796                }
7797            }
7798            _ => Front::Idle,
7799        });
7800        match front {
7801            Front::Idle => Ok(()),
7802            Front::Run(kind, value, promise) => {
7803                self.step_async_generator(generator, &promise, kind, value)
7804            }
7805            Front::Finished(kind, value, promise) => match kind {
7806                ResumeKind::Throw => {
7807                    self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
7808                }
7809                ResumeKind::Next | ResumeKind::Start => {
7810                    let result = self.iterator_result(Value::Undefined, true)?;
7811                    self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
7812                }
7813                ResumeKind::Return => {
7814                    // `js_async_generator_completed_return`: the value is awaited before it
7815                    // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
7816                    // finished generator answers `1`, not a promise.
7817                    let resolved = match self.promise_resolve_value(value) {
7818                        Ok(resolved) => resolved,
7819                        Err(Signal::Throw(reason)) => {
7820                            return self.settle_async_request(
7821                                generator,
7822                                &promise,
7823                                AsyncOutcome::Error(reason),
7824                            );
7825                        }
7826                        Err(other) => return Err(other),
7827                    };
7828                    let done = JsObject::function(
7829                        self.heap,
7830                        Some(self.realm.function_proto.clone()),
7831                        Callable::CompletedReturn {
7832                            generator: generator.clone(),
7833                            promise: promise.clone(),
7834                            rejected: false,
7835                        },
7836                    );
7837                    let failed = JsObject::function(
7838                        self.heap,
7839                        Some(self.realm.function_proto.clone()),
7840                        Callable::CompletedReturn {
7841                            generator: generator.clone(),
7842                            promise: promise.clone(),
7843                            rejected: true,
7844                        },
7845                    );
7846                    let Value::Object(resolved) = resolved else {
7847                        return self.settle_async_request(
7848                            generator,
7849                            &promise,
7850                            AsyncOutcome::Error(Value::Undefined),
7851                        );
7852                    };
7853                    self.perform_then(
7854                        &resolved,
7855                        Some(Value::Object(done)),
7856                        Some(Value::Object(failed)),
7857                    )?;
7858                    Ok(())
7859                }
7860            },
7861        }
7862    }
7863
7864    /// Settle the front request and start the next one.
7865    ///
7866    /// Every path out of [`Interp::step_async_generator`] goes through here, so the
7867    /// "busy" flag and the queue cannot drift: a promise settled without releasing the
7868    /// generator would strand every later request.
7869    fn settle_async_request(
7870        &mut self,
7871        generator: &Gc<JsObject>,
7872        promise: &Gc<JsObject>,
7873        outcome: AsyncOutcome,
7874    ) -> JsResult<()> {
7875        let settled = generator.with_mut(|data| match &mut data.kind {
7876            ObjectKind::Generator(state) => {
7877                let front = state.requests.front();
7878                debug_assert!(
7879                    front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
7880                    "a request settled outside its turn"
7881                );
7882                state.requests.pop_front();
7883                state.async_busy = false;
7884                true
7885            }
7886            _ => false,
7887        });
7888        if settled {
7889            match outcome {
7890                AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
7891                AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
7892            }
7893        }
7894        self.next_async_request(generator)
7895    }
7896
7897    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
7898    ///
7899    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
7900    /// disposer runs **synchronously** — the reference starts it before returning, which
7901    /// a test can observe by logging after the call — and the rest follow once their
7902    /// predecessor settles.
7903    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
7904        let promise = self.new_promise();
7905        let mut pairs = Vec::with_capacity(resources.len());
7906        for (value, method) in resources {
7907            let pair = self.new_array(vec![value, method]);
7908            pairs.push(Value::Object(pair));
7909        }
7910        let remaining = self.new_array(pairs);
7911        self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
7912        Ok(Value::Object(promise))
7913    }
7914
7915    /// One link of the `disposeAsync` chain.
7916    ///
7917    /// Loops while the disposers finish synchronously, and parks on the first thenable it
7918    /// meets — pushing itself back in as the continuation, with the accumulated error
7919    /// carried along so a later failure can still be folded into the `SuppressedError`.
7920    fn dispose_step(
7921        &mut self,
7922        remaining: &Gc<JsObject>,
7923        promise: &Gc<JsObject>,
7924        mut error: Value,
7925    ) -> JsResult<()> {
7926        loop {
7927            let length = remaining.array_length().unwrap_or(0);
7928            if length == 0 {
7929                if matches!(error, Value::Uninitialized) {
7930                    self.fulfill_promise(promise, Value::Undefined);
7931                } else {
7932                    self.reject_promise(promise, error);
7933                }
7934                return Ok(());
7935            }
7936            let Some(Value::Object(pair)) = remaining
7937                .array_get(length - 1)
7938                .filter(|v| !matches!(v, Value::Hole))
7939            else {
7940                remaining.array_truncate(self.heap, length - 1);
7941                continue;
7942            };
7943            remaining.array_truncate(self.heap, length - 1);
7944            let value = pair.array_get(0).unwrap_or(Value::Undefined);
7945            let Some(Value::Object(method)) = pair.array_get(1) else {
7946                continue;
7947            };
7948            if !method.is_callable() {
7949                continue;
7950            }
7951            match self.call_value(Value::Object(method), value, Vec::new()) {
7952                Ok(result) => {
7953                    if !self.is_thenable(&result)? {
7954                        // Finished synchronously; the next disposer is the next iteration.
7955                        continue;
7956                    }
7957                    let awaited = match self.promise_resolve_value(result) {
7958                        Ok(awaited) => awaited,
7959                        Err(Signal::Throw(reason)) => {
7960                            self.reject_promise(promise, reason);
7961                            return Ok(());
7962                        }
7963                        Err(other) => return Err(other),
7964                    };
7965                    let Value::Object(awaited) = awaited else {
7966                        continue;
7967                    };
7968                    let ok = JsObject::function(
7969                        self.heap,
7970                        Some(self.realm.function_proto.clone()),
7971                        Callable::DisposeStep {
7972                            remaining: remaining.clone(),
7973                            promise: promise.clone(),
7974                            error: error.clone(),
7975                            rejected: false,
7976                        },
7977                    );
7978                    let failed = JsObject::function(
7979                        self.heap,
7980                        Some(self.realm.function_proto.clone()),
7981                        Callable::DisposeStep {
7982                            remaining: remaining.clone(),
7983                            promise: promise.clone(),
7984                            error,
7985                            rejected: true,
7986                        },
7987                    );
7988                    self.perform_then(
7989                        &awaited,
7990                        Some(Value::Object(ok)),
7991                        Some(Value::Object(failed)),
7992                    )?;
7993                    return Ok(());
7994                }
7995                Err(Signal::Throw(thrown)) => {
7996                    error = self.merge_dispose_error(thrown, error);
7997                }
7998                Err(other) => return Err(other),
7999            }
8000        }
8001    }
8002
8003    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
8004    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
8005        let Value::Object(object) = value else {
8006            return Ok(false);
8007        };
8008        Ok(matches!(
8009            self.get_property(object, "then")?,
8010            Some(Value::Object(then)) if then.is_callable()
8011        ))
8012    }
8013
8014    /// One step of an async generator, settling `promise` with an `{value, done}` result.
8015    fn step_async_generator(
8016        &mut self,
8017        generator: &Gc<JsObject>,
8018        promise: &Gc<JsObject>,
8019        kind: ResumeKind,
8020        value: Value,
8021    ) -> JsResult<()> {
8022        let stepped = self.resume_generator_detailed(generator, kind, value);
8023        let (value, done, ready, reason) = match stepped {
8024            Ok(stepped) => stepped,
8025            Err(Signal::Throw(reason)) => {
8026                return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
8027            }
8028            Err(other) => return Err(other),
8029        };
8030        // Only an `await` has to wait before the method can answer.
8031        if !done && reason == Some(SuspendKind::Await) {
8032            let awaited = match self.promise_resolve_value(value) {
8033                Ok(awaited) => awaited,
8034                Err(Signal::Throw(reason)) => {
8035                    return self.settle_async_request(
8036                        generator,
8037                        promise,
8038                        AsyncOutcome::Error(reason),
8039                    );
8040                }
8041                Err(other) => return Err(other),
8042            };
8043            let Value::Object(awaited) = awaited else {
8044                return Ok(());
8045            };
8046            let resumed = JsObject::function(
8047                self.heap,
8048                Some(self.realm.function_proto.clone()),
8049                Callable::GeneratorResume {
8050                    generator: generator.clone(),
8051                    promise: promise.clone(),
8052                    kind: ResumeKind::Next,
8053                },
8054            );
8055            let raised = JsObject::function(
8056                self.heap,
8057                Some(self.realm.function_proto.clone()),
8058                Callable::GeneratorResume {
8059                    generator: generator.clone(),
8060                    promise: promise.clone(),
8061                    kind: ResumeKind::Throw,
8062                },
8063            );
8064            self.perform_then(
8065                &awaited,
8066                Some(Value::Object(resumed)),
8067                Some(Value::Object(raised)),
8068            )?;
8069            return Ok(());
8070        }
8071        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
8072        // completes it — both arrive as the settled value rather than as the promise
8073        // object. A plain value skips the round trip, which is also what keeps `yield 1`
8074        // from costing an extra tick.
8075        let awaits_value = self.is_thenable(&value)?;
8076        if awaits_value {
8077            let awaited = match self.promise_resolve_value(value) {
8078                Ok(awaited) => awaited,
8079                Err(Signal::Throw(reason)) => {
8080                    return self.settle_async_request(
8081                        generator,
8082                        promise,
8083                        AsyncOutcome::Error(reason),
8084                    );
8085                }
8086                Err(other) => return Err(other),
8087            };
8088            let Value::Object(awaited) = awaited else {
8089                return Ok(());
8090            };
8091            // A rejected yield throws *at the yield* inside the body, so the rejection
8092            // resumes the generator rather than the method's promise.
8093            let answer = JsObject::function(
8094                self.heap,
8095                Some(self.realm.function_proto.clone()),
8096                Callable::YieldResult {
8097                    generator: generator.clone(),
8098                    promise: promise.clone(),
8099                    done,
8100                },
8101            );
8102            let raise = JsObject::function(
8103                self.heap,
8104                Some(self.realm.function_proto.clone()),
8105                Callable::GeneratorResume {
8106                    generator: generator.clone(),
8107                    promise: promise.clone(),
8108                    kind: ResumeKind::Throw,
8109                },
8110            );
8111            self.perform_then(
8112                &awaited,
8113                Some(Value::Object(answer)),
8114                Some(Value::Object(raise)),
8115            )?;
8116            return Ok(());
8117        }
8118        let result = if ready {
8119            // `yield*` handed back the inner iterator's own result object.
8120            value
8121        } else {
8122            self.iterator_result(value, done)?
8123        };
8124        self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
8125    }
8126
8127    /// The `{value, done}` object an iterator method answers with.
8128    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
8129        let result = self.new_object(Some(self.realm.object_proto.clone()));
8130        result.define_data("value", value);
8131        result.define_data("done", Value::Bool(done));
8132        Ok(Value::Object(result))
8133    }
8134
8135    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
8136    fn step_generator(
8137        &mut self,
8138        state: &mut GeneratorState,
8139        kind: ResumeKind,
8140        value: Value,
8141    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8142        match state.phase {
8143            GeneratorPhase::Executing => {
8144                return Err(self.type_error("cannot invoke a running generator"));
8145            }
8146            GeneratorPhase::Completed => {
8147                // A finished generator answers every resumption without running.
8148                return Ok(match kind {
8149                    ResumeKind::Throw => return Err(Signal::Throw(value)),
8150                    ResumeKind::Return => (value, true, false, None),
8151                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
8152                });
8153            }
8154            GeneratorPhase::SuspendedStart => {
8155                if kind != ResumeKind::Next && kind != ResumeKind::Start {
8156                    // The body never started, so there is nothing to unwind or return
8157                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
8158                    state.frame = None;
8159                    state.phase = GeneratorPhase::Completed;
8160                    return Ok(match kind {
8161                        ResumeKind::Throw => return Err(Signal::Throw(value)),
8162                        _ => (value, true, false, None),
8163                    });
8164                }
8165            }
8166            GeneratorPhase::SuspendedYield => {}
8167        }
8168
8169        let Some(mut frame) = state.frame.take() else {
8170            return Ok((Value::Undefined, true, false, None));
8171        };
8172        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
8173        // number that says which method resumed it; the emitted `if_false` branches on
8174        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
8175        let mut raised = None;
8176        match kind {
8177            ResumeKind::Next | ResumeKind::Start => {
8178                if state.phase == GeneratorPhase::SuspendedYield {
8179                    frame.stack.push(value);
8180                    // An `await` resumes with its value alone; only a `yield` gets the
8181                    // magic number that says which of `next`/`return` resumed it.
8182                    if !state.parked_on_await {
8183                        frame.stack.push(Value::Int(RESUME_NEXT));
8184                    }
8185                }
8186            }
8187            ResumeKind::Return => {
8188                // A `return` on a not-yet-started generator is handled above, so this is
8189                // always a real resumption.
8190                frame.stack.push(value);
8191                frame.stack.push(Value::Int(RESUME_RETURN));
8192            }
8193            ResumeKind::Throw => {
8194                // At a `yield*` the exception is *data* for the delegation: the compiled
8195                // code resumes with the value and magic `2` and calls the inner iterator's
8196                // `throw`. Everywhere else it is raised at the suspension point, so the
8197                // body's own handler sees it.
8198                if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
8199                    frame.stack.push(value);
8200                    frame.stack.push(Value::Int(RESUME_THROW));
8201                } else {
8202                    raised = Some(value);
8203                }
8204            }
8205        }
8206        state.phase = GeneratorPhase::Executing;
8207
8208        let depth = self.frames.len();
8209        self.frames.push(frame);
8210        // A `throw` unwinds from where the frame parked, exactly as if the exception had
8211        // happened at the `yield`.
8212        if let Some(exception) = raised {
8213            if self.catch_here(exception.clone()).is_none() {
8214                self.pop_frame();
8215                state.phase = GeneratorPhase::Completed;
8216                return Err(Signal::Throw(exception));
8217            }
8218        }
8219
8220        // Only the generator's *own* frame ends the generator. The body may call ordinary
8221        // functions, and those push frames of their own: a `Step::Return` from one of them
8222        // is a nested call finishing, not the generator completing. Miscounting that is
8223        // silent — the generator reports the callee's value as its own result and marks
8224        // itself done — so the depth comparison is load-bearing, not defensive.
8225        let own_frame = depth + 1;
8226        loop {
8227            match self.step() {
8228                Ok(Step::Continue) => {}
8229                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
8230                    let mut frame = self.frames.pop().expect("a frame is live");
8231                    // `yield` left the value on the stack; `initial_yield` left nothing.
8232                    let yielded = if reason == SuspendKind::Initial {
8233                        Value::Undefined
8234                    } else {
8235                        frame.stack.pop().unwrap_or(Value::Undefined)
8236                    };
8237                    state.frame = Some(frame);
8238                    state.parked_on_await = reason == SuspendKind::Await;
8239                    state.parked_on_yield_star =
8240                        matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
8241                    state.phase = if reason == SuspendKind::Initial {
8242                        GeneratorPhase::SuspendedStart
8243                    } else {
8244                        GeneratorPhase::SuspendedYield
8245                    };
8246                    // `yield*` hands the inner iterator's own result object straight
8247                    // back, so the caller sees one `{value, done}` rather than a nested
8248                    // one — which is why the third field says "already a result".
8249                    return Ok((
8250                        yielded,
8251                        false,
8252                        reason == SuspendKind::YieldStar,
8253                        Some(reason),
8254                    ));
8255                }
8256                Ok(Step::Suspend(_)) => {
8257                    // A `yield` in a frame other than the generator's would mean a
8258                    // generator body entered as an ordinary call, which
8259                    // `call_or_push` prevents.
8260                    self.unwind_to(depth);
8261                    state.phase = GeneratorPhase::Completed;
8262                    return Err(Signal::Throw(self.make_error(
8263                        "InternalError",
8264                        "a generator body ran as an ordinary call",
8265                    )));
8266                }
8267                Ok(Step::Return(value)) => {
8268                    self.pop_frame();
8269                    if self.frames.len() > depth {
8270                        // A nested call finished: hand the value back to its caller and
8271                        // keep running the generator body.
8272                        self.frames
8273                            .last_mut()
8274                            .expect("a caller is live")
8275                            .stack
8276                            .push(value);
8277                        continue;
8278                    }
8279                    state.phase = GeneratorPhase::Completed;
8280                    // The reference closes the generator's closure variables here; ours
8281                    // live in cells the frame owned, which the drop below releases.
8282                    return Ok((value, true, false, None));
8283                }
8284                Err(Signal::Throw(exception)) => {
8285                    // The frame that threw gets the first chance to catch, exactly as in
8286                    // the ordinary call loop; a frame above the generator's is popped and
8287                    // the exception carries on down.
8288                    let exception = exception;
8289                    loop {
8290                        if self.frames.len() <= depth {
8291                            // The generator's own frame is gone, so nothing here caught it.
8292                            state.phase = GeneratorPhase::Completed;
8293                            return Err(Signal::Throw(exception));
8294                        }
8295                        if self.catch_here(exception.clone()).is_some() {
8296                            break;
8297                        }
8298                        self.pop_frame();
8299                    }
8300                }
8301                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
8302            }
8303        }
8304    }
8305
8306    /// Pop frames until `depth` are left, keeping their buffers.
8307    fn unwind_to(&mut self, depth: usize) {
8308        while self.frames.len() > depth {
8309            self.pop_frame();
8310        }
8311    }
8312    fn call_or_push(
8313        &mut self,
8314        callee: Value,
8315        this: Value,
8316        args: Vec<Value>,
8317    ) -> JsResult<Option<Value>> {
8318        if let Value::Object(function) = &callee
8319            && let Some((code, env)) = bytecode_of(function)
8320        {
8321            // Calling a generator function does not run anything: it captures the
8322            // arguments in a frame and hands back the generator object.
8323            if code.code.kind.is_generator() {
8324                return self.new_generator(callee, this, args).map(Some);
8325            }
8326            // An async function answers a promise and runs its body as a coroutine, so it
8327            // takes the same path as a plain call into it.
8328            if code.code.kind.is_async() {
8329                return self.new_async_function(callee, this, args).map(Some);
8330            }
8331            self.push_frame(code, env, this, args, callee)?;
8332            return Ok(None);
8333        }
8334        self.call_value(callee, this, args).map(Some)
8335    }
8336
8337    /// `new callee(args)`.
8338    ///
8339    /// A constructor differs from a plain call in three ways: it gets a fresh object
8340    /// as `this` whose prototype is the constructor's `prototype` property, its
8341    /// return value is *replaced* by that object unless it returns an object itself,
8342    /// and a native constructor is expected to initialise the object it is given
8343    /// rather than build one.
8344    pub fn construct(
8345        &mut self,
8346        callee: Value,
8347        new_target: Value,
8348        args: Vec<Value>,
8349    ) -> JsResult<Value> {
8350        // `new` on a bound function constructs its *target*, prepending the arguments
8351        // the bind fixed and ignoring the bound `this` — a bound function is a
8352        // constructor only when its target is one, and `new` always makes a fresh
8353        // object of the target's prototype rather than reusing the bound receiver.
8354        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
8355        // ran the body with `this === null` and threw on `this.x = a`.
8356        let mut callee = callee;
8357        let mut new_target = new_target;
8358        let mut args = args;
8359        loop {
8360            let Some(object) = callee.as_object().cloned() else {
8361                return Err(Signal::Throw(
8362                    self.make_error("TypeError", "not a constructor"),
8363                ));
8364            };
8365            // A proxy of a function constructs through its `construct` trap, and the
8366            // trap's answer is the result directly — no fresh object is made here.
8367            if object.proxy_state().is_some() {
8368                return match self.proxy_construct(&object, args, &new_target)? {
8369                    Some(result) => Ok(result),
8370                    None => Err(Signal::Throw(
8371                        self.make_error("TypeError", "proxy target is not a constructor"),
8372                    )),
8373                };
8374            }
8375            // A generator function has no `[[Construct]]`, and the reference names it in
8376            // the message: `new (function* G(){})()` reports "G is not a constructor".
8377            if object.with(|data| match &data.kind {
8378                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
8379                    code.code.kind.is_generator()
8380                }
8381                _ => false,
8382            }) {
8383                let name = object
8384                    .own_property("name")
8385                    .and_then(|property| property.value)
8386                    .map(|value| value.to_js_string())
8387                    .unwrap_or_default();
8388                return Err(Signal::Throw(
8389                    self.make_error("TypeError", &format!("{name} is not a constructor")),
8390                ));
8391            }
8392            let bound = object.with(|data| match &data.kind {
8393                ObjectKind::Function(Callable::Bound {
8394                    target,
8395                    args: leading,
8396                    ..
8397                }) => Some((target.clone(), leading.clone())),
8398                _ => None,
8399            });
8400            let Some((target, leading)) = bound else {
8401                // Not a bound function, so this object is the callee. §7.2.4
8402                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
8403                // refusals above cover only the built-ins the reference also refuses by
8404                // name. Everything else — a method, an arrow, an async function — has no
8405                // `[[Construct]]` either, and answering "yes" here made
8406                // `new (Array.prototype.map)` build an object instead of throwing.
8407                if !object.is_constructor() {
8408                    let name = object
8409                        .own_property("name")
8410                        .and_then(|property| property.value)
8411                        .map(|value| value.to_js_string())
8412                        .unwrap_or_default();
8413                    return Err(Signal::Throw(
8414                        self.make_error("TypeError", &format!("{name} is not a constructor")),
8415                    ));
8416                }
8417                break;
8418            };
8419            let mut all = leading;
8420            all.extend(args);
8421            args = all;
8422            // A bound function that is its own `new.target` stands in for its target:
8423            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
8424            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
8425            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
8426                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
8427                _ => false,
8428            };
8429            if same_wrapper {
8430                new_target = target.clone();
8431            }
8432            callee = target;
8433        }
8434        let Value::Object(function) = &callee else {
8435            unreachable!("the loop above only breaks on an object");
8436        };
8437        // The fresh object's prototype comes from `new.target`, not from the callee: a
8438        // derived constructor reaches here through `super()`, and the instance must be a
8439        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
8440        // an object inheriting `D.prototype` rather than `C.prototype`.
8441        let prototype_source = match new_target.as_object() {
8442            Some(target) => target.clone(),
8443            None => function.clone(),
8444        };
8445        // A native constructor builds its own instance, through `new_ctor_instance`, once it
8446        // has validated its arguments. Pre-building one here would read
8447        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
8448        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
8449        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
8450        let is_native = function.native_creates_own_instance();
8451        let this = if is_native {
8452            Value::Undefined
8453        } else {
8454            let prototype = self.get_property(&prototype_source, "prototype")?;
8455            let prototype = match prototype {
8456                Some(Value::Object(proto)) => Some(proto),
8457                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
8458                // object, the answer is the realm's *intrinsic* prototype for this
8459                // constructor, not `%Object.prototype%`.
8460                _ => {
8461                    let fallback = self.get_property(function, "prototype")?;
8462                    match fallback {
8463                        Some(Value::Object(proto)) => Some(proto),
8464                        _ => Some(self.realm.object_proto.clone()),
8465                    }
8466                }
8467            };
8468            Value::Object(self.new_object(prototype))
8469        };
8470        // `new.target` inside the body is the constructor that was written, so a bound
8471        // function's target sees itself rather than the bound wrapper.
8472        //
8473        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
8474        // `?`, so assigning `None` after the call would be skipped and the failed
8475        // `new.target` would stay visible to every later native call. The symptom was a
8476        // native constructor refusing a plain call — `var s = Symbol(); new
8477        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
8478        // "FinalizationRegistry is not a constructor".
8479        let outer_new_target = self.pending_new_target.replace(new_target);
8480        let result = self.call_value(callee, this.clone(), args);
8481        self.pending_new_target = outer_new_target;
8482        let result = result?;
8483        // A constructor that returns an object overrides `this`; any other return
8484        // value (including `undefined`) is ignored.
8485        Ok(match result {
8486            Value::Object(_) => result,
8487            _ => this,
8488        })
8489    }
8490
8491    /// `new.target` for the call currently being made.
8492    ///
8493    /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
8494    /// it as `this`), but a *host* constructor that builds its own instance is handed
8495    /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
8496    /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
8497    /// it here.
8498    ///
8499    /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
8500    /// receives for a plain call.
8501    pub fn current_new_target(&self) -> Value {
8502        self.pending_new_target.clone().unwrap_or(Value::Undefined)
8503    }
8504
8505    /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
8506    ///
8507    /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
8508    /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
8509    pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
8510        let constructor = self.realm.errors.get("AggregateError").cloned();
8511        let Some(constructor) = constructor else {
8512            return self.make_error("AggregateError", message);
8513        };
8514        let list = self.new_array(errors);
8515        match self.construct(
8516            Value::Object(constructor.clone()),
8517            Value::Object(constructor),
8518            vec![Value::Object(list), self.string(message)],
8519        ) {
8520            Ok(value) => value,
8521            // A user could have replaced `AggregateError` with something that throws; the
8522            // engine still owes the caller a rejection, so it falls back rather than
8523            // turning `Promise.any`'s rejection into a throw.
8524            Err(_) => self.make_error("AggregateError", message),
8525        }
8526    }
8527
8528    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
8529    ///
8530    /// The error classes themselves arrive with the builtins milestone; what
8531    /// matters here is that the thrown value stringifies the way a script printing
8532    /// the caught value expects.
8533    ///
8534    /// `name` and `message` become own properties, which is what makes `e.name` cheap and
8535    /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
8536    /// rely on when they print a caught value.
8537    pub fn make_error(&self, name: &str, message: &str) -> Value {
8538        let proto = self
8539            .realm
8540            .errors
8541            .get(name)
8542            .map(|constructor| self.prototype_of(constructor))
8543            .unwrap_or_else(|| self.realm.error_proto.clone());
8544        let error = self.new_object(Some(proto));
8545        // `name` and `message` are own properties of the instance, which is what
8546        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
8547        // `Error`.
8548        error.define(
8549            "name",
8550            Property::with_attributes(self.string(name), true, false),
8551        );
8552        error.define(
8553            "message",
8554            Property::with_attributes(self.string(message), true, false),
8555        );
8556        // The internal class, which is what tells a printer this is an error rather than a
8557        // plain object with `name` and `message` properties. The constructor path sets it
8558        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
8559        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
8560        // literally `"Error"` in both places — the *name* is read from `name`, which is why
8561        // a `RangeError` still prints as `RangeError`.
8562        self.internal_set(&error, "_class", self.string("Error"));
8563        // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
8564        // answered `false` from `Error.isError` while a constructed one answered `true`,
8565        // because only the constructor set the slot. The reference answers `true` for both
8566        // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
8567        // accessor gated on this slot the omission stopped being cosmetic: `print_error`
8568        // tests `typeof stack === "string"` to decide on a trailing newline, so every
8569        // engine-thrown error lost its blank line.
8570        self.internal_set(&error, "_error_data", Value::Bool(true));
8571        // The trace is captured where the error is *made*, which is where the reference
8572        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
8573        // way out, so a caught engine error already has its stack even if the handler
8574        // never rethrows it.
8575        self.add_stack(&error);
8576        Value::Object(error)
8577    }
8578
8579    /// Give an error object its `stack` property, from the current frame stack.
8580    ///
8581    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
8582    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
8583    /// `stack` a script set, is not rewritten.
8584    pub fn add_stack(&self, object: &Gc<JsObject>) {
8585        self.add_stack_skipping(object, 0);
8586    }
8587
8588    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
8589    ///
8590    /// An `Error` constructor passes 1: the reference builds those traces with
8591    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
8592    /// constructor itself, while a `RangeError` raised inside `toISOString` does
8593    /// report `at toISOString (native)`.
8594    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
8595        if object.has_own("stack") {
8596            return;
8597        }
8598        // The trace is *captured* here but not installed as a property: `stack` is an
8599        // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
8600        // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
8601        // is kept in a hidden slot and the getter materialises it on first read.
8602        //
8603        // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
8604        // shows it — this is the same discipline `_error_data` and `_class` follow.
8605        let trace = self.stack_trace_skipping(skip);
8606        let text = self.string(trace);
8607        self.internal_set(object, "_stack_trace", text);
8608    }
8609
8610    /// The function object currently being called, if any.
8611    ///
8612    /// A native function is a bare `fn` pointer, so it cannot capture which class
8613    /// it belongs to; it reads that from the callee instead. This is also what a
8614    /// stack trace would use.
8615    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
8616        match &self.frames.last()?.callee {
8617            Value::Object(object) => Some(object.clone()),
8618            _ => None,
8619        }
8620    }
8621
8622    /// The `prototype` property of a constructor, falling back to
8623    /// `Object.prototype` for anything that is not shaped like one.
8624    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
8625        constructor
8626            .own_property("prototype")
8627            .and_then(|property| property.value)
8628            .and_then(|value| value.as_object().cloned())
8629            .unwrap_or_else(|| self.realm.object_proto.clone())
8630    }
8631
8632    /// Throw a `TypeError` carrying `message`.
8633    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
8634        Signal::Throw(self.make_error("TypeError", message.as_ref()))
8635    }
8636
8637    /// Throw a `RangeError` carrying `message`.
8638    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
8639        Signal::Throw(self.make_error("RangeError", message.as_ref()))
8640    }
8641
8642    /// The `ReferenceError` a read of an uninitialised binding raises.
8643    /// The name of the binding `slot` refers to, for an error message.
8644    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
8645        match kind {
8646            VarSlot::Loc => self
8647                .frame()
8648                .code
8649                .code
8650                .vars
8651                .get(slot)
8652                .map(|v| v.name.clone()),
8653            VarSlot::Closure => self
8654                .frame()
8655                .code
8656                .code
8657                .closure_vars
8658                .get(slot)
8659                .map(|c| c.name.clone()),
8660        }
8661        .unwrap_or_default()
8662    }
8663
8664    /// Whether `slot` names a `const` binding, which rejects every store after its
8665    /// initialiser.
8666    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
8667        match kind {
8668            VarSlot::Loc => self
8669                .frame()
8670                .code
8671                .code
8672                .vars
8673                .get(slot)
8674                .is_some_and(|v| v.is_const),
8675            VarSlot::Closure => self
8676                .frame()
8677                .code
8678                .code
8679                .closure_vars
8680                .get(slot)
8681                .is_some_and(|c| c.is_const),
8682        }
8683    }
8684
8685    /// The `TypeError` a store to a `const` binding raises.
8686    ///
8687    /// `const` is enforced here rather than at compile time because the binding can be
8688    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
8689    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
8690    /// both halves of what "checked store" means: the dead zone is over, and the
8691    /// binding is writable.
8692    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
8693        let name = self.binding_name(slot, kind);
8694        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
8695    }
8696
8697    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
8698        let name = match kind {
8699            VarSlot::Loc => self
8700                .frame()
8701                .code
8702                .code
8703                .vars
8704                .get(slot)
8705                .map(|v| v.name.clone()),
8706            VarSlot::Closure => self
8707                .frame()
8708                .code
8709                .code
8710                .closure_vars
8711                .get(slot)
8712                .map(|c| c.name.clone()),
8713        }
8714        .unwrap_or_default();
8715        Signal::Throw(self.make_error(
8716            "ReferenceError",
8717            &format!("cannot access '{name}' before initialization"),
8718        ))
8719    }
8720
8721    fn throw_reference(&self, name: &str) -> Signal {
8722        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
8723    }
8724
8725    // -- the instruction loop -----------------------------------------------
8726
8727    // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
8728    // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
8729    // measured at 16% of a tight arithmetic loop's total time.
8730    #[inline(always)]
8731    fn step(&mut self) -> JsResult<Step> {
8732        // The instruction is already decoded (see [`crate::insn`]), so this is an index
8733        // and a `Copy` read rather than a table lookup plus a width switch. Only the
8734        // borrow lives across the boundary; nothing is cloned.
8735        // **One** borrow of the frame: fetch the record, then advance in the same scope.
8736        // The obvious version borrowed it three times (`last` to read, `last_mut` to
8737        // write, and once more inside the handler), and each is a bounds check plus an
8738        // `Option` unwrap — on the one path every instruction takes.
8739        let Some((insn, next)) = ({
8740            let frame = self
8741                .frames
8742                .last_mut()
8743                .expect("step() is only called with a live frame");
8744            // Past the last instruction is a normal return: the compiler ends a function
8745            // with `return`, and a jump to the end of a block lands here.
8746            let insn = frame.insns().get(frame.pc).copied();
8747            match insn {
8748                None => None,
8749                Some(insn) => {
8750                    // A fused record stands for the next few instructions, so the next
8751                    // `pc` is its width ahead — the instructions it replaces are never
8752                    // dispatched. `at` is the byte offset a stack trace reports; it stays
8753                    // an offset because the line table is keyed by bytes.
8754                    frame.at = insn.offset as usize;
8755                    frame.pc += insn.width();
8756                    Some((insn, frame.pc))
8757                }
8758            }
8759        }) else {
8760            return Ok(Step::Return(Value::Undefined));
8761        };
8762        self.check_memory()?;
8763        self.check_interrupt()?;
8764        if insn.fused == crate::insn::Fused::None {
8765            self.execute_instruction(insn.op, insn.a, insn.b, next)
8766        } else {
8767            self.execute_fused(insn)
8768        }
8769    }
8770
8771    /// Run a fused instruction: several bytecode instructions in one dispatch.
8772    ///
8773    /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
8774    /// it cannot throw and cannot allocate — and anything else falls back to the real
8775    /// instructions, in their real order, so an exception leaves the operand stack
8776    /// exactly as it would have been.
8777    #[inline]
8778    fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
8779        use crate::insn::Fused;
8780        let slot = insn.a as usize;
8781        match insn.fused {
8782            // `x = k`: `push k; put_loc x`.
8783            Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
8784            // `x += k`: `get_loc x; push k; add; put_loc x`.
8785            Fused::AddImmLoc => {
8786                let delta = insn.b as i32;
8787                match self.get_loc(slot) {
8788                    Value::Int(left) => {
8789                        // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
8790                        // that built two `Value`s, called a function, and matched on them
8791                        // again to reach this same `checked_add`. It is the innermost
8792                        // operation of every accumulator in every program.
8793                        let answer = match left.checked_add(delta) {
8794                            Some(sum) => Value::Int(sum),
8795                            None => Value::Float(left as f64 + delta as f64),
8796                        };
8797                        self.put_loc(slot, answer);
8798                    }
8799                    other => {
8800                        self.push(other);
8801                        self.push(Value::Int(delta));
8802                        self.binary_add()?;
8803                        let value = self.pop();
8804                        self.put_loc(slot, value);
8805                    }
8806                }
8807            }
8808            // `x += "literal"` and `x += y`: the two shapes that can append in place.
8809            Fused::AddAtomLoc => {
8810                let text = self.atom_wtf8(insn.b as usize);
8811                let right = self.string_wtf8(text);
8812                self.add_into_loc(slot, right)?;
8813            }
8814            Fused::AddLocLoc => {
8815                let source = (insn.a & 0xFFFF) as usize;
8816                let target = (insn.a >> 16) as usize;
8817                let right = self.get_loc(source);
8818                self.add_into_loc(target, right)?;
8819            }
8820            Fused::AddArgLoc => {
8821                let source = (insn.a & 0xFFFF) as usize;
8822                let target = (insn.a >> 16) as usize;
8823                let right = self.get_arg(source);
8824                self.add_into_loc(target, right)?;
8825            }
8826            // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
8827            Fused::PostIncLoc => match self.get_loc(slot) {
8828                Value::Int(left) => {
8829                    let answer = match left.checked_add(1) {
8830                        Some(sum) => Value::Int(sum),
8831                        None => Value::Float(left as f64 + 1.0),
8832                    };
8833                    self.put_loc(slot, answer);
8834                }
8835                other => {
8836                    self.push(other);
8837                    let raw = self.pop();
8838                    let (old, updated) = self.advance_numeric(raw, true)?;
8839                    self.push(old);
8840                    self.push(updated);
8841                    let value = self.pop();
8842                    self.put_loc(slot, value);
8843                    self.pop();
8844                }
8845            },
8846            // `if (!(x < arg)) goto target`: a loop header.
8847            //
8848            // The comparison is computed rather than replayed on the operand stack. That
8849            // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
8850            // that throws: the effects happen in the same order, and a handler truncates
8851            // the stack down to its marker, so the intermediate values are unobservable.
8852            Fused::LtLocArgJump => {
8853                let loc = (insn.a >> 16) as usize;
8854                let arg = (insn.a & 0xFFFF) as usize;
8855                let left = self.get_loc(loc);
8856                let right = self.get_arg(arg);
8857                let taken = match (&left, &right) {
8858                    (Value::Int(left), Value::Int(right)) => !(left < right),
8859                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8860                };
8861                if taken {
8862                    self.frame_mut().pc = insn.b as usize;
8863                }
8864            }
8865            // `i < k` in a loop header, where `k` is an integer literal.
8866            Fused::LtLocImmJump => {
8867                let left = self.get_loc(insn.a as usize);
8868                let right = Value::Int(insn.imm as i32);
8869                let taken = match &left {
8870                    Value::Int(left) => !(*left < insn.imm as i32),
8871                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8872                };
8873                if taken {
8874                    self.frame_mut().pc = insn.b as usize;
8875                }
8876            }
8877            Fused::None => unreachable!("only called for a fused record"),
8878        }
8879        Ok(Step::Continue)
8880    }
8881
8882    /// Run records that cannot call script, cannot throw and cannot change frames.
8883    ///
8884    /// Returns `Some(value)` when the function ran off the end of its instructions (a
8885    /// normal return), and `None` when it stopped in front of an instruction the slow path
8886    /// has to handle — `pc` is written back either way, so `step` resumes at the right
8887    /// place.
8888    ///
8889    /// **The invariant is the whole point.** Every arm here is restricted to work that
8890    /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
8891    /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
8892    /// that the memory limit has to see. An opcode whose operands turn out to need any of
8893    /// that **stops the loop** instead of trying, so the slow path gets the instruction
8894    /// untouched and with its operands still on the stack. That is why the fallback is a
8895    /// `break` and not a duplicated slow arm: a second implementation of the same
8896    /// semantics is how a wrong answer gets in with no test noticing.
8897    ///
8898    /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
8899    /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
8900    fn run_fast(&mut self) -> JsResult<Option<Value>> {
8901        use crate::insn::Fused;
8902        // The outer loop exists only so a `Call` can come back through here: once a
8903        // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
8904        // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
8905        // frame. Re-entering re-reads both from whichever frame is now on top. Every
8906        // other exit from the inner loop returns, so this costs one loop per call.
8907        'outer: loop {
8908            // One reference-count bump per *slow* instruction (a call, an allocation, a
8909            // property access), never one per instruction — that distinction is worth
8910            // two orders of magnitude and was measured as such.
8911            let (code, mut pc) = {
8912                let frame = self.frame();
8913                (frame.code.clone(), frame.pc)
8914            };
8915            let insns = &code.insns;
8916            loop {
8917                let Some(insn) = insns.get(pc).copied() else {
8918                    self.frame_mut().pc = pc;
8919                    return Ok(Some(Value::Undefined));
8920                };
8921                match insn.fused {
8922                    // `x = k`
8923                    Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
8924                    // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
8925                    // object — stops the loop so `binary_add` can decide.
8926                    Fused::AddImmLoc => {
8927                        let slot = insn.a as usize;
8928                        let delta = insn.b as i32;
8929                        let Value::Int(left) = self.get_loc(slot) else {
8930                            return Ok(self.stop(pc));
8931                        };
8932                        let sum = match left.checked_add(delta) {
8933                            Some(sum) => Value::Int(sum),
8934                            None => Value::Float(left as f64 + delta as f64),
8935                        };
8936                        self.put_loc(slot, sum);
8937                    }
8938                    // `x += "literal"` / `x += y`: the operand is a string, so the append
8939                    // either allocates one or grows one. Both are the slow path's business;
8940                    // the fusion's job is only to make the *slot* the sole owner, which is what
8941                    // `execute_fused` needs and what `get_loc` alone destroys.
8942                    Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
8943                        return Ok(self.stop(pc));
8944                    }
8945                    // `x++` on an integer, old value dropped.
8946                    Fused::PostIncLoc => {
8947                        // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
8948                        // value is read in place and overwritten in place, so the reference
8949                        // count it held is released by the same assignment that stores the
8950                        // new one. `get_loc` plus `put_loc` did two borrows, two table
8951                        // lookups and a clone, and this arm is the whole body of a counting
8952                        // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
8953                        let slot = insn.a as usize;
8954                        let frame = self.frames.last_mut().expect("a frame is live");
8955                        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
8956                        let target = if cell < 0 {
8957                            frame.locals.get_mut(slot)
8958                        } else {
8959                            None
8960                        };
8961                        let Some(target) = target else {
8962                            return Ok(self.stop(pc));
8963                        };
8964                        let Value::Int(left) = *target else {
8965                            return Ok(self.stop(pc));
8966                        };
8967                        *target = match left.checked_add(1) {
8968                            Some(sum) => Value::Int(sum),
8969                            None => Value::Float(left as f64 + 1.0),
8970                        };
8971                    }
8972                    // A loop header, `if (!(x < arg)) goto target`, with both sides already
8973                    // integers — which is every `for (i = 0; i < n; i++)` whose counter and
8974                    // bound stayed small integers.
8975                    Fused::LtLocArgJump => {
8976                        let loc = (insn.a >> 16) as usize;
8977                        let arg = (insn.a & 0xFFFF) as usize;
8978                        // One borrow for both slots: this arm *is* the whole loop of a
8979                        // `for (i = 0; i < n; i++)` with an argument bound, so a second
8980                        // `frames.last()` here is paid on every iteration. Measured 7.5% on
8981                        // `dispatch:empty-loop`.
8982                        let (left, right) = {
8983                            let frame = self.frame();
8984                            (frame.read_loc(loc), frame.read_arg(arg))
8985                        };
8986                        // Heavily measured: the bound is very often a `Float` even when the
8987                        // counter is an `Int` — anything that came from `+scriptArgs[2]`,
8988                        // `JSON.parse` or a division is one — so requiring both sides to be
8989                        // `Int` sent every iteration of those loops down the slow path. The
8990                        // comparison below is the same one `relational` makes for two numbers.
8991                        if !is_number(&left) || !is_number(&right) {
8992                            return Ok(self.stop(pc));
8993                        }
8994                        // `if_false` branches on the comparison being false, which is **not**
8995                        // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
8996                        // `>=` is also false and would keep it running forever. Clippy wants the
8997                        // negation folded; that would be a wrong answer.
8998                        let ordered = left.to_number() < right.to_number();
8999                        let take_branch = !ordered;
9000                        if take_branch {
9001                            pc = insn.b as usize;
9002                            continue;
9003                        }
9004                    }
9005                    // The same header with a literal bound: `if (!(x < k)) goto target`.
9006                    // The bound is an immediate, so only the counter needs a type test.
9007                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
9008                    Fused::LtLocImmJump => {
9009                        let left = self.get_loc(insn.a as usize);
9010                        if !is_number(&left) {
9011                            return Ok(self.stop(pc));
9012                        }
9013                        let take_branch = !(left.to_number() < insn.imm as i32 as f64);
9014                        if take_branch {
9015                            pc = insn.b as usize;
9016                            continue;
9017                        }
9018                    }
9019                    Fused::None => match insn.op {
9020                        // -- branches ---------------------------------------------------
9021                        // A jump is an assignment now, because the target is an instruction
9022                        // index. No arithmetic, no resolution table.
9023                        Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9024                            let target = insn.a as usize;
9025                            // A **back-edge** is a loop, and it is the only place an
9026                            // instruction-level checkpoint can stop one: `for(;;){}` compiles
9027                            // to a jump to itself and never leaves this loop, so the
9028                            // per-instruction checks in `step` never run. That is exactly the
9029                            // hole this arm closes — a host's `JS_SetInterruptHandler` did
9030                            // nothing to a `for(;;){}` until it did, which is what
9031                            // `tests/c/embed.c` is for.
9032                            //
9033                            // Polling here rather than on every instruction in this loop is
9034                            // also the reference's choice (`OP_goto` calls
9035                            // `js_poll_interrupts`), and it costs one compare per branch
9036                            // instead of one decrement per instruction.
9037                            if target <= pc {
9038                                self.frame_mut().pc = target;
9039                                self.check_memory()?;
9040                                self.check_interrupt()?;
9041                            }
9042                            pc = target;
9043                            continue;
9044                        }
9045                        // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
9046                        Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
9047                            let taken = self.pop().to_boolean();
9048                            let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
9049                            if taken == want {
9050                                pc = insn.a as usize;
9051                                continue;
9052                            }
9053                        }
9054                        // -- slot access -------------------------------------------------
9055                        // A load's slot is already an operand (see `insn::implicit_operand`);
9056                        // a captured one goes through its cell, which runs no script.
9057                        Opcode::GetLoc
9058                        | Opcode::GetLoc8
9059                        | Opcode::GetLoc0
9060                        | Opcode::GetLoc1
9061                        | Opcode::GetLoc2
9062                        | Opcode::GetLoc3 => {
9063                            let value = self.get_loc(insn.a as usize);
9064                            self.push(value);
9065                        }
9066                        Opcode::PutLoc
9067                        | Opcode::PutLoc8
9068                        | Opcode::PutLoc0
9069                        | Opcode::PutLoc1
9070                        | Opcode::PutLoc2
9071                        | Opcode::PutLoc3 => {
9072                            let value = self.pop();
9073                            self.put_loc(insn.a as usize, value);
9074                        }
9075                        Opcode::GetArg
9076                        | Opcode::GetArg0
9077                        | Opcode::GetArg1
9078                        | Opcode::GetArg2
9079                        | Opcode::GetArg3 => {
9080                            let value = self.get_arg(insn.a as usize);
9081                            self.push(value);
9082                        }
9083                        Opcode::PutArg
9084                        | Opcode::PutArg0
9085                        | Opcode::PutArg1
9086                        | Opcode::PutArg2
9087                        | Opcode::PutArg3 => {
9088                            let value = self.pop();
9089                            self.put_arg(insn.a as usize, value);
9090                        }
9091                        // `a[i]` with an integer index on a dense array: see `fast_array_get`
9092                        // for why a non-hole own element is exactly the slow path's answer.
9093                        // The two operands are *peeked*, so a miss leaves the stack as the
9094                        // slow path expects to find it.
9095                        Opcode::GetArrayEl => {
9096                            // One lookup, not two. The guard used `if …is_some()` and the arm
9097                            // then called it again to get the value — two `peek`s, two
9098                            // `array_get`s and two `Value` clones for one element.
9099                            // `fast_array_get` was 13.1% of `array:indexed`, and the same
9100                            // double call was the first version of the `get_field` fast path.
9101                            let Some(value) = self.fast_array_get() else {
9102                                return Ok(self.stop(pc));
9103                            };
9104                            // `a[i]` consumes both operands and leaves the element in their
9105                            // place: one `truncate` and one write, no `pop`/`push` pair.
9106                            let frame = self.frame_mut();
9107                            frame.stack.truncate(frame.stack.len() - 2);
9108                            frame.stack.push(value);
9109                        }
9110                        // `a[i] = v` on a dense array with an integer index: see
9111                        // `fast_array_set` for why the whole store is one step.
9112                        Opcode::PutArrayEl if self.fast_array_set() => {}
9113                        // `o.x` resolved from the inline cache without leaving the loop.
9114                        //
9115                        // The cache is keyed by `(receiver identity, atom, site)` and a
9116                        // monomorphic read re-validates the same chain every iteration, so
9117                        // each one used to cost a `stop(pc)` — a write of `pc` into the
9118                        // frame, a return out of this loop, a re-dispatch through `step` and
9119                        // a re-entry. `property:monomorphic` spent 18% in
9120                        // `read_field_cached` and 21% in `push`, both across that boundary.
9121                        //
9122                        // The site is `pc + width`, which is exactly the `next` the slow arm
9123                        // passes — the two must agree or every fast lookup misses and
9124                        // re-records the same entry forever.
9125                        //
9126                        // A miss leaves the stack untouched (`fast_field_get` peeks) so the
9127                        // slow arm finds the receiver where it expects it.
9128                        // `name` resolved from the global-variable cache inside the loop.
9129                        //
9130                        // Same shape as `get_field` above and for the same reason: `get_var`
9131                        // was not in the fast loop, so reading a global — which `fib` does
9132                        // once per recursive call, for its own name — cost a `stop(pc)`, a
9133                        // return out of the loop, a `step` re-dispatch and a re-entry, before
9134                        // `get_global` even started its `scopes_are_plain` checks.
9135                        //
9136                        // Everything here is exactly `get_global`'s first branch: not lexical,
9137                        // no `eval` scope, cache hit. Anything else leaves the stack untouched
9138                        // and lets the slow arm decide.
9139                        Opcode::GetVar => {
9140                            let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
9141                                return Ok(self.stop(pc));
9142                            };
9143                            self.push(value);
9144                        }
9145                        Opcode::GetField | Opcode::GetField2 => {
9146                            let Some(value) =
9147                                self.fast_field_get(insn.a as usize, pc + insn.width())
9148                            else {
9149                                return Ok(self.stop(pc));
9150                            };
9151                            if insn.op == Opcode::GetField2 {
9152                                // `get_field2` keeps the receiver for the `call_method` that
9153                                // follows.
9154                                self.push(value);
9155                            } else {
9156                                // `get_field` replaces the receiver, so this is one store over
9157                                // the top slot rather than a `pop` and a `push`: the length
9158                                // never changes, so neither `Vec` arm has a capacity check or a
9159                                // drop to run beyond the one the overwrite itself does.
9160                                let frame = self.frame_mut();
9161                                match frame.stack.last_mut() {
9162                                    Some(slot) => *slot = value,
9163                                    None => return Ok(self.stop(pc)),
9164                                }
9165                            }
9166                        }
9167                        // -- constants ---------------------------------------------------
9168                        Opcode::PushMinus1
9169                        | Opcode::Push0
9170                        | Opcode::Push1
9171                        | Opcode::Push2
9172                        | Opcode::Push3
9173                        | Opcode::Push4
9174                        | Opcode::Push5
9175                        | Opcode::Push6
9176                        | Opcode::Push7
9177                        | Opcode::PushI8
9178                        | Opcode::PushI16
9179                        | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
9180                        // -- stack shuffling ---------------------------------------------
9181                        Opcode::Drop => {
9182                            self.pop();
9183                        }
9184                        // -- arithmetic on two integers ----------------------------------
9185                        //
9186                        // The operands are *looked at* before they are popped, so a non-integer
9187                        // pair leaves the stack exactly as the slow path expects to find it.
9188                        Opcode::Add if self.numeric_pair() => {
9189                            let right = self.pop();
9190                            let left = self.pop();
9191                            // Exactly [`add_numbers`], which is what the slow arm reaches.
9192                            let answer = match (&left, &right) {
9193                                (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
9194                                    Some(sum) => Value::Int(sum),
9195                                    None => Value::Float(*a as f64 + *b as f64),
9196                                },
9197                                _ => Value::Float(left.to_number() + right.to_number()),
9198                            };
9199                            self.push(answer);
9200                        }
9201                        Opcode::Sub
9202                        | Opcode::And
9203                        | Opcode::Or
9204                        | Opcode::Xor
9205                        | Opcode::Shl
9206                        | Opcode::Sar
9207                        | Opcode::Shr
9208                            if self.numeric_pair() =>
9209                        {
9210                            let right = self.pop();
9211                            let left = self.pop();
9212                            let answer =
9213                                arithmetic(insn.op, left, right).expect("numbers cannot throw");
9214                            self.push(answer);
9215                        }
9216                        Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
9217                            if self.numeric_pair() =>
9218                        {
9219                            let right = self.pop();
9220                            let left = self.pop();
9221                            let answer = self
9222                                .relational(insn.op, left, right)
9223                                .expect("numbers cannot throw");
9224                            self.push(answer);
9225                        }
9226                        // -- calls -------------------------------------------------------
9227                        //
9228                        // A plain call: `callee(arg0, …, argN) -> result`.
9229                        //
9230                        // This arm exists because of one measurement. `call:recursion` had
9231                        // **20.4% of its profile in `execute_instruction`** — the *slow*
9232                        // executor — and `fib`'s recursive call is the only thing in that
9233                        // function which is not a fast arm. Every call therefore left this
9234                        // loop via `stop()`, went through `step()`'s dispatch and
9235                        // `execute_instruction`'s match over every opcode, and came back here
9236                        // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
9237                        //
9238                        // Two things make it safe to do here rather than only in the slow path:
9239                        //
9240                        // * the caller's `pc` is stored *before* the call, which is what
9241                        //   `step` does too — so when the callee returns, the caller resumes
9242                        //   after the call and not at it;
9243                        // * `check_memory` runs, because `step` calls it once per instruction
9244                        //   and a call allocates a frame, its locals and its cells. Skipping
9245                        //   the checkpoint here would let a `--memory-limit` script overshoot
9246                        //   by one call per instruction.
9247                        Opcode::Call
9248                        | Opcode::Call0
9249                        | Opcode::Call1
9250                        | Opcode::Call2
9251                        | Opcode::Call3 => {
9252                            let argc = self.argc_operand(insn.op, insn.a);
9253                            let next = pc + insn.width();
9254                            {
9255                                let frame = self
9256                                    .frames
9257                                    .last_mut()
9258                                    .expect("run_fast() is only called with a live frame");
9259                                // `at` is what a stack trace reports for this frame, so a throw
9260                                // inside the callee has to see the call site and not whatever
9261                                // the last `stop()` left there.
9262                                frame.at = insn.offset as usize;
9263                                frame.pc = next;
9264                            }
9265                            self.check_memory()?;
9266                            self.check_interrupt()?;
9267                            let args = self.pop_n(argc);
9268                            let callee = self.pop();
9269                            // A plain call has no receiver; the callee decides what to do with
9270                            // `undefined` (a sloppy function substitutes the global object).
9271                            if let Some(result) =
9272                                self.call_or_push(callee, Value::Undefined, args)?
9273                            {
9274                                // Native, host, generator, async, bound — no frame was pushed,
9275                                // so this loop is still describing the right function. `pc`
9276                                // is advanced by the loop tail like every other arm; only the
9277                                // frame's copy had to be written here, and it already was.
9278                                self.push(result);
9279                            } else {
9280                                // A bytecode callee: its frame is on top now, and `insns` and
9281                                // `pc` both belong to the caller. Start over on the new frame.
9282                                continue 'outer;
9283                            }
9284                        }
9285                        // -- return ------------------------------------------------------
9286                        Opcode::Return => {
9287                            let value = self.pop();
9288                            self.frame_mut().pc = pc + insn.width();
9289                            return Ok(Some(value));
9290                        }
9291                        Opcode::ReturnUndef => {
9292                            self.frame_mut().pc = pc + insn.width();
9293                            return Ok(Some(Value::Undefined));
9294                        }
9295                        // Everything else needs the slow path.
9296                        _ => return Ok(self.stop(pc)),
9297                    },
9298                }
9299                pc += insn.width();
9300            }
9301        }
9302    }
9303
9304    /// Whether the top two operand-stack values are both numbers.
9305    ///
9306    /// The guard the fast loop uses before it takes an arithmetic record: two numbers
9307    /// cannot run script, so the arm may not throw and may not change frames.
9308    fn numeric_pair(&self) -> bool {
9309        is_number(&self.peek(0)) && is_number(&self.peek(1))
9310    }
9311
9312    /// `a[i]` for a dense array and an integer index, without the string round trip.
9313    ///
9314    /// The slow path answers this by turning `i` into a string (`propkey` →
9315    /// `number_to_string`) and then parsing it straight back (`read_field_key` →
9316    /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
9317    /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
9318    /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
9319    /// without even the cheap `Int` formatting.
9320    ///
9321    /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
9322    /// unambiguously the one the slow path would give:
9323    ///
9324    /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
9325    ///   `2^32-1` is the length, not an index),
9326    /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
9327    ///   typed array or an ordinary object, all of which have their own rules),
9328    /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
9329    ///   starts walking the prototype chain, and `a[i]` on a hole must find
9330    ///   `Array.prototype[i]` if it exists rather than `undefined`.
9331    ///
9332    /// The last condition is the one that makes this safe rather than merely fast: an own
9333    /// element always wins over the prototype, so a non-hole hit needs no further lookup.
9334    /// `get_var` answered from the global-variable cache, or `None`.
9335    ///
9336    /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
9337    /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
9338    /// records nothing — the slow arm is about to walk the chain and record it.
9339    fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
9340        let frame = self.frame();
9341        let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
9342        // "Lexical" is presence in the realm's table, not the closure var's flag: a
9343        // `GlobalRef` forwarded through a nested function has its flags cleared.
9344        if self.realm.globals.contains_key(name) {
9345            return None;
9346        }
9347        if !self.scopes_are_plain() {
9348            return None;
9349        }
9350        let object = &self.realm.global;
9351        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
9352        let cached = self.global_cache[site].as_ref()?;
9353        if !object.upgrades_to(&cached.object) {
9354            return None;
9355        }
9356        object.data_property_at(cached.index, name)
9357    }
9358
9359    /// `o.x` answered entirely from the inline cache, or `None`.
9360    ///
9361    /// Read-only on purpose: a miss must not record an entry, because the slow arm is
9362    /// about to do exactly that and recording it twice would rebuild the chain for every
9363    /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
9364    /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
9365    fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
9366        // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
9367        // an object receiver is a reference-count bump that the answer never needs.
9368        let frame = self.frame();
9369        let object = frame.stack.last()?;
9370        let Value::Object(target) = object else {
9371            return None;
9372        };
9373        // A proxy traps the lookup, so no cache entry ever describes it.
9374        if target.proxy_state().is_some() {
9375            return None;
9376        }
9377        let key = frame.code.atom_keys.get(atom)?;
9378        let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
9379        if cached.key != *key {
9380            return None;
9381        }
9382        Self::cached_hit(target, cached)
9383    }
9384
9385    fn fast_array_get(&self) -> Option<Value> {
9386        let Value::Int(index) = self.peek(0) else {
9387            return None;
9388        };
9389        // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
9390        // set for an `i32`.
9391        if index < 0 {
9392            return None;
9393        }
9394        let Value::Object(object) = self.peek(1) else {
9395            return None;
9396        };
9397        match object.array_get(index as usize) {
9398            Some(value) if !matches!(value, Value::Hole) => Some(value),
9399            _ => None,
9400        }
9401    }
9402
9403    /// `a[i] = v` on a dense array with an integer index, as one store.
9404    ///
9405    /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
9406    /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
9407    /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
9408    /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
9409    /// reference at the time it was measured (14.7x).
9410    ///
9411    /// Every condition here is one the slow path would also have to satisfy before
9412    /// storing into the element vector:
9413    ///
9414    /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
9415    ///   accepts as an index;
9416    /// * the target is an array whose elements are writable (`Object.freeze` clears it);
9417    /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
9418    ///   one inside a recorded descriptor, reports `false` and the caller stops.
9419    ///
9420    /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
9421    /// writes the own element too once `array_set` says it did.
9422    fn fast_array_set(&mut self) -> bool {
9423        // Every test runs *before* anything is popped: a refusal has to leave the stack
9424        // exactly as the slow path expects to find it. Popping first and reporting the
9425        // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
9426        // then ran the slow path with nothing to write.
9427        let Value::Int(index) = self.peek(1) else {
9428            return false;
9429        };
9430        // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
9431        if index < 0 {
9432            return false;
9433        }
9434        // Only a real array: a typed array's elements live in its buffer, a string-like
9435        // object has no element vector, and `array_set` on either does nothing.
9436        let Value::Object(object) = self.peek(2) else {
9437            return false;
9438        };
9439        if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
9440            return false;
9441        }
9442        // A non-extensible array reports `false` here, but the *slow* path has to decide
9443        // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
9444        // that with the key and the stack still intact.
9445        if !object.is_extensible() {
9446            return false;
9447        }
9448        // Inside the logical length, so the store cannot change `length`. Combined with
9449        // extensibility above, the only growth left for `array_set` is filling a hole in
9450        // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
9451        // shape this fast path exists for. A store past the length would grow the array,
9452        // and whether that is allowed is the slow path's question.
9453        if index as usize >= object.array_length().unwrap_or(0) {
9454            return false;
9455        }
9456        // The bound `array_set` refuses past. Checking it here keeps that arm from having
9457        // to report a failure after the operands are gone.
9458        if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
9459            return false;
9460        }
9461        let value = self.pop();
9462        self.pop();
9463        self.pop();
9464        object.array_store(self.heap, index as usize, value)
9465    }
9466
9467    /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
9468    fn stop(&mut self, pc: usize) -> Option<Value> {
9469        self.frame_mut().pc = pc;
9470        None
9471    }
9472
9473    fn push(&mut self, value: Value) {
9474        self.frame_mut().stack.push(value);
9475    }
9476
9477    fn pop(&mut self) -> Value {
9478        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
9479    }
9480
9481    fn pop_n(&mut self, count: usize) -> Vec<Value> {
9482        let frame = self.frame_mut();
9483        let start = frame.stack.len().saturating_sub(count);
9484        frame.stack.split_off(start)
9485    }
9486
9487    fn peek(&self, back: usize) -> Value {
9488        let frame = self.frame();
9489        frame
9490            .stack
9491            .get(frame.stack.len().wrapping_sub(1 + back))
9492            .cloned()
9493            .unwrap_or(Value::Undefined)
9494    }
9495
9496    #[allow(clippy::too_many_lines)]
9497    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
9498        use Opcode::*;
9499        match op {
9500            // -- constants and stack shuffling -----------------------------
9501            Nop => {}
9502            PushMinus1 => self.push(Value::Int(-1)),
9503            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
9504                let value = match op {
9505                    Push0 => 0,
9506                    Push1 => 1,
9507                    Push2 => 2,
9508                    Push3 => 3,
9509                    Push4 => 4,
9510                    Push5 => 5,
9511                    Push6 => 6,
9512                    _ => 7,
9513                };
9514                self.push(Value::Int(value));
9515            }
9516            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
9517            PushBigintI32 => {
9518                // The immediate form of a `BigInt` literal; the reference has the same
9519                // split between this and a constant-pool entry.
9520                let value = crate::bigint::BigInt::from_i64(a as i64);
9521                self.push(self.bigint(value));
9522            }
9523            PushTrue => self.push(Value::Bool(true)),
9524            PushFalse => self.push(Value::Bool(false)),
9525            PushEmptyString => self.push(self.string("")),
9526            Undefined => self.push(Value::Undefined),
9527            Null => self.push(Value::Null),
9528            Object => {
9529                let proto = self.realm.object_proto.clone();
9530                self.push(Value::Object(self.new_object(Some(proto))));
9531            }
9532            PushThis => {
9533                let this = self.frame().this.clone();
9534                self.push(this);
9535            }
9536            PushConst | PushConst8 => {
9537                let value = self.constant(a as usize)?;
9538                self.push(value);
9539            }
9540            PushAtomValue => {
9541                let text = self.atom_wtf8(a as usize);
9542                self.push(self.string_wtf8(text));
9543            }
9544            Dup => {
9545                let value = self.peek(0);
9546                self.push(value);
9547            }
9548            Dup2 => {
9549                // `a b -> a b a b`
9550                let b = self.peek(0);
9551                let a = self.peek(1);
9552                self.push(a);
9553                self.push(b);
9554            }
9555            Dup3 => {
9556                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
9557                // prototype and key while reading the current value through them.
9558                let c = self.peek(0);
9559                let b = self.peek(1);
9560                let a = self.peek(2);
9561                self.push(a);
9562                self.push(b);
9563                self.push(c);
9564            }
9565            Swap => {
9566                // `a b -> b a`
9567                let bottom = self.pop();
9568                let top = self.pop();
9569                self.push(bottom);
9570                self.push(top);
9571            }
9572            Perm3 => {
9573                // `a b c -> b a c`, the reference's reordering for a spread method
9574                // call: `obj func array` becomes the `func this array` that `apply`
9575                // takes.
9576                let c = self.pop();
9577                let b = self.pop();
9578                let a = self.pop();
9579                self.push(b);
9580                self.push(a);
9581                self.push(c);
9582            }
9583            Dup1 => {
9584                let value = self.peek(1);
9585                self.push(value);
9586            }
9587            Drop => {
9588                self.pop();
9589            }
9590            Nip => {
9591                // `a b -> b`
9592                let top = self.pop();
9593                self.pop();
9594                self.push(top);
9595            }
9596            Perm4 => {
9597                // `obj prop a b -> a obj prop b`, the reference's reordering for a
9598                // postfix update of a computed element: it puts the *old* value
9599                // underneath the receiver and key so `put_array_el` can consume them
9600                // and leave the old value as the expression's result.
9601                let d = self.pop();
9602                let c = self.pop();
9603                let b = self.pop();
9604                let a = self.pop();
9605                self.push(c);
9606                self.push(a);
9607                self.push(b);
9608                self.push(d);
9609            }
9610            Insert2 => {
9611                // `obj a -> a obj a`
9612                let value = self.pop();
9613                let object = self.pop();
9614                self.push(value.clone());
9615                self.push(object);
9616                self.push(value);
9617            }
9618            Insert3 => {
9619                // `obj prop a -> a obj prop a`
9620                let value = self.pop();
9621                let key = self.pop();
9622                let object = self.pop();
9623                self.push(value.clone());
9624                self.push(object);
9625                self.push(key);
9626                self.push(value);
9627            }
9628            Insert4 => {
9629                // `this obj prop a -> a this obj prop a`
9630                //
9631                // `put_super_value` consumes all four and yields nothing, so the copy
9632                // underneath is what leaves the assignment an expression value.
9633                let value = self.pop();
9634                let key = self.pop();
9635                let object = self.pop();
9636                let receiver = self.pop();
9637                self.push(value.clone());
9638                self.push(receiver);
9639                self.push(object);
9640                self.push(key);
9641                self.push(value);
9642            }
9643            Swap2 => {
9644                // `a b c d -> c d a b`
9645                let d = self.pop();
9646                let c = self.pop();
9647                let b = self.pop();
9648                let a = self.pop();
9649                self.push(c);
9650                self.push(d);
9651                self.push(a);
9652                self.push(b);
9653            }
9654            Rot3l => {
9655                // `x a b -> a b x`
9656                let b = self.pop();
9657                let a = self.pop();
9658                let x = self.pop();
9659                self.push(a);
9660                self.push(b);
9661                self.push(x);
9662            }
9663            Rot3r => {
9664                // `a b c -> c a b`
9665                let c = self.pop();
9666                let b = self.pop();
9667                let a_value = self.pop();
9668                self.push(c);
9669                self.push(a_value);
9670                self.push(b);
9671            }
9672
9673            Rest => {
9674                // `...rest` in a parameter list: the arguments from index `a` on, as a
9675                // real array. It takes nothing off the stack — the arguments are in the
9676                // frame, not on it.
9677                let frame = self.frame();
9678                let from = a as usize;
9679                let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
9680                let array = self.new_array(collected);
9681                self.push(Value::Object(array));
9682            }
9683
9684            // -- slots ------------------------------------------------------
9685            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
9686                let slot = self.slot_operand(op, a);
9687                let value = self.get_loc(slot);
9688                self.push(value);
9689            }
9690            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
9691                let slot = self.slot_operand(op, a);
9692                let value = self.pop();
9693                self.put_loc(slot, value);
9694            }
9695            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
9696                let slot = self.slot_operand(op, a);
9697                let value = self.pop();
9698                self.put_loc(slot, value.clone());
9699                self.push(value);
9700            }
9701            // The `_check` forms are the temporal dead zone: they throw when the
9702            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
9703            // *reads*, so only the two writes may pop — mishandling that quietly
9704            // consumes the value the caller pushed just before.
9705            GetLocCheck => {
9706                let slot = self.slot_operand(op, a);
9707                let value = self.get_loc(slot);
9708                if matches!(value, Value::Uninitialized) {
9709                    return Err(self.dead_zone(slot, VarSlot::Loc));
9710                }
9711                self.push(value);
9712            }
9713            PutLocCheck | SetLocCheck => {
9714                let slot = self.slot_operand(op, a);
9715                let value = self.pop();
9716                if matches!(value, Value::Uninitialized) {
9717                    return Err(self.dead_zone(slot, VarSlot::Loc));
9718                }
9719                // The initialiser goes through `put_loc`, not this, so any store that
9720                // reaches here is a later assignment — which a `const` refuses.
9721                if self.is_read_only(slot, VarSlot::Loc) {
9722                    return Err(self.read_only(slot, VarSlot::Loc));
9723                }
9724                if op == SetLocCheck {
9725                    self.put_loc(slot, value.clone());
9726                    self.push(value);
9727                } else {
9728                    self.put_loc(slot, value);
9729                }
9730            }
9731            PutLocCheckInit => {
9732                // The one store that *initialises* a lexical slot: `this` in a derived
9733                // constructor, which only exists after `super()` has run. A second
9734                // initialisation is the error the reference reports as
9735                // "'this' can be initialized only once".
9736                let slot = self.slot_operand(op, a);
9737                let value = self.pop();
9738                if !matches!(self.get_loc(slot), Value::Uninitialized) {
9739                    return Err(Signal::Throw(self.make_error(
9740                        "ReferenceError",
9741                        "'this' can be initialized only once",
9742                    )));
9743                }
9744                self.put_loc(slot, value);
9745            }
9746            CheckCtor => {
9747                // A class constructor may only run under `new`, which is what makes
9748                // `class A {}; A()` a TypeError.
9749                if matches!(self.frame().new_target, Value::Undefined) {
9750                    return Err(Signal::Throw(self.make_error(
9751                        "TypeError",
9752                        "class constructors must be invoked with 'new'",
9753                    )));
9754                }
9755            }
9756            InitCtor => {
9757                // The body a derived class gets when it declares no constructor:
9758                // forward every argument to the parent constructor, keeping `new.target`.
9759                if matches!(self.frame().new_target, Value::Undefined) {
9760                    return Err(Signal::Throw(self.make_error(
9761                        "TypeError",
9762                        "class constructors must be invoked with 'new'",
9763                    )));
9764                }
9765                let Some(callee) = self.current_callee() else {
9766                    return Err(Signal::Throw(
9767                        self.make_error("TypeError", "no constructor to inherit from"),
9768                    ));
9769                };
9770                let parent = callee.proto().map_or(Value::Null, Value::Object);
9771                let new_target = self.frame().new_target.clone();
9772                let args = self.frame().passed().to_vec();
9773                let result = self.construct(parent, new_target, args)?;
9774                self.push(result);
9775            }
9776            SetLocUninitialized => {
9777                let slot = self.slot_operand(op, a);
9778                self.put_loc(slot, Value::Uninitialized);
9779            }
9780            CloseLoc => {
9781                // "Close" a binding: give it a *fresh* cell holding the current
9782                // value. Closures created before this point keep the old cell and the
9783                // ones created after see the new one, which is what makes every
9784                // iteration of `for (let i ...)` capture its own `i`, and what freezes
9785                // a block-scoped binding when the block ends.
9786                //
9787                // Clearing the slot instead (which this used to do) broke both: a
9788                // closure over a captured block variable read `undefined`, and a loop
9789                // terminated after one iteration.
9790                let slot = self.slot_operand(op, a);
9791                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
9792                if index >= 0 {
9793                    let current = self.frame().cells[index as usize].get();
9794                    let fresh = self.new_cell(current);
9795                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
9796                        *cell = fresh;
9797                    }
9798                }
9799            }
9800            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
9801                let slot = self.slot_operand(op, a);
9802                let value = self.get_arg(slot);
9803                self.push(value);
9804            }
9805            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
9806                let slot = self.slot_operand(op, a);
9807                let value = self.pop();
9808                self.put_arg(slot, value);
9809            }
9810            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
9811                let slot = self.slot_operand(op, a);
9812                let value = self.pop();
9813                self.put_arg(slot, value.clone());
9814                self.push(value);
9815            }
9816
9817            // -- closure variables ------------------------------------------
9818            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
9819                let slot = self.slot_operand(op, a);
9820                // A name a direct `eval` created shadows the binding the compiler chose.
9821                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
9822                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
9823                // and only a runtime lookup can know that.
9824                if let Some(cell) = self.eval_created_local(slot) {
9825                    self.push(cell.get());
9826                    return self.step();
9827                }
9828                let value = self.cell_value(slot)?;
9829                self.push(value);
9830            }
9831            GetVarRefCheck => {
9832                let slot = self.slot_operand(op, a);
9833                let value = self.cell_value(slot)?;
9834                if matches!(value, Value::Uninitialized) {
9835                    return Err(self.dead_zone(slot, VarSlot::Closure));
9836                }
9837                self.push(value);
9838            }
9839            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
9840                let slot = self.slot_operand(op, a);
9841                let value = self.pop();
9842                if let Some(cell) = self.eval_created_local(slot) {
9843                    cell.set(value);
9844                    return self.step();
9845                }
9846                // Same rule as `PutLocCheck`: a checked store to a captured binding
9847                // refuses a `const` once its initialiser has run.
9848                if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
9849                    return Err(self.read_only(slot, VarSlot::Closure));
9850                }
9851                self.set_cell(slot, value)?;
9852            }
9853            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
9854                let slot = self.slot_operand(op, a);
9855                let value = self.pop();
9856                if let Some(cell) = self.eval_created_local(slot) {
9857                    cell.set(value.clone());
9858                    self.push(value);
9859                    return self.step();
9860                }
9861                self.set_cell(slot, value.clone())?;
9862                self.push(value);
9863            }
9864
9865            // -- globals ----------------------------------------------------
9866            GetVar => {
9867                let value = self.get_global(a as usize)?;
9868                self.push(value);
9869            }
9870            GetVarUndef => {
9871                let value = self
9872                    .get_global(a as usize)
9873                    .or_else(|_| Ok(Value::Undefined))?;
9874                self.push(value);
9875            }
9876            DeleteVar => {
9877                // `delete name` for a name that is not a declared binding. A lexical
9878                // global lives in the reference table and cannot be deleted; anything
9879                // reachable only as a property of the global object is *implicit* —
9880                // `x = 1` with no declaration — and goes away if it is configurable,
9881                // which is what `delete` on an implicit global answers.
9882                let name = self.atom_text(a as usize);
9883                let global = self.realm.global.clone();
9884                let deleted = if self.realm.globals.contains_key(&name) {
9885                    false
9886                } else if global.own_property(&name).is_some() {
9887                    self.delete_property(&global, &name)?
9888                } else {
9889                    true
9890                };
9891                self.push(Value::Bool(deleted));
9892            }
9893            PutVar => {
9894                let value = self.pop();
9895                self.put_global(a as usize, value)?;
9896            }
9897            PutVarInit => {
9898                let slot = a as usize;
9899                let value = self.pop();
9900                self.init_global(slot, value)?;
9901            }
9902
9903            // -- arithmetic -------------------------------------------------
9904            Add => self.binary_add()?,
9905            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
9906                let raw_right = self.pop();
9907                let raw_left = self.pop();
9908                // BigInt arithmetic is a separate path, and not only for the type of the
9909                // result: `ToNumber` of a bigint throws, so mixing the two must be an error
9910                // rather than a silent conversion.
9911                if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
9912                    let left = self.primitive_of(raw_left)?;
9913                    let right = self.primitive_of(raw_right)?;
9914                    let value = self.bigint_arithmetic(op, left, right)?;
9915                    self.push(value);
9916                } else {
9917                    let right = self.numeric(raw_right)?;
9918                    let left = self.numeric(raw_left)?;
9919                    self.push(arithmetic(op, left, right)?);
9920                }
9921            }
9922            Neg => {
9923                let raw = self.pop();
9924                match raw {
9925                    // A bigint negates exactly, however wide it is.
9926                    Value::BigInt(big) => {
9927                        let negated = big.negate();
9928                        self.push(self.bigint(negated));
9929                    }
9930                    other => {
9931                        let value = self.numeric(other)?;
9932                        self.push(negate(value));
9933                    }
9934                }
9935            }
9936            Plus => {
9937                let value = self.pop();
9938                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
9939                // unary plus is defined to produce a *number*, which a bigint cannot
9940                // become without loss. It used to fall through to `NaN`.
9941                if matches!(value, Value::BigInt(_)) {
9942                    return Err(self.type_error("cannot convert bigint to number"));
9943                }
9944                let numeric = self.numeric_of(value)?;
9945                self.push(numeric);
9946            }
9947            Inc => {
9948                let raw = self.pop();
9949                let (_, updated) = self.advance_numeric(raw, true)?;
9950                self.push(updated);
9951            }
9952            Dec => {
9953                let raw = self.pop();
9954                let (_, updated) = self.advance_numeric(raw, false)?;
9955                self.push(updated);
9956            }
9957            PostInc | PostDec => {
9958                // `x -> x x+1`: the *new* value ends up on top, so the store the
9959                // compiler emits right after (`put_var`) writes the incremented
9960                // one, while the old value stays underneath for the expression's
9961                // own result. Getting this backwards makes `i++` a no-op, which
9962                // turns `while (i < 3)` into an infinite loop.
9963                let raw = self.pop();
9964                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
9965                self.push(old);
9966                self.push(updated);
9967            }
9968            Not => {
9969                let raw = self.pop();
9970                match raw {
9971                    // `~x` on a bigint is `-x - 1`, exact at any width.
9972                    Value::BigInt(big) => {
9973                        let inverted = big.bitnot();
9974                        self.push(self.bigint(inverted));
9975                    }
9976                    other => {
9977                        let value = self.numeric(other)?;
9978                        self.push(Value::Int(!value.to_int32()));
9979                    }
9980                }
9981            }
9982            Lnot => {
9983                let value = self.pop();
9984                self.push(Value::Bool(!value.to_boolean()));
9985            }
9986
9987            // -- comparison -------------------------------------------------
9988            Lt | Lte | Gt | Gte => {
9989                let right = self.pop();
9990                let left = self.pop();
9991                let answer = self.relational(op, left, right)?;
9992                self.push(answer);
9993            }
9994            Eq | Neq => {
9995                let right = self.pop();
9996                let left = self.pop();
9997                let equal = self.abstract_equals(left, right)?;
9998                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
9999            }
10000            StrictEq => {
10001                let right = self.pop();
10002                let left = self.pop();
10003                self.push(Value::Bool(left.strict_equals(&right)));
10004            }
10005            StrictNeq => {
10006                let right = self.pop();
10007                let left = self.pop();
10008                self.push(Value::Bool(!left.strict_equals(&right)));
10009            }
10010            IsUndefined => {
10011                // `=== undefined`, which is what a destructuring default tests. It is
10012                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
10013                let value = self.pop();
10014                self.push(Value::Bool(matches!(value, Value::Undefined)));
10015            }
10016            IsUndefinedOrNull => {
10017                let value = self.pop();
10018                self.push(Value::Bool(value.is_nullish()));
10019            }
10020            Typeof => {
10021                let value = self.pop();
10022                self.push(self.string(value.type_of()));
10023            }
10024            ToObject => {
10025                // A destructuring *object* pattern starts here, which is why
10026                // `var {} = null` throws. Only `undefined` and `null` are refused; a
10027                // primitive is boxed.
10028                let value = self.pop();
10029                let object = self.object_from(&value)?;
10030                self.push(Value::Object(object));
10031            }
10032            Instanceof => {
10033                let constructor = self.pop();
10034                let object = self.pop();
10035                let answer = self.instance_of(&object, &constructor)?;
10036                self.push(Value::Bool(answer));
10037            }
10038            In => {
10039                let object = self.pop();
10040                let key = self.pop();
10041                let answer = self.has_property(&key, &object)?;
10042                self.push(Value::Bool(answer));
10043            }
10044
10045            // -- control flow -----------------------------------------------
10046            Goto | Goto8 | Goto16 => {
10047                self.frame_mut().pc = a as usize;
10048            }
10049            IfTrue | IfTrue8 => {
10050                let value = self.pop();
10051                if value.to_boolean() {
10052                    self.frame_mut().pc = a as usize;
10053                }
10054            }
10055            IfFalse | IfFalse8 => {
10056                let value = self.pop();
10057                if !value.to_boolean() {
10058                    self.frame_mut().pc = a as usize;
10059                }
10060            }
10061            Catch => {
10062                // Pushes the handler target onto the value stack; `unwind` finds it.
10063                self.push(Value::CatchOffset(a));
10064            }
10065            Gosub => {
10066                self.push(Value::ReturnAddress(next as u32));
10067                self.frame_mut().pc = a as usize;
10068            }
10069            Ret => {
10070                let value = self.pop();
10071                match value {
10072                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
10073                    _ => {
10074                        return Err(Signal::Throw(
10075                            self.make_error("InternalError", "invalid return address"),
10076                        ));
10077                    }
10078                }
10079            }
10080            NipCatch => {
10081                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
10082                // including the marker, keeping the top value.
10083                let top = self.pop();
10084                loop {
10085                    match self.pop() {
10086                        Value::CatchOffset(_) | Value::Undefined => break,
10087                        _ => {}
10088                    }
10089                    if self.frame().stack.is_empty() {
10090                        break;
10091                    }
10092                }
10093                self.push(top);
10094            }
10095            Throw => {
10096                let value = self.pop();
10097                return Err(Signal::Throw(value));
10098            }
10099            ThrowError => {
10100                let name = self.atom_text(a as usize);
10101                let (class, message) = match b {
10102                    0 => ("TypeError", format!("'{name}' is read-only")),
10103                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
10104                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
10105                    // `delete super.x` is a syntax-level mistake the reference reports
10106                    // with this wording, not a property-access failure.
10107                    3 => (
10108                        "ReferenceError",
10109                        "unsupported reference to 'super'".to_string(),
10110                    ),
10111                    4 => (
10112                        "TypeError",
10113                        "iterator does not have a throw method".to_string(),
10114                    ),
10115                    5 => (
10116                        "ReferenceError",
10117                        "invalid assignment left-hand side".to_string(),
10118                    ),
10119                    _ => ("TypeError", format!("invalid operation on '{name}'")),
10120                };
10121                return Err(Signal::Throw(self.make_error(class, &message)));
10122            }
10123            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
10124            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
10125            YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
10126            AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
10127            Await => return Ok(Step::Suspend(SuspendKind::Await)),
10128            ReturnAsync => {
10129                // The reference's `return_async` returns `undefined` and lets the resume
10130                // machinery pick the real value off `sp[-1]`, which is how it tells a
10131                // completion from a suspension. Carrying the value explicitly says the
10132                // same thing without the implicit stack slot.
10133                let value = self.pop();
10134                return Ok(Step::Return(value));
10135            }
10136            Return => {
10137                let value = self.pop();
10138                return Ok(Step::Return(value));
10139            }
10140            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
10141
10142            // -- calls ------------------------------------------------------
10143            Call | Call0 | Call1 | Call2 | Call3 => {
10144                let argc = self.argc_operand(op, a);
10145                let args = self.pop_n(argc);
10146                let callee = self.pop();
10147                // A plain call has no receiver; the callee decides what to do with
10148                // `undefined` (a sloppy function substitutes the global object).
10149                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
10150                    self.push(result);
10151                }
10152            }
10153            CallConstructor => {
10154                // `constructor this_obj args… -> object`. The duplicated
10155                // constructor is `new.target`; this milestone does not expose it,
10156                // so the extra copy is simply consumed here.
10157                let argc = a as usize;
10158                let args = self.pop_n(argc);
10159                let new_target = self.pop();
10160                let callee = self.pop();
10161                let result = self.construct(callee, new_target, args)?;
10162                self.push(result);
10163            }
10164            CallMethod => {
10165                let argc = a as usize;
10166                let args = self.pop_n(argc);
10167                let callee = self.pop();
10168                let this = self.pop();
10169                if let Some(result) = self.call_or_push(callee, this, args)? {
10170                    self.push(result);
10171                }
10172            }
10173            Apply => {
10174                // `func this array -> result`, the spread-call form: the compiler
10175                // builds one array of arguments, and all that is left here is to
10176                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
10177                let array = self.pop();
10178                let this = self.pop();
10179                let callee = self.pop();
10180                let args = self.array_like_to_args(&array)?;
10181                if a & 1 != 0 {
10182                    let result = self.construct(callee, this, args)?;
10183                    self.push(result);
10184                } else if let Some(result) = self.call_or_push(callee, this, args)? {
10185                    self.push(result);
10186                }
10187            }
10188            TailCall | TailCallMethod => {
10189                // `tail_call` is `call` whose result is returned immediately — the
10190                // reference jumps straight to `done` instead of storing the value and
10191                // running on. The callee still gets its own frame, so deep tail
10192                // recursion hits the stack limit exactly like plain recursion does;
10193                // marking this frame lets the return path unwind without needing
10194                // instructions after the call.
10195                let argc = if op == TailCallMethod {
10196                    a as usize
10197                } else {
10198                    self.argc_operand(op, a)
10199                };
10200                let args = self.pop_n(argc);
10201                let callee = self.pop();
10202                let this = if op == TailCallMethod {
10203                    self.pop()
10204                } else {
10205                    Value::Undefined
10206                };
10207                if let Value::Object(function) = &callee
10208                    && let Some((code, env)) = bytecode_of(function)
10209                {
10210                    // A generator or async body is not run here at all: calling it only
10211                    // *creates* the generator/coroutine, so it must not inherit this
10212                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
10213                    // onto `f`'s frame, and the first `yield`/`await` then reported
10214                    // "a generator body ran as an ordinary call".
10215                    if code.code.kind.is_generator() || code.code.kind.is_async() {
10216                        let value = self.call_value(callee, this, args)?;
10217                        return Ok(Step::Return(value));
10218                    }
10219                    self.frame_mut().tail = true;
10220                    self.push_frame(code, env, this, args, callee)?;
10221                    return Ok(Step::Continue);
10222                }
10223                // A native callee has no frame to reuse, so its value is simply
10224                // returned.
10225                let value = self.call_value(callee, this, args)?;
10226                return Ok(Step::Return(value));
10227            }
10228
10229            // -- objects ----------------------------------------------------
10230            SpecialObject => {
10231                let value = self.special_object(a)?;
10232                self.push(value);
10233            }
10234            PrivateSymbol => {
10235                // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
10236                // symbol each time it is evaluated, which is why the compiler evaluates it
10237                // once (at class definition) and stores it in a class-scope binding.
10238                let name = self.atom_text(a as usize);
10239                let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
10240                self.push(Value::Symbol(symbol));
10241            }
10242            GetPrivateField => {
10243                // `obj symbol -> value`. A missing private field is a TypeError, which is what
10244                // makes `#x` inaccessible on any object not built by this class.
10245                let symbol = self.pop();
10246                let object = self.pop();
10247                let value = self.read_private_field(&object, &symbol)?;
10248                self.push(value);
10249            }
10250            PutPrivateField => {
10251                // `obj value symbol ->`, and the store is a plain assignment to a property the
10252                // class already created, so there is no setter to consult.
10253                let symbol = self.pop();
10254                let value = self.pop();
10255                let object = self.pop();
10256                self.write_private_field(&object, &symbol, value)?;
10257            }
10258            DefinePrivateField => {
10259                // `obj symbol value -> obj`: a field initialiser creates the property, and
10260                // redefining one is a TypeError ("already exists").
10261                let value = self.pop();
10262                let symbol = self.pop();
10263                let object = self.pop();
10264                self.define_private_field(&object, &symbol, value)?;
10265                self.push(object);
10266            }
10267            PrivateIn => {
10268                // `obj key -> bool`: `#x in o`. The second operand decides which question is
10269                // being asked, which is the reference's `js_operator_private_in`: a *symbol*
10270                // is a field, so this is an own-property test; a *function* is a method or
10271                // accessor, so this is a brand check.
10272                let key = self.pop();
10273                let object = self.pop();
10274                let Some(target) = object.as_object() else {
10275                    return Err(Signal::Throw(
10276                        self.make_error("TypeError", "invalid 'in' operand"),
10277                    ));
10278                };
10279                let present = match &key {
10280                    Value::Object(_) => self.check_brand(target, &key)?,
10281                    _ => target.own_property_key(&self.private_key(&key)?).is_some(),
10282                };
10283                self.push(Value::Bool(present));
10284            }
10285            AddBrand => {
10286                // `obj home ->`: create the class brand on `home` if it has none, then give
10287                // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
10288                // class definition: only the prototype's copy of the symbol is wanted.
10289                let home = self.pop();
10290                let object = self.pop();
10291                self.add_brand(&object, &home)?;
10292            }
10293            CheckBrand => {
10294                // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
10295                // Both stay, because the caller needs them — `nip` halves a read into its
10296                // value and `call_method` uses the pair as receiver and callee.
10297                let function = self.peek(0);
10298                let object = self.peek(1);
10299                let Some(target) = object.as_object() else {
10300                    return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10301                };
10302                if !self.check_brand(target, &function)? {
10303                    return Err(Signal::Throw(
10304                        self.make_error("TypeError", "invalid brand on object"),
10305                    ));
10306                }
10307            }
10308            GetLength => {
10309                // `get_length` is the `.length` read; an array and a string answer
10310                // from their own length, anything else from the property.
10311                let target = self.pop();
10312                let value = match &target {
10313                    Value::Object(object) => match object.array_length() {
10314                        Some(length) => crate::object::length_value(length),
10315                        None => self.read_field(&target, "length")?,
10316                    },
10317                    Value::String(text) => Value::Int(text.utf16_len() as i32),
10318                    _ => self.read_field(&target, "length")?,
10319                };
10320                self.push(value);
10321            }
10322            GetField | GetField2 => {
10323                let object = self.pop();
10324                // Borrowed out of the code object, not cloned: `atom_key` returns an owned
10325                // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
10326                // just below is what lets the borrow outlive the `&mut self` the lookup
10327                // needs — one refcount bump instead of a key clone plus its drop, on the
10328                // hottest property path there is: every `o.x` and every `o.m()` receiver.
10329                let code = self.frame().code.clone();
10330                let key = &code.atom_keys[a as usize];
10331                let value = self.read_field_cached(&object, key, next)?;
10332                if op == GetField2 {
10333                    self.push(object);
10334                }
10335                self.push(value);
10336            }
10337            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
10338                let key = self.pop();
10339                let object = self.pop();
10340                let key = self.propkey(&key)?;
10341                let value = self.read_field_key(&object, &key)?;
10342                if matches!(op, GetArrayEl2 | GetArrayEl3) {
10343                    self.push(object);
10344                }
10345                if op == GetArrayEl3 {
10346                    // The key goes back in its *value* form, which the compiler stores
10347                    // into the target of a destructuring assignment.
10348                    self.push(match &key {
10349                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
10350                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
10351                    });
10352                }
10353                self.push(value);
10354            }
10355            PutField => {
10356                let value = self.pop();
10357                let object = self.pop();
10358                // Borrowed, like the `get_field` arm: `atom_key` would return an owned
10359                // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
10360                // only reads. `this.value = …` is the write half of the hottest loop in
10361                // `property:method-call`, and `own_property_key` was 4.8% of the case.
10362                let code = self.frame().code.clone();
10363                let key = &code.atom_keys[a as usize];
10364                self.write_field_key(&object, key, value)?;
10365            }
10366            PutArrayEl => {
10367                let value = self.pop();
10368                let key = self.pop();
10369                let object = self.pop();
10370                let key = self.propkey(&key)?;
10371                self.write_field_key(&object, &key, value)?;
10372            }
10373            DefineField => {
10374                let value = self.pop();
10375                let object = self.pop();
10376                // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
10377                // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
10378                // three U+FFFD — a property under a different name from the one
10379                // `o["\uD800"]` reads.
10380                let code = self.frame().code.clone();
10381                let key = code.atom_keys[a as usize].clone();
10382                // No naming here. `{m: function(){}}` is named by the *compiler*, which
10383                // emits `set_name` — and only where `NamedEvaluation` applies, so
10384                // `{m: (0, function(){})}` stays anonymous. Naming every function that
10385                // reaches a property definition got that case wrong, and the compiler is
10386                // the only place that can tell the two apart.
10387                if let Some(target) = object.as_object() {
10388                    // Only an *array* stores into the element vector. A numeric key
10389                    // on an ordinary object is an ordinary property, which is what
10390                    // makes `{1: 'a'}` iterate as a key rather than disappear.
10391                    let stored = target.is_array()
10392                        && key.as_str().and_then(array_index).is_some_and(|index| {
10393                            target.array_set(self.heap, index as usize, value.clone())
10394                        });
10395                    if !stored {
10396                        target.define_data_key(&key, value);
10397                    }
10398                }
10399                self.push(object);
10400            }
10401            DefineArrayEl => {
10402                // `obj key value -> obj key`. The *value* form of the key is what goes
10403                // back on the stack — the compiler stores it into the pattern's binding —
10404                // so the symbol is not stringified on the way through.
10405                let value = self.pop();
10406                let key_value = self.pop();
10407                let object = self.peek(0);
10408                let key = self.propkey(&key_value)?;
10409                self.write_field_key(&object, &key, value)?;
10410                self.push(key_value);
10411            }
10412            SetHomeObject => {
10413                // `obj func -> obj func`: records the object a method was defined on so
10414                // `super` inside it resolves against that object's prototype.
10415                let function = self.peek(0);
10416                let home = self.peek(1);
10417                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
10418                    function.set_home_object(Some(home.clone()));
10419                }
10420            }
10421            Regexp => {
10422                // `pattern flags -> regexp`. A literal compiles here rather than through the
10423                // constructor, which is both what the reference's dedicated opcode is for
10424                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
10425                let flags = self.pop();
10426                let pattern = self.pop();
10427                let pattern = self.to_js_string(&pattern)?;
10428                let flags = self.to_js_string(&flags)?;
10429                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
10430                self.push(Value::Object(object));
10431            }
10432            UsingDisposeInit => {
10433                // The error state a disposal accumulates into. Uninitialised means "no
10434                // failure yet"; anything else is the exception being propagated.
10435                self.push(Value::Uninitialized);
10436            }
10437            UsingCheck => {
10438                // `value -> value, method`: validate and snapshot the disposer now, so a
10439                // later change to `Symbol.dispose` cannot change what gets called, and so a
10440                // value that is not disposable fails before the body runs.
10441                let value = self.pop();
10442                let method = self.using_method_for(&value, a as u8 == 1)?;
10443                self.push(value);
10444                self.push(method);
10445            }
10446            UsingDispose => {
10447                // `error_state -> error_state'`: dispose the variable at `slot` — its value
10448                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
10449                // the pending error.
10450                let slot = self.slot_operand(op, a);
10451                let error_state = self.pop();
10452                let merged = self.using_dispose_once(slot, error_state)?;
10453                self.push(merged);
10454            }
10455            UsingDisposeMerge => {
10456                let new_error = self.pop();
10457                let error_state = self.pop();
10458                let merged = self.merge_dispose_error(new_error, error_state);
10459                self.push(merged);
10460            }
10461            UsingDisposeEnd => {
10462                // A disposal that failed replaces the block's normal completion, so the
10463                // error state becomes a real throw here rather than at the call site.
10464                let error_state = self.pop();
10465                if !matches!(error_state, Value::Uninitialized) {
10466                    return Err(Signal::Throw(error_state));
10467                }
10468            }
10469            UsingDisposeAsync => {
10470                // `await using` needs a promise to await and this runtime has no
10471                // `Promise` builtin, so the disposer is called synchronously and its result
10472                // discarded. That is correct for a disposer that returns nothing and is
10473                // reported as a gap rather than silently skipped.
10474                let slot = self.slot_operand(op, a);
10475                let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
10476                self.push(error_state);
10477            }
10478            GetSuper => {
10479                // `obj -> obj's prototype`: the starting point of a `super` lookup.
10480                let object = self.pop();
10481                let proto = match &object {
10482                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
10483                    _ => Value::Null,
10484                };
10485                self.push(proto);
10486            }
10487            GetSuperValue => {
10488                // `receiver proto key -> value`, searching from `proto` but reporting to
10489                // `receiver`, which is what `super.g` must do for a getter to see `this`.
10490                //
10491                // Three values in, one out: the receiver is *consumed*, not left under the
10492                // result. Leaving it there was invisible for `super.x` in `return` or
10493                // statement position (the result is what gets popped) and corrupted the
10494                // frame everywhere else — `print(super.x)` left the class where the call
10495                // opcode looks for the receiver and called the class itself.
10496                let key = self.pop();
10497                let proto = self.pop();
10498                let receiver = self.pop();
10499                let value = self.super_read(&receiver, &proto, &key)?;
10500                self.push(value);
10501            }
10502            PutSuperValue => {
10503                // `receiver proto key value ->`: a store that starts at `proto` but
10504                // assigns to `receiver`.
10505                let value = self.pop();
10506                let key = self.pop();
10507                let proto = self.pop();
10508                let receiver = self.pop();
10509                self.super_write(&receiver, &proto, &key, value)?;
10510            }
10511            DefineClass => {
10512                // `parent ctor -> ctor proto`: the constructor becomes the class and a
10513                // fresh prototype object lands on top for the methods to go on.
10514                let name = self.atom_text(a as usize);
10515                let (ctor, proto) = self.define_class(&name, b)?;
10516                self.push(ctor);
10517                self.push(Value::Object(proto));
10518            }
10519            DefineClassComputed => {
10520                // `parent ctor key -> ctor proto key`: the computed name stays put so
10521                // `define_field`-style consumers can still read it.
10522                let key = self.pop();
10523                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
10524                let (ctor, proto) = self.define_class(&name, b)?;
10525                self.push(ctor);
10526                self.push(Value::Object(proto));
10527                self.push(key);
10528            }
10529            DefineMethod => {
10530                let function = self.pop();
10531                let object = self.pop();
10532                // The exact key, like `define_field`: a quoted method key may hold an
10533                // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
10534                // that `o["\uD800"]` finds.
10535                let code = self.frame().code.clone();
10536                let key = code.atom_keys[a as usize].clone();
10537                // A method's `[[HomeObject]]` is the object it was defined on, which is
10538                // what `super` inside it resolves against.
10539                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
10540                    function.set_home_object(Some(object.clone()));
10541                }
10542                if let Some(text) = key.as_wtf8() {
10543                    self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
10544                } else {
10545                    self.set_function_name(
10546                        &function,
10547                        &key_with_accessor_prefix(&key.to_string(), b),
10548                    );
10549                }
10550                if let Some(array) = object.as_object() {
10551                    define_function_property(array, &key, function, b);
10552                }
10553                self.push(object);
10554            }
10555            DefineMethodComputed => {
10556                let function = self.pop();
10557                let key = self.pop();
10558                let object = self.pop();
10559                let key = self.propkey(&key)?;
10560                // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
10561                // the name: `super` inside a computed method resolves through it. Without
10562                // this, `class B extends A { [k]() { return super.m() } }` read the
10563                // home object as null and threw.
10564                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
10565                    function.set_home_object(Some(object.clone()));
10566                }
10567                match key.as_wtf8() {
10568                    Some(text) => {
10569                        let name = accessor_prefixed(text, a);
10570                        self.set_function_name_wtf8(&function, &name);
10571                    }
10572                    None => self.set_function_name(
10573                        &function,
10574                        &key_with_accessor_prefix(&key.to_string(), a),
10575                    ),
10576                }
10577                if let Some(array) = object.as_object() {
10578                    define_function_property(array, &key, function, a);
10579                }
10580                self.push(object);
10581            }
10582            SetProto => {
10583                let proto = self.pop();
10584                let object = self.pop();
10585                if let Some(target) = object.as_object() {
10586                    target.set_proto(proto.as_object().cloned());
10587                }
10588                self.push(object);
10589            }
10590            CopyDataProperties => {
10591                let exclusion = self.pop();
10592                let source = self.pop();
10593                let target = self.peek(0);
10594                self.copy_properties(&target, &source, &exclusion)?;
10595                self.push(source);
10596                self.push(exclusion);
10597            }
10598            ToPropkey => {
10599                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
10600                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
10601                // ordinary `"Symbol(b)"` property.
10602                let value = self.pop();
10603                let key = match self.propkey(&value)? {
10604                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
10605                    PropertyKey::String(text) => self.string_wtf8(text),
10606                };
10607                self.push(key);
10608            }
10609            SetName => {
10610                let function = self.peek(0);
10611                let name = self.atom_wtf8(a as usize);
10612                self.set_function_name_wtf8(&function, &name);
10613            }
10614            SetNameComputed => {
10615                let key = self.peek(1);
10616                let function = self.peek(0);
10617                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
10618                self.set_function_name(&function, &name);
10619            }
10620
10621            // -- arrays -----------------------------------------------------
10622            ArrayFrom => {
10623                let count = a as usize;
10624                let elements = self.pop_n(count);
10625                let array = self.new_array(elements);
10626                self.push(Value::Object(array));
10627            }
10628            Append => {
10629                // `array index iterable -> array new_index`
10630                let iterable = self.pop();
10631                self.pop();
10632                let array = self.peek(0);
10633                let added = self.append_enumerate(&array, &iterable)?;
10634                self.push(Value::Int(added));
10635            }
10636
10637            // -- iteration --------------------------------------------------
10638            ForInStart => {
10639                let value = self.pop();
10640                let record = self.for_in_record(&value)?;
10641                self.push(Value::Object(record));
10642            }
10643            ForInNext => {
10644                // `record -> record key done`. The flag is *done*, not "found":
10645                // the compiler tests it with `if_false` to jump back into the body,
10646                // so reporting `true` while keys remain would end the loop at once.
10647                let record = self.peek(0);
10648                match self.for_in_advance(&record)? {
10649                    Some(key) => {
10650                        let text = self.string(key);
10651                        self.push(text);
10652                        self.push(Value::Bool(false));
10653                    }
10654                    None => {
10655                        self.push(Value::Undefined);
10656                        self.push(Value::Bool(true));
10657                    }
10658                }
10659            }
10660            ForOfStart => {
10661                let value = self.pop();
10662                let iterator = self.get_iterator(&value)?;
10663                self.push(iterator.object);
10664                self.push(iterator.next);
10665                self.push(Value::CatchOffset(0));
10666            }
10667            ForOfNext => {
10668                // `iter next catch_offset -> iter next catch_offset value done`.
10669                //
10670                // The operand is how many values sit *above* the iterator triple: a
10671                // destructuring rest element keeps its target array and running index
10672                // there while draining the iterator, so the triple is not at the top.
10673                let extra = a as usize;
10674                let iterator_slot = 2 + extra;
10675                // An exhausted iterator is replaced by `undefined` (see below), so a
10676                // second step must not call `next` again — `Array.from` and a
10677                // destructuring pattern both keep stepping past the end.
10678                let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
10679                    (Value::Undefined, true)
10680                } else {
10681                    let iterator = Iterator {
10682                        object: self.peek(iterator_slot),
10683                        next: self.peek(1 + extra),
10684                    };
10685                    self.iterator_step(&iterator)?
10686                };
10687                if done {
10688                    // The result's `value` is meaningless once the iterator is done:
10689                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
10690                    // rather than binding the generator's return value.
10691                    let top = self.frame().stack.len() - 1 - iterator_slot;
10692                    self.frame_mut().stack[top] = Value::Undefined;
10693                    self.push(Value::Undefined);
10694                    self.push(Value::Bool(true));
10695                } else {
10696                    self.push(value);
10697                    self.push(Value::Bool(false));
10698                }
10699            }
10700            IteratorNext => {
10701                // `iter next catch val -> iter next catch val'`: replace the argument with
10702                // the result of `next(val)`. The triple below stays put, which is why the
10703                // three instructions of the `yield*` loop all address the stack the same way.
10704                let value = self.pop();
10705                let object = self.peek(2);
10706                let next = self.peek(1);
10707                let result = self.call_value(next, object, vec![value])?;
10708                self.push(result);
10709            }
10710            IteratorCall => {
10711                // `iter next catch val -> iter next catch val' flag`.
10712                //
10713                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
10714                // The flag is `true` when the method was missing, which is how the
10715                // caller learns that the inner iterator cannot take part in the
10716                // unwinding.
10717                let value = self.pop();
10718                let object = self.peek(2);
10719                let key = if a & 1 != 0 { "throw" } else { "return" };
10720                let method = self.read_field(&object, key)?;
10721                if matches!(method, Value::Undefined | Value::Null) {
10722                    self.push(value);
10723                    self.push(Value::Bool(true));
10724                } else {
10725                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
10726                    let result = self.call_value(method, object, argument)?;
10727                    self.push(result);
10728                    self.push(Value::Bool(false));
10729                }
10730            }
10731            IteratorCheckObject => {
10732                if !matches!(self.peek(0), Value::Object(_)) {
10733                    return Err(Signal::Throw(
10734                        self.make_error("TypeError", "iterator must return an object"),
10735                    ));
10736                }
10737            }
10738            IteratorClose => {
10739                // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
10740                // calling the iterator's `return` so it can release whatever it holds.
10741                //
10742                // The catch offset goes first, so an exception from `return` is not caught
10743                // by the loop being abandoned. This used to pop the three operands and call
10744                // nothing at all, which made `break` out of a `for of` invisible to an
10745                // iterator with a `return` method.
10746                self.pop();
10747                self.pop();
10748                let iterator = self.pop();
10749                if !matches!(iterator, Value::Undefined) {
10750                    let method = self.read_field(&iterator, "return")?;
10751                    if !matches!(method, Value::Undefined | Value::Null) {
10752                        let result = self.call_value(method, iterator.clone(), Vec::new())?;
10753                        // §7.4.6: a `return` that answers a non-object is a TypeError.
10754                        if !matches!(result, Value::Object(_)) {
10755                            return Err(Signal::Throw(
10756                                self.make_error("TypeError", "iterator must return an object"),
10757                            ));
10758                        }
10759                    }
10760                }
10761            }
10762            Import => {
10763                // `import(specifier)`: the options slot is on top and is not read yet.
10764                let _options = self.pop();
10765                let specifier = self.pop();
10766                let promise = self.dynamic_import(specifier)?;
10767                self.push(promise);
10768            }
10769            ForAwaitOfStart => {
10770                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
10771                // `Symbol.iterator` fallback.
10772                let value = self.pop();
10773                let iterator = self.get_async_iterator(&value)?;
10774                self.push(iterator.object);
10775                self.push(iterator.next);
10776                self.push(Value::CatchOffset(0));
10777            }
10778            ForAwaitOfNext => {
10779                // `for await` steps the iterator and leaves the *result* wrapped in a
10780                // promise, so the `await` the compiler emits right after this can suspend
10781                // on it. Unwrapping happens in `iterator_get_value_done`.
10782                let extra = a as usize;
10783                let iterator_slot = 2 + extra;
10784                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
10785                    Value::Undefined
10786                } else {
10787                    let iterator = Iterator {
10788                        object: self.peek(iterator_slot),
10789                        next: self.peek(1 + extra),
10790                    };
10791                    let next = iterator.next.clone();
10792                    self.call_value(next, iterator.object, Vec::new())?
10793                };
10794                let promise = self.promise_resolve_value(result)?;
10795                self.push(promise);
10796            }
10797            IteratorGetValueDone => {
10798                // `result -> value done`. A missing result object means the iterator was
10799                // already exhausted, which the loop treats as `done`.
10800                let result = self.pop();
10801                let done = match &result {
10802                    Value::Object(object) => self
10803                        .get_property(object, "done")?
10804                        .is_some_and(|value| value.to_boolean()),
10805                    _ => true,
10806                };
10807                if done {
10808                    // Clear the iterator object so the `iterator_close` the loop emits on
10809                    // its way out has nothing to close: `AsyncIteratorClose` must *not* run
10810                    // on normal completion, and this is where a normal completion is
10811                    // recognised — the same trick `for_of_next` uses, which also replaces
10812                    // the slot with `undefined`.
10813                    //
10814                    // The layout is fixed because only `for await` emits this opcode:
10815                    // `iter next catch [result]`, so the iterator is three below the top.
10816                    let depth = self.frame().stack.len();
10817                    if depth >= 3 {
10818                        self.frame_mut().stack[depth - 3] = Value::Undefined;
10819                    }
10820                    self.push(Value::Undefined);
10821                    self.push(Value::Bool(true));
10822                } else {
10823                    let Value::Object(object) = &result else {
10824                        self.push(Value::Undefined);
10825                        self.push(Value::Bool(true));
10826                        return Ok(Step::Continue);
10827                    };
10828                    let value = self
10829                        .get_property(object, "value")?
10830                        .unwrap_or(Value::Undefined);
10831                    self.push(value);
10832                    self.push(Value::Bool(false));
10833                }
10834            }
10835
10836            Delete => {
10837                // `delete obj[key]`, where the key was just pushed. Deleting an array
10838                // index leaves a *hole* rather than closing the gap, and a
10839                // non-configurable property answers `false` and stays.
10840                let key = self.pop();
10841                let target = self.pop();
10842                let key = self.propkey(&key)?;
10843                let text_label = key.as_str().unwrap_or("").to_string();
10844                let deleted = match &target {
10845                    Value::Object(object) => {
10846                        let object = object.clone();
10847                        self.delete_property_key(&object, &key)?
10848                    }
10849                    // A string's `length` and its index properties are
10850                    // non-configurable, so deleting one answers `false`.
10851                    Value::String(text) => {
10852                        !(text_label == "length"
10853                            || array_index(&text_label)
10854                                .is_some_and(|index| (index as usize) < text.utf16_len()))
10855                    }
10856                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
10857                    // object to delete from, and only a *boxable* primitive has one.
10858                    Value::Undefined | Value::Null => {
10859                        return Err(Signal::Throw(
10860                            self.make_error("TypeError", "cannot convert to object"),
10861                        ));
10862                    }
10863                    // Any other primitive has no own properties; deleting nothing
10864                    // succeeds.
10865                    _ => true,
10866                };
10867                // §13.5.1.2: in strict mode a `delete` that answers `false` is a
10868                // `TypeError` rather than a `false` result. Sloppy mode silently reports
10869                // the refusal, which is why the same statement throws here but not there.
10870                if !deleted && self.current_strict() {
10871                    return Err(Signal::Throw(
10872                        self.make_error("TypeError", "cannot delete property"),
10873                    ));
10874                }
10875                self.push(Value::Bool(deleted));
10876            }
10877
10878            // -- exceptions and bookkeeping ---------------------------------
10879            Fclosure | Fclosure8 => {
10880                let value = self.closure(a as usize)?;
10881                self.push(value);
10882            }
10883
10884            other => {
10885                let name = other.info().name;
10886                return Err(Signal::Throw(self.make_error(
10887                    "InternalError",
10888                    &format!("{name} is not implemented yet"),
10889                )));
10890            }
10891        }
10892        Ok(Step::Continue)
10893    }
10894
10895    // -- operand helpers ----------------------------------------------------
10896
10897    /// The slot index an operand names, taking short forms into account.
10898    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
10899        use Opcode::*;
10900        match op {
10901            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
10902            | SetVarRef0 => 0,
10903            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
10904            | SetVarRef1 => 1,
10905            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
10906            | SetVarRef2 => 2,
10907            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
10908            | SetVarRef3 => 3,
10909            _ => a as usize,
10910        }
10911    }
10912
10913    /// The argument count of a call, taking `call0`…`call3` into account.
10914    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
10915        use Opcode::*;
10916        match op {
10917            Call0 => 0,
10918            Call1 => 1,
10919            Call2 => 2,
10920            Call3 => 3,
10921            _ => a as usize,
10922        }
10923    }
10924
10925    /// The atom's name as a property key.
10926    ///
10927    /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
10928    /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
10929    /// `String::clone` was a heap allocation and a copy — per property access.
10930    /// The atom at `index`, as a property key.
10931    ///
10932    /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
10933    /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
10934    /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
10935    /// 5.3% of `property:monomorphic`.
10936    /// The atom's text, exactly — including an unpaired surrogate.
10937    ///
10938    /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
10939    /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
10940    /// `atom_text` below is for the other kind of use, where the atom is a key in the
10941    /// engine's own tables.
10942    fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
10943        self.frame()
10944            .code
10945            .code
10946            .atoms
10947            .get(index)
10948            .map(|atom| match atom {
10949                Atom::Str(text) => text.clone(),
10950                Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
10951                // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
10952                Atom::Null => crate::value::Wtf8::new(String::new()),
10953            })
10954            .unwrap_or_default()
10955    }
10956
10957    fn atom_text(&self, index: usize) -> String {
10958        self.frame()
10959            .code
10960            .code
10961            .atoms
10962            .get(index)
10963            .map(|atom| match atom {
10964                // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
10965                // compare it to an identifier, and a surrogate-bearing name is reachable
10966                // through `atom_wtf8` where it matters.
10967                Atom::Str(text) => text.to_string_lossy().into_owned(),
10968                Atom::Index(value) => value.to_string(),
10969                // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
10970                // `throw_error`, `delete super.x`) never read it.
10971                Atom::Null => String::new(),
10972            })
10973            .unwrap_or_default()
10974    }
10975
10976    fn constant(&mut self, index: usize) -> JsResult<Value> {
10977        let constant = self.frame().code.code.cpool.get(index).cloned();
10978        Ok(match &constant {
10979            Some(Constant::Number(number)) => Value::Float(*number),
10980            Some(Constant::String(text)) => self.string_wtf8(text.clone()),
10981            Some(Constant::BigInt { digits, radix }) => {
10982                match crate::bigint::BigInt::from_radix(digits, *radix) {
10983                    Some(big) => self.bigint(big),
10984                    // A literal the parser accepted is always parseable; a failure here
10985                    // would be a compiler bug, so it reads as an `InternalError`.
10986                    None => {
10987                        return Err(Signal::Throw(
10988                            self.make_error("InternalError", "unparseable bigint literal"),
10989                        ));
10990                    }
10991                }
10992            }
10993            Some(Constant::Function(_)) => {
10994                return Err(Signal::Throw(
10995                    self.make_error("InternalError", "a bare function constant"),
10996                ));
10997            }
10998            // A tagged template's call site: a frozen array of the cooked chunks with a
10999            // frozen `raw` array beside it, which is what `String.raw` reads back.
11000            Some(Constant::Template { cooked, raw }) => {
11001                let cooked_values: Vec<Value> = cooked
11002                    .iter()
11003                    .map(|chunk| match chunk {
11004                        Some(text) => self.string_wtf8(text.clone()),
11005                        None => Value::Undefined,
11006                    })
11007                    .collect();
11008                let raw_values: Vec<Value> =
11009                    raw.iter().map(|text| self.string(text.clone())).collect();
11010                let raw_array = self.new_array(raw_values);
11011                raw_array.set_extensible(false);
11012                let template = self.new_array(cooked_values);
11013                template.define(
11014                    "raw",
11015                    Property::with_attributes(Value::Object(raw_array), false, false),
11016                );
11017                template.set_extensible(false);
11018                Value::Object(template)
11019            }
11020            _ => Value::Undefined,
11021        })
11022    }
11023
11024    /// The reference cell a closure-variable slot names.
11025    ///
11026    /// Two kinds of binding share this addressing: a genuine closure variable
11027    /// (captured from an enclosing function) lives in this frame's environment,
11028    /// while a *declared global* lives in the realm so that a script, a function
11029    /// declaration and their uses all see one binding. A plain `Global` — an
11030    /// undeclared name that may be satisfied by the global object — has no cell at
11031    /// all, which is how `typeof x` still works for a name that does not exist.
11032    /// The reference cell a closure-variable slot names.
11033    ///
11034    /// The environment is resolved once, when the closure is built, and this is
11035    /// just the lookup afterwards. A *declared global* is in there too, pointing at
11036    /// the realm's cell, so a script, a hoisted function declaration and their uses
11037    /// all share one binding. A plain `Global` — a name the script never declared —
11038    /// is read and written through `get_var`/`put_var` by name instead, which is
11039    /// what lets the global object satisfy it.
11040    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
11041        self.frame().env.cells.get(slot).cloned()
11042    }
11043
11044    /// Whether `slot` refers to a global binding through the reference table.
11045    ///
11046    /// A global's cell in the closure environment only exists so the slot has
11047    /// something to point at; the binding itself lives on the global object (a `var`)
11048    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
11049    /// be routed, not performed on the placeholder.
11050    fn is_global_slot(&self, slot: usize) -> bool {
11051        self.frame()
11052            .code
11053            .code
11054            .closure_vars
11055            .get(slot)
11056            .is_some_and(|c| {
11057                // A module's declarations and imports are *not* globals: their cells are
11058                // the module environment's, filled by the host, so the placeholder routing
11059                // must not apply to them.
11060                matches!(
11061                    c.closure_type,
11062                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
11063                )
11064            })
11065    }
11066
11067    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
11068        if self.is_global_slot(slot) {
11069            return self.get_global(slot);
11070        }
11071        Ok(self
11072            .var_ref_cell(slot)
11073            .map(|cell| cell.get())
11074            .unwrap_or(Value::Undefined))
11075    }
11076
11077    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
11078        // A function declaration is hoisted by storing into a global reference before
11079        // the body runs, so this path is also what puts it on the global object.
11080        if self.is_global_slot(slot) {
11081            return self.put_global(slot, value);
11082        }
11083        if let Some(cell) = self.var_ref_cell(slot) {
11084            cell.set(value);
11085        }
11086        Ok(())
11087    }
11088
11089    // -- closures -----------------------------------------------------------
11090
11091    /// Build the closure for the function constant `index`.
11092    ///
11093    /// Every entry in the child's closure table names where its binding lives in
11094    /// *this* frame: a local or argument slot that was marked captured, or a cell
11095    /// this frame is itself holding. That is how a variable three functions deep
11096    /// stays one binding.
11097    fn closure(&mut self, index: usize) -> JsResult<Value> {
11098        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
11099        else {
11100            return Err(Signal::Throw(
11101                self.make_error("InternalError", "fclosure of a non-function"),
11102            ));
11103        };
11104        let mut cells = Vec::with_capacity(function.closure_vars.len());
11105        for closure_var in &function.closure_vars {
11106            let cell = match closure_var.closure_type {
11107                ClosureType::Arg => {
11108                    let slot = closure_var.var_idx as usize;
11109                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
11110                }
11111                ClosureType::Local => {
11112                    let slot = closure_var.var_idx as usize;
11113                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
11114                }
11115                ClosureType::Ref | ClosureType::GlobalRef => {
11116                    // A `Ref` names a cell in this frame's own closure table; a
11117                    // `GlobalRef` also starts there, then resolves by name below.
11118                    let slot = closure_var.var_idx as usize;
11119                    if let Some(cell) = self.frame().env.cells.get(slot) {
11120                        cells.push(cell.clone());
11121                        continue;
11122                    }
11123                    -1
11124                }
11125                _ => -1,
11126            };
11127            if cell >= 0 {
11128                let cell = self.frame().cells[cell as usize].clone();
11129                cells.push(cell);
11130                continue;
11131            }
11132            // A global: the cell is created on demand and shared through the realm,
11133            // so every function sees one binding.
11134            let name = closure_var.name.clone();
11135            let cell = match self.realm.globals.get(&name) {
11136                Some(cell) => cell.clone(),
11137                None => {
11138                    let cell = self.new_cell(Value::Undefined);
11139                    self.realm.globals.insert(name.clone(), cell.clone());
11140                    cell
11141                }
11142            };
11143            cells.push(cell);
11144        }
11145        let name = function.name.clone();
11146        // `.length` is the arity before any default or rest parameter, not the number
11147        // of slots a pattern parameter needs.
11148        let length = function.defined_args;
11149        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
11150        // function and an arrow function do not. A *method* also does not, but that is not
11151        // known here — the method is marked when the `[[HomeObject]]` is attached (see
11152        // `set_home_object`), which is the moment it becomes a method.
11153        let function_kind = function.kind;
11154        let constructible =
11155            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
11156        let code = Gc::new(self.heap, CompiledCode::new(*function));
11157        // A closure built inside an `eval` inherits the eval's view of the enclosing
11158        // bindings, so it can still read them once the eval has returned.
11159        let eval_scope = self
11160            .active_eval_scope
11161            .clone()
11162            .or_else(|| self.frame().env.eval_scope.clone());
11163        // A closure sees the variables a direct `eval` declared in the frame it was
11164        // created in — the ones declared before *and after* it, so the same object is
11165        // shared; only the phase bounds which of them are visible.
11166        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
11167        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
11168        let env = Gc::new(
11169            self.heap,
11170            ClosureEnv {
11171                cells,
11172                eval_scope,
11173                local_vars,
11174                local_phase,
11175            },
11176        );
11177        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
11178        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
11179        // the only thing that carries `Symbol.toStringTag`, so without it
11180        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
11181        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
11182        let proto = match function_kind {
11183            js_compile::bytecode::FunctionKind::AsyncGenerator => self
11184                .realm
11185                .async_generator_function_proto
11186                .clone()
11187                .or_else(|| self.realm.function_proto.clone().into()),
11188            js_compile::bytecode::FunctionKind::Generator => self
11189                .realm
11190                .generator_function_proto
11191                .clone()
11192                .or_else(|| self.realm.function_proto.clone().into()),
11193            js_compile::bytecode::FunctionKind::Async => self
11194                .realm
11195                .async_function_proto
11196                .clone()
11197                .or_else(|| self.realm.function_proto.clone().into()),
11198            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
11199        };
11200        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
11201        object.set_constructible(constructible);
11202        object.define(
11203            "length",
11204            Property::name_or_length(Value::Int(length as i32)),
11205        );
11206        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
11207        // that checks the own-property descriptor fails if the property is missing.
11208        object.define("name", Property::name_or_length(self.string(name)));
11209        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
11210        // when `[[Construct]]` is created, so a generator, an async function and an arrow
11211        // function have none of their own. Installing it unconditionally gave
11212        // `Array.fromAsync` (an async function) an own `prototype` property, which
11213        // `builtin.js` checks for absence.
11214        if constructible {
11215            self.install_function_prototype(&object);
11216        }
11217        Ok(Value::Object(object))
11218    }
11219
11220    // -- conversions used by the operators ----------------------------------
11221
11222    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
11223        // `+x` is `ToNumber`, which for a string parses it and for an object runs
11224        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
11225        // string, which then behaves differently in every later comparison.
11226        match value {
11227            Value::Int(_) | Value::Float(_) => Ok(value),
11228            other => Ok(Value::Float(self.to_js_number(&other)?)),
11229        }
11230    }
11231
11232    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
11233    ///
11234    /// Returns the *converted* old value and the new one, because the two callers need
11235    /// different halves: `++x` yields the new value, while `x++` yields the old one and
11236    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
11237    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
11238    /// boolean.
11239    ///
11240    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
11241    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
11242    /// a bigint algorithm then ran exactly once.
11243    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
11244        if let Value::BigInt(big) = &value {
11245            let one = crate::bigint::BigInt::from_i64(1);
11246            let next = if up { big.add(&one) } else { big.sub(&one) };
11247            return Ok((value, self.bigint(next)));
11248        }
11249        let old = self.numeric(value)?;
11250        let new = if up {
11251            increment(old.clone())
11252        } else {
11253            decrement(old.clone())
11254        };
11255        Ok((old, new))
11256    }
11257
11258    fn numeric(&mut self, value: Value) -> JsResult<Value> {
11259        // `ToNumber` on an object runs `ToPrimitive` first, which is how
11260        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
11261        // heard at all. Reading the object's own tag instead (`other.to_number()`)
11262        // turned the whole operand into `NaN` and swallowed the exception.
11263        match value {
11264            Value::Int(_) | Value::Float(_) => Ok(value),
11265            other => Ok(Value::Float(self.to_js_number(&other)?)),
11266        }
11267    }
11268
11269    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
11270    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
11271        match value {
11272            Value::BigInt(big) => Ok((**big).clone()),
11273            // The reference words this the same way for every operator, so a failing
11274            // script reads identically; the operator itself adds nothing a caller can use.
11275            _ => Err(Signal::Throw(
11276                self.make_error("TypeError", "cannot convert bigint to number"),
11277            )),
11278        }
11279    }
11280
11281    /// Arithmetic where at least one operand is a `BigInt`.
11282    ///
11283    /// The two numeric types never mix, so a bigint paired with anything else is an error
11284    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
11285    /// that the relational operators handle it separately.
11286    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
11287        use Opcode::*;
11288        let a = self.bigint_operand(&left)?;
11289        let b = self.bigint_operand(&right)?;
11290        let result = match op {
11291            Add => a.add(&b),
11292            Sub => a.sub(&b),
11293            Mul => a.mul(&b),
11294            Div | Mod => {
11295                let Some((quotient, remainder)) = a.div_rem(&b) else {
11296                    return Err(Signal::Throw(
11297                        self.make_error("RangeError", "division by zero"),
11298                    ));
11299                };
11300                if op == Div { quotient } else { remainder }
11301            }
11302            Pow => {
11303                let Some(value) = a.pow(&b) else {
11304                    return Err(Signal::Throw(self.make_error(
11305                        "RangeError",
11306                        "BigInt exponent must be non-negative and not absurdly large",
11307                    )));
11308                };
11309                value
11310            }
11311            And => a.bitand(&b),
11312            Or => a.bitor(&b),
11313            Xor => a.bitxor(&b),
11314            Shl | Sar => {
11315                // A shift count is a `BigInt` here, and both directions are exact; a
11316                // negative count would be the other direction, which the spec forbids.
11317                let Some(count) = b.to_i64() else {
11318                    return Err(Signal::Throw(
11319                        self.make_error("RangeError", "BigInt shift count is too large"),
11320                    ));
11321                };
11322                if count < 0 {
11323                    return Err(Signal::Throw(self.make_error(
11324                        "RangeError",
11325                        "BigInt shift count must be non-negative",
11326                    )));
11327                }
11328                if op == Shl {
11329                    a.shl(count as u64)
11330                } else {
11331                    a.shr(count as u64)
11332                }
11333            }
11334            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
11335            _ => {
11336                return Err(Signal::Throw(self.make_error(
11337                    "TypeError",
11338                    "BigInts have no unsigned right shift, use >> instead",
11339                )));
11340            }
11341        };
11342        Ok(self.bigint(result))
11343    }
11344
11345    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
11346    ///
11347    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
11348    /// is on the mathematical values, and nothing is rounded first.
11349    /// `<`, `<=`, `>`, `>=`.
11350    ///
11351    /// Both operands go through `ToPrimitive` **before** the comparison, which is what
11352    /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
11353    /// It is a `?`-returning function for exactly that reason: an object operand can run
11354    /// script, and script can throw. The old version compared `to_number` of the raw
11355    /// values, which answered `false` for every object instead of calling `valueOf` —
11356    /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
11357    /// never ran.
11358    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
11359        // The hot arm first: `i < n` with both sides already integers. No conversion, no
11360        // call, nothing that can throw.
11361        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
11362            let ordering = Some(left.cmp(right));
11363            return Ok(ordering_answer(op, ordering));
11364        }
11365        // Anything that can run script has to be converted first, in this order.
11366        let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
11367        {
11368            (
11369                self.to_primitive(left, Hint::Number)?,
11370                self.to_primitive(right, Hint::Number)?,
11371            )
11372        } else {
11373            (left, right)
11374        };
11375        let ordering = match (&left, &right) {
11376            // The loop condition `i < n` is integer against integer, and it runs once
11377            // per iteration of every loop in every program. Without this arm it took the
11378            // `to_number` path twice, which is a `match` plus a conversion each.
11379            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
11380            (Value::String(a), Value::String(b)) => {
11381                Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
11382            }
11383            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
11384            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
11385            // is true even though `2.5` has no bigint form.
11386            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
11387                let b = other.to_number();
11388                if b.is_nan() {
11389                    None
11390                } else {
11391                    compare_bigint_and_f64(a, b)
11392                }
11393            }
11394            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
11395                let a = other.to_number();
11396                if a.is_nan() {
11397                    None
11398                } else {
11399                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
11400                }
11401            }
11402            _ => left.to_number().partial_cmp(&right.to_number()),
11403        };
11404        Ok(ordering_answer(op, ordering))
11405    }
11406
11407    fn binary_add(&mut self) -> JsResult<()> {
11408        let right = self.pop();
11409        let left = self.pop();
11410        // Two integers add without any of the machinery below: no `ToPrimitive` (an
11411        // `Int` is already primitive), no string check, no bigint check, no allocation.
11412        // `x += 1` in a loop is the single most common instruction sequence in real
11413        // script, and it used to walk every one of those checks before reaching the
11414        // same `checked_add`.
11415        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
11416            self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
11417            return Ok(());
11418        }
11419        let left = self.primitive_of(left)?;
11420        let right = self.primitive_of(right)?;
11421        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
11422        // that check comes before the bigint one: `"" + 1n` is a string, not a
11423        // mixed-type error.
11424        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
11425            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
11426            // `TypeError`, the one place a symbol and a string do not mix.
11427            // Keep the operands as strings rather than as bytes: `JsString::concat` decides
11428            // between a copy and a rope from their lengths, and a rope is what turns
11429            // `text += "abc"` in a loop from quadratic into linear.
11430            if let (Value::String(left), Value::String(right)) = (&left, &right) {
11431                // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
11432                // reports as `InternalError: string too long`.
11433                let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
11434                    return Err(Signal::Throw(
11435                        self.make_error("InternalError", "string too long"),
11436                    ));
11437                };
11438                self.push(Value::String(Gc::new(self.heap, joined)));
11439                return Ok(());
11440            }
11441            // At least one operand was not a string, so `ToString` it. This rejects a
11442            // symbol, which is the one place a symbol and a string do not mix.
11443            let left = self.checked_to_wtf8(&left)?;
11444            let right = self.checked_to_wtf8(&right)?;
11445            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
11446            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
11447            let text = left.concat(&right);
11448            self.push(self.string_wtf8(text));
11449            return Ok(());
11450        }
11451        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
11452        // not a conversion.
11453        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
11454            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
11455            self.push(value);
11456            return Ok(());
11457        }
11458        let left = self.numeric(left)?;
11459        let right = self.numeric(right)?;
11460        self.push(add_numbers(left, right));
11461        Ok(())
11462    }
11463
11464    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
11465        self.to_primitive(value, Hint::Default)
11466    }
11467
11468    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
11469    ///
11470    /// The order depends on the hint: the "number" order tries `valueOf` first and
11471    /// `toString` second, the "string" order the other way round, and the default
11472    /// hint uses the number order. A result that is still an object is a `TypeError`,
11473    /// because no built-in `valueOf`/`toString` returns one.
11474    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
11475        let Value::Object(object) = &value else {
11476            return Ok(value);
11477        };
11478        // A Date overrides the default hint to mean "string", which is what
11479        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
11480        // this, `"" + new Date()` would print the milliseconds, not the date.
11481        let hint = if hint == Hint::Default && is_date_object(self, object) {
11482            Hint::String
11483        } else {
11484            hint
11485        };
11486        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
11487        // handed the hint as a string. This is the hook a Date uses for its default hint
11488        // and a script uses to take over conversion entirely.
11489        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
11490        // `GetMethod`, not "is it a callable object": the property has to be read and then
11491        // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
11492        // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
11493        // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
11494        // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
11495        // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
11496        // callable.
11497        match self.get_property_key(object, &key)? {
11498            None | Some(Value::Undefined) | Some(Value::Null) => {}
11499            Some(Value::Object(function)) if function.is_callable() => {
11500                let hint = match hint {
11501                    Hint::String => "string",
11502                    Hint::Number => "number",
11503                    Hint::Default => "default",
11504                };
11505                let hint = self.string(hint);
11506                let result = self.call_value(
11507                    Value::Object(function),
11508                    Value::Object(object.clone()),
11509                    vec![hint],
11510                )?;
11511                if !matches!(result, Value::Object(_)) {
11512                    return Ok(result);
11513                }
11514                return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
11515            }
11516            Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
11517        }
11518        let order: [&str; 2] = match hint {
11519            Hint::String => ["toString", "valueOf"],
11520            Hint::Number | Hint::Default => ["valueOf", "toString"],
11521        };
11522        let receiver = object.clone();
11523        for method in order {
11524            if let Some(function) = self.get_property(&receiver, method)?
11525                && matches!(&function, Value::Object(object) if object.is_callable())
11526            {
11527                let result =
11528                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
11529                if !matches!(result, Value::Object(_)) {
11530                    return Ok(result);
11531                }
11532            }
11533        }
11534        Err(self.type_error("cannot convert object to primitive value"))
11535    }
11536
11537    /// `ToString` with the object case going through `ToPrimitive`.
11538    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
11539        if matches!(value, Value::Object(_)) {
11540            let primitive = self.to_primitive(value.clone(), Hint::String)?;
11541            return Ok(primitive.to_js_string());
11542        }
11543        // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
11544        // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
11545        // callers that want that strictness call [`Interp::to_string_strict`] — putting the
11546        // check here broke `String(Symbol())` and 45 cases that print a symbol.
11547        Ok(value.to_js_string())
11548    }
11549
11550    /// `ToString(value)`, with §7.1.19's symbol refusal.
11551    ///
11552    /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
11553    /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
11554    /// operations and conflating them cost 45 cases in one direction and 6 in the other.
11555    pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
11556        if matches!(value, Value::Symbol(_)) {
11557            return Err(self.type_error("cannot convert a Symbol to a string"));
11558        }
11559        if matches!(value, Value::Object(_)) {
11560            let primitive = self.to_primitive(value.clone(), Hint::String)?;
11561            if matches!(primitive, Value::Symbol(_)) {
11562                return Err(self.type_error("cannot convert a Symbol to a string"));
11563            }
11564            return Ok(primitive.to_js_string());
11565        }
11566        Ok(value.to_js_string())
11567    }
11568
11569    /// `ToString` that keeps the string's code units instead of flattening them.
11570    ///
11571    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
11572    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
11573    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
11574        if matches!(value, Value::Symbol(_)) {
11575            return Err(Signal::Throw(
11576                self.make_error("TypeError", "cannot convert symbol to string"),
11577            ));
11578        }
11579        // An object runs `ToPrimitive` first, which may itself produce a symbol.
11580        let value = self.to_primitive(value.clone(), Hint::String)?;
11581        match value {
11582            Value::Symbol(_) => Err(Signal::Throw(
11583                self.make_error("TypeError", "cannot convert symbol to string"),
11584            )),
11585            Value::String(text) => Ok(text.wtf8().clone()),
11586            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
11587        }
11588    }
11589
11590    /// `ToNumber` with the object case going through `ToPrimitive`.
11591    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
11592        let value = if matches!(value, Value::Object(_)) {
11593            self.to_primitive(value.clone(), Hint::Number)?
11594        } else {
11595            value.clone()
11596        };
11597        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
11598        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
11599        // `NaN` to stay total, and the operators check for the bigint themselves — but
11600        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
11601        // refuse, and answering `NaN` made them silently wrong instead.
11602        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
11603        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
11604        match value {
11605            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
11606            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
11607            other => Ok(other.to_number()),
11608        }
11609    }
11610
11611    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
11612    /// [`ElementType::write`].
11613    ///
11614    /// This is separated from the write because both conversions are observable script —
11615    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
11616    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
11617    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
11618    /// setters, and a plain `a[i] = v`.
11619    pub(crate) fn element_value(
11620        &mut self,
11621        element: crate::builtins::typedarray::ElementType,
11622        value: Value,
11623    ) -> JsResult<Value> {
11624        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
11625        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
11626        let primitive = match &value {
11627            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
11628            _ => value,
11629        };
11630        if element.is_bigint() {
11631            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
11632            Ok(Value::BigInt(Gc::new(self.heap, big)))
11633        } else {
11634            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
11635            Ok(Value::Float(self.to_js_number(&primitive)?))
11636        }
11637    }
11638
11639    /// `ToPropertyKey`: what a computed member access uses as its key.
11640    ///
11641    /// A symbol is returned as itself, never stringified — that is what keeps
11642    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
11643    pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
11644        match value {
11645            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
11646            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
11647            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
11648            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
11649            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
11650                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
11651                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
11652                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
11653                    other.to_js_string(),
11654                ))),
11655            },
11656            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
11657        }
11658    }
11659
11660    /// `ToPropertyKey` for the callers that can only use a string key.
11661    ///
11662    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
11663    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
11664    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
11665    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
11666    /// program continues with a value nobody asked for.
11667    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
11668        use crate::value::Wtf8;
11669        Ok(match value {
11670            // A string key keeps its code units. Going through a lossy `String` would make
11671            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
11672            Value::String(text) => text.wtf8().clone(),
11673            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
11674            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
11675            // falling back to its `ToString` would print `[object Object]`.
11676            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
11677                Value::String(text) => text.wtf8().clone(),
11678                other => Wtf8::new(other.to_js_string()),
11679            },
11680            other => Wtf8::new(other.to_js_string()),
11681        })
11682    }
11683
11684    // -- object operations used by instructions -----------------------------
11685
11686    /// Read `object[key]`, returning `undefined` when the property is missing.
11687    ///
11688    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
11689    /// primitive (looking through its prototype) as well as an object — which is what
11690    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
11691    /// argument needs too.
11692    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
11693        self.read_field_key(object, &PropertyKey::from(key))
11694    }
11695
11696    /// [`Interp::read_field`] with a key that may be a symbol.
11697    ///
11698    /// A symbol key never reaches the string shortcuts: a string's `length` and its
11699    /// indices are string properties, and a symbol named `length` is a different
11700    /// property that a string primitive cannot have.
11701    /// [`Interp::read_field_key`], with an inline cache in front of it.
11702    ///
11703    /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
11704    /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
11705    /// without this the engine walked the chain and compared ~40 property names on each
11706    /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
11707    ///
11708    /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
11709    /// missing property. Those answers depend on running code or on state the guard below
11710    /// does not cover, and a wrong answer here is far more expensive than a lookup.
11711    ///
11712    /// A hit is re-validated against the *whole* walked chain, not just the level that
11713    /// answered: the receiver and every prototype down to that level must still be the same
11714    /// object (weakly, so a collected and reallocated object is a miss) with unchanged
11715    /// property-table *lengths* — which is what catches a property appearing on an
11716    /// intermediate prototype and shadowing the cached one.
11717    pub fn read_field_cached(
11718        &mut self,
11719        object: &Value,
11720        key: &PropertyKey,
11721        slot: usize,
11722    ) -> JsResult<Value> {
11723        let index = Self::field_cache_slot(object, key, slot);
11724        let Value::Object(target) = object else {
11725            return self.read_field_key(object, key);
11726        };
11727        if target.proxy_state().is_some() {
11728            return self.read_field_key(object, key);
11729        }
11730        if let Some(cached) = &self.field_cache[index]
11731            && cached.key == *key
11732            && let Some(value) = Self::cached_hit(target, cached)
11733        {
11734            return Ok(value);
11735        }
11736        let value = self.read_field_key(object, key)?;
11737        self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
11738        Ok(value)
11739    }
11740
11741    /// Whether a cache entry still describes this lookup, and if so the value.
11742    ///
11743    /// The guard is the whole point of the entry: identity plus property-table length for
11744    /// every level walked. Re-checked per level rather than once at the receiving end,
11745    /// because a shadowing property can appear anywhere along the chain.
11746    fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
11747        // Level 0 — the receiver itself answered — without the `Gc` clone this loop
11748        // starts with: a clone is a reference-count bump and a drop, and for
11749        // `property:monomorphic` every single hit takes only this arm.
11750        let (weak, len) = cached.chain[0].as_ref()?;
11751        if !target.upgrades_to(weak) {
11752            return None;
11753        }
11754        if cached.level == 0 {
11755            // Length and key and accessor-ness in one borrow: see `cached_property_at`.
11756            return target.cached_property_at(cached.index, &cached.key, *len);
11757        }
11758        if target.props_len() != *len {
11759            return None;
11760        }
11761        let mut level = 1;
11762        let mut current = target.proto()?;
11763        loop {
11764            let (weak, len) = cached.chain[level].as_ref()?;
11765            if !current.upgrades_to(weak) || current.props_len() != *len {
11766                return None;
11767            }
11768            if level == cached.level as usize {
11769                // The level that answered: the value is only reusable while the key is
11770                // still there and still a plain data property.
11771                return current.cached_data_property(cached.index, &cached.key);
11772            }
11773            current = current.proto()?;
11774            level += 1;
11775        }
11776    }
11777
11778    /// Build a cache entry for a lookup that just went through the slow path.
11779    ///
11780    /// Records the chain only when the answer came from a plain data property at a level
11781    /// the fixed-size array can hold; everything else simply leaves the slot empty, which
11782    /// costs the next lookup the walk it would have cost anyway.
11783    fn record_field_lookup(
11784        target: &Gc<JsObject>,
11785        key: &PropertyKey,
11786        _value: Value,
11787    ) -> Option<FieldCache> {
11788        let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
11789            [None, None, None];
11790        let mut current = target.clone();
11791        for level in 0..MAX_CACHED_CHAIN {
11792            chain[level] = Some((current.downgrade(), current.props_len()));
11793            if let Some((found, _)) = current.own_property_index(key) {
11794                // `own_property_index` declines an accessor and a hole, which is exactly
11795                // the set that must not be cached.
11796                return Some(FieldCache {
11797                    key: key.clone(),
11798                    index: found,
11799                    level: level as u8,
11800                    chain,
11801                });
11802            }
11803            current = current.proto()?;
11804        }
11805        None
11806    }
11807
11808    /// Which cache slot a lookup uses.
11809    ///
11810    /// Mixes the object's address, the name and the site, so that two properties of one
11811    /// object, and one property of two objects, land in different slots — which is what lets
11812    /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
11813    /// other iteration.
11814    fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
11815        let mut hash = match object {
11816            Value::Object(object) => object.address(),
11817            _ => 0,
11818        };
11819        hash = hash
11820            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
11821            .rotate_left(17)
11822            .wrapping_add(key.hash_code());
11823        hash = hash.wrapping_add(site.wrapping_mul(31));
11824        // The table is a power of two, so the low bits are the slot.
11825        hash & (FIELD_CACHE_SLOTS - 1)
11826    }
11827
11828    /// Read `key` from `object`, without the inline cache.
11829    ///
11830    /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
11831    /// prototype chain, while the cached form answers an own data property from memory.
11832    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
11833        let text = key.as_str().unwrap_or("");
11834        let Value::Object(object) = object else {
11835            // Reading a property of `undefined`/`null` is the classic TypeError.
11836            if object.is_nullish() {
11837                return Err(Signal::Throw(self.make_error(
11838                    "TypeError",
11839                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
11840                )));
11841            }
11842            // A string has `length` and index access without being boxed.
11843            if let Value::String(value) = object {
11844                if text == "length" {
11845                    return Ok(Value::Int(value.utf16_len() as i32));
11846                }
11847                if let Some(index) = array_index(text) {
11848                    return Ok(match value.wtf8().unit_at(index as usize) {
11849                        Some(unit) => self.string_wtf8(unit),
11850                        None => Value::Undefined,
11851                    });
11852                }
11853            }
11854            // A property of a primitive is looked up on its prototype: this is what
11855            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
11856            let prototype = match object {
11857                Value::String(_) => self.realm.string_proto.clone(),
11858                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11859                Value::Bool(_) => self.realm.boolean_proto.clone(),
11860                // A symbol's methods live on `Symbol.prototype`, reached the same way —
11861                // `sym.description` reads through the prototype, not off the symbol.
11862                Value::Symbol(_) => self.realm.symbol_proto.clone(),
11863                // …and a bigint's on `BigInt.prototype`, which is how
11864                // `(255n).toString(16)` reaches its method.
11865                Value::BigInt(_) => self.realm.bigint_proto.clone(),
11866                _ => None,
11867            };
11868            if let Some(prototype) = prototype
11869                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
11870            {
11871                return Ok(value);
11872            }
11873            return Ok(Value::Undefined);
11874        };
11875        Ok(self
11876            .get_property_key(object, key)?
11877            .unwrap_or(Value::Undefined))
11878    }
11879
11880    /// The `#name` a private symbol stands for, for error messages.
11881    ///
11882    /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
11883    /// was made from.
11884    fn private_name(symbol: &Value) -> Option<String> {
11885        match symbol {
11886            Value::Symbol(symbol) if symbol.is_private() => Some(
11887                symbol
11888                    .description()
11889                    .map(|text| text.to_string())
11890                    .unwrap_or_default(),
11891            ),
11892            _ => None,
11893        }
11894    }
11895
11896    /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
11897    ///
11898    /// Every private-field opcode takes the symbol the class stored in its own scope; a
11899    /// non-symbol here would be a compiler bug, and the reference guards it with
11900    /// `JS_ThrowTypeErrorNotASymbol`.
11901    fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
11902        match symbol {
11903            Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
11904            _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
11905        }
11906    }
11907
11908    /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
11909    ///
11910    /// Three early errors, all from the reference: a non-object receiver, a non-extensible
11911    /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
11912    /// would hit if the parser did not reject it first.
11913    fn define_private_field(
11914        &mut self,
11915        object: &Value,
11916        symbol: &Value,
11917        value: Value,
11918    ) -> JsResult<()> {
11919        let key = self.private_key(symbol)?;
11920        let Some(target) = object.as_object() else {
11921            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11922        };
11923        if !target.is_extensible() {
11924            return Err(Signal::Throw(
11925                self.make_error("TypeError", "object is not extensible"),
11926            ));
11927        }
11928        if target.own_property_key(&key).is_some() {
11929            let name = Self::private_name(symbol).unwrap_or_default();
11930            return Err(Signal::Throw(self.make_error(
11931                "TypeError",
11932                &format!("private class field '{name}' already exists"),
11933            )));
11934        }
11935        target.define_data_key(&key, value);
11936        Ok(())
11937    }
11938
11939    /// `JS_GetPrivateField`: only an own property, never the prototype chain.
11940    fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
11941        let key = self.private_key(symbol)?;
11942        let Some(target) = object.as_object() else {
11943            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11944        };
11945        match target.own_property_key(&key) {
11946            Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
11947            None => {
11948                let name = Self::private_name(symbol).unwrap_or_default();
11949                Err(Signal::Throw(self.make_error(
11950                    "TypeError",
11951                    &format!("private class field '{name}' does not exist"),
11952                )))
11953            }
11954        }
11955    }
11956
11957    /// `JS_SetPrivateField`: the store half of the same rule.
11958    fn write_private_field(
11959        &mut self,
11960        object: &Value,
11961        symbol: &Value,
11962        value: Value,
11963    ) -> JsResult<()> {
11964        let key = self.private_key(symbol)?;
11965        let Some(target) = object.as_object() else {
11966            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11967        };
11968        if target.write_value_key(&key, value) {
11969            return Ok(());
11970        }
11971        let name = Self::private_name(symbol).unwrap_or_default();
11972        Err(Signal::Throw(self.make_error(
11973            "TypeError",
11974            &format!("private class field '{name}' does not exist"),
11975        )))
11976    }
11977
11978    /// The `in` half: does `object` have this private field?
11979    /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
11980    ///
11981    /// The symbol is created once per class — the first `add_brand` on a given home object
11982    /// makes it, every later one reuses it, which is what ties the prototype, the constructor
11983    /// and each instance to one identity. `obj` being `null` is not an error: the class-level
11984    /// emit for the *instance* brand passes null because all it wants is the symbol.
11985    fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
11986        let Some(home_object) = home.as_object() else {
11987            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11988        };
11989        let symbol = match home_object.private_brand() {
11990            Some(symbol) => symbol,
11991            None => {
11992                let symbol = Gc::new(
11993                    self.heap,
11994                    crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
11995                );
11996                home_object.set_private_brand(symbol.clone());
11997                symbol
11998            }
11999        };
12000        let Some(target) = object.as_object() else {
12001            // Not an object: nothing to brand. The reference does the same, and `undefined`
12002            // here would otherwise turn a field initialiser into a TypeError.
12003            return Ok(());
12004        };
12005        if !target.is_extensible() {
12006            return Err(Signal::Throw(
12007                self.make_error("TypeError", "object is not extensible"),
12008            ));
12009        }
12010        if target.carries_brand(&symbol) {
12011            return Err(Signal::Throw(
12012                self.make_error("TypeError", "private method is already present"),
12013            ));
12014        }
12015        target.add_brand(symbol);
12016        Ok(())
12017    }
12018
12019    /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
12020    ///
12021    /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
12022    /// decides whether to throw.
12023    fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
12024        let Some(function) = function.as_object() else {
12025            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12026        };
12027        let Some(home) = function.home_object() else {
12028            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12029        };
12030        let Some(brand) = home.private_brand() else {
12031            return Err(Signal::Throw(
12032                self.make_error("TypeError", "expecting <brand> private field"),
12033            ));
12034        };
12035        Ok(object.carries_brand(&brand))
12036    }
12037
12038    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
12039        let Value::Object(object) = object else {
12040            return Err(Signal::Throw(self.make_error(
12041                "TypeError",
12042                &format!("cannot set property '{key}' of {}", object.to_js_string()),
12043            )));
12044        };
12045        // The write half of the property inline cache, in effect: an own, writable,
12046        // non-accessor data property already holds this key, so `[[Set]]` has nothing to
12047        // decide — no prototype walk (an own property shadows the chain before a setter
12048        // there could matter), no extensibility check (the object already has the key),
12049        // and no `[[DefineOwnProperty]]`.
12050        //
12051        // `this.value = …` inside a method is the whole write side of
12052        // `property:method-call`, and it was reaching `set_property_with_key` with its
12053        // proxy test, its typed-array test, its array-index test and finally a linear
12054        // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
12055        //
12056        // Every disqualifier is checked here: a proxy traps the set, an array index and
12057        // `length` live outside the property table, and a typed array's element is stored
12058        // through its view's element type.
12059        if object.proxy_state().is_none()
12060            && !object.is_array()
12061            && object.typed_array_element_type().is_none()
12062            && object.write_value_key(key, value.clone())
12063        {
12064            return Ok(());
12065        }
12066        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
12067        let on_failure = if self.frame().code.code.strict {
12068            DeleteFailure::Throw
12069        } else {
12070            DeleteFailure::Ignore
12071        };
12072        self.set_property_with_key(object, key, value, on_failure)
12073    }
12074
12075    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
12076    ///
12077    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
12078    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
12079    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
12080    /// `Number.parseInt(sym)` — so those callers use this instead.
12081    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
12082        if matches!(value, Value::Symbol(_)) {
12083            return Err(Signal::Throw(
12084                self.make_error("TypeError", "cannot convert symbol to string"),
12085            ));
12086        }
12087        // An object runs `ToPrimitive` first, which may itself produce a symbol —
12088        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
12089        let value = self.to_primitive(value.clone(), Hint::String)?;
12090        if matches!(value, Value::Symbol(_)) {
12091            return Err(Signal::Throw(
12092                self.make_error("TypeError", "cannot convert symbol to string"),
12093            ));
12094        }
12095        Ok(value.to_js_string())
12096    }
12097
12098    /// `ToPropertyKey` for a builtin that takes a key argument.
12099    ///
12100    /// Fallible: a key whose `toString` throws has to propagate that error, both for
12101    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
12102    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
12103    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
12104    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
12105        self.propkey(value)
12106    }
12107
12108    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
12109    ///
12110    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
12111    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
12112    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
12113    /// `RangeError` — and why this cannot be a plain `ToNumber`.
12114    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
12115        let number = match value {
12116            Value::Int(number) => *number as f64,
12117            Value::Float(number) => *number,
12118            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
12119            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
12120            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
12121            // reference answers 0.
12122            Value::Null | Value::Bool(_) => value.to_number(),
12123            _ => {
12124                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
12125                match primitive {
12126                    Value::Int(number) => number as f64,
12127                    Value::Float(number) => number,
12128                    other => {
12129                        // `ToString` then `ToNumber`, so a string length goes through the
12130                        // full numeric-literal grammar: `"0x00B"` is 11 and `"  5  "` is 5.
12131                        // `Value::to_number` on the string already implements exactly that.
12132                        let text = self.to_js_string(&other)?;
12133                        crate::value::string_to_number(&text)
12134                    }
12135                }
12136            }
12137        };
12138        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
12139        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
12140        // is a `RangeError`, not `0`.
12141        if !number.is_finite()
12142            || number.fract() != 0.0
12143            || !(0.0..=u32::MAX as f64).contains(&number)
12144        {
12145            return Err(self.range_error("invalid array length"));
12146        }
12147        Ok(number as u32)
12148    }
12149
12150    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
12151    /// `Object.getOwnPropertySymbols` put in their result array.
12152    pub fn key_value(&self, key: &PropertyKey) -> Value {
12153        match key {
12154            PropertyKey::String(text) => self.string_wtf8(text.clone()),
12155            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
12156        }
12157    }
12158
12159    /// Fill in a String exotic object: `_value`, `length` and the index properties.
12160    ///
12161    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
12162    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
12163    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
12164    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
12165    /// the two paths had drifted; this is the one both now use.
12166    ///
12167    /// The indices are *code units*, so an astral character occupies two of them — the
12168    /// same rule `s.length` and `s[i]` follow.
12169    /// Give an already-created object the internal slot that makes it a wrapper of
12170    /// `value`, so the primitive's prototype methods work on it.
12171    ///
12172    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
12173    /// which are wrappers of their own type holding the empty value.
12174    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
12175        self.internal_set(object, "_value", value);
12176    }
12177
12178    pub(crate) fn init_string_wrapper(
12179        &mut self,
12180        object: &Gc<JsObject>,
12181        text: &Gc<crate::value::JsString>,
12182    ) {
12183        object.define(
12184            "length",
12185            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
12186        );
12187        for index in 0..text.utf16_len() {
12188            if let Some(unit) = text.wtf8().unit_at(index) {
12189                object.define(
12190                    &index.to_string(),
12191                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
12192                    Property::with_attributes(self.string_wtf8(unit), false, true),
12193                );
12194            }
12195        }
12196        object.define_key(
12197            &self.internal_slot("_value"),
12198            Property::with_attributes(Value::String(text.clone()), false, false),
12199        );
12200    }
12201
12202    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
12203    ///
12204    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
12205    /// throws. The wrapper carries its primitive in `_value` — the same slot
12206    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
12207    /// on a boxed value no constructor ever built.
12208    pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12209        let (prototype, primitive) = match value {
12210            Value::Object(object) => return Ok(object.clone()),
12211            Value::String(text) => {
12212                let object = self.new_object(self.realm.string_proto.clone());
12213                self.init_string_wrapper(&object, text);
12214                return Ok(object);
12215            }
12216            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
12217            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
12218            // A symbol and a bigint box into wrappers whose methods live on
12219            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
12220            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
12221            // branch below instead produced an object with *no* prototype, so those
12222            // methods were unreachable on a box.
12223            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
12224            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
12225            Value::Undefined | Value::Null => {
12226                return Err(Signal::Throw(self.make_error(
12227                    "TypeError",
12228                    &format!("cannot convert {} to object", value.to_js_string()),
12229                )));
12230            }
12231            _ => (None, value.clone()),
12232        };
12233        let object = self.new_object(prototype);
12234        self.internal_set(&object, "_value", primitive);
12235        Ok(object)
12236    }
12237
12238    /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
12239    ///
12240    /// Split out for a reader that has to create the object *before* it knows what it wraps:
12241    /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
12242    /// written before its primitive, so the placeholder has to exist first and be filled in
12243    /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
12244    /// than a second in the deserialiser.
12245    pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
12246        let prototype = match value {
12247            Value::String(_) => self.realm.string_proto.clone(),
12248            Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
12249            Value::Bool(_) => self.realm.boolean_proto.clone(),
12250            Value::Symbol(_) => self.realm.symbol_proto.clone(),
12251            Value::BigInt(_) => self.realm.bigint_proto.clone(),
12252            _ => {
12253                return Err(Signal::Throw(self.make_error(
12254                    "TypeError",
12255                    &format!("cannot box {}", value.to_js_string()),
12256                )));
12257            }
12258        };
12259        object.set_proto(prototype);
12260        if let Value::String(text) = value {
12261            self.init_string_wrapper(object, text);
12262            return Ok(());
12263        }
12264        self.internal_set(object, "_value", value.clone());
12265        Ok(())
12266    }
12267
12268    /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
12269    ///
12270    /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
12271    /// through the `Symbol` function object, so the registry is reachable as a method rather
12272    /// than only from `builtins::symbol`.
12273    pub fn symbol_for(&mut self, key: &str) -> Value {
12274        if let Some(existing) = self.realm.symbol_registry.get(key) {
12275            return existing.clone();
12276        }
12277        let symbol = crate::builtins::symbol::symbol_value(
12278            self,
12279            crate::value::JsSymbol::registered(key.to_string()),
12280        );
12281        self.realm
12282            .symbol_registry
12283            .insert(key.to_string(), symbol.clone());
12284        symbol
12285    }
12286
12287    /// `a == b`, the coercing comparison.
12288    ///
12289    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
12290    /// which is what makes `[] == ""` true: `[]` becomes `""` via
12291    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
12292    /// because the conversion is allowed to call script code, so the two primitive
12293    /// operands are handed back to it.
12294    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
12295        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
12296            return Ok(left.loose_equals(&right));
12297        }
12298        // `null == undefined` holds even though neither is an object.
12299        if matches!(left, Value::Undefined | Value::Null)
12300            && matches!(right, Value::Undefined | Value::Null)
12301        {
12302            return Ok(true);
12303        }
12304        if matches!(left, Value::Undefined | Value::Null)
12305            || matches!(right, Value::Undefined | Value::Null)
12306        {
12307            return Ok(false);
12308        }
12309        // Two objects compare by identity. Only an object *against a primitive* is
12310        // converted, which is why `{} == {}` is false while `[] == ""` is true.
12311        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
12312            return Ok(a.ptr_eq(b));
12313        }
12314        let left = self.to_primitive(left, Hint::Default)?;
12315        let right = self.to_primitive(right, Hint::Default)?;
12316        Ok(left.loose_equals(&right))
12317    }
12318
12319    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
12320        let Value::Object(object) = object else {
12321            return Err(Signal::Throw(
12322                self.make_error("TypeError", "cannot use 'in' on a non-object"),
12323            ));
12324        };
12325        let key = self.propkey(key)?;
12326        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
12327        // trap. One implementation, so an array's derived `length` and its inherited holes
12328        // cannot be right in one caller and wrong in another.
12329        self.has_own_or_inherited(object, &key)
12330    }
12331
12332    /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
12333    ///
12334    /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
12335    /// whole reason the operator is a hook rather than a prototype walk.
12336    pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
12337        if let Value::Object(function) = constructor {
12338            let key = self.realm.well_known_key(WellKnown::HasInstance);
12339            let method = self.get_property_key(function, &key)?;
12340            if let Some(method) = method
12341                && !matches!(method, Value::Undefined)
12342            {
12343                let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
12344                return Ok(answer.to_boolean());
12345            }
12346        }
12347        self.instance_of(object, constructor)
12348    }
12349
12350    /// `OrdinaryHasInstance`: the prototype walk on its own.
12351    pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
12352        self.instance_of(object, constructor)
12353    }
12354
12355    /// `IsArray`: an array, or a proxy whose target is one.
12356    ///
12357    /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
12358    /// makes `Array.isArray(new Proxy([], {}))` true.
12359    pub fn is_array_value(&self, value: &Value) -> bool {
12360        match value {
12361            Value::Object(object) => {
12362                if let Some(state) = object.proxy_state() {
12363                    return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
12364                }
12365                object.is_array()
12366            }
12367            _ => false,
12368        }
12369    }
12370
12371    /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
12372    ///
12373    /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
12374    /// in a Rust closure would hide GC values from the collector. A host-supplied job is
12375    /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
12376    /// see [`Interp::enqueue_job_function`].
12377    pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
12378        // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
12379        // the handler is reported rather than lost — the same reason a `then` reaction needs a
12380        // promise to settle.
12381        let promise = self.new_promise();
12382        self.fulfill_promise(&promise, Value::Undefined);
12383        self.jobs.push_back(Job::Reaction {
12384            handler: Some(function),
12385            argument: Value::Undefined,
12386            rejected: false,
12387            promise,
12388        });
12389        Ok(())
12390    }
12391
12392    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
12393        let Value::Object(target) = object else {
12394            return Ok(false);
12395        };
12396        let Value::Object(function) = constructor else {
12397            return Err(Signal::Throw(self.make_error(
12398                "TypeError",
12399                "right-hand side of 'instanceof' is not callable",
12400            )));
12401        };
12402        let prototype = self.get_property(function, "prototype")?;
12403        let Some(Value::Object(prototype)) = prototype else {
12404            return Ok(false);
12405        };
12406        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
12407        // which is also what makes `proxyOfInstance instanceof C` work.
12408        let mut current = Some(target.clone());
12409        while let Some(object) = current {
12410            if object.ptr_eq(&prototype) {
12411                return Ok(true);
12412            }
12413            current = self.object_prototype_of(&object)?;
12414        }
12415        Ok(false)
12416    }
12417
12418    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
12419    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
12420        if let Some(proto) = self.proxy_get_prototype_of(object)? {
12421            return Ok(proto);
12422        }
12423        if let Some(exotic) = object.exotic()
12424            && let Some(proto) = exotic.get_prototype(self, object)?
12425        {
12426            return Ok(proto);
12427        }
12428        Ok(object.proto())
12429    }
12430
12431    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
12432    pub fn object_set_prototype_of(
12433        &mut self,
12434        object: &Gc<JsObject>,
12435        proto: Option<Gc<JsObject>>,
12436    ) -> JsResult<bool> {
12437        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
12438            return Ok(answer);
12439        }
12440        if let Some(exotic) = object.exotic()
12441            && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
12442        {
12443            return Ok(answer);
12444        }
12445        // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
12446        // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
12447        // inheriting from itself, which every later prototype walk then had to defend
12448        // against — and `Reflect.setPrototypeOf` reported success for an operation the
12449        // language says is impossible.
12450        if let Some(proto) = &proto {
12451            let mut current = Some(proto.clone());
12452            let mut guard = 0;
12453            while let Some(node) = current {
12454                if node.ptr_eq(object) {
12455                    return Err(Signal::Throw(
12456                        self.make_error("TypeError", "circular prototype chain"),
12457                    ));
12458                }
12459                guard += 1;
12460                if guard > 1000 {
12461                    break;
12462                }
12463                current = node.proto();
12464            }
12465        }
12466        object.set_proto(proto);
12467        Ok(true)
12468    }
12469
12470    /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
12471    ///
12472    /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
12473    /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
12474    /// already one.
12475    pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
12476        // An integer-indexed exotic object answers from `IsValidIntegerIndex` alone
12477        // (§10.4.5.2 step 1.b) — the prototype chain is *not* consulted for a canonical
12478        // numeric index. That is observable twice over: a view that has been resized out
12479        // of bounds has no indices, so `2 in view` must then be `false` even when
12480        // `Object.getPrototypeOf(view)[2]` exists, and a key like `"-1"` or `"1.5"` is
12481        // canonical-numeric-but-invalid, so `in` answers `false` where an ordinary
12482        // lookup would have found `TypedArray.prototype["1.5"]`. A proxy is excluded
12483        // because it has no `[[ViewedArrayBuffer]]` slot of its own.
12484        if object.typed_array_parts().is_some()
12485            && object.proxy_state().is_none()
12486            && let Some(numeric) = canonical_numeric_index(key)
12487        {
12488            return Ok(typed_array_index_is_valid(object, numeric));
12489        }
12490        let mut current = Some(object.clone());
12491        // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
12492        let mut guard = 0;
12493        while let Some(node) = current {
12494            guard += 1;
12495            if guard > 1000 {
12496                return Ok(false);
12497            }
12498            let own = self.object_get_own_property(&node, key)?;
12499            if own.is_some() {
12500                return Ok(true);
12501            }
12502            current = self.object_prototype_of(&node)?;
12503        }
12504        Ok(false)
12505    }
12506
12507    /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
12508    ///
12509    /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
12510    /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
12511    /// boolean as well, and it needs the receiver to be the one the caller named.
12512    pub fn set_property_with_key_receiver(
12513        &mut self,
12514        object: &Gc<JsObject>,
12515        key: &PropertyKey,
12516        value: Value,
12517        receiver: Option<&Value>,
12518        on_failure: DeleteFailure,
12519    ) -> JsResult<bool> {
12520        let receiver = receiver
12521            .cloned()
12522            .unwrap_or_else(|| Value::Object(object.clone()));
12523        if object.proxy_state().is_some() {
12524            return match self.proxy_set(object, key, value, &receiver)? {
12525                Some(accepted) => Ok(accepted),
12526                None => Ok(true),
12527            };
12528        }
12529        // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
12530        // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
12531        // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
12532        // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
12533        //
12534        // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
12535        //
12536        // * `SameValue(O, Receiver)` stores into the buffer, converting first;
12537        // * an *invalid* index with a different receiver answers `true` and does nothing,
12538        //   not even converting `V` (`valueOfCalls` stays 0);
12539        // * a valid index with a different receiver falls through to
12540        //   `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
12541        //   value lands on the **receiver**, unconverted, and can be refused by a
12542        //   non-extensible receiver, an accessor, or a read-only index there.
12543        //
12544        // The last one used to write into the view itself, which left `target[0]` changed
12545        // and `receiver[0]` untouched — backwards.
12546        if object.typed_array_element_type().is_some()
12547            && let Some(numeric) = canonical_numeric_index(key)
12548        {
12549            let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
12550            if same {
12551                self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
12552                return Ok(true);
12553            }
12554            if !typed_array_index_is_valid(object, numeric) {
12555                return Ok(true);
12556            }
12557            let Some(receiver) = receiver.as_object().cloned() else {
12558                return Ok(false);
12559            };
12560            if let Some(existing) = self.object_get_own_property(&receiver, key)? {
12561                if existing.is_accessor() || !existing.writable {
12562                    return Ok(false);
12563                }
12564                let property = Property {
12565                    value: Some(value),
12566                    ..existing
12567                };
12568                return self.object_define_own_property(&receiver, key, property);
12569            }
12570            return self.object_define_own_property(&receiver, key, Property::data(value));
12571        }
12572        // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
12573        // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
12574        // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
12575        // `Reflect.set` to *report* the refusal instead of raising.
12576        //
12577        // A receiver that is not the object turns the whole operation into
12578        // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
12579        // `[[Set]]` rather than a lookup — that is what makes
12580        // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
12581        // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
12582        // writes to `object`, so it cannot express that and is only used when the two are
12583        // the same.
12584        let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
12585        if !same {
12586            return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
12587        }
12588        // Same receiver: the plain path below writes into `object`, which is right, but it
12589        // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
12590        // boolean, so the two step-1 refusals have to be read off the own descriptor here.
12591        if let Some(existing) = self.object_get_own_property(object, key)? {
12592            if existing.is_accessor() {
12593                return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
12594                    Some(setter) => {
12595                        self.call_value(setter, receiver, vec![value])?;
12596                        Ok(true)
12597                    }
12598                    None => Ok(false),
12599                };
12600            }
12601            if !existing.writable {
12602                return Ok(false);
12603            }
12604        }
12605        // Otherwise it is an ordinary create-or-write into `object` itself.
12606        self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
12607        Ok(true)
12608    }
12609
12610    /// `[[IsExtensible]]`, with the proxy trap when there is one.
12611    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
12612        if let Some(answer) = self.proxy_is_extensible(object)? {
12613            return Ok(answer);
12614        }
12615        if let Some(exotic) = object.exotic()
12616            && let Some(answer) = exotic.is_extensible(self, object)?
12617        {
12618            return Ok(answer);
12619        }
12620        Ok(object.is_extensible())
12621    }
12622
12623    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
12624    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
12625        if let Some(answer) = self.proxy_prevent_extensions(object)? {
12626            return Ok(answer);
12627        }
12628        if let Some(exotic) = object.exotic()
12629            && let Some(answer) = exotic.prevent_extensions(self, object)?
12630        {
12631            return Ok(answer);
12632        }
12633        object.set_extensible(false);
12634        Ok(true)
12635    }
12636
12637    fn copy_properties(
12638        &mut self,
12639        target: &Value,
12640        source: &Value,
12641        exclusion: &Value,
12642    ) -> JsResult<()> {
12643        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
12644        // does contribute: its index properties are own, enumerable and writable, which
12645        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
12646        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
12647        // is a no-op.
12648        let Some(target) = target.as_object() else {
12649            return Ok(());
12650        };
12651        let source_object = match source {
12652            Value::Object(object) => object.clone(),
12653            Value::String(text) => {
12654                // Untaken keys are the string's indices, which are code units.
12655                for index in 0..text.utf16_len() {
12656                    if let Some(unit) = text.wtf8().unit_at(index) {
12657                        target.define_data(&index.to_string(), self.string_wtf8(unit));
12658                    }
12659                }
12660                return Ok(());
12661            }
12662            _ => return Ok(()),
12663        };
12664        // An object *rest* element passes the keys already taken by the literal part as
12665        // an array of strings; a spread passes `null`, which excludes nothing. Only the
12666        // string keys of the exclusion array are meaningful, so an array is read by its
12667        // elements rather than by its own property names.
12668        let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
12669        if let Value::Object(list) = exclusion
12670            && let Some(length) = list.array_length()
12671        {
12672            for index in 0..length {
12673                if let Some(value) = list.array_get(index) {
12674                    excluded.push(self.propkey_of(&value)?);
12675                }
12676            }
12677        }
12678        let source = &source_object;
12679        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
12680        // Reading the property table directly made every spread of a proxy empty.
12681        let keys = self.object_own_property_keys(source)?;
12682        for as_key in keys {
12683            if as_key.is_symbol() {
12684                // A spread copies string-keyed properties only.
12685                continue;
12686            }
12687            if excluded.contains(&crate::value::Wtf8::new(
12688                as_key.as_str().unwrap_or_default(),
12689            )) {
12690                continue;
12691            }
12692            let enumerable = self
12693                .object_get_own_property(source, &as_key)?
12694                .is_some_and(|property| property.enumerable);
12695            if !enumerable {
12696                continue;
12697            }
12698            let value = self
12699                .get_property_key(source, &as_key)?
12700                .unwrap_or(Value::Undefined);
12701            target.define_data_key(&as_key, value);
12702        }
12703        Ok(())
12704    }
12705
12706    // -- iteration ---------------------------------------------------------
12707
12708    /// One object's own keys in enumeration order: array indices ascending, then the
12709    /// rest in insertion order.
12710    ///
12711    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
12712    /// whether the key is enumerable, which the caller resolves per key because an
12713    /// array's elements are not in the same store as its named properties.
12714    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
12715        // An index can arrive twice, once from the array's element store and once from
12716        // its property map, so the numeric keys go through a map that keeps the
12717        // enumerable answer if either source gave one.
12718        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
12719        for (key, enumerable) in &own {
12720            if let Some(index) = key.as_str().and_then(array_index) {
12721                let entry = numeric.entry(index).or_insert(false);
12722                *entry = *entry || *enumerable;
12723            }
12724        }
12725        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
12726            .into_iter()
12727            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
12728            .collect();
12729        ordered.extend(
12730            own.into_iter()
12731                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
12732        );
12733        ordered
12734    }
12735
12736    /// Build the key list a `for-in` loop walks.
12737    ///
12738    /// The order is the specification's: own properties before inherited ones, and
12739    /// within one object the integer-like keys in ascending numeric order ahead of the
12740    /// string keys in insertion order. A shadowed key only appears once, and a key that
12741    /// is a non-enumerable own property anywhere nearer is skipped entirely.
12742    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12743        let record = self.new_object(None);
12744        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
12745        // A proxy supplies its own key list, and — the reason this is not just another
12746        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
12747        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
12748        // descriptor there.
12749        if let Value::Object(object) = value
12750            && object.proxy_state().is_some()
12751        {
12752            let own = self
12753                .proxy_own_keys(object)?
12754                .unwrap_or_else(|| object.own_property_keys());
12755            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
12756            let mut numeric: Vec<u32> = Vec::new();
12757            let mut rest: Vec<PropertyKey> = Vec::new();
12758            for key in own {
12759                match key.as_str().and_then(array_index) {
12760                    Some(index) => numeric.push(index),
12761                    None => rest.push(key),
12762                }
12763            }
12764            numeric.sort_unstable();
12765            ordered.extend(
12766                numeric
12767                    .into_iter()
12768                    .map(|index| PropertyKey::from(index.to_string())),
12769            );
12770            ordered.extend(rest);
12771            for (index, key) in ordered.into_iter().enumerate() {
12772                record.define_data(&index.to_string(), self.key_value(&key));
12773            }
12774            record.define_data("__index", Value::Int(0));
12775            // The mark that makes `for_in_advance` re-ask the proxy per key.
12776            record.define_data("__proxy", Value::Object(object.clone()));
12777            return Ok(record);
12778        }
12779        if let Value::Object(object) = value {
12780            let mut chain = vec![object.clone()];
12781            chain.extend(object.chain());
12782            // Every own string key the walk has seen, enumerable or not. A
12783            // non-enumerable own property still hides a same-named enumerable one
12784            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
12785            // keeps `x` out of the loop even when the prototype has one.
12786            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
12787            for object in chain {
12788                let mut own: Vec<(crate::value::Wtf8, bool)> = object
12789                    .own_property_keys()
12790                    .iter()
12791                    .filter_map(|key| key.as_wtf8().cloned())
12792                    .map(|key| {
12793                        let enumerable = object
12794                            .own_property(&key.to_string_lossy())
12795                            .map(|property| property.enumerable)
12796                            .unwrap_or(false);
12797                        (key, enumerable)
12798                    })
12799                    .collect();
12800                if let Some(length) = object.array_length() {
12801                    own.retain(|(key, _)| key.as_str() != Some("length"));
12802                    for index in 0..length {
12803                        if object.array_get(index).is_some() {
12804                            own.push((crate::value::Wtf8::new(index.to_string()), true));
12805                        }
12806                    }
12807                }
12808                // Integer-like keys come first in ascending order, then the rest in
12809                // insertion order — and the ordering is *per object*, not for the chain
12810                // as a whole: one pass over every collected key lifted a prototype's
12811                // `"4"` above the target's own `x`/`y`, which is not the order
12812                // `for…in` reports.
12813                for (key, enumerable) in Self::order_own_keys(own) {
12814                    if visited.contains(&key) {
12815                        continue;
12816                    }
12817                    visited.push(key.clone());
12818                    if enumerable {
12819                        keys.push(key);
12820                    }
12821                }
12822            }
12823        }
12824        for (index, key) in keys.into_iter().enumerate() {
12825            record.define_data(&index.to_string(), self.string_wtf8(key));
12826        }
12827        record.define_data("__index", Value::Int(0));
12828        Ok(record)
12829    }
12830
12831    /// The next key of a `for…in` record, `None` when the loop is done.
12832    ///
12833    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
12834    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
12835    /// the loop reaches it, so a handler that stops reporting a key partway through drops
12836    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
12837    /// key the handler had already withdrawn.
12838    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
12839        let Value::Object(record) = record else {
12840            return Ok(None);
12841        };
12842        let proxy = record
12843            .own_property("__proxy")
12844            .and_then(|property| property.value);
12845        loop {
12846            let index = record
12847                .own_property("__index")
12848                .and_then(|property| property.value)
12849                .map(|value| value.to_int32())
12850                .unwrap_or(0);
12851            let Some(candidate) = record
12852                .own_property(&index.to_string())
12853                .and_then(|property| property.value)
12854            else {
12855                return Ok(None);
12856            };
12857            record.define_data("__index", Value::Int(index + 1));
12858            let text = candidate.to_js_string();
12859            let Some(Value::Object(proxy)) = &proxy else {
12860                return Ok(Some(text));
12861            };
12862            // The candidate is already a key string here, so the lookup does not need a
12863            // second `ToPropertyKey` conversion.
12864            let key = PropertyKey::from(text.as_str());
12865            let live = match self.proxy_get_own_property(proxy, &key)? {
12866                Some(descriptor) => descriptor,
12867                // Not a proxy after all, or it lost its state: fall back to the target.
12868                None => proxy.own_property_key(&key),
12869            };
12870            if live.is_some_and(|property| property.enumerable) {
12871                return Ok(Some(text));
12872            }
12873            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
12874            // next one.
12875        }
12876    }
12877
12878    /// The iterator for `for-of`: the object and its `next` method.
12879    ///
12880    /// An object that already carries a `next` method is used as it is — that is what
12881    /// `arr.values()` returns — and only arrays and strings get the built-in
12882    /// sequence iterator.
12883    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
12884    ///
12885    /// Callers that must choose between the iterable and the array-like protocol — the
12886    /// typed-array constructor is the main one — need to ask *before* committing to one.
12887    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
12888        let key = self.realm.well_known_key(WellKnown::Iterator);
12889        let method = self.read_field_key(value, &key)?;
12890        if matches!(method, Value::Undefined | Value::Null) {
12891            return Ok(false);
12892        }
12893        if !matches!(&method, Value::Object(object) if object.is_callable()) {
12894            return Err(Signal::Throw(
12895                self.make_error("TypeError", "Symbol.iterator is not callable"),
12896            ));
12897        }
12898        Ok(true)
12899    }
12900
12901    /// Collect everything an iterable yields.
12902    ///
12903    /// The cap is a guard against a generator that never ends: an unbounded collect would
12904    /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
12905    /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
12906    /// `MAX_ARRAY_LIKE` in the `Array` builtins.
12907    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
12908        const MAX_ITEMS: usize = 1 << 24;
12909        let iterator = self.get_iterator(value)?;
12910        let mut out = Vec::new();
12911        loop {
12912            let (element, done) = self.iterator_step(&iterator)?;
12913            if done {
12914                return Ok(out);
12915            }
12916            out.push(element);
12917            if out.len() > MAX_ITEMS {
12918                // Close before refusing: the walk is being abandoned, so the iterator's
12919                // `return` has to run (§7.4.6). Leaving it open left a `finally` block
12920                // unrun and a locked resource unreleased.
12921                self.close_iterator_after_throw(&iterator)?;
12922                return Err(self.range_error("iterable is too long to collect"));
12923            }
12924        }
12925    }
12926
12927    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
12928    ///
12929    /// A native constructor calls this once it has validated its arguments, which is the
12930    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
12931    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
12932    /// never reached. The prototype comes from `new.target` when it is an object, and from
12933    /// `default_proto` otherwise.
12934    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12935        let proto = self.ctor_prototype(default_proto)?;
12936        Ok(self.new_object(Some(proto)))
12937    }
12938
12939    /// An **array** whose prototype comes from `new.target`.
12940    ///
12941    /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
12942    /// instance from `new.target.prototype`, and building a plain array instead made every
12943    /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
12944    pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
12945        let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
12946        Ok(JsObject::array(self.heap, Some(proto), 0))
12947    }
12948
12949    /// `new.target.prototype` when this is a construction, or `None` for a plain call.
12950    ///
12951    /// The `Option` form is for the constructors that build their instance in a helper which
12952    /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
12953    /// from `await`'s internal promise, and only the first has a `new.target`.
12954    fn ctor_prototype_opt(
12955        &mut self,
12956        default_proto: Option<Gc<JsObject>>,
12957    ) -> JsResult<Option<Gc<JsObject>>> {
12958        let Some(target) = self.pending_new_target.clone() else {
12959            return Ok(default_proto);
12960        };
12961        let Some(target) = target.as_object().cloned() else {
12962            return Ok(default_proto);
12963        };
12964        match self.get_property(&target, "prototype")? {
12965            Some(Value::Object(proto)) => Ok(Some(proto)),
12966            _ => Ok(default_proto),
12967        }
12968    }
12969
12970    /// `new.target.prototype`, or `default_proto` when this is a plain call.
12971    fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12972        let Some(target) = self.pending_new_target.clone() else {
12973            return Ok(default_proto);
12974        };
12975        let Some(target) = target.as_object().cloned() else {
12976            return Ok(default_proto);
12977        };
12978        match self.get_property(&target, "prototype")? {
12979            Some(Value::Object(proto)) => Ok(proto),
12980            _ => Ok(default_proto),
12981        }
12982    }
12983
12984    /// `CreateDataPropertyOrThrow(O, key, value)`.
12985    ///
12986    /// A *definition*, not an assignment. The difference is visible the moment the target
12987    /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
12988    /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
12989    /// replaces the descriptor. It is a `TypeError` only when the definition itself is
12990    /// refused (`configurable: false`).
12991    ///
12992    /// The fast path exists because this is called once per element by `map`, `filter`,
12993    /// `slice` and friends: a plain array with no custom element descriptors and a writable
12994    /// `length` can store straight into its element vector.
12995    pub fn create_data_property_or_throw(
12996        &mut self,
12997        object: &Gc<JsObject>,
12998        index: usize,
12999        value: Value,
13000    ) -> JsResult<()> {
13001        if object.is_array()
13002            && object.elements_writable()
13003            && !object.has_element_descriptors()
13004            && object.is_extensible()
13005            && object.array_set(self.heap, index, value.clone())
13006        {
13007            return Ok(());
13008        }
13009        let key = PropertyKey::from(index.to_string());
13010        let property = Property {
13011            value: Some(value),
13012            writable: true,
13013            enumerable: true,
13014            configurable: true,
13015            ..Property::default()
13016        };
13017        // `CreateDataProperty` always asks for the default attributes, so it can only ever
13018        // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
13019        // the rest. Checking here rather than inside `object_define_own_property` is
13020        // deliberate: that function receives a fully-populated `Property` and cannot tell
13021        // an omitted attribute from an explicit `false`, so the generic check it would need
13022        // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
13023        // writable property (that cost eight `Object/defineProperty` tests).
13024        if let Some(existing) = self.object_get_own_property(object, &key)?
13025            && !existing.configurable
13026        {
13027            return Err(self.type_error("cannot create the property"));
13028        }
13029        if self.object_define_own_property(object, &key, property)? {
13030            return Ok(());
13031        }
13032        Err(self.type_error("cannot create the property"))
13033    }
13034
13035    /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
13036    ///
13037    /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
13038    /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
13039    /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
13040    /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
13041    /// run user code and both can throw.
13042    pub fn species_constructor(
13043        &mut self,
13044        object: &Gc<JsObject>,
13045        default: Value,
13046    ) -> JsResult<Value> {
13047        let Some(constructor) = self.get_property(object, "constructor")? else {
13048            return Ok(default);
13049        };
13050        let constructor = match constructor {
13051            Value::Undefined => return Ok(default),
13052            Value::Object(constructor) => constructor,
13053            _ => return Err(self.type_error("constructor is not an object")),
13054        };
13055        let key = self.realm.well_known_key(WellKnown::Species);
13056        let species = self.get_property_key(&constructor, &key)?;
13057        match species {
13058            None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
13059            Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
13060            Some(_) => Err(self.type_error("species is not a constructor")),
13061        }
13062    }
13063
13064    /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
13065    ///
13066    /// The result is an array of `length` holes whose prototype comes from
13067    /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
13068    /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
13069    /// is why the `IsArray` check is the first step and not an optimisation.
13070    pub fn array_species_create(
13071        &mut self,
13072        original: &Value,
13073        length: usize,
13074    ) -> JsResult<Gc<JsObject>> {
13075        let Some(object) = original.as_object().cloned() else {
13076            return Ok(self.new_array_of_length(length));
13077        };
13078        if !object.is_array() {
13079            return Ok(self.new_array_of_length(length));
13080        }
13081        // A `constructor` that *is* this realm's `Array` means "the default", and skipping
13082        // it here is what keeps `Array.prototype.map` from calling `Array` at all.
13083        let Some(constructor) = self.get_property(&object, "constructor")? else {
13084            return Ok(self.new_array_of_length(length));
13085        };
13086        let species = match constructor {
13087            Value::Undefined => return Ok(self.new_array_of_length(length)),
13088            Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
13089                return Ok(self.new_array_of_length(length));
13090            }
13091            Value::Object(constructor) => {
13092                let key = self.realm.well_known_key(WellKnown::Species);
13093                match self.get_property_key(&constructor, &key)? {
13094                    None | Some(Value::Undefined) | Some(Value::Null) => {
13095                        return Ok(self.new_array_of_length(length));
13096                    }
13097                    Some(species) => species,
13098                }
13099            }
13100            _ => return Ok(self.new_array_of_length(length)),
13101        };
13102        // `IsConstructor(species)` decides whether step 7 may construct at all; a species
13103        // that is merely callable is the `create-species-non-ctor` case.
13104        if !matches!(&species, Value::Object(object) if object.is_constructor()) {
13105            return Err(self.type_error("species is not a constructor"));
13106        }
13107        let created = self.construct(species.clone(), species, vec![Value::Int(length as i32)])?;
13108        let Some(created) = created.as_object().cloned() else {
13109            return Err(self.type_error("species constructor did not answer an object"));
13110        };
13111        // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
13112        // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
13113        // object, and `create-species-with-non-writable-property` asserts exactly that.
13114        // The length is set for the array case; the generic case is the caller's
13115        // `Set(A, "length", …)`.
13116        if created.is_array() {
13117            created.array_set_length(self.heap, length);
13118        }
13119        Ok(created)
13120    }
13121
13122    /// Whether `object` is this realm's `%Array%`.
13123    fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
13124        self.realm
13125            .array_constructor
13126            .as_ref()
13127            .is_some_and(|array| array.ptr_eq(object))
13128    }
13129
13130    /// A fresh `length`-hole array with the intrinsic prototype.
13131    pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
13132        let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
13133        array.array_set_length(self.heap, length);
13134        array
13135    }
13136
13137    /// Whether this call is a construction, i.e. `new.target` is defined.
13138    ///
13139    /// A native constructor receives `this = undefined` (it builds its own instance), so it
13140    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
13141    /// The native function currently executing, if any.
13142    pub fn current_native(&self) -> Option<Gc<JsObject>> {
13143        self.current_native.clone()
13144    }
13145
13146    /// Whether this call is a construction, i.e. `new.target` is defined.
13147    pub fn is_constructing(&self) -> bool {
13148        self.pending_new_target.is_some()
13149    }
13150
13151    /// The `TypeError` a constructor too primitive to have a wrapper raises.
13152    ///
13153    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
13154    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
13155    /// happens inside the native function, which is why the trace carries an
13156    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
13157    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
13158    /// constructor`, and an unnamed one reports the leading space of `" is not a
13159    /// constructor"` because the reference formats the empty name as it is.
13160    ///
13161    /// It is also the answer for a `new.target` that cannot be named at all — not a
13162    /// function, or a throwing `name` getter — where the reference falls back to the bare
13163    /// `not a constructor`.
13164    pub fn not_a_constructor_error(&mut self) -> Signal {
13165        let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
13166        self.not_a_constructor_error_for(target)
13167    }
13168
13169    /// The same `TypeError` for an explicit target, for the callers that check
13170    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
13171    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
13172        let target = match target {
13173            Value::Object(target) if target.is_callable() => target,
13174            _ => return self.type_error("not a constructor"),
13175        };
13176        let name = match self.get_property(&target, "name") {
13177            Ok(Some(value)) => value.to_js_string(),
13178            _ => return self.type_error("not a constructor"),
13179        };
13180        self.type_error(format!("{name} is not a constructor"))
13181    }
13182
13183    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
13184    ///
13185    /// True whenever `new.target` is not the callee itself, or when it has no usable
13186    /// `prototype` — the cases where reading the property is observable at all.
13187    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
13188        match &self.pending_new_target {
13189            Some(Value::Object(target)) => !target.ptr_eq(callee),
13190            Some(_) => true,
13191            None => false,
13192        }
13193    }
13194
13195    /// The symbol key for one of the engine's own hidden slots.
13196    ///
13197    /// Cached on the realm, so every object of a kind shares one key and a slot can be
13198    /// read back by name.
13199    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
13200        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
13201            return PropertyKey::Symbol(symbol.clone());
13202        }
13203        let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
13204        self.realm
13205            .internal_slots
13206            .borrow_mut()
13207            .insert(name, Value::Symbol(symbol.clone()));
13208        PropertyKey::Symbol(symbol)
13209    }
13210
13211    /// Read a hidden slot, or `None` when the object has none of that name.
13212    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
13213        let slots = self.realm.internal_slots.borrow();
13214        let Value::Symbol(symbol) = slots.get(name)? else {
13215            return None;
13216        };
13217        object
13218            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
13219            .and_then(|property| property.value)
13220    }
13221
13222    /// Define a hidden slot.
13223    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
13224        let key = self.internal_slot(name);
13225        object.define_key(&key, Property::with_attributes(value, false, false));
13226    }
13227
13228    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
13229    ///
13230    /// The method is looked up on the value (through its prototype), called with no
13231    /// arguments, and its result becomes the iterator. A generator gets here through
13232    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
13233    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
13234    ///
13235    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
13236    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
13237    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
13238    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
13239    /// does, and a user-defined iterable works without a special case.
13240    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
13241    /// `Symbol.iterator`.
13242    ///
13243    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
13244    /// iterable is legal there, and each value it produces is simply already settled by
13245    /// the time the `await` around it runs.
13246    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
13247        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
13248        let method = self.read_field_key(value, &async_key)?;
13249        // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
13250        // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
13251        // is *present but not callable* is a TypeError — it does not mean "try the other
13252        // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
13253        // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
13254        // guard is there to catch.
13255        let absent = matches!(method, Value::Undefined | Value::Null);
13256        if !absent {
13257            let Value::Object(object) = &method else {
13258                return Err(Signal::Throw(
13259                    self.make_error("TypeError", "value is not iterable"),
13260                ));
13261            };
13262            if !object.is_callable() {
13263                return Err(Signal::Throw(
13264                    self.make_error("TypeError", "value is not iterable"),
13265                ));
13266            }
13267        }
13268        if absent {
13269            return self.get_iterator(value);
13270        }
13271        let iterator = self.call_value(method, value.clone(), Vec::new())?;
13272        if !matches!(iterator, Value::Object(_)) {
13273            return Err(Signal::Throw(
13274                self.make_error("TypeError", "iterator is not an object"),
13275            ));
13276        }
13277        let next = self.read_field(&iterator, "next")?;
13278        Ok(Iterator {
13279            object: iterator,
13280            next,
13281        })
13282    }
13283
13284    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
13285        let key = self.realm.well_known_key(WellKnown::Iterator);
13286        let method = self.read_field_key(value, &key)?;
13287        let Value::Object(function) = &method else {
13288            return Err(Signal::Throw(self.make_error(
13289                "TypeError",
13290                &format!("{} is not iterable", value.to_js_string()),
13291            )));
13292        };
13293        if !function.is_callable() {
13294            return Err(Signal::Throw(self.make_error(
13295                "TypeError",
13296                &format!("{} is not iterable", value.to_js_string()),
13297            )));
13298        }
13299        let iterator = self.call_value(method, value.clone(), Vec::new())?;
13300        // The spec requires an object here; a primitive iterator has no `next` to call
13301        // and would fail one step later with a confusing message.
13302        if !matches!(iterator, Value::Object(_)) {
13303            return Err(Signal::Throw(
13304                self.make_error("TypeError", "iterator is not an object"),
13305            ));
13306        }
13307        let next = self.read_field(&iterator, "next")?;
13308        Ok(Iterator {
13309            object: iterator,
13310            next,
13311        })
13312    }
13313
13314    /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
13315    /// cannot replace it.
13316    fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
13317        let method = self.read_field(&iterator.object, "return")?;
13318        if matches!(method, Value::Undefined | Value::Null) {
13319            return Ok(());
13320        }
13321        if !matches!(&method, Value::Object(object) if object.is_callable()) {
13322            return Err(self.type_error("iterator return is not a function"));
13323        }
13324        self.call_value(method, iterator.object.clone(), Vec::new())?;
13325        Ok(())
13326    }
13327
13328    /// One step of an internal iterator: the value and whether it is exhausted.
13329    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
13330        // A real iterator (`next` is a function) answers with a result object.
13331        if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
13332            let result =
13333                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
13334            let Some(result) = result.as_object().cloned() else {
13335                return Err(self.type_error("iterator result is not an object"));
13336            };
13337            let done = self
13338                .get_property(&result, "done")?
13339                .is_some_and(|value| value.to_boolean());
13340            // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
13341            // `done` is false. Reading it unconditionally ran a throwing `value` getter on
13342            // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
13343            // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
13344            // made an unrelated `value` getter observable after the loop was over.
13345            if done {
13346                return Ok((Value::Undefined, true));
13347            }
13348            let value = self
13349                .get_property(&result, "value")?
13350                .unwrap_or(Value::Undefined);
13351            return Ok((value, false));
13352        }
13353        // An iterator whose `next` is not callable is treated as exhausted, which is
13354        // what `for (x of {})` relies on: `for_of_start` has already refused the ones
13355        // that are not iterable at all.
13356        Ok((Value::Undefined, true))
13357    }
13358
13359    /// `[...iterable]`: append everything the iterator yields, and answer the next
13360    /// index.
13361    ///
13362    /// This goes through the same iterator machinery `for-of` uses rather than copying
13363    /// an array's elements, because a spread source is any iterable: a string spreads
13364    /// into its characters and an array iterator spreads into its results. Handling
13365    /// only arrays made `[..."ab"]` come out empty with no error at all.
13366    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
13367        let Some(target) = array.as_object().cloned() else {
13368            return Ok(0);
13369        };
13370        let start = target.array_length().unwrap_or(0);
13371        let mut added = 0;
13372        let iterator = self.get_iterator(iterable)?;
13373        loop {
13374            let (value, done) = self.iterator_step(&iterator)?;
13375            if done {
13376                break;
13377            }
13378            target.array_set(self.heap, start + added, value);
13379            added += 1;
13380        }
13381        Ok((start + added) as i32)
13382    }
13383
13384    /// How an uncaught exception is reported.
13385    ///
13386    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
13387    /// with `ToString` — `js_std_dump_error` is three lines that end in
13388    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
13389    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
13390    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
13391    ///
13392    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
13393    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
13394    /// `toString`"; it does call it, but only for objects of a class it does not know how
13395    /// to walk, and never for errors, arrays or plain objects.
13396    ///
13397    /// A printer that fails must not take the reporter down with it, so that case falls
13398    /// back to the `ToString` rendering.
13399    pub fn describe_exception(&mut self, value: &Value) -> String {
13400        match crate::print::sprint(self, value) {
13401            Ok(text) => text,
13402            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
13403        }
13404    }
13405
13406    /// The file name of whatever is running, innermost frame first.
13407    ///
13408    /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
13409    /// innermost frame's file name, without distinguishing a module body from a plain
13410    /// script. `import()` uses it as the base for a relative specifier, which is why
13411    /// `import('./x.js')` inside a script resolves next to the script and not next to the
13412    /// process's working directory.
13413    pub fn script_or_module_name(&self) -> Option<String> {
13414        self.script_or_module_name_at(0)
13415    }
13416
13417    /// [`Interp::script_or_module_name`] `level` frames further out.
13418    ///
13419    /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
13420    /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
13421    /// frame without a file name is skipped rather than counted, because a native call
13422    /// pushes no frame of its own and so cannot be a level.
13423    pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
13424        self.frames
13425            .iter()
13426            .rev()
13427            .filter_map(|frame| frame.code.code.filename.clone())
13428            .nth(level)
13429    }
13430
13431    /// The current call stack, formatted the way `qjs` prints `error.stack`.
13432    ///
13433    /// One `    at name (file:line:col)` line per active frame, innermost first. The
13434    /// position is the one recorded for the instruction each frame is stopped on, which
13435    /// is why the compiler builds a pc-to-position table per function: without it a
13436    /// trace could only name the function, not the line inside it.
13437    ///
13438    /// A frame whose code has no positions prints just `(file)`, matching the
13439    /// reference's output for stripped bytecode.
13440    pub fn stack_trace(&self) -> String {
13441        self.stack_trace_skipping(0)
13442    }
13443
13444    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
13445    fn stack_trace_skipping(&self, skip: usize) -> String {
13446        // One ordered list, innermost first, so `skip` counts the same thing whether the
13447        // frames it leaves out are native or bytecode. Indices rather than references: a
13448        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
13449        let depth = self.frames.len();
13450        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
13451        // A native entered while `at` bytecode frames were live was called *from* the
13452        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
13453        // entered at the current depth are therefore innermost of all.
13454        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
13455            for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
13456                if *at == wanted {
13457                    order.push((true, index));
13458                }
13459            }
13460        };
13461        push_natives(&mut order, depth);
13462        for index in (0..depth).rev() {
13463            order.push((false, index));
13464            push_natives(&mut order, index);
13465        }
13466        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
13467        // barrier. Natives entered at exactly the barrier depth are the eval entry point
13468        // itself (`evalScript (native)`), and the reference leaves those out too.
13469        if let Some(barrier) = self.trace_barriers.last().copied() {
13470            order.retain(|(is_native, index)| match is_native {
13471                true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
13472                false => *index >= barrier,
13473            });
13474        }
13475
13476        let mut out = String::new();
13477        for (is_native, index) in order.into_iter().skip(skip) {
13478            match is_native {
13479                true => {
13480                    out.push_str("    at ");
13481                    let (native, _) = &self.native_frames[index];
13482                    let name = native
13483                        .own_property("name")
13484                        .and_then(|property| property.value)
13485                        .map(|value| value.to_js_string())
13486                        .unwrap_or_default();
13487                    out.push_str(&name);
13488                    out.push_str(" (native)\n");
13489                }
13490                false => {
13491                    let frame = &self.frames[index];
13492                    let code = &frame.code.code;
13493                    let file = code.filename.as_deref().unwrap_or("<input>");
13494                    // The name comes from the function *object*, not from the compiled code:
13495                    // an anonymous function expression is named by the property it is stored
13496                    // in (`{valueOf: function(){}}`), which only the object knows.
13497                    let bound_name = match &frame.callee {
13498                        Value::Object(object) => {
13499                            object
13500                                .own_property("name")
13501                                .and_then(|property| match property.value {
13502                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
13503                                        Some(text.to_string_lossy().into_owned())
13504                                    }
13505                                    _ => None,
13506                                })
13507                        }
13508                        _ => None,
13509                    };
13510                    // No callee object means the body was entered by the host, so the
13511                    // name has to come from the compiled code. Two cases differ:
13512                    //
13513                    // * an *unnamed* function of any kind — the reference reads the
13514                    //   `name` property, finds it empty, and prints `<anonymous>`;
13515                    // * a *module* body, which has no `name` property at all: the
13516                    //   reference builds that function object with `js_closure2` and
13517                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
13518                    //   so a trace reaching it also prints `<anonymous>` — while a
13519                    //   *script* body prints `<eval>`, its `name`.
13520                    let unnamed = code.name.is_empty() || code.module.is_some();
13521                    out.push_str("    at ");
13522                    match bound_name.as_deref() {
13523                        Some(name) => out.push_str(name),
13524                        None if unnamed => out.push_str("<anonymous>"),
13525                        None => out.push_str(&code.name),
13526                    }
13527                    match code.position_at(frame.at as u32) {
13528                        Some((line, column)) => {
13529                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
13530                        }
13531                        None => out.push_str(&format!(" ({file})\n")),
13532                    }
13533                }
13534            }
13535        }
13536        out
13537    }
13538
13539    /// Give an anonymous function the name of the property it is stored in.
13540    ///
13541    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
13542    /// enumerable and not configurable, and a function that already has a real name
13543    /// keeps it.
13544    ///
13545    /// "Already named" means a *non-empty* name: every function object is created with
13546    /// a `name` of `""` so the property exists on all of them, and treating that empty
13547    /// string as a name left every anonymous function nameless — which is how a stack
13548    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
13549    /// `SetFunctionName`, for a name that came from source text.
13550    fn set_function_name(&mut self, function: &Value, name: &str) {
13551        self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
13552    }
13553
13554    /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
13555    /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
13556    fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
13557        let Value::Object(object) = function else {
13558            return;
13559        };
13560        // `SetFunctionName` applies to *functions* and classes only, and only when they are
13561        // anonymous. Without the callability guard, `{value: someObject}` renamed
13562        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
13563        // on the right-hand side of a property. That is how a `zipKeyed` result object
13564        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
13565        // has no `NamedEvaluation` at all.
13566        if !object.is_callable() {
13567            return;
13568        }
13569        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
13570            && !existing.wtf8().is_empty()
13571        {
13572            return;
13573        }
13574        let text = self.string_wtf8(name.clone());
13575        object.define("name", Property::name_or_length(text));
13576    }
13577
13578    // -- global declarations -----------------------------------------------
13579
13580    /// Declare a global binding, creating its reference cell.
13581    /// Declare a `var` or function global, whose home is the global object.
13582    ///
13583    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
13584    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
13585    /// such as `print`, or a redeclaration — is left alone.
13586    pub fn declare_var_global(&mut self, name: &str) {
13587        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
13588        // global object is exactly the leak `typeof my_var === "undefined"` after
13589        // `eval("var my_var=2")` rules out.
13590        if let Some(scope) = self.eval_scope.as_mut() {
13591            scope.entry(name.to_string()).or_insert(Value::Undefined);
13592            return;
13593        }
13594        // A sloppy direct eval declares into its *caller's* variable environment. Doing
13595        // this on the global object instead made `eval("var c = 1")` inside a parameter
13596        // list overwrite a global `c`, and made two calls to the same function share one
13597        // binding.
13598        if let Some(cell) = self.declare_eval_local(name) {
13599            cell.set(Value::Undefined);
13600            return;
13601        }
13602        let global = self.realm.global.clone();
13603        if global.own_property(name).is_some() {
13604            return;
13605        }
13606        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
13607        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
13608        // whole point of that trick and what lets `Object.defineProperty` reshape it
13609        // afterwards. `eval_scope` is `Some` while an eval is running.
13610        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
13611        global.define(
13612            name,
13613            Property {
13614                value: Some(Value::Undefined),
13615                writable: true,
13616                enumerable: true,
13617                configurable: from_eval,
13618                ..Property::default()
13619            },
13620        );
13621    }
13622
13623    /// Declare a *lexical* global binding, which starts in its dead zone.
13624    ///
13625    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
13626    /// global object and is created when its initialiser runs.
13627    pub fn declare_global(&mut self, name: &str, is_const: bool) {
13628        if is_const {
13629            self.realm.lexical_consts.insert(name.to_string());
13630        }
13631        if !self.realm.globals.contains_key(name) {
13632            // `Uninitialized` rather than `Undefined`: the binding exists but is not
13633            // readable until its initialiser runs, and that is what `let x` before
13634            // `x = 1` has to observe.
13635            let cell = self.new_cell(Value::Uninitialized);
13636            self.realm.globals.insert(name.to_string(), cell);
13637            self.realm.declared.push(name.to_string());
13638        }
13639    }
13640}
13641
13642/// The bytecode and environment of a function object, if it is a bytecode function.
13643///
13644/// Extracted before a call so no borrow of the object is held across it.
13645fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
13646    function.with(|data| match &data.kind {
13647        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
13648        _ => None,
13649    })
13650}
13651
13652/// A native call target, extracted before the call so no borrow is held.
13653enum NativeCall {
13654    Native(NativeFn),
13655    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
13656    /// not hold that object's `RefCell` borrow.
13657    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
13658    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
13659    Bound {
13660        target: Value,
13661        this: Value,
13662        leading: Vec<Value>,
13663    },
13664    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
13665    Revoker(crate::object::ProxyRef),
13666    /// A promise's `resolve`.
13667    PromiseResolve(Gc<JsObject>),
13668    /// A promise's `reject`.
13669    PromiseReject(Gc<JsObject>),
13670    /// The executor `NewPromiseCapability(C)` hands a user constructor.
13671    CapabilityExecutor {
13672        state: Gc<JsObject>,
13673    },
13674    /// One leg of a `then` that settles through a user capability.
13675    ThenShim {
13676        handler: Option<Value>,
13677        resolve: Value,
13678        reject: Value,
13679        fulfilled: bool,
13680    },
13681    /// One continuation of an `await`.
13682    AwaitResume {
13683        coroutine: Gc<JsObject>,
13684        promise: Gc<JsObject>,
13685        kind: ResumeKind,
13686    },
13687    /// One element of a `Promise` combinator settling.
13688    CombinatorSettle {
13689        state: Gc<JsObject>,
13690        index: usize,
13691        fulfilled: bool,
13692    },
13693    /// One of `Promise.prototype.finally`'s two shims.
13694    FinallyShim {
13695        callback: Option<Value>,
13696        fulfilled: bool,
13697        constructor: Value,
13698    },
13699    /// Settle a promise with a fixed outcome.
13700    SettlePromise {
13701        promise: Gc<JsObject>,
13702        value: Value,
13703        rejected: bool,
13704    },
13705    /// Continue an async generator after its `await` settled.
13706    GeneratorResume {
13707        generator: Gc<JsObject>,
13708        promise: Gc<JsObject>,
13709        kind: ResumeKind,
13710    },
13711    /// Read a module namespace's binding out of its cell.
13712    ModuleBinding(Gc<Cell>),
13713    /// Finish a completed async generator's `return(v)` once `v` has settled.
13714    CompletedReturn {
13715        generator: Gc<JsObject>,
13716        promise: Gc<JsObject>,
13717        rejected: bool,
13718    },
13719    /// Answer a pending async-generator method with `{value, done}`.
13720    YieldResult {
13721        generator: Gc<JsObject>,
13722        promise: Gc<JsObject>,
13723        done: bool,
13724    },
13725    /// One step of `AsyncDisposableStack.disposeAsync`.
13726    DisposeStep {
13727        remaining: Gc<JsObject>,
13728        promise: Gc<JsObject>,
13729        error: Value,
13730        rejected: bool,
13731    },
13732}
13733
13734/// What a store does when the object refuses the write.
13735#[derive(Clone, Copy, PartialEq, Eq)]
13736pub enum DeleteFailure {
13737    /// Raise a `TypeError`, which is what strict mode and every built-in does.
13738    Throw,
13739    /// Ignore the write, which is what a sloppy-mode assignment does.
13740    Ignore,
13741}
13742
13743/// Whether `object` is a `Date` instance, by the class tag it carries.
13744///
13745/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
13746/// builtins module depending on the interpreter's conversion order.
13747fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
13748    interp
13749        .internal_get(object, "_class")
13750        .is_some_and(|value| value.to_js_string() == "Date")
13751}
13752
13753/// Which type `ToPrimitive` prefers when it converts an object.
13754#[derive(Clone, Copy, PartialEq, Eq)]
13755pub enum Hint {
13756    /// The default hint, which behaves like [`Hint::Number`].
13757    Default,
13758    /// `Number(obj)` and the arithmetic operators.
13759    Number,
13760    /// `String(obj)` and `ToPropertyKey`.
13761    String,
13762}
13763
13764/// Which table a binding slot indexes, for the messages that name it.
13765#[derive(Clone, Copy)]
13766enum VarSlot {
13767    Loc,
13768    Closure,
13769}
13770
13771/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
13772fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
13773    Ok(this)
13774}
13775
13776/// An internal iterator: the sequence plus a cursor.
13777pub(crate) struct Iterator {
13778    pub(crate) object: Value,
13779    pub(crate) next: Value,
13780}
13781
13782/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
13783/// and plain `a` for a method.
13784///
13785/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
13786/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
13787/// reads `at get a (file:1:2)`.
13788/// The same prefixing, for a name that may hold an unpaired surrogate.
13789fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
13790    let prefix = match flags & 3 {
13791        1 => "get ",
13792        2 => "set ",
13793        _ => return key.clone(),
13794    };
13795    let mut units: Vec<u16> = prefix.encode_utf16().collect();
13796    units.extend_from_slice(&key.to_units());
13797    crate::value::Wtf8::from_units(&units)
13798}
13799
13800fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
13801    match flags & 3 {
13802        1 => format!("get {key}"),
13803        2 => format!("set {key}"),
13804        _ => key.to_string(),
13805    }
13806}
13807
13808/// Define a method or accessor property, per the `define_method` flag byte.
13809///
13810/// The low two bits pick value/getter/setter and bit 2 marks the property
13811/// enumerable.
13812///
13813/// A getter and a setter arrive as two separate `define_method` instructions, and the
13814/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
13815/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
13816/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
13817/// `JS_DefineProperty`, which leaves the other half alone.
13818fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
13819    let enumerable = flags & 4 != 0;
13820    let kind = flags & 3;
13821    let existing = object.own_property_key(key);
13822    let property = match kind {
13823        1 => Property {
13824            getter: Some(function),
13825            // The setter half, if this literal already defined one.
13826            setter: existing
13827                .filter(Property::is_accessor)
13828                .and_then(|p| p.setter),
13829            enumerable,
13830            configurable: true,
13831            ..Property::default()
13832        },
13833        2 => Property {
13834            getter: existing
13835                .filter(Property::is_accessor)
13836                .and_then(|p| p.getter),
13837            setter: Some(function),
13838            enumerable,
13839            configurable: true,
13840            ..Property::default()
13841        },
13842        _ => Property {
13843            value: Some(function),
13844            writable: true,
13845            enumerable,
13846            configurable: true,
13847            ..Property::default()
13848        },
13849    };
13850    object.define_key(key, property);
13851}
13852
13853// ---------------------------------------------------------------------------
13854// Operand decoding
13855// ---------------------------------------------------------------------------
13856
13857/// How `print` renders a value: the reference's `JS_PrintValue`.
13858///
13859/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
13860/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
13861/// The format is reproduced closely because the test suite compares output text:
13862///
13863/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
13864/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
13865/// * a cycle prints `[circular N]` with `N` the stack index of the object;
13866/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
13867///   end print as `<N empty item(s)>`;
13868/// * a string is quoted inside a container but raw at the top level, which is why
13869///   `print("x")` and `print(["x"])` differ.
13870pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
13871    // A string argument is printed raw: `js_print` converts it with `ToString`
13872    // instead of dumping it, and the quoting only appears inside a container.
13873    if let Value::String(text) = value {
13874        return text.to_string_lossy().into_owned();
13875    }
13876    let mut printer = Printer {
13877        interp,
13878        out: String::new(),
13879        stack: Vec::new(),
13880    };
13881    printer.value(value, 0);
13882    printer.out
13883}
13884
13885/// The internal class name an object carries, when it has one.
13886fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
13887    interp
13888        .internal_get(object, "_class")
13889        .map(|value| value.to_js_string())
13890}
13891
13892/// A string property, looked up the way `GetProperty` does: own first, then the
13893/// prototype chain. Needed because the print formatter holds the interpreter
13894/// immutably and so cannot run getters.
13895fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
13896    let mut current = Some(object.clone());
13897    // Bounded, because a prototype cycle would otherwise loop forever.
13898    for _ in 0..100 {
13899        let node = current?;
13900        if let Some(property) = node.own_property(name)
13901            && let Some(value) = property.value
13902        {
13903            return Some(value.to_js_string());
13904        }
13905        current = node.with(|data| data.proto.clone());
13906    }
13907    None
13908}
13909
13910/// The `JS_PrintValue` state: output, and the objects currently being printed.
13911struct Printer<'a, 'rt> {
13912    /// Kept for the class-name lookups that typed arrays and `Date` will need.
13913    #[allow(dead_code)]
13914    interp: &'a Interp<'rt>,
13915    out: String,
13916    stack: Vec<Gc<JsObject>>,
13917}
13918
13919impl Printer<'_, '_> {
13920    /// Depth past which a container is summarised by its class name.
13921    const MAX_DEPTH: usize = 2;
13922
13923    fn value(&mut self, value: &Value, level: usize) {
13924        match value {
13925            Value::Undefined
13926            | Value::Uninitialized
13927            | Value::Hole
13928            | Value::CatchOffset(_)
13929            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
13930            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
13931            // The printer writes a bigint the way the language spells one, so a dump is
13932            // unambiguous about which kind of number it is showing.
13933            Value::BigInt(big) => {
13934                self.out.push_str(&big.to_decimal_string());
13935                self.out.push('n');
13936            }
13937            Value::Null => self.out.push_str("null"),
13938            Value::Bool(true) => self.out.push_str("true"),
13939            Value::Bool(false) => self.out.push_str("false"),
13940            Value::Int(number) => self.out.push_str(&number.to_string()),
13941            Value::Float(number) => {
13942                self.out
13943                    .push_str(&crate::value::number_to_string_for_print(*number));
13944            }
13945            Value::String(text) => self.print_string(&text.to_string_lossy()),
13946            Value::Object(object) => self.object(object, level),
13947        }
13948    }
13949
13950    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
13951        // A cycle is reported rather than followed; the index is where the object
13952        // already sits in the print stack, which is what the reference shows.
13953        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
13954            self.out.push_str(&format!("[circular {index}]"));
13955            return;
13956        }
13957        if object.is_callable() {
13958            let name = object
13959                .own_property("name")
13960                .and_then(|property| property.value)
13961                .map(|value| value.to_js_string())
13962                .unwrap_or_default();
13963            if name.is_empty() {
13964                self.out.push_str("[Function (anonymous)]");
13965            } else {
13966                self.out.push_str(&format!("[Function {name}]"));
13967            }
13968            return;
13969        }
13970        if level >= Self::MAX_DEPTH {
13971            let class = if object.is_array() { "Array" } else { "Object" };
13972            self.out.push_str(&format!("[{class}]"));
13973            return;
13974        }
13975        // `Date` and `Error` print as themselves rather than as bags of properties:
13976        // the ISO string, and `Name: message` followed by the trace.
13977        if let Some(class) = class_of(self.interp, object) {
13978            if class == "Date" {
13979                self.date(object);
13980                return;
13981            }
13982            if class == "Error" {
13983                self.error(object);
13984                return;
13985            }
13986        }
13987        self.stack.push(object.clone());
13988        if object.is_array() {
13989            self.array(object, level);
13990        } else {
13991            self.plain_object(object, level);
13992        }
13993        self.stack.pop();
13994    }
13995
13996    /// A Date prints as its ISO string; an invalid one falls through to the plain
13997    /// object form, the way the reference falls back when `toISOString` throws.
13998    fn date(&mut self, object: &Gc<JsObject>) {
13999        let value = self
14000            .interp
14001            .internal_get(object, "_date_value")
14002            .map(|value| value.to_number());
14003        match value.and_then(crate::builtins::date::iso_string) {
14004            Some(text) => self.out.push_str(&text),
14005            None => self.plain_object(object, 0),
14006        }
14007    }
14008
14009    /// `Name: message`, then the trace with its trailing newline removed.
14010    fn error(&mut self, object: &Gc<JsObject>) {
14011        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
14012        self.out.push_str(&name);
14013        if let Some(message) = inherited(object, "message")
14014            && !message.is_empty()
14015        {
14016            self.out.push_str(": ");
14017            self.out.push_str(&message);
14018        }
14019        if let Some(stack) = inherited(object, "stack") {
14020            self.out.push('\n');
14021            self.out.push_str(stack.trim_end_matches('\n'));
14022        }
14023    }
14024
14025    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
14026        let elements = object.array_elements().unwrap_or_default();
14027        self.out.push_str("[ ");
14028        // An interior hole means the array is "sparse": the reference prints those
14029        // as `index: value` pairs and says nothing about the holes themselves, while
14030        // a hole run at the end becomes a single `<N empty items>` note.
14031        let last_present = elements
14032            .iter()
14033            .rposition(|value| !matches!(value, Value::Hole));
14034        let has_interior_hole = match last_present {
14035            Some(last) => elements[..last]
14036                .iter()
14037                .any(|value| matches!(value, Value::Hole)),
14038            None => false,
14039        };
14040        let mut first = true;
14041        if has_interior_hole {
14042            let mut index = 0;
14043            while index < elements.len() {
14044                let value = &elements[index];
14045                if matches!(value, Value::Hole) {
14046                    index += 1;
14047                    continue;
14048                }
14049                if !first {
14050                    self.out.push_str(", ");
14051                }
14052                first = false;
14053                self.out.push_str(&format!("{index}: "));
14054                self.value(value, level + 1);
14055                index += 1;
14056            }
14057        } else {
14058            for (index, value) in elements.iter().enumerate() {
14059                if matches!(value, Value::Hole) {
14060                    continue;
14061                }
14062                if !first {
14063                    self.out.push_str(", ");
14064                }
14065                first = false;
14066                let _ = index;
14067                self.value(value, level + 1);
14068            }
14069            if let Some(last) = last_present {
14070                let trailing = elements.len() - last - 1;
14071                if trailing > 0 {
14072                    if !first {
14073                        self.out.push_str(", ");
14074                    }
14075                    self.out.push_str(&format!(
14076                        "<{trailing} empty item{}>",
14077                        if trailing > 1 { "s" } else { "" }
14078                    ));
14079                }
14080            } else if !elements.is_empty() {
14081                let count = elements.len();
14082                self.out.push_str(&format!(
14083                    "<{count} empty item{}>",
14084                    if count > 1 { "s" } else { "" }
14085                ));
14086            }
14087        }
14088        self.out.push_str(" ]");
14089    }
14090
14091    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
14092        self.out.push_str("{ ");
14093        let mut first = true;
14094        for key in object.own_keys() {
14095            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
14096                continue;
14097            };
14098            if !property.enumerable {
14099                continue;
14100            }
14101            if !first {
14102                self.out.push_str(", ");
14103            }
14104            first = false;
14105            self.out
14106                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
14107                    &key.to_string_lossy(),
14108                )));
14109            self.out.push_str(": ");
14110            // An accessor has no value to dump; the reference names the half that
14111            // exists instead of calling it.
14112            if property.is_accessor() {
14113                let text = match (property.getter.is_some(), property.setter.is_some()) {
14114                    (true, true) => "[Getter/Setter]",
14115                    (false, true) => "[Setter]",
14116                    _ => "[Getter]",
14117                };
14118                self.out.push_str(text);
14119            } else {
14120                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
14121            }
14122        }
14123        self.out.push_str(" }");
14124    }
14125
14126    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
14127    fn print_string(&mut self, text: &str) {
14128        self.out.push('"');
14129        for character in text.chars() {
14130            match character {
14131                '"' => self.out.push_str("\\\""),
14132                '\\' => self.out.push_str("\\\\"),
14133                '\n' => self.out.push_str("\\n"),
14134                '\r' => self.out.push_str("\\r"),
14135                '\t' => self.out.push_str("\\t"),
14136                c if (c as u32) < 0x20 => {
14137                    self.out.push_str(&format!("\\u{:04x}", c as u32));
14138                }
14139                c => self.out.push(c),
14140            }
14141        }
14142        self.out.push('"');
14143    }
14144}
14145
14146/// How `print` renders a value.
14147///
14148/// `ToString`, except that negative zero keeps its sign — the reference's host
14149/// printer does that while `String(-0)` is `"0"`.
14150pub fn display(value: &Value) -> String {
14151    match value {
14152        Value::Float(number) => crate::value::number_to_string_for_print(*number),
14153        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
14154            "undefined".to_string()
14155        }
14156        other => other.to_js_string(),
14157    }
14158}
14159
14160// ---------------------------------------------------------------------------
14161// Numeric operators
14162// ---------------------------------------------------------------------------
14163
14164/// `a + b` keeping the `Int` representation when it fits.
14165fn add_numbers(left: Value, right: Value) -> Value {
14166    match (&left, &right) {
14167        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
14168            Some(sum) => Value::Int(sum),
14169            None => Value::Float(*a as f64 + *b as f64),
14170        },
14171        _ => Value::Float(left.to_number() + right.to_number()),
14172    }
14173}
14174
14175/// The arithmetic operators other than `+`, which needs string concatenation.
14176fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
14177    use Opcode::*;
14178    // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
14179    // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
14180    // *before* the match, so even the arms that never needed `a` or `b` paid for it.
14181    if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
14182        return Ok(match op {
14183            And => Value::Int(x & y),
14184            Or => Value::Int(x | y),
14185            Xor => Value::Int(x ^ y),
14186            Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
14187            Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
14188            Shr => match (*x as u32) >> ((*y as u32) & 31) {
14189                shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
14190                shifted => Value::Float(shifted as f64),
14191            },
14192            Sub => match x.checked_sub(*y) {
14193                Some(value) => Value::Int(value),
14194                None => Value::Float(*x as f64 - *y as f64),
14195            },
14196            _ => return arithmetic_slow(op, left, right),
14197        });
14198    }
14199    arithmetic_slow(op, left, right)
14200}
14201
14202/// [`arithmetic`] for everything the integer fast path above does not take.
14203fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
14204    use Opcode::*;
14205    let (a, b) = (left.to_number(), right.to_number());
14206    Ok(match op {
14207        Sub => match (&left, &right) {
14208            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
14209                Some(value) => Value::Int(value),
14210                None => Value::Float(a - b),
14211            },
14212            _ => Value::Float(a - b),
14213        },
14214        Mul => Value::Float(a * b),
14215        Div => Value::Float(a / b),
14216        Mod => Value::Float(js_mod(a, b)),
14217        Pow => Value::Float(a.powf(b)),
14218        And => Value::Int(left.to_int32() & right.to_int32()),
14219        Or => Value::Int(left.to_int32() | right.to_int32()),
14220        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
14221        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
14222        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
14223        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
14224        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
14225        // fits the small-integer representation stays an `Int`; the rest become a
14226        // float, which is how the reference keeps `n >>> 0` non-negative.
14227        Shr => {
14228            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
14229            match i32::try_from(shifted) {
14230                Ok(value) => Value::Int(value),
14231                Err(_) => Value::Float(shifted as f64),
14232            }
14233        }
14234        _ => Value::Float(a),
14235    })
14236}
14237
14238/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
14239///
14240/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
14241/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
14242/// slow path where the rules live.
14243fn is_number(value: &Value) -> bool {
14244    matches!(value, Value::Int(_) | Value::Float(_))
14245}
14246
14247/// The `Value::Bool` a comparison operator answers for `ordering`.
14248///
14249/// `None` is the unordered case — a `NaN` on either side — and every operator answers
14250/// false for it, including `<=` and `>=`.
14251fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
14252    use Opcode::*;
14253    let answer = match (op, ordering) {
14254        (_, None) => false,
14255        (Lt, Some(ordering)) => ordering.is_lt(),
14256        (Lte, Some(ordering)) => ordering.is_le(),
14257        (Gt, Some(ordering)) => ordering.is_gt(),
14258        (Gte, Some(ordering)) => ordering.is_ge(),
14259        _ => false,
14260    };
14261    Value::Bool(answer)
14262}
14263
14264/// `%`, which follows the sign of the dividend rather than Rust's.
14265fn js_mod(left: f64, right: f64) -> f64 {
14266    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
14267        return f64::NAN;
14268    }
14269    if right.is_infinite() {
14270        return left;
14271    }
14272    let remainder = left % right;
14273    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
14274    // the spec makes the sign match the dividend.
14275    if remainder == 0.0 {
14276        0.0f64.copysign(left)
14277    } else {
14278        remainder
14279    }
14280}
14281
14282fn negate(value: Value) -> Value {
14283    match value {
14284        Value::Int(0) => Value::Float(-0.0),
14285        Value::Int(i) => Value::Int(-i),
14286        other => Value::Float(-other.to_number()),
14287    }
14288}
14289
14290fn increment(value: Value) -> Value {
14291    match value {
14292        Value::Int(i) => match i.checked_add(1) {
14293            Some(next) => Value::Int(next),
14294            None => Value::Float(i as f64 + 1.0),
14295        },
14296        other => Value::Float(other.to_number() + 1.0),
14297    }
14298}
14299
14300fn decrement(value: Value) -> Value {
14301    match value {
14302        Value::Int(i) => match i.checked_sub(1) {
14303            Some(next) => Value::Int(next),
14304            None => Value::Float(i as f64 - 1.0),
14305        },
14306        other => Value::Float(other.to_number() - 1.0),
14307    }
14308}
14309
14310/// Compare a `BigInt` with an `f64` on their mathematical values.
14311///
14312/// Neither side is rounded to the other's precision: the number is split into its integer
14313/// part (compared as an exact bigint) and its fraction, which is what decides the answer
14314/// when the integer parts are equal. An infinite value is larger than every bigint.
14315fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
14316    use std::cmp::Ordering;
14317    if number.is_nan() {
14318        return None;
14319    }
14320    if number.is_infinite() {
14321        return Some(if number > 0.0 {
14322            Ordering::Less
14323        } else {
14324            Ordering::Greater
14325        });
14326    }
14327    let truncated = number.trunc();
14328    // A number wider than `i128` still has an exact integer part, but no bigint form we can
14329    // build cheaply; the sign of the difference is all that is needed, so compare against
14330    // the bigint's own magnitude instead.
14331    if truncated.abs() >= 1.7e38 {
14332        let big_as_f64 = big.to_f64();
14333        return big_as_f64.partial_cmp(&number);
14334    }
14335    let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
14336    match big.cmp(&integer) {
14337        Ordering::Equal => {
14338            // Same integer part: the fraction decides, and a negative number's fraction is
14339            // below the integer (`-1.5` truncates to `-1`).
14340            if number > truncated {
14341                Some(Ordering::Less)
14342            } else if number < truncated {
14343                Some(Ordering::Greater)
14344            } else {
14345                Some(Ordering::Equal)
14346            }
14347        }
14348        other => Some(other),
14349    }
14350}
14351
14352/// `CanonicalNumericIndexString(argument)` (§7.1.21).
14353///
14354/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
14355/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
14356/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
14357/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
14358/// rather than treating it as `0`.
14359fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
14360    let PropertyKey::String(text) = key else {
14361        // A symbol is never an index.
14362        return None;
14363    };
14364    let text = text.to_string_lossy();
14365    if text == "-0" {
14366        return Some(-0.0);
14367    }
14368    let number: f64 = text.parse().ok()?;
14369    // The round-trip test *is* the definition: only the canonical spelling qualifies.
14370    // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
14371    // `"0.10"` does not.
14372    let rendered = Value::Float(number).to_js_string();
14373    (rendered == text).then_some(number)
14374}
14375
14376/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
14377///
14378/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
14379/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
14380/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
14381/// numeric and invalid, which is why they stop the prototype chain instead of falling
14382/// through it.
14383///
14384/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
14385/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
14386/// `in`, `delete` and `defineProperty` separately to make sure it does not.
14387fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
14388    numeric.is_finite()
14389        && numeric.fract() == 0.0
14390        && !(numeric == 0.0 && numeric.is_sign_negative())
14391        && numeric >= 0.0
14392        && object
14393            .typed_array_length()
14394            .is_some_and(|length| (numeric as usize) < length)
14395}