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    /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
202    ///
203    /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
204    /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
205    /// `[object Iterator Helper]`).
206    pub iterator_helper_proto: Option<Gc<JsObject>>,
207    /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
208    /// that was not already an `Iterator`.
209    ///
210    /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
211    /// untouched and does *not* override `@@toStringTag`, so
212    /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
213    pub iterator_wrap_proto: Option<Gc<JsObject>>,
214    /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
215    pub generator_function_proto: Option<Gc<JsObject>>,
216    /// `%AsyncFunction.prototype%`.
217    pub async_function_proto: Option<Gc<JsObject>>,
218    /// `%AsyncGeneratorFunction.prototype%`.
219    pub async_generator_function_proto: Option<Gc<JsObject>>,
220    /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
221    ///
222    /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
223    /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
224    /// prototype per iterator made every array iterator's prototype distinct.
225    pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
226    /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
227    ///
228    /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
229    /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
230    /// both faster and impossible to break from a script.
231    well_known_symbols: WellKnownSymbols,
232    /// The classes the host registered, and the prototype each one hands its instances.
233    pub host_classes: HostClasses,
234}
235
236/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
237///
238/// One per realm, because a class id is only meaningful within the runtime that handed it
239/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
240/// a host class cannot collide.
241pub struct HostClasses {
242    /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
243    /// `JS_GetOpaque(val, 0)` has to match nothing.
244    next_id: u32,
245    /// What each registered class does.
246    defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
247    /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
248    ///
249    /// A strong reference, so the prototype a host installed outlives every script
250    /// reference to it — which is what `JS_SetClassProto` promises.
251    protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
252}
253
254impl HostClasses {
255    fn new() -> HostClasses {
256        HostClasses {
257            next_id: 1,
258            defs: std::collections::BTreeMap::new(),
259            protos: std::collections::BTreeMap::new(),
260        }
261    }
262
263    /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
264    pub fn register(&mut self, def: ClassDef) -> ClassId {
265        let id = ClassId::from_raw(self.next_id);
266        self.next_id += 1;
267        self.defs.insert(id, std::rc::Rc::new(def));
268        id
269    }
270
271    /// Register `def` under an id the caller already has (`JS_NewClass`).
272    ///
273    /// The C API splits "get an id" from "register a class" because a module may be
274    /// initialised lazily; registering twice under one id replaces the definition, and an
275    /// object created under the old one keeps the old behaviour, since it carries its own
276    /// reference.
277    pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
278        if !id.is_valid() {
279            return false;
280        }
281        // Keep the counter past any id handed out explicitly, so a later `register` cannot
282        // reuse one.
283        self.next_id = self.next_id.max(id.get() + 1);
284        self.defs.insert(id, std::rc::Rc::new(def));
285        true
286    }
287
288    /// What `id` was registered with.
289    pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
290        self.defs.get(&id).cloned()
291    }
292
293    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
294    pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
295        self.protos.insert(id, proto);
296    }
297
298    /// The prototype installed for `id`, if the host installed one.
299    pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
300        self.protos.get(&id).cloned()
301    }
302
303    /// How many classes the host registered.
304    pub fn len(&self) -> usize {
305        self.defs.len()
306    }
307
308    /// Whether no class has been registered.
309    pub fn is_empty(&self) -> bool {
310        self.defs.is_empty()
311    }
312}
313
314impl Default for HostClasses {
315    fn default() -> HostClasses {
316        HostClasses::new()
317    }
318}
319
320/// One binding of the frame that called `eval`, so the eval'd code can read and
321/// write it by name.
322struct EvalBinding {
323    /// The name it was declared with.
324    name: String,
325    /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
326    /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
327    /// a function that declares `a` must find that `a`.
328    frame: usize,
329    /// Which table of that frame it lives in.
330    slot: EvalSlot,
331    /// The slot index within that table.
332    index: usize,
333}
334
335/// Which table of a frame an [`EvalBinding`] indexes.
336#[derive(Clone, Copy)]
337enum EvalSlot {
338    Arg,
339    Local,
340}
341
342/// One activation record.
343struct Frame {
344    /// The bytecode being run.
345    code: Gc<CompiledCode>,
346    /// The cells this closure captured.
347    env: Gc<ClosureEnv>,
348    /// The `this` binding.
349    this: Value,
350    /// Argument slots, sized to the declared parameter count.
351    args: Vec<Value>,
352    /// How many values the caller actually passed, which is what `arguments.length`
353    /// reports and what `...rest` slices from.
354    passed_count: usize,
355    /// The passed values, **only when they do not fit in [`Self::args`]**.
356    ///
357    /// `args` is sized to the declared parameters, so a call that passes no more than
358    /// that already holds every passed value in its first `passed_count` slots — copying
359    /// them here as well was two writes and a buffer per call, on the hottest path in
360    /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
361    /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
362    /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
363    /// its own copy.
364    ///
365    /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
366    /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
367    /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
368    /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
369    /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
370    /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
371    #[allow(clippy::box_collection)]
372    passed_overflow: Option<Box<Vec<Value>>>,
373    /// Local slots.
374    locals: Vec<Value>,
375    /// Reference cells for this frame's own captured bindings.
376    cells: Vec<Gc<Cell>>,
377    /// The operand stack.
378    stack: Vec<Value>,
379    /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
380    local_vars: Option<Gc<LocalVars>>,
381
382    /// Index of the next instruction, not a byte offset.
383    ///
384    /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
385    /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
386    /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
387    /// `Frame`, and `frames.push` copies the whole struct on every call.
388    pc: usize,
389    /// Byte offset of the instruction being executed, which is what a stack trace
390    /// reports. `pc` has already moved past it by the time an instruction runs.
391    ///
392    /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
393    at: usize,
394    /// The callee, so a native builtin can tell which constructor it is.
395    callee: Value,
396    /// `new.target`: the constructor under `new`, `undefined` for a plain call.
397    new_target: Value,
398    /// What this frame costs against [`Interp::stack_limit`], in bytes.
399    ///
400    /// Cached rather than recomputed because it is charged on every call and a call is the
401    /// hottest thing in the interpreter.
402    cost: usize,
403    /// [`Interp::stack_used`] before this frame was pushed.
404    ///
405    /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
406    /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
407    /// leave the counter wrong. There are eight places that drop frames; one subtraction
408    /// forgotten in any of them would leak budget until the depth limit moved.
409    stack_base: usize,
410    /// Whether this frame's body ended in a `tail_call`.
411    ///
412    /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
413    /// with its own frame just like `call` does and only skips storing the result
414    /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
415    /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
416    /// pushed as usual, and this marker makes its return value the *caller's* return
417    /// value without running the instructions after the call.
418    tail: bool,
419}
420
421impl Frame {
422    /// Read a local slot, taking the frame as `self`.
423    ///
424    /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
425    /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
426    /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
427    /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
428    /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
429    #[inline]
430    fn read_loc(&self, slot: usize) -> Value {
431        let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
432        if cell == -1 {
433            return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
434        }
435        match self.cells.get(cell as usize) {
436            Some(cell) => cell.get(),
437            None => Value::Undefined,
438        }
439    }
440
441    /// [`Self::read_loc`] for an argument slot.
442    #[inline]
443    fn read_arg(&self, slot: usize) -> Value {
444        let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
445        if cell == -1 {
446            return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
447        }
448        match self.cells.get(cell as usize) {
449            Some(cell) => cell.get(),
450            None => Value::Undefined,
451        }
452    }
453
454    /// The values the caller actually passed, which is what `arguments` exposes.
455    ///
456    /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
457    fn passed(&self) -> &[Value] {
458        match &self.passed_overflow {
459            Some(values) => values,
460            None => &self.args[..self.passed_count],
461        }
462    }
463
464    /// The decoded instructions of the function this frame runs.
465    ///
466    /// A method rather than `frame.code.insns` at the call site so that the borrow is
467    /// obviously of the frame — the dispatch loop holds one across a `get`.
468    fn insns(&self) -> &[crate::insn::Insn] {
469        &self.code.insns
470    }
471}
472
473impl js_gc::Trace for Frame {
474    fn trace(&self, tracer: &mut js_gc::Tracer) {
475        self.code.trace(tracer);
476        self.env.trace(tracer);
477        self.this.trace(tracer);
478        for value in &self.args {
479            value.trace(tracer);
480        }
481        for value in self.passed() {
482            value.trace(tracer);
483        }
484        for value in &self.locals {
485            value.trace(tracer);
486        }
487        for cell in &self.cells {
488            cell.trace(tracer);
489        }
490        if let Some(local_vars) = &self.local_vars {
491            tracer.visit(local_vars);
492        }
493        for value in &self.stack {
494            value.trace(tracer);
495        }
496        self.callee.trace(tracer);
497        self.new_target.trace(tracer);
498    }
499}
500
501/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
502/// emitted `if_false` treats as "keep going".
503/// How many finished frames' value buffers are kept for reuse.
504const RECYCLE_SLOTS: usize = 8;
505
506/// The largest buffer worth keeping. See [`Interp::free_values`].
507const RECYCLE_MAX_CAPACITY: usize = 4096;
508
509const RESUME_NEXT: i32 = 0;
510/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
511/// generator fall into its `return_async`.
512const RESUME_RETURN: i32 = 1;
513/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
514/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
515/// must forward the exception into the inner iterator rather than finish.
516const RESUME_THROW: i32 = 2;
517
518/// One microtask.
519///
520/// The queue holds *data* rather than closures because its contents are GC values: a
521/// closure would be invisible to the collector, and a pending reaction is exactly the
522/// kind of thing that must keep its handlers and its promise alive.
523pub enum Job {
524    /// A `then` reaction about to run.
525    Reaction {
526        /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
527        handler: Option<Value>,
528        /// The value or reason to call it with.
529        argument: Value,
530        /// Whether the source promise rejected, which decides the pass-through kind.
531        rejected: bool,
532        /// The promise the answer settles.
533        promise: Gc<JsObject>,
534    },
535    /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
536    Thenable {
537        /// The `then` that was found on the value.
538        then: Value,
539        /// The thenable itself, which becomes `then`'s `this`.
540        value: Value,
541        /// The promise being resolved.
542        promise: Gc<JsObject>,
543    },
544    /// A pending `import(specifier)`.
545    Import {
546        /// The specifier, already converted to a string.
547        specifier: String,
548        /// The module that asked, which the specifier resolves against.
549        referrer: String,
550        /// The promise `import()` handed back.
551        promise: Gc<JsObject>,
552    },
553    /// An async generator resuming after the value it awaited settled.
554    GeneratorResume {
555        /// The async generator to continue.
556        generator: Gc<JsObject>,
557        /// The promise the pending method returned.
558        promise: Gc<JsObject>,
559        /// Whether this delivers the value or raises the reason.
560        kind: ResumeKind,
561        /// The settled value, or the rejection reason.
562        value: Value,
563    },
564    /// An async function resuming after the value it awaited settled.
565    Resume {
566        /// The body, parked in a coroutine.
567        coroutine: Gc<JsObject>,
568        /// The promise the async function handed its caller.
569        promise: Gc<JsObject>,
570        /// Whether this resumption delivers a value or raises one.
571        kind: ResumeKind,
572        /// The settled value, or the rejection reason.
573        value: Value,
574    },
575}
576
577/// One macro-task: work the event loop owes the script but has not run yet.
578///
579/// The microtask queue ([`Job`]) is different: those run before the host regains control.
580/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
581/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
582/// logic: the engine decides *what* is due, the host decides *how to wait*.
583///
584/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
585/// reference counting even though nothing else references it — the same rule the `HostFn`
586/// documentation states from the other side (a host closure must not hold a `Gc`, so the
587/// `Gc` lives here instead).
588pub enum Task {
589    /// A `setTimeout` that is due at `due_at`.
590    ///
591    /// There is no `setInterval` variant because the reference has no `os.setInterval` at
592    /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
593    /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
594    /// would give this engine a timer the reference cannot produce, with nothing to
595    /// compare it against.
596    Timer {
597        /// The id `setTimeout` returned, for `clearTimeout`.
598        id: i32,
599        /// What to call when it fires.
600        callback: Value,
601        /// When it becomes runnable, as a monotonic instant.
602        due_at: std::time::Instant,
603    },
604}
605
606/// A descriptor the host has to poll, and which directions have a handler.
607///
608/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
609/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
610/// blocks on it, and the host reports back through [`Interp::fire_fd`].
611#[derive(Debug, Clone, Copy, PartialEq, Eq)]
612pub struct FdInterest {
613    /// The descriptor to watch.
614    pub fd: i32,
615    /// Whether `os.setReadHandler` registered a callback.
616    pub read: bool,
617    /// Whether `os.setWriteHandler` registered a callback.
618    pub write: bool,
619}
620
621/// The callbacks registered for one descriptor, per direction.
622#[derive(Default)]
623pub(crate) struct FdHandlers {
624    /// `os.setReadHandler`'s callback.
625    pub read: Option<Value>,
626    /// `os.setWriteHandler`'s callback.
627    pub write: Option<Value>,
628}
629
630/// The file name `eval` reports, which the reference does not inherit from the caller.
631///
632/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
633/// reference and the names show up in stack traces.
634/// The description of the private symbol a class brand is made from.
635///
636/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
637/// place no script can reach, since no expression can name a private symbol.
638const BRAND_DESCRIPTION: &str = "brand";
639
640/// One validated property lookup.
641///
642/// Covers both own-property hits and prototype hits. The second kind was deliberately left
643/// uncached at first ("a prototype hit depends on more than the object and the name"), and
644/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
645/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
646/// names on every iteration (measured: 100 ns per call over an empty loop).
647pub struct FieldCache {
648    /// The name, so two different properties of one object do not collide.
649    key: PropertyKey,
650    /// Where the value was found, relative to the chain below.
651    index: usize,
652    /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
653    level: u8,
654    /// The receiver and every prototype down to (and including) the level that answered,
655    /// each with the length of its property table at the time.
656    ///
657    /// That length is the whole guard, and it is sufficient for the ways the answer can
658    /// change without a lookup: adding or deleting any property moves it, and a
659    /// same-length rewrite is caught by `cached_data_property` re-checking the key and
660    /// refusing an accessor. Storing the *whole* chain — not just the object that answered
661    /// — is what catches a property appearing on an *intermediate* prototype and shadowing
662    /// the one that was cached.
663    ///
664    /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
665    /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
666    chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
667}
668
669/// How many links of a prototype chain a [`FieldCache`] remembers.
670///
671/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
672/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
673/// at three.
674const MAX_CACHED_CHAIN: usize = 3;
675
676/// A remembered global-variable lookup.
677///
678/// A `var` global is an ordinary property of the global object, so reading one walks the
679/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
680/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
681/// fixed by the bytecode, and the slot in the object's table only changes if the global
682/// object is mutated, which the index-and-name check below catches.
683pub struct GlobalCache {
684    /// The global object the lookup was resolved on, weakly.
685    object: js_gc::WeakGc<JsObject>,
686    /// Index of the data property in the global object's table.
687    index: usize,
688}
689
690/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
691const GLOBAL_CACHE_SLOTS: usize = 1024;
692
693/// How many property lookups are remembered.
694///
695/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
696/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
697/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
698/// lookup itself. Making it bigger stops helping: the working set of a real program's
699/// property sites is bounded by its code size.
700const FIELD_CACHE_SLOTS: usize = 4096;
701
702/// How much the heap may grow past the last `out of memory` before saying it again.
703///
704/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
705/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
706/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
707/// because it looks like it works. The reference gets this for free: it fails inside
708/// `js_malloc`, and its printing path happens not to allocate.
709///
710/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
711/// allocating is stopped within a rounding error of the limit) and far above what a
712/// handler needs.
713const OOM_HYSTERESIS: usize = 64 * 1024;
714
715/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
716pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
717
718/// How many instructions run between polls of [`Interp::interrupt`].
719///
720/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
721/// order of magnitude on both implementations — which is what lets a C driver compare its
722/// output byte for byte (see `scripts/m15-capi.sh --embed`).
723pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
724
725/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
726///
727/// Chosen so that the byte budget is what actually decides for every ordinary
728/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
729/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
730/// millions of frames.
731pub const MAX_FRAMES: usize = 200_000;
732
733const EVAL_FILE: &str = "<input>";
734
735/// The file name `std.evalScript` reports.
736const EVAL_SCRIPT_FILE: &str = "<evalScript>";
737
738/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
739///
740/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
741/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
742fn clamp_delay(delay_ms: f64) -> std::time::Duration {
743    // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
744    // on a float, which reads as a typo even when it is deliberate. Both NaN and a
745    // non-positive delay mean "due now".
746    if delay_ms.is_nan() || delay_ms <= 0.0 {
747        return std::time::Duration::ZERO;
748    }
749    std::time::Duration::from_secs_f64(delay_ms / 1000.0)
750}
751
752impl js_gc::Trace for Task {
753    fn trace(&self, tracer: &mut js_gc::Tracer) {
754        let Task::Timer { callback, .. } = self;
755        callback.trace(tracer);
756    }
757}
758
759/// What one turn of the event loop did, so the caller cannot spin by accident.
760///
761/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
762/// core until the timer is due. Naming the three cases makes the wait explicit.
763#[derive(Debug, Clone, Copy, PartialEq, Eq)]
764pub enum Turn {
765    /// Something ran. Call again immediately — there may be more ready work.
766    Ran,
767    /// Nothing is runnable, but descriptors are registered: the host must poll
768    /// [`Interp::pending_fds`] for at most this long, then report readiness with
769    /// [`Interp::fire_fd`].
770    ///
771    /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
772    /// the failure this project treats as worst — a handler that silently never fires —
773    /// so the two cannot be confused by accident.
774    Poll(std::time::Duration),
775    /// Nothing is runnable yet, but something is pending. Block at most this long, then
776    /// call again.
777    Wait(std::time::Duration),
778    /// Nothing is pending at all: the loop is done.
779    Done,
780}
781
782impl js_gc::Trace for Job {
783    fn trace(&self, tracer: &mut js_gc::Tracer) {
784        match self {
785            Job::Reaction {
786                handler,
787                argument,
788                promise,
789                ..
790            } => {
791                if let Some(handler) = handler {
792                    handler.trace(tracer);
793                }
794                argument.trace(tracer);
795                tracer.visit(promise);
796            }
797            Job::Thenable {
798                then,
799                value,
800                promise,
801            } => {
802                then.trace(tracer);
803                value.trace(tracer);
804                tracer.visit(promise);
805            }
806            Job::Resume {
807                coroutine,
808                promise,
809                value,
810                ..
811            } => {
812                tracer.visit(coroutine);
813                tracer.visit(promise);
814                value.trace(tracer);
815            }
816            Job::Import { promise, .. } => tracer.visit(promise),
817            Job::GeneratorResume {
818                generator,
819                promise,
820                value,
821                ..
822            } => {
823                tracer.visit(generator);
824                tracer.visit(promise);
825                value.trace(tracer);
826            }
827        }
828    }
829}
830
831/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
832#[derive(Debug, Clone, Copy, PartialEq, Eq)]
833pub enum ResumeKind {
834    /// The generator was just created and is being run to its first suspension.
835    Start,
836    /// `next(v)`.
837    Next,
838    /// `return(v)`.
839    Return,
840    /// `throw(e)`.
841    Throw,
842}
843
844/// A generator object's saved execution.
845///
846/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
847/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
848/// separately allocated buffers.
849pub struct GeneratorState {
850    /// The detached frame, or `None` once the generator has finished or while it runs.
851    frame: Option<Frame>,
852    /// How far it got.
853    phase: GeneratorPhase,
854    /// Whether the last suspension was an `await` rather than a `yield`.
855    ///
856    /// The two resume with *different stack shapes*: a `yield` is re-entered with the
857    /// value and a magic number, because the emitted code branches on which method
858    /// resumed it, while an `await` simply continues with its value. Getting this wrong
859    /// leaves an extra value on the operand stack that the next instruction then
860    /// consumes — a wrong answer rather than a crash.
861    parked_on_await: bool,
862    /// Whether the last suspension was a `yield*` rather than a plain `yield`.
863    ///
864    /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
865    /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
866    /// has to be forwarded into the inner iterator's `throw` method instead — which is the
867    /// `rethrow` branch the compiled delegation emits — because that is the whole point of
868    /// delegating. Tracking it as part of the phase, the way the reference splits
869    /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
870    /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
871    /// exception and never reached `xs.throw`.
872    parked_on_yield_star: bool,
873    /// Pending `next`/`return`/`throw` calls, oldest first.
874    ///
875    /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
876    /// called back to back must answer in that order, with the second call's value
877    /// arriving at the *second* `yield`. Running each call straight into the body — which
878    /// is what this engine did before — delivered the last queued value to whichever
879    /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
880    /// `a === b ===` the final argument.
881    ///
882    /// The front entry is the one being served; it stays there (with `async_busy` set)
883    /// until its promise settles, because an `await` inside the body is a suspension of
884    /// the *driver*, not the end of the request.
885    requests: std::collections::VecDeque<AsyncRequest>,
886    /// Whether the front request is in flight.
887    async_busy: bool,
888}
889
890/// How one async-generator request ended.
891enum AsyncOutcome {
892    /// The method answered this `{value, done}`.
893    Value(Value),
894    /// The body threw.
895    Error(Value),
896}
897
898/// One queued `next`/`return`/`throw` on an async generator: the reference's
899/// `JSAsyncGeneratorRequest`.
900pub struct AsyncRequest {
901    /// Which method was called.
902    kind: ResumeKind,
903    /// Its argument.
904    value: Value,
905    /// The promise the method answered.
906    promise: Gc<JsObject>,
907}
908
909/// Which of §27.5.3.3's states a generator is in.
910#[derive(Debug, Clone, Copy, PartialEq, Eq)]
911enum GeneratorPhase {
912    /// Created, `initial_yield` reached, body not entered.
913    SuspendedStart,
914    /// Parked at a `yield`.
915    SuspendedYield,
916    /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
917    Executing,
918    /// Finished; the frame is gone.
919    Completed,
920}
921
922impl js_gc::Trace for GeneratorState {
923    fn trace(&self, tracer: &mut js_gc::Tracer) {
924        if let Some(frame) = &self.frame {
925            frame.trace(tracer);
926        }
927        for request in &self.requests {
928            request.value.trace(tracer);
929            tracer.visit(&request.promise);
930        }
931    }
932}
933
934/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
935/// them in.
936///
937/// Each is a field rather than a map entry because the runtime reads them on hot paths
938/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
939/// failure — reaching a default here means the builtin did not install, and every
940/// accessor panics rather than silently answering `undefined`.
941///
942/// [`builtins::symbol`]: crate::builtins::symbol
943#[derive(Default)]
944pub struct WellKnownSymbols {
945    /// The symbol values, positionally. Empty until `Symbol` installs.
946    symbols: Vec<Value>,
947}
948
949/// Which well-known symbol a caller wants.
950///
951/// A typed accessor beats passing a name around: a typo is a compile error rather than
952/// an `undefined` key that quietly matches nothing.
953#[derive(Debug, Clone, Copy, PartialEq, Eq)]
954pub enum WellKnown {
955    /// `Symbol.toPrimitive`.
956    ToPrimitive,
957    /// `Symbol.iterator`.
958    Iterator,
959    /// `Symbol.match`.
960    Match,
961    /// `Symbol.matchAll`.
962    MatchAll,
963    /// `Symbol.replace`.
964    Replace,
965    /// `Symbol.search`.
966    Search,
967    /// `Symbol.split`.
968    Split,
969    /// `Symbol.toStringTag`.
970    ToStringTag,
971    /// `Symbol.isConcatSpreadable`.
972    IsConcatSpreadable,
973    /// `Symbol.hasInstance`.
974    HasInstance,
975    /// `Symbol.species`.
976    Species,
977    /// `Symbol.unscopables`.
978    Unscopables,
979    /// `Symbol.asyncIterator`.
980    AsyncIterator,
981    /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
982    Disposable,
983    /// `Symbol.asyncDispose` — the awaited form.
984    AsyncDisposable,
985}
986
987impl WellKnown {
988    /// The index `Symbol`'s installer creates this symbol at.
989    fn index(self) -> usize {
990        match self {
991            WellKnown::ToPrimitive => 0,
992            WellKnown::Iterator => 1,
993            WellKnown::Match => 2,
994            WellKnown::MatchAll => 3,
995            WellKnown::Replace => 4,
996            WellKnown::Search => 5,
997            WellKnown::Split => 6,
998            WellKnown::ToStringTag => 7,
999            WellKnown::IsConcatSpreadable => 8,
1000            WellKnown::HasInstance => 9,
1001            WellKnown::Species => 10,
1002            WellKnown::Unscopables => 11,
1003            WellKnown::AsyncIterator => 12,
1004            WellKnown::Disposable => 13,
1005            WellKnown::AsyncDisposable => 14,
1006        }
1007    }
1008}
1009
1010impl Realm {
1011    /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1012    pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1013        self.well_known_symbols.symbols = symbols;
1014    }
1015
1016    /// A well-known symbol.
1017    pub fn well_known(&self, which: WellKnown) -> Value {
1018        self.well_known_symbols
1019            .symbols
1020            .get(which.index())
1021            .cloned()
1022            .unwrap_or(Value::Undefined)
1023    }
1024
1025    /// The well-known symbol as a property key.
1026    pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1027        match self.well_known(which) {
1028            Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1029            // Unreachable once `Symbol` has installed; an empty string key matches
1030            // nothing, which degrades to "the object has no such method".
1031            _ => PropertyKey::from(String::new()),
1032        }
1033    }
1034}
1035
1036/// The interpreter: a realm plus a frame stack.
1037pub struct Interp<'a> {
1038    /// The heap everything is allocated on.
1039    pub heap: &'a Heap,
1040    /// The realm.
1041    pub realm: Realm,
1042    /// Active frames, outermost first.
1043    frames: Vec<Frame>,
1044    /// Value buffers from frames that have finished, reused by the next call.
1045    ///
1046    /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1047    /// the locals and the operand stack — and free all four on return. `call:recursion`
1048    /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1049    /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1050    ///
1051    /// Bounded in both directions: a few buffers per kind, and none larger than
1052    /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1053    /// and keeping its buffer would pin that memory for the rest of the run.
1054    free_values: Vec<Vec<Value>>,
1055    /// A strict-mode `eval`'s own variable scope, while its script runs.
1056    ///
1057    /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1058    /// become a global. Name lookups still fall through to the realm, which is why
1059    /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1060    eval_scope: Option<BTreeMap<String, Value>>,
1061    /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1062    /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1063    eval_depth: usize,
1064    /// The calling frame's own bindings, which the running `eval` can read and write.
1065    ///
1066    /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1067    /// come from the frame, and a write is applied back to the frame (or to the cell
1068    /// the frame captured) when the eval finishes. That is what makes
1069    /// `f("a = 3")` visible to the caller as `a === 3`.
1070    eval_bindings: Vec<EvalBinding>,
1071    /// The calling frame's `arguments`, while an `eval` runs.
1072    ///
1073    /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1074    /// own yet still has to see the caller's `arguments`.
1075    eval_arguments: Option<Value>,
1076    /// The `with` objects live at the moment the running `eval` started, innermost first.
1077    ///
1078    /// `None` outside an eval, which is what keeps a finished block's object from
1079    /// shadowing ordinary bytecode reads.
1080    eval_with: Option<Vec<Gc<JsObject>>>,
1081    /// The bindings the running direct `eval` makes visible, as name → cell.
1082    ///
1083    /// Set for the duration of an eval and then restored, but every closure created
1084    /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1085    /// `eval("f = () => i")` work after the eval has returned.
1086    active_eval_scope: Option<Gc<EvalScope>>,
1087    /// The frame that called the direct `eval` currently running, if any.
1088    ///
1089    /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1090    /// on the global object, which is what keeps
1091    /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1092    /// gives each call its own `x`.
1093    eval_caller: Option<Option<usize>>,
1094    /// The caller's `new.target`, while an `eval` runs.
1095    ///
1096    /// The eval'd code is a script with no constructor of its own, so it inherits the
1097    /// one the enclosing function was called with.
1098    eval_new_target: Option<Value>,
1099    /// `new.target` for the frame about to be pushed.
1100    ///
1101    /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1102    /// value reaches the frame without threading a parameter through every call site.
1103    pending_new_target: Option<Value>,
1104    /// Names of the native functions currently executing, outermost first.
1105    ///
1106    /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1107    /// trace still names it with `(native)` instead of a position, so the names are
1108    /// tracked separately and stitched into [`Interp::stack_trace`].
1109    ///
1110    /// The third field is how many bytecode frames were live when the native was entered,
1111    /// which is what places it *among* them rather than before all of them. Native
1112    /// functions used to be emitted up front on the grounds that they never re-enter
1113    /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1114    /// The natives currently running, innermost last: the function object and the
1115    /// depth it was entered at.
1116    ///
1117    /// The *name* is deliberately not stored. It used to be, read with
1118    /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1119    /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1120    /// benchmark. A stack trace is built rarely; it can read the name then.
1121    native_frames: Vec<(Gc<JsObject>, usize)>,
1122    /// The native function currently executing, for the ones that have to know *which*
1123    /// function they are — a typed-array constructor reads its element type off itself.
1124    ///
1125    /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1126    /// reports whatever the enclosing bytecode frame was called with.
1127    current_native: Option<Gc<JsObject>>,
1128    /// Text written by `print` and friends, in order.
1129    ///
1130    /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1131    /// once at the end, which is also when upstream's line buffering becomes
1132    /// visible for the cases compared here.
1133    pub output: String,
1134    /// Where `print` also writes, as it goes. `output` keeps the full log for
1135    /// [`crate::Context::output`]; this is the live copy, flushed per line.
1136    ///
1137    /// Both exist on purpose. A host that gives a script a sink sees output *when it
1138    /// happens* — which is what a timer callback's `console.log` has to do, and what the
1139    /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1140    /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1141    /// would show a script's output all at once when it finished.
1142    pub output_sink: Option<Box<dyn std::io::Write>>,
1143    /// Where recent property reads found their value.
1144    ///
1145    /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1146    /// table remembering *which object* and *which entry of its property table* answered a
1147    /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1148    /// can move; the property can become an accessor), which is what makes a stale entry a
1149    /// miss rather than a wrong answer.
1150    ///
1151    /// The object is held weakly: a cache that held it strongly would keep up to
1152    /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1153    /// program cannot see and cannot work around.
1154    pub field_cache: Vec<Option<FieldCache>>,
1155    /// Global lookups, by binding slot. See [`GlobalCache`].
1156    global_cache: Vec<Option<GlobalCache>>,
1157    /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1158    /// under its limit. See [`Interp::check_memory`].
1159    pub oom_reported_at: usize,
1160    /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1161    /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1162    ///
1163    /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1164    /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1165    /// host that wants to stop a runaway script must not have to wait for it to return.
1166    ///
1167    /// Two things this cannot do, both of them differences a host can observe:
1168    ///
1169    /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1170    ///   uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1171    ///   needs a signal that the `catch` machinery does not see, which is a change to
1172    ///   [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1173    ///   a host that stops the script itself.
1174    /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1175    ///   also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1176    ///   both, so the difference is when the counter hits zero, not whether it will.
1177    pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1178    /// Instructions until the next [`Interp::interrupt`] poll.
1179    pub interrupt_counter: u32,
1180    /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1181    ///
1182    /// A separate field from [`Interp::uncatchable`] because the two live for different
1183    /// spans. This one is the host's standing request; it survives the start of an
1184    /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1185    /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1186    /// for both was the first attempt and it did nothing at all: the outermost `execute`
1187    /// cleared it before the script it was set for had a chance to throw.
1188    pub uncatchable_next: bool,
1189    /// Whether the exception now unwinding may be caught by a `catch`.
1190    ///
1191    /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1192    /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1193    /// a host stopping a runaway loop is not fought by the loop.
1194    ///
1195    /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1196    /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1197    /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1198    /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1199    pub uncatchable: bool,
1200    /// The most stack a JavaScript call chain may use, in bytes of frame state.
1201    ///
1202    /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1203    /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1204    /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1205    /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1206    /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1207    /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1208    ///
1209    /// The numbers come out close for the same reason a C frame and a heap frame of this
1210    /// shape cost about the same (both are a few hundred bytes, dominated by the value
1211    /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1212    /// and this engine lands in the same neighbourhood — measured, not fudged, by
1213    /// `crates/quickjs-cli/tests/limits.rs`.
1214    pub stack_limit: usize,
1215    /// The most frames that may be live at once, whatever the byte budget says.
1216    ///
1217    /// A second bound for a reason the reference does not have: our frames cost less than
1218    /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1219    /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1220    /// `--stack-size 1G` from being a memory bomb.
1221    pub max_frames: usize,
1222    /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1223    ///
1224    /// Script execution does not return until this has drained, which is what makes
1225    /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1226    /// than never. Reactions append to it while it drains, so the loop is a `while` and
1227    /// not a `for`.
1228    pub(crate) jobs: std::collections::VecDeque<Job>,
1229    /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1230    ///
1231    /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1232    /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1233    pub(crate) tasks: Vec<Task>,
1234    /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1235    /// barrier'd evaluation started.
1236    ///
1237    /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1238    /// lets a REPL report an error from the line it just evaluated without also reporting
1239    /// its own readline loop.
1240    trace_barriers: Vec<usize>,
1241    /// `os.signal` handlers, keyed by signal number.
1242    ///
1243    /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1244    /// a handler cannot be freed while it is still registered.
1245    pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1246    /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1247    ///
1248    /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1249    /// that is only reachable from a host closure could be freed while still registered.
1250    pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1251    /// The next timer id.
1252    ///
1253    /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1254    /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1255    next_timer_id: i32,
1256    /// Errors thrown by timer callbacks, already rendered.
1257    ///
1258    /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1259    /// that throws has no promise behind it. Both are reported by the host at the end of
1260    /// the loop, but only one is fixed up by a later `.catch`.
1261    timer_errors: Vec<String>,
1262    /// The module registry, keyed by canonical name.
1263    pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1264    /// How the host turns a specifier into bytes.
1265    pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1266    /// The module the host was asked to run, for `import.meta.main`.
1267    pub main_module_name: Option<String>,
1268    /// Module bodies currently running, innermost last.
1269    ///
1270    /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1271    /// this is the only place that knows which module that is.
1272    pub module_stack: Vec<String>,
1273    /// Rejections that no handler has claimed, with the promise they belong to.
1274    ///
1275    /// A `then` registered later prunes its entry, which is why the promise is kept: the
1276    /// reason alone cannot say whether somebody eventually listened.
1277    unhandled: Vec<(Gc<JsObject>, Value)>,
1278}
1279
1280impl<'a> Interp<'a> {
1281    /// Build an interpreter over `heap`, with a fresh realm.
1282    pub fn new(heap: &'a Heap) -> Interp<'a> {
1283        let object_proto = JsObject::ordinary(heap, None);
1284        let function_proto = JsObject::function(
1285            heap,
1286            Some(object_proto.clone()),
1287            Callable::Native {
1288                func: |_, _, _| Ok(Value::Undefined),
1289                own_instance: false,
1290            },
1291        );
1292        let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1293        let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1294        let mut interp = Interp {
1295            heap,
1296            realm: Realm {
1297                global,
1298                object_proto,
1299                function_proto,
1300                array_proto,
1301                array_constructor: None,
1302                promise_constructor: None,
1303                globals: BTreeMap::new(),
1304                declared: Vec::new(),
1305                lexical_consts: BTreeSet::new(),
1306                errors: BTreeMap::new(),
1307                string_proto: None,
1308                number_proto: None,
1309                boolean_proto: None,
1310                bigint_proto: None,
1311                error_proto: JsObject::ordinary(heap, None),
1312                date_proto: JsObject::ordinary(heap, None),
1313                generator_proto: JsObject::ordinary(heap, None),
1314                promise_proto: None,
1315                async_generator_proto: None,
1316                symbol_proto: None,
1317                symbol_registry: BTreeMap::new(),
1318                internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1319                regexp_proto: None,
1320                regexp_ctor: None,
1321                suppressed_error_proto: None,
1322                disposable_stack_proto: None,
1323                map_proto: None,
1324                set_proto: None,
1325                finalization_registries: Vec::new(),
1326                array_buffer_proto: None,
1327                typed_array_proto: None,
1328                typed_array_protos: Vec::new(),
1329                data_view_proto: None,
1330                async_disposable_stack_proto: None,
1331                iterator_proto: None,
1332                iterator_helper_proto: None,
1333                iterator_wrap_proto: None,
1334                generator_function_proto: None,
1335                async_function_proto: None,
1336                async_generator_function_proto: None,
1337                iterator_protos: std::collections::BTreeMap::new(),
1338                well_known_symbols: WellKnownSymbols::default(),
1339                host_classes: HostClasses::new(),
1340            },
1341            frames: Vec::new(),
1342            free_values: Vec::new(),
1343            global_cache: {
1344                let mut cache = Vec::new();
1345                cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1346                cache
1347            },
1348            eval_scope: None,
1349            eval_depth: 0,
1350            eval_bindings: Vec::new(),
1351            eval_arguments: None,
1352            eval_with: None,
1353            active_eval_scope: None,
1354            eval_caller: None,
1355            pending_new_target: None,
1356            eval_new_target: None,
1357            native_frames: Vec::new(),
1358            current_native: None,
1359            output: String::new(),
1360            output_sink: None,
1361            field_cache: {
1362                let mut cache = Vec::new();
1363                cache.resize_with(FIELD_CACHE_SLOTS, || None);
1364                cache
1365            },
1366            oom_reported_at: 0,
1367            interrupt: None,
1368            interrupt_counter: INTERRUPT_POLL_INTERVAL,
1369            uncatchable_next: false,
1370            uncatchable: false,
1371            // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1372            // absent.
1373            stack_limit: DEFAULT_STACK_SIZE,
1374            max_frames: MAX_FRAMES,
1375            jobs: std::collections::VecDeque::new(),
1376            tasks: Vec::new(),
1377            trace_barriers: Vec::new(),
1378            signal_handlers: std::collections::BTreeMap::new(),
1379            fd_handlers: std::collections::BTreeMap::new(),
1380            next_timer_id: 1,
1381            timer_errors: Vec::new(),
1382            modules: std::collections::BTreeMap::new(),
1383            module_loader: None,
1384            main_module_name: None,
1385            module_stack: Vec::new(),
1386            unhandled: Vec::new(),
1387        };
1388        crate::builtins::install(&mut interp);
1389        interp
1390    }
1391
1392    // -- allocation helpers -------------------------------------------------
1393
1394    /// A new string value.
1395    /// A `BigInt` value from a computed big integer.
1396    pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1397        Value::BigInt(Gc::new(self.heap, value))
1398    }
1399
1400    /// A string value from bytes that are already WTF-8, which is how a string with an
1401    /// unpaired surrogate reaches a `Value`.
1402    pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1403        Value::string_wtf8(self.heap, text)
1404    }
1405
1406    /// A new string value, from text that is valid UTF-8.
1407    pub fn string(&self, text: impl Into<String>) -> Value {
1408        Value::string(self.heap, text)
1409    }
1410
1411    /// A new ordinary object with the given prototype.
1412    pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1413        JsObject::ordinary(self.heap, proto)
1414    }
1415
1416    // -- host classes -------------------------------------------------------
1417
1418    /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1419    pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1420        self.realm.host_classes.register(def)
1421    }
1422
1423    /// Register `def` under an id the host already holds (`JS_NewClass`).
1424    ///
1425    /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1426    /// `JS_NewClass`.
1427    pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1428        self.realm.host_classes.define(id, def)
1429    }
1430
1431    /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1432    pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1433        self.realm.host_classes.set_proto(id, proto);
1434    }
1435
1436    /// The prototype installed for `id`, if any.
1437    pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1438        self.realm.host_classes.proto(id)
1439    }
1440
1441    /// A new instance of `id` (`JS_NewObjectProtoClass`).
1442    ///
1443    /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1444    /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1445    /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1446    /// host installed none.
1447    ///
1448    /// Answers `None` for an id that was never registered: the C API would return an
1449    /// exception, and silently making an ordinary object instead would move the failure to
1450    /// the first `JS_GetOpaque` that no longer matches.
1451    pub fn new_host_object(
1452        &mut self,
1453        proto: Option<Gc<JsObject>>,
1454        class_id: ClassId,
1455    ) -> Option<Gc<JsObject>> {
1456        let class = self.realm.host_classes.def(class_id)?;
1457        let proto = proto
1458            .or_else(|| self.realm.host_classes.proto(class_id))
1459            .or_else(|| Some(self.realm.object_proto.clone()));
1460        Some(JsObject::host_object(self.heap, proto, class_id, class))
1461    }
1462
1463    /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1464    ///
1465    /// `None` covers both answers the C API gives as a null pointer — the value is not an
1466    /// object, it is an object of another class, or the class never got a payload. A host
1467    /// that has to tell them apart uses [`JsObject::host_class_id`].
1468    pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1469        let object = value.as_object()?;
1470        if object.host_class_id()? != class_id {
1471            return None;
1472        }
1473        object.host_opaque()
1474    }
1475
1476    /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1477    pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1478        match value.as_object() {
1479            Some(object) => object.set_host_opaque(opaque),
1480            None => false,
1481        }
1482    }
1483
1484    /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1485    ///
1486    /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1487    /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1488    /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1489    /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1490    /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1491    /// said `[object Object]` instead of `[object Array Iterator]`.
1492    ///
1493    /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1494    /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1495    /// its own.
1496    pub fn new_iterator_prototype(
1497        &mut self,
1498        tag: &str,
1499        next: crate::object::NativeFn,
1500    ) -> Gc<JsObject> {
1501        if let Some(existing) = self.realm.iterator_protos.get(tag) {
1502            return existing.clone();
1503        }
1504        let parent = self.realm.iterator_proto.clone();
1505        let proto = self.new_object(parent);
1506        let next = self.new_native("next", 0, next);
1507        proto.define(
1508            "next",
1509            Property::with_attributes(Value::Object(next), true, false),
1510        );
1511        let key = self.realm.well_known_key(WellKnown::Iterator);
1512        let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1513        proto.define_key(
1514            &key,
1515            Property::with_attributes(Value::Object(identity), true, false),
1516        );
1517        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1518        let tag_value = self.string(tag);
1519        proto.define_key(&tag_key, Property::with_attributes(tag_value, false, false));
1520        self.realm
1521            .iterator_protos
1522            .insert(tag.to_string(), proto.clone());
1523        proto
1524    }
1525
1526    /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1527    ///
1528    /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1529    /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1530    /// produced. That is why the two branches are not merged.
1531    pub fn object_own_property_keys(
1532        &mut self,
1533        object: &Gc<JsObject>,
1534    ) -> JsResult<Vec<PropertyKey>> {
1535        if let Some(keys) = self.proxy_own_keys(object)? {
1536            return Ok(keys);
1537        }
1538        // Integer-like keys ascending, then the string keys in insertion order, then the
1539        // symbols — the order every schema that walks an object expects.
1540        let entries = object.property_entries();
1541        let mut numeric: Vec<u32> = Vec::new();
1542        let mut strings: Vec<PropertyKey> = Vec::new();
1543        let mut symbols: Vec<PropertyKey> = Vec::new();
1544        for (key, _) in entries {
1545            match &key {
1546                // A class-private name is never reported by any enumeration: that is the
1547                // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1548                // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1549                // symbol skip, `Object.assign`) therefore cannot see it.
1550                PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1551                PropertyKey::Symbol(_) => symbols.push(key),
1552                PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1553                    Some(index) => {
1554                        if !numeric.contains(&index) {
1555                            numeric.push(index);
1556                        }
1557                    }
1558                    None => strings.push(key),
1559                },
1560            }
1561        }
1562        numeric.sort_unstable();
1563        let mut keys: Vec<PropertyKey> = numeric
1564            .into_iter()
1565            .map(|index| PropertyKey::from(index.to_string()))
1566            .collect();
1567        keys.extend(strings);
1568        keys.extend(symbols);
1569        Ok(keys)
1570    }
1571
1572    /// The state behind a promise object, or `None` when `object` is not one.
1573    pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1574        object.with(|data| match &data.kind {
1575            ObjectKind::Promise(state) => Some(state.clone()),
1576            _ => None,
1577        })
1578    }
1579
1580    /// A new pending promise.
1581    pub fn new_promise(&mut self) -> Gc<JsObject> {
1582        // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1583        // the one place every promise is built, and a subclass that builds its instances
1584        // somewhere else would be invisible to `instanceof`.
1585        let default = self.realm.promise_proto.clone();
1586        // A throwing `new.target.prototype` getter cannot be reported from here — this is
1587        // the raw promise constructor and its result is not `JsResult` — so the rejection is
1588        // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1589        // `prototype` getter therefore still gets a working promise; the alternative is a
1590        // panic, and the throwing path is covered by `Promise`'s own argument validation.
1591        let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1592        let promise = JsObject::ordinary(self.heap, proto);
1593        promise.with_mut(|data| {
1594            data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1595                crate::object::PromiseState::default(),
1596            )));
1597        });
1598        promise
1599    }
1600
1601    /// Fulfil `promise`, unless it has already settled.
1602    ///
1603    /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1604    /// after `reject`, changes nothing.
1605    pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1606        let Some(state) = self.promise_state(promise) else {
1607            return;
1608        };
1609        let reactions = {
1610            let mut state = state.borrow_mut();
1611            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1612                return;
1613            }
1614            state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1615            std::mem::take(&mut state.reactions)
1616        };
1617        self.queue_reactions(reactions, value, false);
1618    }
1619
1620    /// Reject `promise`, unless it has already settled.
1621    pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1622        let Some(state) = self.promise_state(promise) else {
1623            return;
1624        };
1625        let reactions = {
1626            let mut state = state.borrow_mut();
1627            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1628                return;
1629            }
1630            state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1631            std::mem::take(&mut state.reactions)
1632        };
1633        // Remember it only when nothing is listening *now*; a `then` registered later
1634        // prunes the entry in `perform_then`.
1635        if reactions.is_empty() {
1636            self.unhandled.push((promise.clone(), reason.clone()));
1637        }
1638        self.queue_reactions(reactions, reason, true);
1639    }
1640
1641    /// Queue one job per reaction.
1642    ///
1643    /// This is what makes `then` asynchronous even on an already-settled promise:
1644    /// `p.then(f); g()` calls `g` first.
1645    fn queue_reactions(
1646        &mut self,
1647        reactions: Vec<crate::object::PromiseReaction>,
1648        argument: Value,
1649        rejected: bool,
1650    ) {
1651        for reaction in reactions {
1652            let handler = if rejected {
1653                reaction.on_rejected.clone()
1654            } else {
1655                reaction.on_fulfilled.clone()
1656            };
1657            self.jobs.push_back(Job::Reaction {
1658                handler,
1659                argument: argument.clone(),
1660                rejected,
1661                promise: reaction.promise,
1662            });
1663        }
1664    }
1665
1666    /// `NewPromiseCapability` as the executor receives it: the promise plus its
1667    /// resolve/reject pair.
1668    ///
1669    /// The pair are callable objects rather than Rust closures, because the script gets
1670    /// them and may stash them for later.
1671    pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1672        let promise = self.new_promise();
1673        // Both handlers are built-ins with an empty name and length 1, in
1674        // `length`-then-`name` order — `reject-function-property-order` reads the order back
1675        // off `Object.getOwnPropertyNames`.
1676        let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1677        let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1678        (promise, Value::Object(resolve), Value::Object(reject))
1679    }
1680
1681    /// §27.2.1.5 `NewPromiseCapability(C)`.
1682    ///
1683    /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1684    /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1685    /// decide what capability it hands back. That is the whole mechanism behind subclassing
1686    /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1687    /// silently ignored argument.
1688    ///
1689    /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1690    /// the engine's own executor is exactly what `new_promise_capability` builds.
1691    pub fn new_promise_capability_for(
1692        &mut self,
1693        constructor: &Value,
1694    ) -> JsResult<(Value, Value, Value)> {
1695        let Some(object) = constructor.as_object().cloned() else {
1696            return Err(self.type_error("promise constructor is not a constructor"));
1697        };
1698        if !object.is_constructor() {
1699            return Err(self.type_error("promise constructor is not a constructor"));
1700        }
1701        if self
1702            .realm
1703            .promise_constructor
1704            .as_ref()
1705            .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1706        {
1707            let (promise, resolve, reject) = self.new_promise_capability();
1708            return Ok((Value::Object(promise), resolve, reject));
1709        }
1710        let state = self.new_object(Some(self.realm.object_proto.clone()));
1711        let executor = self.builtin_function(
1712            "",
1713            1,
1714            Callable::CapabilityExecutor {
1715                state: state.clone(),
1716            },
1717        );
1718        let promise = self.construct(
1719            Value::Object(object.clone()),
1720            Value::Object(object),
1721            vec![Value::Object(executor)],
1722        )?;
1723        // The pair is read *after* the constructor returns, so a constructor that never
1724        // called its executor, or called it with non-callables, is the spec's step 11
1725        // `TypeError` — not something the engine can paper over.
1726        let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1727            return Err(self.type_error("promise executor never ran"));
1728        };
1729        let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1730            return Err(self.type_error("promise executor never ran"));
1731        };
1732        for handler in [&resolve, &reject] {
1733            if !matches!(handler, Value::Object(object) if object.is_callable()) {
1734                return Err(self.type_error("promise capability handler is not callable"));
1735            }
1736        }
1737        Ok((promise, resolve, reject))
1738    }
1739
1740    /// §27.2.3.1 `PromiseResolve(C, x)`.
1741    ///
1742    /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1743    /// an `x` that is already a promise of exactly this constructor is handed back
1744    /// unchanged, and anything else gets a fresh capability from `C`.
1745    pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1746        if let Value::Object(object) = &value
1747            && self.promise_state(object).is_some()
1748        {
1749            // `x.constructor === C` means "already the right kind", so no capability is
1750            // built — which is observable through a `resolve` that counts its calls.
1751            let x_constructor = self.get_property(object, "constructor")?;
1752            let same = match (
1753                x_constructor.as_ref().and_then(Value::as_object),
1754                constructor.as_object(),
1755            ) {
1756                (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1757                _ => false,
1758            };
1759            if same {
1760                return Ok(value);
1761            }
1762        }
1763        let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1764        self.call_value(resolve, Value::Undefined, vec![value])?;
1765        Ok(promise)
1766    }
1767
1768    /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1769    /// promise, as `{ value: completion }`.
1770    ///
1771    /// The three cases are the reference's, and they differ on purpose:
1772    ///
1773    /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1774    ///   exception before any promise exists;
1775    /// * a **runtime** error rejects the returned promise;
1776    /// * success resolves it with `{ value }`, where the value is the script's completion
1777    ///   value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1778    ///   {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1779    ///   `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1780    ///   `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1781    ///
1782    /// # What this does not do
1783    ///
1784    /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1785    /// is evaluated in an async context, so `await` outside a function is legal. That needs
1786    /// the parser and the suspension machinery to accept a suspended top-level script, and
1787    /// is not implemented — such source is a syntax error here. Everything else about the
1788    /// flag is reproduced.
1789    pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1790        // The barrier goes up before compiling: a *parse* failure is reported with a trace
1791        // too, and the reference truncates that one at the same place as a runtime failure.
1792        if barrier {
1793            let depth = self.frames.len();
1794            self.trace_barriers.push(depth);
1795        }
1796        // Compiled before the promise exists, so a parse failure propagates as a throw
1797        // instead of being folded into a rejection.
1798        let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1799            Ok(compiled) => compiled,
1800            Err(error) => {
1801                if barrier {
1802                    self.trace_barriers.pop();
1803                }
1804                return Err(error);
1805            }
1806        };
1807        // An async body answers its own promise, and that promise is what the reference
1808        // hands back — the same object, not a wrapper around it. Its resolution value is
1809        // the `{value}` object the compiled epilogue built.
1810        if compiled.kind.is_async() {
1811            let strict = compiled.strict;
1812            let promise = self.run_eval_script(compiled, strict)?;
1813            if barrier {
1814                self.trace_barriers.pop();
1815            }
1816            return Ok(promise);
1817        }
1818        let (promise, resolve, reject) = self.new_promise_capability();
1819        let strict = compiled.strict;
1820        match self.run_eval_script(compiled, strict) {
1821            Ok(value) => {
1822                // `{ value }` is a plain object, so resolving with it adopts nothing even
1823                // when the completion value is itself a promise.
1824                let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1825                self.set_property(&wrapped, "value", value)?;
1826                self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1827            }
1828            Err(Signal::Throw(error)) => {
1829                self.call_value(reject, Value::Undefined, vec![error])?;
1830            }
1831            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1832        }
1833        if barrier {
1834            self.trace_barriers.pop();
1835        }
1836        Ok(Value::Object(promise))
1837    }
1838
1839    /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1840    ///
1841    /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1842    /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1843    /// timer table, where the collector already scans it.
1844    pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1845        let (promise, resolve, _reject) = self.new_promise_capability();
1846        let resolve = self.new_host_function(
1847            "resolve",
1848            1,
1849            Box::new(
1850                move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1851                    let value = args.first().cloned().unwrap_or(Value::Undefined);
1852                    interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1853                },
1854            ),
1855        );
1856        // The timer keeps the resolver alive: it is a property of the timer entry, and the
1857        // timer table is part of what the collector walks.
1858        self.schedule_timer(Value::Object(resolve), delay_ms);
1859        Ok(Value::Object(promise))
1860    }
1861
1862    /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1863    /// new promise resolved with it.
1864    pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1865        if let Value::Object(object) = &value
1866            && self.promise_state(object).is_some()
1867        {
1868            return Ok(value);
1869        }
1870        let promise = self.new_promise();
1871        self.resolve_promise_with(&promise, value)?;
1872        Ok(Value::Object(promise))
1873    }
1874
1875    /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1876    pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1877        // Resolving a promise with itself is a `TypeError`. The check exists because the
1878        // alternative is a chain of self-reactions that never settles.
1879        if let Value::Object(object) = &value
1880            && object.ptr_eq(promise)
1881        {
1882            // The spec rejects *and* throws, so both the promise and the caller see it.
1883            let thrown = self.type_error("cannot resolve a promise with itself");
1884            let Signal::Throw(error) = thrown.clone() else {
1885                unreachable!("type_error always throws")
1886            };
1887            self.reject_promise(promise, error);
1888            return Err(thrown);
1889        }
1890        let then = match &value {
1891            Value::Object(object) => self.get_property(object, "then")?,
1892            _ => None,
1893        };
1894        let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1895        if !callable_then {
1896            // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1897            self.fulfill_promise(promise, value);
1898            return Ok(());
1899        }
1900        // Adopting a thenable is asynchronous — `then` is called from a job, never from
1901        // inside `resolve`, so a script cannot make a promise settle synchronously.
1902        self.jobs.push_back(Job::Thenable {
1903            then: then.expect("checked callable"),
1904            value,
1905            promise: promise.clone(),
1906        });
1907        Ok(())
1908    }
1909
1910    /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
1911    ///
1912    /// `C.resolve` is user code and may answer a plain thenable rather than one of this
1913    /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
1914    ///
1915    /// The property read is **not** short-circuitable even for a real promise: the spec says
1916    /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
1917    /// expects it to run. Skipping the read for promises not only lost the throw, it made
1918    /// the combinator's loop infinite — the test's iterator never sets `done`.
1919    pub fn invoke_then(
1920        &mut self,
1921        thenable: Value,
1922        on_fulfilled: Value,
1923        on_rejected: Value,
1924    ) -> JsResult<()> {
1925        let then = match &thenable {
1926            Value::Object(object) => self.get_property(object, "then")?,
1927            primitive => {
1928                let boxed = self.object_from(primitive)?;
1929                self.get_property(&boxed, "then")?
1930            }
1931        };
1932        let Some(then) = then else {
1933            return Err(self.type_error("thenable has no then method"));
1934        };
1935        if !matches!(&then, Value::Object(object) if object.is_callable()) {
1936            return Err(self.type_error("then is not a function"));
1937        }
1938        self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
1939        Ok(())
1940    }
1941
1942    /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
1943    ///
1944    /// `Promise.prototype.then` in one step: register a reaction and answer the derived
1945    /// promise.
1946    pub fn perform_then(
1947        &mut self,
1948        promise: &Gc<JsObject>,
1949        on_fulfilled: Option<Value>,
1950        on_rejected: Option<Value>,
1951    ) -> JsResult<Value> {
1952        let Some(state) = self.promise_state(promise) else {
1953            return Err(self.type_error("not a promise"));
1954        };
1955        // Whether a rejection handler is being attached decides whether a recorded
1956        // rejection stops being unhandled, so it is read before the values are moved.
1957        let has_rejection_handler = on_rejected.is_some();
1958        let derived = self.new_promise();
1959        let reaction = crate::object::PromiseReaction {
1960            on_fulfilled,
1961            on_rejected,
1962            promise: derived.clone(),
1963        };
1964        let settled = {
1965            let mut state = state.borrow_mut();
1966            // A rejection somebody reacts to is no longer unhandled.
1967            state.handled = true;
1968            match &state.status {
1969                crate::object::PromiseStatus::Pending => {
1970                    state.reactions.push(reaction.clone());
1971                    None
1972                }
1973                crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
1974                crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
1975            }
1976        };
1977        // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
1978        // later, means somebody is listening after all.
1979        if has_rejection_handler {
1980            self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
1981        }
1982        if let Some((argument, rejected)) = settled {
1983            let handler = if rejected {
1984                reaction.on_rejected
1985            } else {
1986                reaction.on_fulfilled
1987            };
1988            self.jobs.push_back(Job::Reaction {
1989                handler,
1990                argument,
1991                rejected,
1992                promise: reaction.promise,
1993            });
1994        }
1995        Ok(Value::Object(derived))
1996    }
1997
1998    /// The rejections nobody listened to, formatted the way the reference reports them.
1999    ///
2000    /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2001    /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2002    /// unhandled at the point the queue drains, because a `then` may still be attached
2003    /// before the host acts on it.
2004    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2005        let entries = std::mem::take(&mut self.unhandled);
2006        // Somebody may have attached a handler after the rejection was recorded, so the
2007        // promise is the authority rather than the list.
2008        let still_unhandled: Vec<Value> = entries
2009            .into_iter()
2010            .filter_map(|(promise, reason)| {
2011                let handled = self
2012                    .promise_state(&promise)
2013                    .map(|state| state.borrow().handled)
2014                    .unwrap_or(true);
2015                (!handled).then_some(reason)
2016            })
2017            .collect();
2018        still_unhandled
2019            .into_iter()
2020            .map(|reason| {
2021                let text = self.describe_exception(&reason);
2022                let stack = match &reason {
2023                    Value::Object(object) => self
2024                        .get_property(object, "stack")
2025                        .ok()
2026                        .flatten()
2027                        .map(|value| value.to_js_string())
2028                        // `stack` carries a trailing newline of its own, which would leave
2029                        // a blank line between two reported rejections.
2030                        .map(|text| text.trim_end().to_string())
2031                        .unwrap_or_default(),
2032                    _ => String::new(),
2033                };
2034                if stack.is_empty() {
2035                    format!("Possibly unhandled promise rejection: {text}")
2036                } else {
2037                    format!("Possibly unhandled promise rejection: {text}\n{stack}")
2038                }
2039            })
2040            .collect()
2041    }
2042
2043    /// Run the microtask queue to exhaustion.
2044    ///
2045    /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2046    /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2047    /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2048    ///
2049    /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2050    /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2051    /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2052    pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2053        crate::builtins::json::parse_text(self, text, true)
2054    }
2055
2056    /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2057    ///
2058    /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2059    /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2060    /// immediately, and `setTimeout(f, -1)` is ordinary code.
2061    ///
2062    /// The callback is called with **no arguments**. The reference stores only the function
2063    /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2064    /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2065    /// extra arguments arrive as `undefined`.
2066    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2067        let id = self.next_timer_id;
2068        // Wrap rather than grow: the id reaches the script as an `Int32`.
2069        self.next_timer_id = if self.next_timer_id == i32::MAX {
2070            1
2071        } else {
2072            self.next_timer_id + 1
2073        };
2074        let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2075        self.tasks.push(Task::Timer {
2076            id,
2077            callback,
2078            due_at,
2079        });
2080        id
2081    }
2082
2083    /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2084    /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2085    pub fn cancel_timer(&mut self, id: i32) -> bool {
2086        let before = self.tasks.len();
2087        self.tasks.retain(|task| match task {
2088            Task::Timer { id: task_id, .. } => *task_id != id,
2089        });
2090        self.tasks.len() != before
2091    }
2092
2093    /// How long until the earliest pending timer, or `None` when none is pending.
2094    pub fn next_timeout(&self) -> Option<std::time::Duration> {
2095        let now = std::time::Instant::now();
2096        self.tasks
2097            .iter()
2098            .map(|task| match task {
2099                Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2100            })
2101            .min()
2102    }
2103
2104    /// Run one turn of the event loop.
2105    ///
2106    /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2107    /// run at most one due timer, then drain again. The blocking belongs to the caller
2108    /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2109    /// is how it asks.
2110    ///
2111    /// One timer per turn rather than all of them: a timer callback may schedule another
2112    /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2113    /// starve the microtask queue.
2114    pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2115        self.drain_jobs()?;
2116        let now = std::time::Instant::now();
2117        // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2118        // followed by `setTimeout(g, 1)` must run `g` first.
2119        let due = self
2120            .tasks
2121            .iter()
2122            .enumerate()
2123            .filter(|(_, task)| match task {
2124                Task::Timer { due_at, .. } => *due_at <= now,
2125            })
2126            .min_by_key(|(_, task)| match task {
2127                Task::Timer { due_at, .. } => *due_at,
2128            })
2129            .map(|(index, _)| index);
2130        let Some(index) = due else {
2131            // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2132            // descriptor is registered but no timer is closer, so a script that never
2133            // touches the descriptor still gets control back. Without a cap a handler on a
2134            // descriptor that is never ready would block for as long as the host allows.
2135            let timeout = self
2136                .next_timeout()
2137                .unwrap_or(std::time::Duration::from_secs(10))
2138                .min(std::time::Duration::from_secs(10));
2139            if !self.fd_handlers.is_empty() {
2140                // Blocking on a timer while descriptors are registered would starve them,
2141                // and blocking on the descriptors while a timer is due would delay it; the
2142                // host polls with the earlier of the two deadlines, which this timeout is.
2143                return Ok(Turn::Poll(timeout));
2144            }
2145            return Ok(match self.next_timeout() {
2146                Some(wait) => Turn::Wait(wait),
2147                None => Turn::Done,
2148            });
2149        };
2150        let Task::Timer { callback, .. } = self.tasks.remove(index);
2151        let this = Value::Undefined;
2152        // A throwing timer callback must not stop the loop: the reference reports it and
2153        // keeps going, because the alternative is that one bad timer silently stops every
2154        // later one.
2155        // No arguments: see `schedule_timer` — the reference calls the callback bare.
2156        match self.call_value(callback, this, Vec::new()) {
2157            Ok(_) => {}
2158            Err(Signal::Throw(value)) => {
2159                let text = self.describe_exception(&value);
2160                self.timer_errors.push(text);
2161            }
2162            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2163        }
2164        self.drain_jobs()?;
2165        Ok(Turn::Ran)
2166    }
2167
2168    /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2169    ///
2170    /// `callback` of `None` unregisters that direction, and an entry with neither direction
2171    /// left is removed — the reference does the same, so a script can rely on
2172    /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2173    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2174        let entry = self.fd_handlers.entry(fd).or_default();
2175        if readable {
2176            entry.read = callback;
2177        } else {
2178            entry.write = callback;
2179        }
2180        if entry.read.is_none() && entry.write.is_none() {
2181            self.fd_handlers.remove(&fd);
2182        }
2183    }
2184
2185    /// Register or clear an `os.signal` handler.
2186    ///
2187    /// `None` removes it; the host separately restores the default disposition or sets
2188    /// ignore, because which of those happened is the script's choice (`null` versus
2189    /// `undefined`) and not something this table can express.
2190    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2191        match handler {
2192            Some(handler) => {
2193                self.signal_handlers.insert(signal, handler);
2194            }
2195            None => {
2196                self.signal_handlers.remove(&signal);
2197            }
2198        }
2199    }
2200
2201    /// Run the handler for `signal`, reporting whether one ran.
2202    ///
2203    /// A throwing handler is reported and the loop continues, like a timer's.
2204    pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2205        let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2206            return Ok(false);
2207        };
2208        match self.call_value(handler, Value::Undefined, Vec::new()) {
2209            Ok(_) => {}
2210            Err(Signal::Throw(value)) => {
2211                let text = self.describe_exception(&value);
2212                self.timer_errors.push(text);
2213            }
2214            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2215        }
2216        self.drain_jobs()?;
2217        Ok(true)
2218    }
2219
2220    /// The descriptors the host has to poll, and in which direction.
2221    ///
2222    /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2223    /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2224    /// `os_poll` asks for.
2225    pub fn pending_fds(&self) -> Vec<FdInterest> {
2226        self.fd_handlers
2227            .iter()
2228            .map(|(fd, entry)| FdInterest {
2229                fd: *fd,
2230                read: entry.read.is_some(),
2231                write: entry.write.is_some(),
2232            })
2233            .collect()
2234    }
2235
2236    /// Call the handler registered for `fd`, reporting whether one ran.
2237    ///
2238    /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2239    /// poll iteration and then restarts the loop, because the handler may have changed the
2240    /// registration list underneath it; doing the same here keeps a handler that
2241    /// unregisters itself from being called with stale state.
2242    ///
2243    /// A throwing handler is reported and the loop continues — a bad handler must not stop
2244    /// every later one, exactly as with timers.
2245    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2246        let Some(entry) = self.fd_handlers.get(&fd) else {
2247            return Ok(false);
2248        };
2249        let callback = if readable {
2250            entry.read.clone()
2251        } else if writable {
2252            entry.write.clone()
2253        } else {
2254            None
2255        };
2256        let Some(callback) = callback else {
2257            return Ok(false);
2258        };
2259        self.drain_jobs()?;
2260        match self.call_value(callback, Value::Undefined, Vec::new()) {
2261            Ok(_) => {}
2262            Err(Signal::Throw(value)) => {
2263                let text = self.describe_exception(&value);
2264                self.timer_errors.push(text);
2265            }
2266            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2267        }
2268        self.drain_jobs()?;
2269        Ok(true)
2270    }
2271
2272    /// Take the errors timer callbacks threw, leaving the list empty.
2273    pub fn take_timer_errors(&mut self) -> Vec<String> {
2274        std::mem::take(&mut self.timer_errors)
2275    }
2276
2277    /// Whether anything is still pending: a microtask or a timer.
2278    pub fn has_pending_work(&self) -> bool {
2279        !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2280    }
2281
2282    /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2283    pub fn has_pending_timers_or_jobs(&self) -> bool {
2284        !self.jobs.is_empty() || !self.tasks.is_empty()
2285    }
2286
2287    /// Run every queued microtask, including ones queued while draining.
2288    pub fn drain_jobs(&mut self) -> JsResult<()> {
2289        // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2290        // would spin forever, so the drain is bounded the way the call stack is.
2291        let mut budget = 1_000_000usize;
2292        while let Some(job) = self.jobs.pop_front() {
2293            if budget == 0 {
2294                return Err(Signal::Throw(
2295                    self.make_error("InternalError", "promise job queue did not drain"),
2296                ));
2297            }
2298            budget -= 1;
2299            self.run_job(job)?;
2300            // `FinalizationRegistry` at the job boundary: this is the safe point where the
2301            // engine may run script that the script itself did not ask for. Doing it here
2302            // rather than from a drop hook is what keeps the callback out of arbitrary
2303            // engine bookkeeping — see `builtins::weak`'s header.
2304            crate::builtins::weak::drain_finalizers(self)?;
2305        }
2306        // A script that queued no jobs may still have dropped targets, so the checkpoint
2307        // runs once more after the queue empties.
2308        crate::builtins::weak::drain_finalizers(self)?;
2309        Ok(())
2310    }
2311
2312    /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2313    ///
2314    /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2315    /// `None` and is swept out here. This is also where the realm learns that a registry
2316    /// died, which is why it is a mutation rather than a read.
2317    pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2318        let handles = std::mem::take(&mut self.realm.finalization_registries);
2319        let mut live = Vec::with_capacity(handles.len());
2320        for handle in handles {
2321            let Some(object) = handle.upgrade() else {
2322                continue;
2323            };
2324            let Some(state) = object.finalization_state() else {
2325                continue;
2326            };
2327            live.push((object.clone(), *state));
2328            self.realm.finalization_registries.push(object.downgrade());
2329        }
2330        live
2331    }
2332
2333    /// Run one microtask.
2334    fn run_job(&mut self, job: Job) -> JsResult<()> {
2335        match job {
2336            Job::Reaction {
2337                handler: None,
2338                argument,
2339                rejected,
2340                promise,
2341            } => {
2342                // No handler: the settlement passes straight through to the derived
2343                // promise, which is why `p.catch(f)` ignores fulfilments.
2344                if rejected {
2345                    self.reject_promise(&promise, argument);
2346                } else {
2347                    self.fulfill_promise(&promise, argument);
2348                }
2349                Ok(())
2350            }
2351            Job::Reaction {
2352                handler: Some(handler),
2353                argument,
2354                promise,
2355                ..
2356            } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2357                Ok(answer) => {
2358                    if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2359                        self.reject_promise(&promise, error);
2360                    }
2361                    Ok(())
2362                }
2363                Err(Signal::Throw(reason)) => {
2364                    self.reject_promise(&promise, reason);
2365                    Ok(())
2366                }
2367                Err(other) => Err(other),
2368            },
2369            Job::Thenable {
2370                then,
2371                value,
2372                promise,
2373            } => {
2374                // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2375                // the value it produces settles `promise`.
2376                // The thenable's `then` gets this promise's own pair, so whatever it
2377                // produces settles `promise`.
2378                let resolve = JsObject::function(
2379                    self.heap,
2380                    Some(self.realm.function_proto.clone()),
2381                    Callable::PromiseResolve(promise.clone()),
2382                );
2383                let reject = JsObject::function(
2384                    self.heap,
2385                    Some(self.realm.function_proto.clone()),
2386                    Callable::PromiseReject(promise.clone()),
2387                );
2388                match self.call_value(
2389                    then,
2390                    value,
2391                    vec![Value::Object(resolve), Value::Object(reject)],
2392                ) {
2393                    Ok(_) => Ok(()),
2394                    Err(Signal::Throw(reason)) => {
2395                        self.reject_promise(&promise, reason);
2396                        Ok(())
2397                    }
2398                    Err(other) => Err(other),
2399                }
2400            }
2401            Job::Resume {
2402                coroutine,
2403                promise,
2404                kind,
2405                value,
2406            } => self.drive_async(&coroutine, &promise, kind, value),
2407            Job::GeneratorResume {
2408                generator,
2409                promise,
2410                kind,
2411                value,
2412            } => self.step_async_generator(&generator, &promise, kind, value),
2413            Job::Import {
2414                specifier,
2415                referrer,
2416                promise,
2417            } => {
2418                self.run_dynamic_import(&specifier, &referrer, &promise);
2419                Ok(())
2420            }
2421        }
2422    }
2423
2424    /// One element of a `Promise` combinator settled.
2425    ///
2426    /// The shared state object holds the result array, the number still outstanding, and
2427    /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2428    /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2429    /// to settle, only whatever `Sub` said a capability is.
2430    ///
2431    /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2432    /// and `any` must ignore every later settlement, and `all` must not report a second
2433    /// rejection after the first.
2434    fn settle_combinator(
2435        &mut self,
2436        state: &Gc<JsObject>,
2437        index: usize,
2438        fulfilled: bool,
2439        value: Value,
2440    ) -> JsResult<()> {
2441        let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2442        // Each element settles at most once: a thenable may call `onFulfilled` twice
2443        // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2444        // call a no-op. Without it the second call decremented `remaining` again and settled
2445        // `all` with a short values array (`call-resolve-element-items`).
2446        let done = field("done");
2447        let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2448        let settled = field("settled").is_some_and(|value| value.to_boolean());
2449        if settled {
2450            return Ok(());
2451        }
2452        if let Some(Value::Object(done)) = &done {
2453            if done
2454                .array_get(index)
2455                .is_some_and(|value| value.to_boolean())
2456            {
2457                return Ok(());
2458            }
2459            done.array_set(self.heap, index, Value::Bool(true));
2460        }
2461        let resolve = field("resolve");
2462        let reject = field("reject");
2463        let results = field("results").and_then(|value| value.as_object().cloned());
2464        // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2465        // promise: the handler is a plain function the constructor chose.
2466        let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2467            if let Some(handler) = handler {
2468                interp.call_value(handler, Value::Undefined, vec![value])?;
2469            }
2470            Ok(())
2471        };
2472        match kind {
2473            // `race`: the first settlement wins and stops the rest.
2474            3 => {
2475                state.define_data("settled", Value::Bool(true));
2476                let handler = if fulfilled { resolve } else { reject };
2477                settle_with(self, handler, value)?;
2478                return Ok(());
2479            }
2480            // `all`: the first rejection wins outright.
2481            0 if !fulfilled => {
2482                state.define_data("settled", Value::Bool(true));
2483                settle_with(self, reject, value)?;
2484                return Ok(());
2485            }
2486            // `any`: the first fulfilment wins.
2487            2 if fulfilled => {
2488                state.define_data("settled", Value::Bool(true));
2489                settle_with(self, resolve, value)?;
2490                return Ok(());
2491            }
2492            _ => {}
2493        }
2494        let Some(results) = &results else {
2495            return Ok(());
2496        };
2497        match kind {
2498            0 => {
2499                results.array_set(self.heap, index, value);
2500            }
2501            // `allSettled` never rejects; each slot records what happened.
2502            1 => {
2503                let record = self.new_object(Some(self.realm.object_proto.clone()));
2504                if fulfilled {
2505                    record.define_data("status", self.string("fulfilled"));
2506                    record.define_data("value", value);
2507                } else {
2508                    record.define_data("status", self.string("rejected"));
2509                    record.define_data("reason", value);
2510                }
2511                results.array_set(self.heap, index, Value::Object(record));
2512            }
2513            // `any`: a rejection is parked in the errors array and the sweep continues.
2514            2 => {
2515                results.array_set(self.heap, index, value);
2516            }
2517            _ => {}
2518        }
2519        let remaining = field("remaining")
2520            .map(|value| value.to_int32())
2521            .unwrap_or(0);
2522        let left = remaining - 1;
2523        state.define_data("remaining", Value::Int(left));
2524        if left != 0 {
2525            return Ok(());
2526        }
2527        state.define_data("settled", Value::Bool(true));
2528        match kind {
2529            0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2530            2 => {
2531                // The rejection is an `AggregateError` whose `errors` is the results array
2532                // itself — the slots are the reasons, in input order.
2533                let errors = results.array_elements().unwrap_or_default();
2534                let error = self.aggregate_error(errors, "all promises were rejected");
2535                settle_with(self, reject, error)?;
2536            }
2537            _ => {}
2538        }
2539        Ok(())
2540    }
2541
2542    /// Build an async function's result: a promise whose body runs as a coroutine.
2543    pub fn new_async_function(
2544        &mut self,
2545        function: Value,
2546        this: Value,
2547        args: Vec<Value>,
2548    ) -> JsResult<Value> {
2549        let promise = self.new_promise();
2550        let coroutine = self.new_coroutine(function, this, args)?;
2551        if let Err(Signal::Throw(reason)) =
2552            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2553        {
2554            self.reject_promise(&promise, reason);
2555        }
2556        Ok(Value::Object(promise))
2557    }
2558
2559    /// The coroutine an async body runs in.
2560    ///
2561    /// Generator-shaped and never exposed to the script: what makes `await` work is the
2562    /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2563    /// than growing a second state machine. The difference is only in the ending — a
2564    /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2565    /// Run `code` as an async function body, answering the promise it settles.
2566    ///
2567    /// Used for a module with top-level `await`: its body is an async function whose
2568    /// caller is the host, so there is no function object to pass through
2569    /// [`Interp::new_async_function`].
2570    pub fn run_async_body(
2571        &mut self,
2572        code: Gc<CompiledCode>,
2573        env: Gc<ClosureEnv>,
2574        this: Value,
2575    ) -> JsResult<Value> {
2576        let promise = self.new_promise();
2577        let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2578        if let Err(Signal::Throw(reason)) =
2579            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2580        {
2581            self.reject_promise(&promise, reason);
2582        }
2583        Ok(Value::Object(promise))
2584    }
2585
2586    fn new_coroutine(
2587        &mut self,
2588        function: Value,
2589        this: Value,
2590        args: Vec<Value>,
2591    ) -> JsResult<Gc<JsObject>> {
2592        let Some(object) = function.as_object().cloned() else {
2593            return Err(self.type_error("not a function"));
2594        };
2595        let Some((code, env)) = bytecode_of(&object) else {
2596            return Err(self.type_error("not a function"));
2597        };
2598        self.new_coroutine_from(code, env, this, args)
2599    }
2600
2601    /// Build a coroutine over an already-resolved body.
2602    fn new_coroutine_from(
2603        &mut self,
2604        code: Gc<CompiledCode>,
2605        env: Gc<ClosureEnv>,
2606        this: Value,
2607        args: Vec<Value>,
2608    ) -> JsResult<Gc<JsObject>> {
2609        let function = Value::Undefined;
2610        self.push_frame(code, env, this, args, function)?;
2611        let frame = self.frames.pop().expect("push_frame just pushed it");
2612        let state = GeneratorState {
2613            frame: Some(frame),
2614            phase: GeneratorPhase::SuspendedStart,
2615            parked_on_await: false,
2616            parked_on_yield_star: false,
2617            requests: std::collections::VecDeque::new(),
2618            async_busy: false,
2619        };
2620        let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2621        coroutine.with_mut(|data| {
2622            data.kind = ObjectKind::Generator(Box::new(state));
2623        });
2624        Ok(coroutine)
2625    }
2626
2627    /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2628    /// `await` and `value` is what it awaited.
2629    fn resume_coroutine(
2630        &mut self,
2631        coroutine: &Gc<JsObject>,
2632        kind: ResumeKind,
2633        value: Value,
2634    ) -> JsResult<(Value, bool)> {
2635        let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2636            ObjectKind::Generator(state) => Some(std::mem::replace(
2637                state.as_mut(),
2638                GeneratorState {
2639                    frame: None,
2640                    phase: GeneratorPhase::Executing,
2641                    parked_on_await: false,
2642                    parked_on_yield_star: false,
2643                    requests: std::collections::VecDeque::new(),
2644                    async_busy: false,
2645                },
2646            )),
2647            _ => None,
2648        }) else {
2649            return Err(self.type_error("not a coroutine"));
2650        };
2651        let result = self.step_generator(&mut state, kind, value);
2652        coroutine.with_mut(|data| {
2653            data.kind = ObjectKind::Generator(Box::new(state));
2654        });
2655        let (value, done, _ready, _reason) = result?;
2656        Ok((value, done))
2657    }
2658
2659    /// Advance an async body and settle its promise with the outcome.
2660    fn drive_async(
2661        &mut self,
2662        coroutine: &Gc<JsObject>,
2663        promise: &Gc<JsObject>,
2664        kind: ResumeKind,
2665        value: Value,
2666    ) -> JsResult<()> {
2667        match self.resume_coroutine(coroutine, kind, value) {
2668            Ok((value, true)) => {
2669                // `Ok` with `done` means the body finished *normally*, even when it was
2670                // resumed by a `throw` — `try { await p } catch {}` completes by
2671                // returning. Only the `Err` arm below is a rejection.
2672                //
2673                // Resolving rather than fulfilling matters: `return promise` in an async
2674                // body adopts the inner promise, so `async function f(){ return
2675                // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2676                // promise.
2677                if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2678                    self.reject_promise(promise, reason);
2679                }
2680                Ok(())
2681            }
2682            Ok((value, false)) => {
2683                // Parked on `await`: follow what it awaited and resume with the outcome.
2684                let awaited = match self.promise_resolve_value(value) {
2685                    Ok(awaited) => awaited,
2686                    Err(Signal::Throw(error)) => {
2687                        self.reject_promise(promise, error);
2688                        return Ok(());
2689                    }
2690                    Err(other) => return Err(other),
2691                };
2692                self.hook_await(awaited, coroutine, promise)
2693            }
2694            Err(Signal::Throw(reason)) => {
2695                self.reject_promise(promise, reason);
2696                Ok(())
2697            }
2698            Err(other) => Err(other),
2699        }
2700    }
2701
2702    /// Arrange for `coroutine` to resume when `awaited` settles.
2703    fn hook_await(
2704        &mut self,
2705        awaited: Value,
2706        coroutine: &Gc<JsObject>,
2707        promise: &Gc<JsObject>,
2708    ) -> JsResult<()> {
2709        let resumed = JsObject::function(
2710            self.heap,
2711            Some(self.realm.function_proto.clone()),
2712            Callable::AwaitResume {
2713                coroutine: coroutine.clone(),
2714                promise: promise.clone(),
2715                kind: ResumeKind::Next,
2716            },
2717        );
2718        let raised = JsObject::function(
2719            self.heap,
2720            Some(self.realm.function_proto.clone()),
2721            Callable::AwaitResume {
2722                coroutine: coroutine.clone(),
2723                promise: promise.clone(),
2724                kind: ResumeKind::Throw,
2725            },
2726        );
2727        // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2728        // guarantees one; the fallback keeps a mis-shaped value from panicking.
2729        let Value::Object(awaited) = &awaited else {
2730            self.jobs.push_back(Job::Resume {
2731                coroutine: coroutine.clone(),
2732                promise: promise.clone(),
2733                kind: ResumeKind::Next,
2734                value: awaited,
2735            });
2736            return Ok(());
2737        };
2738        self.perform_then(
2739            awaited,
2740            Some(Value::Object(resumed)),
2741            Some(Value::Object(raised)),
2742        )?;
2743        Ok(())
2744    }
2745
2746    /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2747    /// things an engine keeps outside it — array elements and an array's `length`.
2748    fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2749        if let Some(property) = object.own_property_key(key) {
2750            return Some(property);
2751        }
2752        // An array's elements live in their own vector rather than the property table, so
2753        // a descriptor for one has to be synthesized — with the attributes an element has.
2754        if let Some(index) = key.as_str().and_then(array_index)
2755            && let Some(value) = object.array_get(index as usize)
2756            && !matches!(value, Value::Hole)
2757        {
2758            return Some(Property::data(value));
2759        }
2760        // `length` is an own property of an array that is not in its property table
2761        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2762        // and non-enumerable.
2763        if key.as_str() == Some("length")
2764            && let Some(length) = object.array_length()
2765        {
2766            return Some(Property {
2767                value: Some(crate::object::length_value(length)),
2768                writable: object.length_writable(),
2769                enumerable: false,
2770                configurable: false,
2771                getter: None,
2772                setter: None,
2773            });
2774        }
2775        None
2776    }
2777
2778    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2779    pub fn object_get_own_property(
2780        &mut self,
2781        object: &Gc<JsObject>,
2782        key: &PropertyKey,
2783    ) -> JsResult<Option<Property>> {
2784        if let Some(answer) = self.proxy_get_own_property(object, key)? {
2785            return Ok(answer);
2786        }
2787        if let Some(exotic) = object.exotic()
2788            && let Some(answer) = exotic.get_own_property(self, object, key)?
2789        {
2790            return Ok(answer);
2791        }
2792        Ok(Self::ordinary_own_property(object, key))
2793    }
2794
2795    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
2796    pub fn object_define_own_property(
2797        &mut self,
2798        object: &Gc<JsObject>,
2799        key: &PropertyKey,
2800        property: Property,
2801    ) -> JsResult<bool> {
2802        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
2803            return Ok(accepted);
2804        }
2805        // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
2806        // non-extensible object. The check lives here rather than in the callers because
2807        // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
2808        // `Array.prototype.filter` uses to store its result, and a species object made
2809        // non-extensible by its own constructor must make that a `TypeError`
2810        // (`target-array-non-extensible`).
2811        if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
2812            return Ok(false);
2813        }
2814        // A host class that intercepts definitions owns the attributes of the properties it
2815        // defines: `_class`-style storage on the native side is the usual reason.
2816        if let Some(exotic) = object.exotic()
2817            && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
2818        {
2819            return Ok(accepted);
2820        }
2821        // An array index is stored in the element vector, which can hold a plain value and
2822        // nothing else. An accessor — or a data property with non-default attributes —
2823        // therefore has to live in the property table, and the element slot is blanked so
2824        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
2825        // {get})` stored the accessor where no read ever looked, and the array kept
2826        // answering its old value.
2827        // An array's `length` is not stored in the property table, so defining it has to
2828        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
2829        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
2830        // {value: 1})` reported success and changed nothing.
2831        if key.as_str() == Some("length") && object.is_array() {
2832            // `{writable: false}` on `length` does not change the length, but it does make
2833            // it read-only — after which neither a later `{writable: true}` nor a store
2834            // past the end may succeed.
2835            if property.value.is_none() {
2836                if !object.length_writable() && property.writable {
2837                    return Ok(false);
2838                }
2839                object.set_length_writable(property.writable);
2840                return Ok(true);
2841            }
2842            if !object.length_writable() {
2843                return Ok(false);
2844            }
2845        }
2846        if key.as_str() == Some("length")
2847            && object.is_array()
2848            && let Some(value) = property.value.clone()
2849        {
2850            let requested = value.to_number();
2851            let valid = requested.is_finite()
2852                && requested >= 0.0
2853                && requested.fract() == 0.0
2854                && requested <= u32::MAX as f64;
2855            if !valid {
2856                return Err(self.range_error("invalid array length"));
2857            }
2858            // Truncating deletes the elements above the new length, and a non-configurable
2859            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
2860            // makes `a.length = 2` fail rather than quietly drop it.
2861            let current = object.array_length().unwrap_or(0);
2862            let requested = requested as usize;
2863            if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
2864                return Ok(false);
2865            }
2866            object.array_set_length(self.heap, requested);
2867            return Ok(true);
2868        }
2869        let plain = property.writable
2870            && property.enumerable
2871            && property.configurable
2872            && !property.is_accessor();
2873        if let Some(index) = key.as_str().and_then(array_index)
2874            && object.is_array()
2875        {
2876            // Growing the array needs a writable `length`: after
2877            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
2878            // be added.
2879            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
2880                return Ok(false);
2881            }
2882            if plain && property.value.is_some() {
2883                // An ordinary element: the vector is where a read looks first, so it has
2884                // to be the vector that changes — unless the index is too far out to be
2885                // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
2886                // one property, because past its own limit it stores the index as an
2887                // ordinary key. Falling through to `define_key` below is the same choice,
2888                // and the alternative was worse: the store used to be *dropped* and the
2889                // length left at 0, which is a silent wrong answer.
2890                let value = property.value.clone().unwrap_or(Value::Undefined);
2891                object.delete_key(key);
2892                if object.array_set(self.heap, index as usize, value) {
2893                    return Ok(true);
2894                }
2895                // Past the dense limit the element lives in the table like any property.
2896                object.note_element_descriptor();
2897                object.define_key(key, property);
2898                // A sparse store past the dense limit still extends `length`, which is what
2899                // `a[a.length] = v` relies on — but only extends: shortening would delete
2900                // the sparse properties above the index, including this one.
2901                if index as usize + 1 > object.array_length().unwrap_or(0) {
2902                    object.array_set_length(self.heap, index as usize + 1);
2903                }
2904                return Ok(true);
2905            }
2906            // A non-plain element — an accessor, or an attribute that is not the default —
2907            // lives in the table while the slot becomes a hole. Recording it keeps every
2908            // later `a[i] = v` off the dense path, where the write would have shadowed the
2909            // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
2910            // replace the accessor with a plain data property.
2911            object.note_element_descriptor();
2912            object.define_key(key, property);
2913            // The slot stays, so `length` does not shrink; a hole is not an element, so
2914            // the table entry is now what a read finds.
2915            object.array_set(self.heap, index as usize, Value::Hole);
2916            return Ok(true);
2917        }
2918        object.define_key(key, property);
2919        Ok(true)
2920    }
2921
2922    /// Build a proxy object over `target`, with its traps read from `handler`.
2923    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
2924        JsObject::proxy(self.heap, target, handler)
2925    }
2926
2927    /// The `revoke` function for a proxy's slots.
2928    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
2929        JsObject::function(
2930            self.heap,
2931            Some(self.realm.function_proto.clone()),
2932            Callable::Revoker(slots),
2933        )
2934    }
2935
2936    /// A new array.
2937    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
2938        let array = JsObject::array(
2939            self.heap,
2940            Some(self.realm.array_proto.clone()),
2941            elements.len(),
2942        );
2943        for (index, element) in elements.into_iter().enumerate() {
2944            array.array_set(self.heap, index, element);
2945        }
2946        array
2947    }
2948
2949    /// A new native function object.
2950    ///
2951    /// The observable `name` and `length` are installed as properties here, which is
2952    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
2953    /// so `f.name = "x"` behaves like the writable property it is.
2954    /// A native constructor that builds its own instance after validating its arguments.
2955    ///
2956    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
2957    /// check runs before `new.target.prototype` is read.
2958    pub fn new_native_ctor(
2959        &self,
2960        name: impl Into<String>,
2961        length: u32,
2962        func: NativeFn,
2963    ) -> Gc<JsObject> {
2964        let function = JsObject::function(
2965            self.heap,
2966            Some(self.realm.function_proto.clone()),
2967            Callable::Native {
2968                func,
2969                own_instance: true,
2970            },
2971        );
2972        function.set_constructible(true);
2973        function.define(
2974            "length",
2975            Property::name_or_length(Value::Int(length as i32)),
2976        );
2977        function.define("name", Property::name_or_length(self.string(name)));
2978        function
2979    }
2980
2981    /// A native constructor that lets `new` build the instance first.
2982    ///
2983    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
2984    /// validation that must precede reading `new.target.prototype`, so the object can be
2985    /// created before the implementation runs. Distinct from [`Interp::new_native`],
2986    /// which makes a *method* and therefore not a constructor at all.
2987    pub fn new_native_constructor(
2988        &self,
2989        name: impl Into<String>,
2990        length: u32,
2991        func: NativeFn,
2992    ) -> Gc<JsObject> {
2993        let function = self.new_native(name, length, func);
2994        function.set_constructible(true);
2995        function
2996    }
2997
2998    /// A new host function object: a native closure that carries its own state.
2999    ///
3000    /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3001    /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3002    /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3003    /// this safe: the closure must not capture a `Gc`.
3004    pub fn new_host_function(
3005        &self,
3006        name: impl Into<String>,
3007        length: u32,
3008        func: crate::object::HostFn,
3009    ) -> Gc<JsObject> {
3010        self.new_host_inner(name.into(), length, func, false)
3011    }
3012
3013    /// A host constructor: `new` hands it `this = undefined`, so it validates its
3014    /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3015    pub fn new_host_ctor(
3016        &self,
3017        name: impl Into<String>,
3018        length: u32,
3019        func: crate::object::HostFn,
3020    ) -> Gc<JsObject> {
3021        let function = self.new_host_inner(name.into(), length, func, true);
3022        function.set_constructible(true);
3023        // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3024        // installs its own methods on it, so it starts as a plain object.
3025        let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3026        function.define(
3027            "prototype",
3028            Property {
3029                value: Some(Value::Object(proto)),
3030                writable: true,
3031                enumerable: false,
3032                configurable: false,
3033                ..Property::default()
3034            },
3035        );
3036        function
3037    }
3038
3039    fn new_host_inner(
3040        &self,
3041        name: String,
3042        length: u32,
3043        func: crate::object::HostFn,
3044        own_instance: bool,
3045    ) -> Gc<JsObject> {
3046        let function = JsObject::function(
3047            self.heap,
3048            Some(self.realm.function_proto.clone()),
3049            Callable::Host {
3050                func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3051                own_instance,
3052            },
3053        );
3054        function.define(
3055            "length",
3056            Property::name_or_length(Value::Int(length as i32)),
3057        );
3058        function.define("name", Property::name_or_length(self.string(name)));
3059        function
3060    }
3061
3062    /// A callable object with the `length`/`name` a built-in function has, in that order.
3063    ///
3064    /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3065    /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3066    /// [`JsObject::function`] defines neither, which is why every capability helper built
3067    /// with it reported no own `length` and no own `name` at all.
3068    ///
3069    /// The attributes are the spec's for a built-in: not writable, not enumerable,
3070    /// configurable.
3071    pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3072        let function =
3073            JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3074        function.define(
3075            "length",
3076            Property::name_or_length(Value::Int(length as i32)),
3077        );
3078        function.define("name", Property::name_or_length(self.string(name)));
3079        function
3080    }
3081
3082    /// A new native function object.
3083    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3084        let function = JsObject::function(
3085            self.heap,
3086            Some(self.realm.function_proto.clone()),
3087            Callable::Native {
3088                func,
3089                own_instance: false,
3090            },
3091        );
3092        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3093        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3094        // `length,name` and this listed `name,length`. A bytecode function already gets it
3095        // the right way round; only native ones were built backwards.
3096        function.define(
3097            "length",
3098            Property::name_or_length(Value::Int(length as i32)),
3099        );
3100        function.define("name", Property::name_or_length(self.string(name)));
3101        function
3102    }
3103
3104    /// A new bound function.
3105    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3106        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3107        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3108        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3109        let constructible = target
3110            .as_object()
3111            .is_some_and(|target| target.is_constructor());
3112        let bound = JsObject::function(
3113            self.heap,
3114            Some(self.realm.function_proto.clone()),
3115            Callable::Bound { target, this, args },
3116        );
3117        bound.set_constructible(constructible);
3118        bound
3119    }
3120
3121    /// A new reference cell.
3122    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3123        Gc::new(self.heap, Cell::new(value))
3124    }
3125
3126    // -- running ------------------------------------------------------------
3127
3128    /// Evaluate `code` as a script body and return its completion value.
3129    /// Compile and run `source` for the engine's own use, returning its completion value.
3130    ///
3131    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3132    /// needs to be a real async function, and the engine already runs those as coroutines,
3133    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3134    ///
3135    /// Differences from [`Self::eval_in_global`], both deliberate:
3136    ///
3137    /// * It does **not** drain the microtask queue. Install runs while the realm is still
3138    ///   being built, and the source is an IIFE that only constructs a closure, so there
3139    ///   is nothing to drain — and draining here would run script-queued jobs in the
3140    ///   middle of `install`.
3141    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3142    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3143    ///   and it should not look like the user wrote something wrong.
3144    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3145        let program = match js_parse::parse_script(source) {
3146            Ok(program) => program,
3147            Err(error) => {
3148                let message = format!("builtin source does not parse: {error}");
3149                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3150            }
3151        };
3152        let mut code = match js_compile::compile_script(&program) {
3153            Ok(code) => code,
3154            Err(error) => {
3155                let message = format!("builtin source does not compile: {}", error.message);
3156                return Err(Signal::Throw(self.make_error("InternalError", &message)));
3157            }
3158        };
3159        // The frame has to name something, and `<builtin>` is what a stack trace through
3160        // this code should say.
3161        code.set_filename("<builtin>");
3162        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3163        let closure_vars = compiled.code.closure_vars.clone();
3164        let env = self.global_env(&closure_vars);
3165        let this = Value::Object(self.realm.global.clone());
3166        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3167    }
3168
3169    /// Run an already-parsed script and drain the microtasks it queued.
3170    ///
3171    /// The drain is what lets an `async` function's body advance past its first `await`
3172    /// before the host sees the result: nothing else pumps the job queue.
3173    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3174        let this = Value::Object(self.realm.global.clone());
3175        self.run_script_with_this(code, this)
3176    }
3177
3178    /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3179    ///
3180    /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3181    /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3182    /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3183    /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3184    /// state the next script evaluation tripped over.
3185    pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3186        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3187        let closure_vars = compiled.code.closure_vars.clone();
3188        let env = self.global_env(&closure_vars);
3189        let callee = Value::Undefined;
3190        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3191        // The script is done, so the microtasks it queued run before the host sees the
3192        // result. Without this an `async` function's body would never advance past its
3193        // first `await`, because nothing else drains the queue.
3194        self.drain_jobs()?;
3195        Ok(result)
3196    }
3197
3198    /// Compile and run `source` in global scope, returning its completion value.
3199    ///
3200    /// This is what `eval` and `new Function` use. Running it as a script means it
3201    /// sees the global object and nothing else, which is right for `eval("1+1")` and
3202    /// for a `Function` body; a *direct* eval that reads a local variable would need
3203    /// the compiler to hand its variable environment over, which is not implemented.
3204    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3205        self.eval_in_global_named(source, EVAL_FILE, false)
3206    }
3207
3208    /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3209    ///
3210    /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3211    /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3212    /// through the code, so they cannot share one constant.
3213    pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3214        self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3215    }
3216
3217    /// Evaluate `source` as a global script, reported under `file`.
3218    ///
3219    /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3220    /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3221    /// from inside a C callback, where the interpreter is the running one rather than a
3222    /// context's own.
3223    pub fn eval_in_global_named(
3224        &mut self,
3225        source: &str,
3226        file: &str,
3227        barrier: bool,
3228    ) -> JsResult<Value> {
3229        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3230        // eval-created global binding — configurable, unlike a script's own `var`.
3231        self.eval_depth += 1;
3232        if barrier {
3233            let depth = self.frames.len();
3234            self.trace_barriers.push(depth);
3235        }
3236        let result = self.eval_in_global_inner(source, file);
3237        if barrier {
3238            self.trace_barriers.pop();
3239        }
3240        self.eval_depth -= 1;
3241        result
3242    }
3243
3244    fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3245        let compiled = self.compile_global_script(source, file, false)?;
3246        let strict = compiled.strict;
3247        self.run_eval_script(compiled, strict)
3248    }
3249
3250    /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3251    ///
3252    /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3253    /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3254    /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3255    /// direct eval's is.
3256    pub fn eval_script_with_this(
3257        &mut self,
3258        source: &str,
3259        file: &str,
3260        this: Value,
3261    ) -> JsResult<Value> {
3262        let program = match js_parse::parse_script(source) {
3263            Ok(program) => program,
3264            Err(error) => {
3265                return Err(Signal::Throw(self.syntax_error_at(
3266                    file,
3267                    error.span.start.line,
3268                    error.span.start.column,
3269                    &error.message,
3270                )));
3271            }
3272        };
3273        let mut compiled = match js_compile::compile_script(&program) {
3274            Ok(compiled) => compiled,
3275            Err(error) => {
3276                return Err(Signal::Throw(self.syntax_error_at(
3277                    file,
3278                    error.span.start.line,
3279                    error.span.start.column,
3280                    &error.message,
3281                )));
3282            }
3283        };
3284        compiled.set_filename(file);
3285        self.run_script_with_this(compiled, this)
3286    }
3287
3288    /// Parse and compile `source` as a global script, without running it.
3289    ///
3290    /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3291    /// before a promise exists to reject — while still evaluating in the same eval context
3292    /// (direct-eval strictness, `new.target`, `super`).
3293    fn compile_global_script(
3294        &mut self,
3295        source: &str,
3296        file: &str,
3297        async_body: bool,
3298    ) -> JsResult<CompiledFunction> {
3299        // A *direct* eval inherits the strictness of the code that called it, which is
3300        // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3301        // implicit global. The caller's frame is the innermost one here, because a
3302        // native function does not push a frame of its own.
3303        let strict = self.current_strict();
3304        // `eval` runs in the caller's function context, so `new.target` is legal here
3305        // even though the source is a bare script — and so is `super.x` when the caller
3306        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3307        // caller's, which is what `special_object 4` already does.
3308        let context = js_parse::EvalContext {
3309            in_method: self.enclosing_home_object().is_some(),
3310            // `super()` belongs to a derived constructor, and an eval'd body is not a
3311            // constructor at all: the caller frame's `this` is already built.
3312            in_derived_constructor: false,
3313        };
3314        // A *global* eval is not a function body: `new.target` and `super` are out of
3315        // reach there. Its `{async: true}` form differs in the other direction — the body
3316        // may `await` — so the two flags are independent and the reference sets both from
3317        // the eval type rather than from the caller.
3318        let parsed = if async_body {
3319            js_parse::parse_suspensible_global_eval(source, strict)
3320        } else {
3321            js_parse::parse_eval_script_in(source, strict, context)
3322        };
3323        let program = match parsed {
3324            Ok(program) => program,
3325            Err(error) => {
3326                // The message is bare: the position lives in `fileName`,
3327                // `lineNumber`, `columnNumber` and the stack frame above, which is where
3328                // the reference puts it. An `invalid source: L:C: ` prefix made
3329                // `e.message` differ from the reference while the stack already agreed.
3330                return Err(Signal::Throw(self.syntax_error_at(
3331                    file,
3332                    error.span.start.line,
3333                    error.span.start.column,
3334                    &error.message,
3335                )));
3336            }
3337        };
3338        let mut compiled = match if async_body {
3339            js_compile::compile_script_suspensible(&program)
3340        } else {
3341            js_compile::compile_script(&program)
3342        } {
3343            Ok(compiled) => compiled,
3344            // A construct the compiler does not handle yet is reported the same way a
3345            // parse error is: it happens before anything runs, so the trace is the
3346            // position in the source followed by the caller.
3347            Err(error) => {
3348                return Err(Signal::Throw(self.syntax_error_at(
3349                    file,
3350                    error.span.start.line,
3351                    error.span.start.column,
3352                    &error.message,
3353                )));
3354            }
3355        };
3356        compiled.set_filename(file);
3357        Ok(compiled)
3358    }
3359
3360    /// Run an `eval`'d script in the caller's scope.
3361    ///
3362    /// Three things have to come from the calling frame, because the eval'd code is a
3363    /// script and would otherwise see only the global object:
3364    ///
3365    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3366    /// * `arguments`, exposed as a binding of the eval's own scope, so
3367    ///   `f("arguments.length", 1)` sees the caller's arguments;
3368    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3369    ///   `eval("var v = 1")` into the global object.
3370    ///
3371    /// Locals of the calling function are *not* reachable: that needs the compiler to
3372    /// hand its variable environment over, which this milestone does not do.
3373    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3374        // `this` and `arguments` come from the innermost frame only — those are not
3375        // lexical — while the name bindings come from the whole chain of frames, part
3376        // of it being ordinary scope resolution.
3377        // An arrow has no `this` of its own, so an `eval` inside one inherits the
3378        // enclosing function's receiver — the lexical `this` the arrow was compiled to
3379        // read from its closure.
3380        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3381        // variable environment is the innermost frame of all: an arrow's own body is where
3382        // `var`s declared by an `eval` inside it belong.
3383        let caller_index = self
3384            .frames
3385            .iter()
3386            .rposition(|frame| !frame.code.code.is_arrow)
3387            .or_else(|| self.frames.len().checked_sub(1));
3388        let env_index = self.frames.len().checked_sub(1);
3389        let caller = caller_index.and_then(|index| self.frames.get(index));
3390        let (this, passed) = match caller {
3391            Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3392            // No frame at all: the eval is running at the top level, so there is
3393            // nothing to inherit and the global receiver is right.
3394            None => (Value::Object(self.realm.global.clone()), Vec::new()),
3395        };
3396        // Innermost frame first, so the first binding found for a name is the one that
3397        // shadows the rest. A script frame (`<eval>`) contributes nothing.
3398        let mut bindings: Vec<EvalBinding> = Vec::new();
3399        // The calling function's own bindings, resolved by the compiler at the call
3400        // site. That table is the only reliable answer when a name is declared twice in
3401        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3402        // body means, and guessing by declaration order picks the wrong one as soon as
3403        // two loops in a row use the same name.
3404        // Only a *direct* eval sees the caller's scope. The compiler records a site for
3405        // every direct call — a bare `eval(...)` callee — so finding one at the current
3406        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3407        // callee to a value first and leave no site behind.
3408        let mut direct = false;
3409        let mut resolved_here = false;
3410        if let Some(frame) = self.frames.last() {
3411            let (line, column) = frame
3412                .code
3413                .code
3414                .position_at(frame.at as u32)
3415                .unwrap_or_default();
3416            // The nearest site at or before the current position, not an exact match:
3417            // the recorded position of the `call` instruction is the callee's, which
3418            // sits a few columns inside the call expression the compiler recorded. A
3419            // site is unique per call, so "the closest one behind us" identifies it.
3420            if let Some(site) = frame
3421                .code
3422                .code
3423                .eval_sites
3424                .iter()
3425                .filter(|site| (site.line, site.column) <= (line, column))
3426                .max_by_key(|site| (site.line, site.column))
3427            {
3428                direct = true;
3429                resolved_here = true;
3430                for binding in &site.bindings {
3431                    // An enclosing function's frame sits `owner` levels below the one
3432                    // running the call.
3433                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3434                    else {
3435                        continue;
3436                    };
3437                    bindings.push(EvalBinding {
3438                        name: binding.name.clone(),
3439                        frame,
3440                        slot: if binding.is_arg {
3441                            EvalSlot::Arg
3442                        } else {
3443                            EvalSlot::Local
3444                        },
3445                        index: binding.index as usize,
3446                    });
3447                }
3448            }
3449        }
3450        for frame_index in (0..self.frames.len()).rev() {
3451            // Skip the innermost frame's flat scan when the compiler already answered
3452            // for it; an enclosing frame still needs one, because the eval resolves
3453            // those names dynamically.
3454            if resolved_here && frame_index == self.frames.len() - 1 {
3455                continue;
3456            }
3457            let frame = &self.frames[frame_index];
3458            for (index, arg) in frame.code.code.args.iter().enumerate() {
3459                bindings.push(EvalBinding {
3460                    name: arg.name.clone(),
3461                    frame: frame_index,
3462                    slot: EvalSlot::Arg,
3463                    index,
3464                });
3465            }
3466            for (index, local) in frame.code.code.vars.iter().enumerate() {
3467                bindings.push(EvalBinding {
3468                    name: local.name.clone(),
3469                    frame: frame_index,
3470                    slot: EvalSlot::Local,
3471                    index,
3472                });
3473            }
3474        }
3475        let mut seen = BTreeSet::new();
3476        bindings.retain(|binding| seen.insert(binding.name.clone()));
3477
3478        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
3479        // elements is all the spec's ordinary uses need.
3480        //
3481        // Known divergence: this is bound for a *global* eval too, where there is no
3482        // caller and the reference throws `'arguments' is not defined`. Deciding properly
3483        // needs "does the calling frame have an `arguments` of its own", which is not
3484        // recorded anywhere the runtime can see — the caller of a direct eval has one, a
3485        // script or eval body does not, and `eval(b)` passes the callee as a value so even
3486        // the call-site detection does not answer it. Modelled as a binding in the caller's
3487        // variable environment, this would fall out; that is a larger change than the one
3488        // this comment is attached to.
3489        let arguments = Value::Object(self.new_array(passed));
3490
3491        // Only a *strict* eval gets a variable environment of its own. A sloppy one
3492        // declares its `var`s in the caller's — which for a top-level eval is the global
3493        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
3494        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
3495        // vanish into a scope nobody reads back from.
3496        let previous_scope = if code_strict {
3497            self.eval_scope.replace(BTreeMap::new())
3498        } else {
3499            None
3500        };
3501        let previous_arguments = self.eval_arguments.replace(arguments);
3502        let previous_with = self.eval_with.replace(self.with_objects());
3503        let inherited_new_target = self
3504            .frames
3505            .iter()
3506            .rev()
3507            .find(|frame| !frame.code.code.is_arrow)
3508            .map(|frame| frame.new_target.clone());
3509        let previous_new_target = self
3510            .eval_new_target
3511            .replace(inherited_new_target.unwrap_or(Value::Undefined));
3512        let eval_cells = self.eval_cells_for(&bindings);
3513        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
3514        // A sloppy direct eval declares its `var`s in the caller's variable environment;
3515        // `declare_eval_local` needs to know which frame that is.
3516        // An indirect eval gets the global environment, so nothing of the caller's is
3517        // recorded as the place its `var`s belong.
3518        let previous_caller = self
3519            .eval_caller
3520            .replace(if direct { env_index } else { None });
3521        // The cell-based view of the same bindings, which is what a closure created
3522        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3523        // whose compiler did not put a binding in a cell simply does not appear here —
3524        // reads and writes still work through `eval_bindings`, they just cannot outlive
3525        // the eval.
3526        let previous_eval_scope = self
3527            .active_eval_scope
3528            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3529        let compiled = Gc::new(self.heap, CompiledCode::new(code));
3530        let closure_vars = compiled.code.closure_vars.clone();
3531        let env = self.global_env(&closure_vars);
3532        let callee = Value::Undefined;
3533        // An async body does not run here: it becomes a coroutine and answers a promise,
3534        // which is what makes `await` legal in it. `this` still has to be the caller's
3535        // (for a global eval, the global object), because `this` is not part of `await`.
3536        let result = if compiled.code.kind.is_async() {
3537            self.run_async_body(compiled, env, this)
3538        } else {
3539            self.execute(compiled, env, this, Vec::new(), callee)
3540        };
3541        self.eval_scope = previous_scope;
3542        self.eval_arguments = previous_arguments;
3543        self.eval_with = previous_with;
3544        self.eval_new_target = previous_new_target;
3545        self.eval_bindings = previous_bindings;
3546        self.eval_caller = previous_caller;
3547        self.active_eval_scope = previous_eval_scope;
3548        result
3549    }
3550
3551    /// The cell-backed subset of `bindings`, in the same priority order.
3552    ///
3553    /// Both lookup routes have to agree — the eval's own reads go through
3554    /// [`Interp::eval_binding_value`] and the closures it builds go through
3555    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
3556    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
3557    /// is not in a cell simply does not appear: reads and writes still work, they just
3558    /// cannot be handed to a closure that outlives the eval.
3559    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
3560        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
3561        for binding in bindings {
3562            let Some(frame) = self.frames.get(binding.frame) else {
3563                continue;
3564            };
3565            let cell = match binding.slot {
3566                EvalSlot::Arg => frame
3567                    .code
3568                    .arg_cell
3569                    .get(binding.index)
3570                    .copied()
3571                    .unwrap_or(-1),
3572                EvalSlot::Local => frame
3573                    .code
3574                    .loc_cell
3575                    .get(binding.index)
3576                    .copied()
3577                    .unwrap_or(-1),
3578            };
3579            if cell < 0 {
3580                continue;
3581            }
3582            if let Some(cell) = frame.cells.get(cell as usize) {
3583                names.push((binding.name.clone(), cell.clone()));
3584            }
3585        }
3586        names
3587    }
3588
3589    /// A `SyntaxError` that reports where in the source it happened.
3590    ///
3591    /// Compile-time failures never run, so they have no frame of their own; the
3592    /// reference still puts the position first in the trace, with no function name and
3593    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
3594    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
3595    /// reference borrows), which is how a script reads the position without parsing
3596    /// the trace.
3597    /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
3598    ///
3599    /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
3600    /// `columnNumber`, which is how the reference prints one. A positionless error
3601    /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
3602    /// the reference raises it from `js_resolve_module`, where there is no position.
3603    pub(crate) fn syntax_error_plain(
3604        &mut self,
3605        error: &js_parse::SyntaxError,
3606        file: &str,
3607    ) -> Value {
3608        if error.positionless {
3609            return self.make_error("SyntaxError", &error.message);
3610        }
3611        self.syntax_error_at(
3612            file,
3613            error.span.start.line,
3614            error.span.start.column,
3615            &error.message,
3616        )
3617    }
3618
3619    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
3620        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
3621        let value = self.make_error("SyntaxError", message);
3622        if let Value::Object(object) = &value {
3623            let text = self.string(blamed);
3624            object.define("stack", Property::with_attributes(text, true, true));
3625            let name = self.string(file);
3626            object.define("fileName", Property::with_attributes(name, true, true));
3627            object.define(
3628                "lineNumber",
3629                Property::with_attributes(Value::Int(line as i32), true, true),
3630            );
3631            object.define(
3632                "columnNumber",
3633                Property::with_attributes(Value::Int(column as i32), true, true),
3634            );
3635        }
3636        value
3637    }
3638
3639    /// Run a compiled script whose completion value is a function, returning it.
3640    ///
3641    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
3642    /// get the closure out, which keeps the constant-pool plumbing in one place.
3643    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
3644        self.run_script(code)
3645    }
3646
3647    /// The environment of a script or of any function compiled at global scope:
3648    /// every entry is a global binding, so each one resolves to the realm's cell.
3649    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
3650        let mut cells = Vec::with_capacity(closure_vars.len());
3651        for closure_var in closure_vars {
3652            let cell = match closure_var.closure_type {
3653                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
3654                    if closure_var.is_lexical =>
3655                {
3656                    // A lexical declaration: the cell is created here holding the
3657                    // dead-zone marker, which is what makes the binding exist and
3658                    // unreadable before its initialiser runs.
3659                    self.declare_global(&closure_var.name, closure_var.is_const);
3660                    self.realm.globals[&closure_var.name].clone()
3661                }
3662                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
3663                    // A `var` or function declaration becomes a property of the global
3664                    // object, and it exists from here on — which is why
3665                    // `print(v); var v = 1` prints `undefined` instead of raising.
3666                    // Declaring it at instantiation time (rather than at the
3667                    // initialiser) is also what makes it non-configurable: the store
3668                    // then lands on an existing property instead of creating one.
3669                    self.declare_var_global(&closure_var.name);
3670                    // The cell is a placeholder that nothing indexes; it cannot be
3671                    // omitted because the slot has to hold something.
3672                    self.new_cell(Value::Undefined)
3673                }
3674                _ => {
3675                    // An undeclared global is read by name; the cell is a
3676                    // placeholder that nothing indexes.
3677                    self.new_cell(Value::Undefined)
3678                }
3679            };
3680            cells.push(cell);
3681        }
3682        Gc::new(
3683            self.heap,
3684            ClosureEnv {
3685                cells,
3686                eval_scope: None,
3687                local_vars: None,
3688                local_phase: 1,
3689            },
3690        )
3691    }
3692
3693    /// Push a frame and run until it returns.
3694    pub(crate) fn execute(
3695        &mut self,
3696        code: Gc<CompiledCode>,
3697        env: Gc<ClosureEnv>,
3698        this: Value,
3699        args: Vec<Value>,
3700        callee: Value,
3701    ) -> JsResult<Value> {
3702        let depth = self.frames.len();
3703        if depth == 0 {
3704            // A throw that reached the host ends the *active* mode: the next one is catchable
3705            // again. The standing request (`uncatchable_next`) is deliberately untouched — a
3706            // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
3707            // for the throw that evaluation will raise.
3708            self.uncatchable = false;
3709        }
3710        self.push_frame(code, env, this, args, callee)?;
3711        loop {
3712            // The fast loop first: it runs whole runs of records with `pc` in a register.
3713            //
3714            // `step`'s `pc` lives in the frame, so every instruction writes it back and
3715            // reads it again — a store, a load and two bounds checks that a loop body does
3716            // not need, because nothing outside the loop can run in between. This is the
3717            // classic split: advance a register, and only spill it when leaving.
3718            //
3719            // `Some(value)` means the function ended by running off the end of its
3720            // instruction array, which is a normal return.
3721            let step = match self.run_fast() {
3722                Ok(Some(value)) => Ok(Step::Return(value)),
3723                Ok(None) => self.step(),
3724                Err(signal) => Err(signal),
3725            };
3726            match step {
3727                Ok(Step::Continue) => {}
3728                Ok(Step::Return(value)) => {
3729                    self.pop_frame();
3730                    // A frame that ended in a `tail_call` hands its value straight to
3731                    // its caller: nothing after the call can run, so every frame above
3732                    // the callee unwinds with the same value. See [`Frame::tail`] —
3733                    // the reference does not reuse frames either, so recursion depth
3734                    // and the stack-overflow limit behave the same way.
3735                    while self.frames.len() > depth && self.frame().tail {
3736                        self.pop_frame();
3737                    }
3738                    if self.frames.len() == depth {
3739                        return Ok(value);
3740                    }
3741                    // The caller resumes with the value on its stack.
3742                    self.frames
3743                        .last_mut()
3744                        .expect("a caller is live")
3745                        .stack
3746                        .push(value);
3747                }
3748                Err(Signal::Throw(value)) => {
3749                    // The host's standing request becomes the active mode for this unwind,
3750                    // and is consumed here so it does not leak into the next throw.
3751                    if self.uncatchable_next {
3752                        self.uncatchable_next = false;
3753                        self.uncatchable = true;
3754                    }
3755                    // An uncatchable throw walks past every `catch` on the way out. The
3756                    // frames are still popped, because the values they hold have to be
3757                    // dropped — only the search for a handler is skipped.
3758                    if self.uncatchable {
3759                        while self.frames.len() > depth {
3760                            self.frames.pop();
3761                        }
3762                        return Err(Signal::Throw(value));
3763                    }
3764                    // A handler lives on the stack of the frame that is throwing —
3765                    // `catch` pushed it there — so this frame gets the first chance
3766                    // to catch before it is popped.
3767                    let value = value;
3768                    loop {
3769                        if self.frames.len() <= depth {
3770                            return Err(Signal::Throw(value));
3771                        }
3772                        if self.catch_here(value.clone()).is_some() {
3773                            break;
3774                        }
3775                        self.frames.pop();
3776                    }
3777                }
3778                // A `yield` in a frame that `execute` is running directly means a
3779                // generator body was entered as an ordinary call, which only happens if
3780                // the generator check in `call_or_push` was bypassed.
3781                Ok(Step::Suspend(_)) => {
3782                    return Err(Signal::Throw(self.make_error(
3783                        "InternalError",
3784                        "a generator body ran as an ordinary call",
3785                    )));
3786                }
3787                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
3788            }
3789        }
3790    }
3791
3792    /// Install a handler for `value` if this frame has one, resuming at it.
3793    ///
3794    /// The scan is the reference's: walk the frame's stack downwards looking for the
3795    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
3796    /// `0` is an enumerator marker rather than a handler — it exists so that a
3797    /// `break` out of a `for-of` can find and close the iterator — so it is skipped
3798    /// here and the unwinding continues.
3799    fn catch_here(&mut self, value: Value) -> Option<()> {
3800        let frame = self.frames.last_mut()?;
3801        while let Some(top) = frame.stack.pop() {
3802            if let Value::CatchOffset(offset) = top {
3803                if offset == 0 {
3804                    continue;
3805                }
3806                frame.stack.push(value);
3807                frame.pc = offset as usize;
3808                return Some(());
3809            }
3810        }
3811        None
3812    }
3813
3814    fn push_frame(
3815        &mut self,
3816        code: Gc<CompiledCode>,
3817        env: Gc<ClosureEnv>,
3818        this: Value,
3819        mut args: Vec<Value>,
3820        callee: Value,
3821    ) -> JsResult<()> {
3822        // Two bounds, and the byte budget is the one that decides in practice. The
3823        // reference's message is `stack overflow` on an `InternalError`, not V8's
3824        // `Maximum call stack size exceeded` on a *string* — the difference is visible:
3825        // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
3826        let frame_cost = Self::frame_cost(&code);
3827        let stack_base = self.stack_used();
3828        if self.frames.len() >= self.max_frames
3829            || stack_base.saturating_add(frame_cost) > self.stack_limit
3830        {
3831            return Err(Signal::Throw(
3832                self.make_error("InternalError", "stack overflow"),
3833            ));
3834        }
3835        let arg_count = code.code.args.len();
3836        // How many were actually passed, which `arguments.length` reports and
3837        // `assert(x)` depends on: a call with one argument must not look like a call
3838        // with one argument and an explicit `undefined`.
3839        let passed = args.len();
3840        // Missing arguments are `undefined` in their slots; extra ones are dropped
3841        // from the slots but still reachable through `arguments`.
3842        //
3843        // A call that passes no more than the declared parameters needs **no** copy:
3844        // after the resize below, `args[..passed]` *is* the passed values. Only the
3845        // extra ones — which `truncate` is about to drop — have to be kept, and they are
3846        // the rare case. This used to copy every call: one `Value` clone per argument
3847        // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
3848        let passed_overflow = (passed > arg_count).then(|| {
3849            let mut values = self.take_values(passed, Value::Undefined);
3850            values[..passed].clone_from_slice(&args[..passed]);
3851            values
3852        });
3853        // Only when the counts differ, which for the overwhelmingly common call — as many
3854        // arguments as parameters — is never. `resize` followed by `truncate` on equal
3855        // lengths is two length compares and nothing else, but this is the hottest few
3856        // instructions in the engine: `call:recursion` executes it twice per `fib` step.
3857        if passed != arg_count {
3858            args.resize(arg_count, Value::Undefined);
3859            args.truncate(arg_count);
3860        }
3861        let cell_count = code.code.var_ref_count as usize;
3862        let mut cells = Vec::with_capacity(cell_count);
3863        for _ in 0..cell_count {
3864            cells.push(self.new_cell(Value::Undefined));
3865        }
3866        let locals = self.take_values(code.code.vars.len(), Value::Undefined);
3867        // A captured argument lives in its cell, not in the argument slot, so the
3868        // incoming value has to be moved there before the body runs.
3869        for (slot, cell) in code.arg_cell.iter().enumerate() {
3870            if *cell >= 0
3871                && let Some(value) = args.get(slot).cloned()
3872            {
3873                cells[*cell as usize].set(value);
3874            }
3875        }
3876        // Sloppy mode substitutes the global object for a missing receiver and boxes a
3877        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
3878        // reports `object`. Strict mode passes the value through untouched.
3879        let this = if code.code.strict {
3880            this
3881        } else if this.is_nullish() {
3882            Value::Object(self.realm.global.clone())
3883        } else if matches!(this, Value::Object(_)) {
3884            this
3885        } else {
3886            match crate::builtins::this_object(self, &this) {
3887                Ok(boxed) => Value::Object(boxed),
3888                Err(_) => this,
3889            }
3890        };
3891        let stack_depth = code.code.stack_size as usize + 1;
3892        // Taken before the `push` borrows `self.frames`, because the operand stack comes
3893        // out of the same recycle pool the locals did.
3894        let stack = self.take_values(stack_depth, Value::Undefined);
3895        self.frames.push(Frame {
3896            code,
3897            env,
3898            this,
3899            args,
3900            passed_count: passed,
3901            passed_overflow: passed_overflow.map(Box::new),
3902            locals,
3903            cells,
3904            local_vars: None,
3905            // Exactly the depth the compiler computed, so the operand stack never
3906            // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
3907            // that reallocated on its way in — a malloc per call.) The recycle pool keeps
3908            // the buffer between calls, so "exactly" costs nothing after the first one.
3909            stack,
3910            pc: 0,
3911            at: 0,
3912            callee,
3913            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
3914            cost: frame_cost,
3915            stack_base,
3916            tail: false,
3917        });
3918        Ok(())
3919    }
3920
3921    /// A value buffer of `len` slots, from the recycle pool when there is one.
3922    ///
3923    /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
3924    fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
3925        // A frame with no locals asks for nothing, and that is most frames: taking a
3926        // buffer out of the pool, clearing it and resizing it to zero is four operations
3927        // and a pool pop for an empty `Vec`, which is free to construct.
3928        if len == 0 {
3929            return Vec::new();
3930        }
3931        let mut buffer = self.free_values.pop().unwrap_or_default();
3932        buffer.clear();
3933        buffer.resize(len, fill);
3934        buffer
3935    }
3936
3937    /// Return a finished frame's value buffers for the next call to reuse.
3938    fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
3939        for mut buffer in [
3940            std::mem::take(&mut frame.locals),
3941            frame
3942                .passed_overflow
3943                .take()
3944                .map(|buffer| *buffer)
3945                .unwrap_or_default(),
3946            std::mem::take(&mut frame.stack),
3947        ] {
3948            // **Empty it here, not when it is reused.** A holding buffer in the pool is a
3949            // GC root: it kept every value the frame held reachable, which is invisible
3950            // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
3951            // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
3952            // exactly that within one run — the target `{}` of a finished IIFE was still
3953            // in its operand stack, in the pool.
3954            buffer.clear();
3955            // A buffer with no capacity is what `Vec::new` is; putting it back would just
3956            // fill the pool with nothing to offer.
3957            if free_values.len() < RECYCLE_SLOTS
3958                && buffer.capacity() > 0
3959                && buffer.capacity() <= RECYCLE_MAX_CAPACITY
3960            {
3961                free_values.push(buffer);
3962            }
3963        }
3964    }
3965
3966    /// Pop a finished frame and keep its buffers.
3967    ///
3968    /// Every place that drops a frame goes through here: a recycled buffer is also where
3969    /// the values it held are dropped (`clear` runs the drops), so skipping this loses
3970    /// nothing but the reuse.
3971    fn pop_frame(&mut self) -> Option<()> {
3972        // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
3973        // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
3974        let last = self.frames.len().checked_sub(1)?;
3975        Self::recycle(&mut self.free_values, &mut self.frames[last]);
3976        self.frames.truncate(last);
3977        Some(())
3978    }
3979
3980    /// Poll the host's interrupt handler, if one is installed.
3981    ///
3982    /// The counter is what keeps this off the hot path when nobody asked: the early return is
3983    /// one `Option` test, and with no handler installed the whole function is that test —
3984    /// `check_memory` next door already costs more, so this cannot be what shows up in a
3985    /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
3986    #[inline]
3987    fn check_interrupt(&mut self) -> JsResult<()> {
3988        if self.interrupt.is_none() {
3989            return Ok(());
3990        }
3991        if self.interrupt_counter > 0 {
3992            self.interrupt_counter -= 1;
3993            return Ok(());
3994        }
3995        self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
3996        // The closure is taken out for the duration so that a handler which re-enters the
3997        // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
3998        let mut handler = self.interrupt.take().expect("checked above");
3999        let abort = handler();
4000        self.interrupt = Some(handler);
4001        if abort {
4002            // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4003            // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4004            // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4005            // documentation says.
4006            self.uncatchable = true;
4007            return Err(Signal::Throw(
4008                self.make_error("InternalError", "interrupted"),
4009            ));
4010        }
4011        Ok(())
4012    }
4013
4014    /// A memory checkpoint: does the heap still fit under its limit?
4015    ///
4016    /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4017    /// a `Cell` read and a predictable branch, and the point of asking that often is that
4018    /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4019    /// only at calls would let it run until the machine died, which is the exact failure
4020    /// `--memory-limit` exists to prevent.
4021    ///
4022    /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4023    /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4024    /// script that catches it, drops the reference and carries on is legitimate: measured
4025    /// on `qjs --memory-limit 1M`, the engine recovers.
4026    fn check_memory(&mut self) -> JsResult<()> {
4027        // One `Cell` read and a predictable branch when no limit is set, and an integer
4028        // compare when one is. Containers report their own growth as it happens
4029        // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4030        // walking it here was the first version and it was O(live) per 256 instructions,
4031        // which turned a 100k-element push loop into a five-minute one.
4032        let Some(limit) = self.heap.memory_limit() else {
4033            return Ok(());
4034        };
4035        let used = self.heap.used_bytes();
4036        if used <= limit {
4037            // Back under the limit — a collection or a dropped reference did it. The next
4038            // time it goes over is a new failure, not a repeat of this one.
4039            self.oom_reported_at = 0;
4040            return Ok(());
4041        }
4042        // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4043        // block runs normally after `out of memory` — it allocates nothing, so nothing
4044        // fails. A check that re-fired on every instruction made the handler itself throw,
4045        // which is a dead end: the error became unobservable from script.
4046        //
4047        // Comparing against the total at the last report gives the same behaviour: the
4048        // handler runs while the total is unchanged, and the very next allocation over the
4049        // limit fails.
4050        if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4051        {
4052            return Ok(());
4053        }
4054        self.oom_reported_at = used;
4055        Err(Signal::Throw(
4056            self.make_error("InternalError", "out of memory"),
4057        ))
4058    }
4059
4060    /// Fail before allocating `payload` bytes, if they would not fit.
4061    ///
4062    /// For the allocations whose size comes from script data — `new Array(n)`,
4063    /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4064    /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4065    /// answering NULL for the one big request.
4066    pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4067        if self.heap.fits(payload) {
4068            return Ok(());
4069        }
4070        Err(Signal::Throw(
4071            self.make_error("InternalError", "out of memory"),
4072        ))
4073    }
4074
4075    /// Bytes of frame state the live call chain accounts for.
4076    pub fn stack_used(&self) -> usize {
4077        match self.frames.last() {
4078            Some(frame) => frame.stack_base + frame.cost,
4079            None => 0,
4080        }
4081    }
4082
4083    /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4084    ///
4085    /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4086    /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4087    /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4088    /// instead. That is the whole difference between the two models: it rations C stack, we
4089    /// ration frame state, and both quantities are dominated by the value slots — which is
4090    /// why the two depths come out comparable rather than merely proportional.
4091    fn frame_cost(code: &CompiledCode) -> usize {
4092        let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4093        std::mem::size_of::<Frame>()
4094            + std::mem::size_of::<Value>() * slots
4095            + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4096    }
4097
4098    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4099    ///
4100    /// Only names the eval created are here: a name the frame already declared statically
4101    /// is written through to its own slot instead, so this cannot shadow a real local.
4102    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4103        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4104        let (local_vars, phase) = self.visible_local_vars()?;
4105        if !local_vars.contains(name) {
4106            return None;
4107        }
4108        local_vars.get(name, phase)
4109    }
4110
4111    /// The variables a direct `eval` declared, as the code currently running sees them.
4112    ///
4113    /// Inside an eval that is the *caller's* set — the eval's own variable environment
4114    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4115    /// else it is the current frame's, falling back to the frame the closure was created
4116    /// in.
4117    /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4118    ///
4119    /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4120    /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4121    /// refcount operations (the clone out of the frame, the drop at the end of the match)
4122    /// just to be asked `is_none`.
4123    fn has_visible_local_vars(&self) -> bool {
4124        let index = match self.eval_caller.flatten() {
4125            Some(caller) => caller,
4126            None => match self.frames.len().checked_sub(1) {
4127                Some(top) => top,
4128                None => return false,
4129            },
4130        };
4131        match self.frames.get(index) {
4132            Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4133            None => false,
4134        }
4135    }
4136
4137    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4138        // While an `eval` runs, its own frame is on top but its variable environment is
4139        // the *caller's* — so the caller is what the lookup has to start from.
4140        let (index, phase) = match self.eval_caller.flatten() {
4141            Some(caller) => (
4142                caller,
4143                if self.in_parameter_list_at(caller) {
4144                    0
4145                } else {
4146                    1
4147                },
4148            ),
4149            None => (
4150                self.frames.len().checked_sub(1)?,
4151                if self.in_parameter_list() { 0 } else { 1 },
4152            ),
4153        };
4154        let frame = self.frames.get(index)?;
4155        // The frame's own variables, or — for an arrow, which has no variable environment
4156        // of its own — the one it was created in, which `ClosureEnv` carries.
4157        if let Some(local_vars) = frame.local_vars.clone() {
4158            return Some((local_vars, phase));
4159        }
4160        frame
4161            .env
4162            .local_vars
4163            .clone()
4164            .map(|local_vars| (local_vars, frame.env.local_phase))
4165    }
4166
4167    /// Whether the innermost frame is still evaluating its parameter list.
4168    ///
4169    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4170    /// and a closure created there may only see that much of [`LocalVars`].
4171    fn in_parameter_list(&self) -> bool {
4172        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4173    }
4174
4175    /// [`Interp::in_parameter_list`] for a specific frame.
4176    fn in_parameter_list_at(&self, frame: usize) -> bool {
4177        let Some(frame) = self.frames.get(frame) else {
4178            return false;
4179        };
4180        let code = &frame.code.code;
4181        if !code.has_parameter_expressions {
4182            return false;
4183        }
4184        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4185        // function as its body and let a direct `eval` act accordingly.
4186        if code.body_start == (0, 0) {
4187            return false;
4188        }
4189        match code.position_at(frame.at as u32) {
4190            Some(position) => position < code.body_start,
4191            None => false,
4192        }
4193    }
4194
4195    fn frame(&self) -> &Frame {
4196        self.frames.last().expect("a frame is live")
4197    }
4198
4199    fn frame_mut(&mut self) -> &mut Frame {
4200        self.frames.last_mut().expect("a frame is live")
4201    }
4202
4203    // -- slot access --------------------------------------------------------
4204
4205    /// Move a local's value out, leaving `undefined` in the slot.
4206    ///
4207    /// `None` for a captured slot: its value lives in a cell shared with every closure
4208    /// that closed over it, so it can never be exclusively ours and must not be taken.
4209    ///
4210    /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4211    /// for every read and fatal for this one — a clone is exactly the second handle that
4212    /// rules out growing the string in place.
4213    fn take_loc(&mut self, slot: usize) -> Option<Value> {
4214        let frame = self.frames.last_mut()?;
4215        if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4216            return None;
4217        }
4218        frame
4219            .locals
4220            .get_mut(slot)
4221            .map(|value| std::mem::replace(value, Value::Undefined))
4222    }
4223
4224    /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4225    /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4226    ///
4227    /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4228    /// it** — the value is put back before the general path runs — so a `valueOf` that
4229    /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4230    /// error as it would have without the fusion. This is why the in-place attempt is a
4231    /// `take` and not a `get`: an optimisation that changes what an exception observes is
4232    /// a wrong answer with a good excuse.
4233    fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4234        // The take is `matches!`-guarded on the *right* operand only, and the taken value
4235        // is put back on every path that does not append. An earlier version wrote the two
4236        // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4237        // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4238        // through with its value already taken and dropped: the general path below then
4239        // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4240        // A wrong answer, from an optimisation, with every test green.
4241        if matches!(right, Value::String(_))
4242            && let Some(taken) = self.take_loc(slot)
4243        {
4244            if let Value::String(mut left) = taken {
4245                let appended = match left.get_mut() {
4246                    Some(string) => string.append_in_place(
4247                        // The pattern is the one `matches!` just checked.
4248                        match &right {
4249                            Value::String(text) => text,
4250                            _ => unreachable!("guarded above"),
4251                        },
4252                    ),
4253                    None => None,
4254                };
4255                self.put_loc(slot, Value::String(left));
4256                if let Some(added) = appended {
4257                    // The buffer grew where it stood, so the heap's running total has to
4258                    // be told: `measure_used` would report the new length, and the two must
4259                    // agree or the subtraction at free time leaves the counter wrong.
4260                    self.heap.adjust_payload(added as isize);
4261                    return Ok(());
4262                }
4263            } else {
4264                self.put_loc(slot, taken);
4265            }
4266        }
4267        // The two-number case, without an operand stack round trip. Everything below
4268        // this point is the *general* path: push both, call `binary_add`, pop the answer,
4269        // store it — five operations and two `Value` clones for what is one integer add.
4270        // `AddImmLoc` already answers this shape that way; the fusion above it was written
4271        // for string append and never got the numeric half, so `t += i` — a counting loop
4272        // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4273        let left = self.get_loc(slot);
4274        if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4275            self.put_loc(
4276                slot,
4277                match a.checked_add(*b) {
4278                    Some(sum) => Value::Int(sum),
4279                    None => Value::Float(*a as f64 + *b as f64),
4280                },
4281            );
4282            return Ok(());
4283        }
4284        self.push(left);
4285        self.push(right);
4286        self.binary_add()?;
4287        let value = self.pop();
4288        self.put_loc(slot, value);
4289        Ok(())
4290    }
4291
4292    fn get_arg(&self, slot: usize) -> Value {
4293        self.frame().read_arg(slot)
4294    }
4295
4296    fn put_arg(&mut self, slot: usize, value: Value) {
4297        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4298        if cell == -1 {
4299            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4300                *slot = value;
4301            }
4302        } else {
4303            self.frame().cells[cell as usize].set(value);
4304        }
4305    }
4306
4307    fn get_loc(&self, slot: usize) -> Value {
4308        // The cell mapping is `-1` for every slot that was not captured — which is all of
4309        // them in a function that creates no closure. `Frame::read_loc` tests that first,
4310        // so the common case is one array read and a clone: 20% of every loop iteration
4311        // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4312        // sample of `dispatch:arith`).
4313        self.frame().read_loc(slot)
4314    }
4315
4316    fn put_loc(&mut self, slot: usize, value: Value) {
4317        // One borrow instead of three, and the cell check on the frame we already hold.
4318        let frame = self.frames.last_mut().expect("a frame is live");
4319        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4320        if cell < 0 {
4321            if let Some(slot) = frame.locals.get_mut(slot) {
4322                *slot = value;
4323            }
4324        } else if let Some(cell) = frame.cells.get(cell as usize) {
4325            cell.set(value);
4326        }
4327    }
4328
4329    // -- globals ------------------------------------------------------------
4330
4331    /// The name a global-slot operand refers to.
4332    fn global_name(&self, slot: usize) -> String {
4333        self.frame()
4334            .code
4335            .code
4336            .closure_vars
4337            .get(slot)
4338            .map(|c| c.name.clone())
4339            .unwrap_or_default()
4340    }
4341
4342    /// The facts about a global binding that decide where it lives.
4343    ///
4344    /// A script's globals split in two, and the split is observable: `var` and
4345    /// function declarations become properties of the global object (`globalThis.v`
4346    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4347    /// declarations live in the global *lexical* environment and are invisible there
4348    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4349    /// `is_lexical` flag means the answer is already in the bytecode.
4350    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4351        let name = self.global_name(slot);
4352        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4353        // while forwarding a reference through a nested function is built with the
4354        // flags cleared, so `const c` would look like an ordinary `var` from inside a
4355        // closure. Presence in the realm's lexical table is the same fact, recorded
4356        // once, and every slot sees it.
4357        let lexical = self.realm.globals.contains_key(&name);
4358        let is_const = self.realm.lexical_consts.contains(&name);
4359        (name, lexical, is_const)
4360    }
4361
4362    /// The value of `name` in the innermost active `with` object, if any.
4363    ///
4364    /// The active objects are the [`VarKind::With`] locals of every frame still running,
4365    /// innermost frame first and innermost block first within one. Walking frames rather
4366    /// than keeping a separate stack is what makes a closure called from inside a `with`
4367    /// see it, and what keeps the object alive only as long as the block is.
4368    /// The innermost active `with` object that has `name`, if any.
4369    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4370        let objects = self.eval_with.clone().unwrap_or_default();
4371        for object in objects {
4372            let key = self.string(name.to_string());
4373            if self
4374                .has_property(&key, &Value::Object(object.clone()))
4375                .ok()?
4376            {
4377                return Some(object);
4378            }
4379        }
4380        None
4381    }
4382
4383    /// Every active `with` object, innermost first.
4384    fn with_objects(&self) -> Vec<Gc<JsObject>> {
4385        let mut objects = Vec::new();
4386        for frame in self.frames.iter().rev() {
4387            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4388                if var.kind != js_compile::VarKind::With {
4389                    continue;
4390                }
4391                // A captured binding lives in its cell and not in the slot list, so the
4392                // cell is consulted first — a closure created inside the block is exactly
4393                // what makes the object captured. Before the store runs the slot still
4394                // holds `undefined`, and a `with` object is always boxed, so a non-object
4395                // entry is simply not in scope yet.
4396                let value = frame
4397                    .code
4398                    .loc_cell
4399                    .get(index)
4400                    .copied()
4401                    .filter(|cell| *cell >= 0)
4402                    .and_then(|cell| frame.cells.get(cell as usize))
4403                    .map(|cell| cell.get())
4404                    .or_else(|| frame.locals.get(index).cloned());
4405                if let Some(Value::Object(object)) = value {
4406                    objects.push(object);
4407                }
4408            }
4409        }
4410        objects
4411    }
4412
4413    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4414        for object in self.eval_with.clone().unwrap_or_default() {
4415            let key = self.string(name.to_string());
4416            if self.has_property(&key, &Value::Object(object.clone()))? {
4417                return Ok(Some(self.read_field(&Value::Object(object), name)?));
4418            }
4419        }
4420        Ok(None)
4421    }
4422
4423    /// Whether every scope between here and the global object is an ordinary one.
4424    ///
4425    /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4426    /// bytecode resolved; when any is live the general path has to run in full order. When
4427    /// none is — every ordinary program — a global read is a property read and nothing
4428    /// else, and that is worth caching.
4429    fn scopes_are_plain(&self) -> bool {
4430        self.eval_caller.is_none()
4431            && self.eval_with.is_none()
4432            && self.eval_arguments.is_none()
4433            && self.eval_bindings.is_empty()
4434            && self.eval_scope.is_none()
4435            // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4436            // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4437            // its `ClosureEnv`, so the test has to be the same one the general path makes.
4438            // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4439            // upstream corpus caught and no unit test did.
4440            && !self.has_visible_local_vars()
4441            && self.frame().env.eval_scope.is_none()
4442    }
4443
4444    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4445        // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4446        // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4447        // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4448        // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4449        // borrow outlive the `&mut self` the lookup needs.
4450        //
4451        // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4452        // forwarded through a nested function has its flags cleared, so the flag cannot
4453        // be believed.
4454        let code = self.frame().code.clone();
4455        let name = code
4456            .code
4457            .closure_vars
4458            .get(slot)
4459            .map(|c| c.name.as_str())
4460            .unwrap_or_default();
4461        let lexical = self.realm.globals.contains_key(name);
4462        // The common case, first: an ordinary global `var`, with a cache in front of the
4463        // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4464        // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4465        // cache hit and return without touching any of it.
4466        if !lexical && self.scopes_are_plain() {
4467            return self.get_plain_global(name, slot);
4468        }
4469        if name == "arguments"
4470            && let Some(arguments) = &self.eval_arguments
4471        {
4472            return Ok(arguments.clone());
4473        }
4474        // A `with` block around the *call site* is part of the scope an `eval` sees, so
4475        // the objects live when the eval started are consulted before anything else. The
4476        // snapshot is taken at entry rather than scanning the frames on every read: a
4477        // block that has already finished still leaves its object in the slot, and a
4478        // bytecode read outside the block must not see it.
4479        if let Some(value) = self.with_lookup(name)? {
4480            return Ok(value);
4481        }
4482        // A variable a direct `eval` declared shadows everything the compiler resolved,
4483        // including an enclosing function's binding: the eval put it in the caller's own
4484        // variable environment, which is nearer than any captured scope.
4485        if let Some((local_vars, phase)) = self.visible_local_vars()
4486            && let Some(cell) = local_vars.get(name, phase)
4487        {
4488            return Ok(cell.get());
4489        }
4490        // The frame that called `eval` is the innermost scope the eval'd code sees, so
4491        // its local `a` wins over a global `a`.
4492        if let Some(value) = self.eval_binding_value(name) {
4493            return Ok(value);
4494        }
4495        // A closure created by an `eval` resolves its free names against the bindings
4496        // that eval saw, even after the eval (and its frames) are gone.
4497        if let Some(cell) = self
4498            .frame()
4499            .env
4500            .eval_scope
4501            .as_ref()
4502            .and_then(|scope| scope.get(name))
4503        {
4504            let value = cell.get();
4505            if matches!(value, Value::Uninitialized) {
4506                return Err(self.throw_reference(name));
4507            }
4508            return Ok(value);
4509        }
4510        // A binding declared by the strict `eval` currently running shadows anything
4511        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
4512        if let Some(scope) = &self.eval_scope
4513            && let Some(value) = scope.get(name)
4514        {
4515            return Ok(value.clone());
4516        }
4517        if lexical {
4518            // A lexical global is a binding in a side table, so the dead zone is
4519            // visible and it is nowhere on the global object.
4520            if let Some(cell) = self.realm.globals.get(name) {
4521                let value = cell.get();
4522                if matches!(value, Value::Uninitialized) {
4523                    return Err(self.throw_reference(name));
4524                }
4525                return Ok(value);
4526            }
4527            return Err(self.throw_reference(name));
4528        }
4529        // A `var` global is an ordinary property, so the prototype chain and the
4530        // global object's own builtins are all reachable through it.
4531        match self.get_property(&self.realm.global.clone(), name)? {
4532            Some(value) => Ok(value),
4533            None => Err(self.throw_reference(name)),
4534        }
4535    }
4536
4537    /// Read a plain global `var`: a cached own data property, or the full lookup.
4538    ///
4539    /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
4540    /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
4541    fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
4542        let object = self.realm.global.clone();
4543        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4544        if let Some(cached) = &self.global_cache[site]
4545            && object.upgrades_to(&cached.object)
4546            && let Some(value) = object.data_property_at(cached.index, name)
4547        {
4548            return Ok(value);
4549        }
4550        // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
4551        // chain exactly as before, then remember the answer if it is worth remembering.
4552        let Some(value) = self.get_property(&object, name)? else {
4553            return Err(self.throw_reference(name));
4554        };
4555        if let Some(index) = object.own_data_index(name) {
4556            self.global_cache[site] = Some(GlobalCache {
4557                object: object.downgrade(),
4558                index,
4559            });
4560        }
4561        Ok(value)
4562    }
4563
4564    /// Store to a global binding.
4565    ///
4566    /// Returns a signal when the store is refused: a `const` global may only be
4567    /// written by its initialiser, and a non-configurable `var` global may not be
4568    /// deleted but is always writable.
4569    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4570        let (name, lexical, is_const) = self.global_binding(slot);
4571
4572        // An assignment inside a `with` writes through to the object that supplies the
4573        // name, which for an `eval` means consulting the same chain `get_global` does.
4574        if let Some(owner) = self.with_owner(&name) {
4575            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
4576            return Ok(());
4577        }
4578        // A variable the running eval *declared* takes the write before any caller
4579        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
4580        // environment even when an enclosing function has a `var c` of its own.
4581        if self.eval_caller.flatten().is_some()
4582            && let Some((local_vars, phase)) = self.visible_local_vars()
4583            && local_vars.contains(&name)
4584            && let Some(cell) = local_vars.get(&name, phase)
4585        {
4586            cell.set(value);
4587            return Ok(());
4588        }
4589        // A binding of the frame that called `eval` takes the write, which is what
4590        // makes `f("a = 3")` change the caller's `a`.
4591        if self.set_eval_binding(&name, &value)? {
4592            return Ok(());
4593        }
4594        // A closure that outlived its `eval` writes through to the same cell it reads.
4595        if let Some(cell) = self
4596            .frame()
4597            .env
4598            .eval_scope
4599            .as_ref()
4600            .and_then(|scope| scope.get(&name))
4601            .cloned()
4602        {
4603            cell.set(value);
4604            return Ok(());
4605        }
4606        // Inside a strict `eval`, a name it declared itself is stored there. An
4607        // *assignment* to a name nobody declared is not a declaration, so it falls
4608        // through: strict mode raises `ReferenceError` for it, which is what
4609        // `eval("1 + (@not_def = 1)")` has to do.
4610        if let Some(scope) = self.eval_scope.as_mut()
4611            && scope.contains_key(&name)
4612        {
4613            scope.insert(name, value);
4614            return Ok(());
4615        }
4616        if lexical {
4617            if let Some(cell) = self.realm.globals.get(&name).cloned() {
4618                if is_const && !matches!(cell.get(), Value::Uninitialized) {
4619                    return Err(self.read_only_global(&name));
4620                }
4621                cell.set(value);
4622                return Ok(());
4623            }
4624            // Writing an undeclared lexical global is a `ReferenceError` in strict
4625            // mode and a silent global creation otherwise; creating the cell here
4626            // keeps both paths from losing the value.
4627            let cell = self.new_cell(value);
4628            self.realm.globals.insert(name, cell);
4629            return Ok(());
4630        }
4631        // A variable a direct `eval` declared in this call shadows the global object, even
4632        // when the global already has a property of that name — `var c = "global"` at the
4633        // top level must not capture `eval("var c = 1")` inside a function.
4634        if let Some((local_vars, phase)) = self.visible_local_vars()
4635            && local_vars.contains(&name)
4636            && let Some(cell) = local_vars.get(&name, phase)
4637        {
4638            cell.set(value);
4639            return Ok(());
4640        }
4641        let global = self.realm.global.clone();
4642        match global.own_property(&name) {
4643            // A `var` global is writable, so the store goes straight through — but
4644            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
4645            // store (a non-writable or accessor-without-setter global) is a silent
4646            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
4647            // split every other assignment has.
4648            Some(_) => {
4649                let on_failure = if self.current_strict() {
4650                    DeleteFailure::Throw
4651                } else {
4652                    DeleteFailure::Ignore
4653                };
4654                self.set_property_with(&global, &name, value, on_failure)
4655            }
4656            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
4657            // declaration creates a *configurable* property, which is what makes it
4658            // deletable and is the one way a global differs from a declared `var`.
4659            // In strict mode the same store is a `ReferenceError` instead: that is the
4660            // whole point of strict mode, and creating the global silently meant
4661            // `"use strict"; x = 1` looked like it worked.
4662            None => {
4663                if self.current_strict() {
4664                    return Err(self.throw_reference(&name));
4665                }
4666                // A direct eval declares here rather than on the global object: its
4667                // `var`s belong to the caller's variable environment. `declare_eval_local`
4668                // also covers a plain assignment to a variable an earlier eval made.
4669                if let Some(cell) = self.declare_eval_local(&name) {
4670                    cell.set(value);
4671                    return Ok(());
4672                }
4673                global.define_data(&name, value);
4674                Ok(())
4675            }
4676        }
4677    }
4678
4679    /// The value of a binding of the frame that called `eval`, if there is one.
4680    fn eval_binding_value(&self, name: &str) -> Option<Value> {
4681        let binding = self
4682            .eval_bindings
4683            .iter()
4684            .find(|binding| binding.name == name)?;
4685        let owner = self.frames.get(binding.frame)?;
4686        let (slot, index) = (binding.slot, binding.index);
4687        Some(match slot {
4688            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4689                cell if cell >= 0 => owner
4690                    .cells
4691                    .get(cell as usize)
4692                    .map(|cell| cell.get())
4693                    .unwrap_or(Value::Undefined),
4694                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
4695            },
4696            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4697                cell if cell >= 0 => owner
4698                    .cells
4699                    .get(cell as usize)
4700                    .map(|cell| cell.get())
4701                    .unwrap_or(Value::Undefined),
4702                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
4703            },
4704        })
4705    }
4706
4707    /// Write to a binding of the frame that called `eval`.
4708    ///
4709    /// `Ok(false)` means no binding matched and the caller should keep looking. A
4710    /// matched binding can still refuse the store, which is why this is fallible: a
4711    /// `const` is read-only everywhere, and a named function expression's own name is
4712    /// read-only in strict mode.
4713    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
4714        let Some(binding) = self
4715            .eval_bindings
4716            .iter()
4717            .find(|binding| binding.name == name)
4718        else {
4719            return Ok(false);
4720        };
4721        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
4722        let strict = self.current_strict();
4723        let Some(owner) = self.frames.get_mut(frame) else {
4724            return Ok(false);
4725        };
4726        match slot {
4727            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4728                cell if cell >= 0 => {
4729                    if let Some(cell) = owner.cells.get(cell as usize) {
4730                        cell.set(value.clone());
4731                    }
4732                }
4733                _ => {
4734                    if let Some(slot) = owner.args.get_mut(index) {
4735                        *slot = value.clone();
4736                    }
4737                }
4738            },
4739            EvalSlot::Local => {
4740                let declared = owner.code.code.vars.get(index);
4741                // A `const` is read-only even through `eval`. The realm records this for
4742                // globals (see `lexical_consts`), but a local's `const`-ness is only in
4743                // the bytecode, so this is where it has to be enforced.
4744                if declared.is_some_and(|var| var.is_const) {
4745                    return Err(self.read_only_local(name));
4746                }
4747                // The name of a named function expression is read-only too, but only
4748                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
4749                // such a name is ignored, the same as a direct store would be.
4750                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
4751                    return if strict {
4752                        Err(self.read_only_local(name))
4753                    } else {
4754                        Ok(true)
4755                    };
4756                }
4757                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4758                    cell if cell >= 0 => {
4759                        if let Some(cell) = owner.cells.get(cell as usize) {
4760                            cell.set(value.clone());
4761                        }
4762                    }
4763                    _ => {
4764                        if let Some(slot) = owner.locals.get_mut(index) {
4765                            *slot = value.clone();
4766                        }
4767                    }
4768                }
4769            }
4770        }
4771        Ok(true)
4772    }
4773
4774    /// The `TypeError` an assignment to a read-only binding raises.
4775    fn read_only_local(&self, name: &str) -> Signal {
4776        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4777    }
4778
4779    /// Declare `name` as a variable of the frame that called the running `eval`.
4780    ///
4781    /// `None` when there is no direct eval in progress, or it was called from the top
4782    /// level — then the caller's variable environment *is* the global one and the
4783    /// existing path is right.
4784    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
4785        let caller = self.eval_caller.flatten()?;
4786        // The bottom frame is the top-level script, whose variable environment *is* the
4787        // global one — so `eval("var x = 1")` at the top level still creates a global.
4788        if caller == 0 {
4789            return None;
4790        }
4791        // A name the eval's *own* variable environment already binds is not a new
4792        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
4793        // `arguments`, and creating a second binding would leave the first — the one
4794        // closures read — untouched. A binding of an *outer* frame does not count: a
4795        // declaration shadows it rather than writing through.
4796        if self
4797            .eval_bindings
4798            .iter()
4799            .any(|binding| binding.name == name && binding.frame == caller)
4800        {
4801            return None;
4802        }
4803        let phase = if self.in_parameter_list_at(caller) {
4804            0
4805        } else {
4806            1
4807        };
4808        self.frame_local_vars(caller)?;
4809        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
4810        if let Some(cell) = local_vars.get(name, 1) {
4811            return Some(cell);
4812        }
4813        let cell = self.new_cell(Value::Undefined);
4814        Some(local_vars.declare(name, phase, cell))
4815    }
4816
4817    /// Make sure `frame` has a `LocalVars`, creating it on demand.
4818    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
4819        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
4820            return Some(local_vars.clone());
4821        }
4822        let local_vars = Gc::new(self.heap, LocalVars::new());
4823        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
4824        Some(local_vars)
4825    }
4826
4827    /// Whether the realm already has a binding for `name`, lexically or as an *own*
4828    /// property of the global object. Used to decide whether a store inside an
4829    /// `eval` writes through to the realm or declares a binding of its own.
4830    ///
4831    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
4832    /// write to `Object.prototype.toString`, and must not shadow it either.
4833    fn global_knows(&mut self, name: &str) -> bool {
4834        if self.realm.globals.contains_key(name) {
4835            return true;
4836        }
4837        self.realm.global.own_property(name).is_some()
4838    }
4839
4840    /// Whether the code currently running is strict.
4841    ///
4842    /// Read off the frame's function, which is where the parser's answer ended up; a
4843    /// native function never runs strict-only checks, and there is no frame at all
4844    /// before the first script.
4845    pub fn current_strict(&self) -> bool {
4846        self.frames
4847            .last()
4848            .is_some_and(|frame| frame.code.code.strict)
4849    }
4850
4851    /// Initialise a declared global, which is what ends its dead zone.
4852    ///
4853    /// A `var` global becomes a property of the global object: writable, so a later
4854    /// assignment goes through, and non-configurable, so `delete` refuses.
4855    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4856        let (name, lexical, _) = self.global_binding(slot);
4857        // A `var` declared by the strict `eval` currently running belongs to the
4858        // eval's scope, not to the global object: `eval("var v = 1")` must not make
4859        // `typeof v` answer `"number"` afterwards. A name the realm already has is
4860        // initialised in place, which is what a re-declaration inside eval does.
4861        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
4862            self.eval_scope
4863                .as_mut()
4864                .expect("checked above")
4865                .insert(name, value);
4866            return Ok(());
4867        }
4868        if let Some(scope) = self.eval_scope.as_mut()
4869            && scope.contains_key(&name)
4870        {
4871            scope.insert(name, value);
4872            return Ok(());
4873        }
4874        if lexical {
4875            // The cell exists (created at declaration time) holding the dead-zone
4876            // marker; storing the value is what makes the binding readable.
4877            if let Some(cell) = self.realm.globals.get(&name).cloned() {
4878                cell.set(value);
4879                return Ok(());
4880            }
4881            let cell = self.new_cell(value);
4882            self.realm.globals.insert(name, cell);
4883            return Ok(());
4884        }
4885        let global = self.realm.global.clone();
4886        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
4887        // to answer `false` and leave the binding in place. `with_attributes` ties
4888        // `configurable` to `writable`, so the property is built field by field.
4889        global.define(
4890            &name,
4891            Property {
4892                value: Some(value),
4893                writable: true,
4894                enumerable: true,
4895                configurable: false,
4896                ..Property::default()
4897            },
4898        );
4899        Ok(())
4900    }
4901
4902    /// The `TypeError` a store to a `const` global raises.
4903    fn read_only_global(&self, name: &str) -> Signal {
4904        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4905    }
4906
4907    // -- properties ---------------------------------------------------------
4908
4909    /// Read `object[key]`, following the prototype chain.
4910    ///
4911    /// An inherited accessor runs with the *receiver* as `this`, which is why the
4912    /// lookup returns the owner rather than just the value.
4913    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
4914        self.get_property_key(object, &PropertyKey::from(key))
4915    }
4916
4917    /// [`Interp::get_property`] with a key that may be a symbol.
4918    pub fn get_property_key(
4919        &mut self,
4920        object: &Gc<JsObject>,
4921        key: &PropertyKey,
4922    ) -> JsResult<Option<Value>> {
4923        self.get_property_key_for(object, None, key)
4924    }
4925
4926    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
4927    ///
4928    /// The receiver matters when the property is found on a *prototype*: a getter has to
4929    /// see the object the read started from. For a primitive that is the primitive
4930    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
4931    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
4932    /// the owner.
4933    pub fn get_property_key_for(
4934        &mut self,
4935        object: &Gc<JsObject>,
4936        receiver: Option<&Value>,
4937        key: &PropertyKey,
4938    ) -> JsResult<Option<Value>> {
4939        // A proxy answers for itself, before any of the shortcuts below: `new
4940        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
4941        // have.
4942        if object.proxy_state().is_some() {
4943            let receiver = receiver
4944                .cloned()
4945                .unwrap_or_else(|| Value::Object(object.clone()));
4946            return self.proxy_get(object, &receiver, key);
4947        }
4948        // A host class's `get_property` trap replaces the whole read, prototype walk
4949        // included — that is what makes a native accessor free rather than a JavaScript
4950        // getter call.
4951        if let Some(exotic) = object.exotic() {
4952            let receiver_value = receiver
4953                .cloned()
4954                .unwrap_or_else(|| Value::Object(object.clone()));
4955            if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
4956                return Ok(Some(value));
4957            }
4958            // With no `get_property` trap, a `get_own_property` trap still answers for the
4959            // object itself: `[[Get]]` asks each object in the chain for its own descriptor
4960            // and the hook lives exactly there. A key the trap reports as absent is still
4961            // looked for on the prototype, which is why the search resumes *above*.
4962            if let Some(property) = exotic.get_own_property(self, object, key)? {
4963                return match property {
4964                    Some(property) => self.read_property(property, object, receiver),
4965                    None => match lookup_key_above(object, key) {
4966                        Some((_, property)) => self.read_property(property, object, receiver),
4967                        None => Ok(None),
4968                    },
4969                };
4970            }
4971        }
4972        // The element-vector and `length` shortcuts are string-only: an array index
4973        // has no symbol spelling.
4974        if let Some(text) = key.as_str() {
4975            if let Some(value) = self.own_element(object, text) {
4976                return Ok(Some(value));
4977            }
4978            // `length` is not stored as a property: an array's length is its element
4979            // count, and keeping one copy of it is what makes `push`/`pop` and
4980            // `a.length = n` agree.
4981            if let Some(length) = object.array_length()
4982                && text == "length"
4983            {
4984                // Not `Value::Int(length as i32)`: see [`length_value`].
4985                return Ok(Some(crate::object::length_value(length)));
4986            }
4987        }
4988        match lookup_key(object, key) {
4989            Some((_, property)) => self.read_property(property, object, receiver),
4990            None => Ok(None),
4991        }
4992    }
4993
4994    /// The value a property read answers.
4995    ///
4996    /// One place rather than three, because an accessor has to run with the *receiver* as
4997    /// `this` whether the descriptor came from the property table, an exotic
4998    /// `get_own_property` trap, or a prototype above one.
4999    fn read_property(
5000        &mut self,
5001        property: Property,
5002        object: &Gc<JsObject>,
5003        receiver: Option<&Value>,
5004    ) -> JsResult<Option<Value>> {
5005        if property.is_accessor() {
5006            match &property.getter {
5007                Some(getter) if !matches!(getter, Value::Undefined) => {
5008                    let receiver = receiver
5009                        .cloned()
5010                        .unwrap_or_else(|| Value::Object(object.clone()));
5011                    self.call_value(getter.clone(), receiver, Vec::new())
5012                        .map(Some)
5013                }
5014                // An accessor with no getter reads as `undefined`.
5015                _ => Ok(Some(Value::Undefined)),
5016            }
5017        } else {
5018            Ok(property.value)
5019        }
5020    }
5021
5022    /// `super.key` — start the search at `proto`, but report to `receiver`.
5023    ///
5024    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5025    /// found on the prototype of a class has to see the *instance* as `this`, and a
5026    /// plain property read off `proto` would lose that.
5027    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5028        let start = self.require_object(proto)?;
5029        let key = self.propkey(key)?;
5030        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5031        if matches!(proto, Value::Null) {
5032            return Ok(Value::Undefined);
5033        }
5034        match lookup_key(&start, &key) {
5035            Some((_, property)) if property.is_accessor() => match &property.getter {
5036                Some(getter) if !matches!(getter, Value::Undefined) => {
5037                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
5038                }
5039                _ => Ok(Value::Undefined),
5040            },
5041            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5042            None => Ok(Value::Undefined),
5043        }
5044    }
5045
5046    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5047    ///
5048    /// A setter found on the prototype runs with `receiver` as `this`; a data property
5049    /// is shadowed by a new own property on the receiver, the same rule an ordinary
5050    /// assignment follows.
5051    fn super_write(
5052        &mut self,
5053        receiver: &Value,
5054        proto: &Value,
5055        key: &Value,
5056        value: Value,
5057    ) -> JsResult<()> {
5058        let target = self.require_object(receiver)?;
5059        let key = self.propkey(key)?;
5060        if !matches!(proto, Value::Null)
5061            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5062        {
5063            if property.is_accessor() {
5064                if let Some(setter) = &property.setter
5065                    && !matches!(setter, Value::Undefined)
5066                {
5067                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5068                }
5069                return Ok(());
5070            }
5071            // A data property on the prototype is writable or not; reading `owner` at
5072            // all is only for the attribute check.
5073            if !property.writable {
5074                return Err(self.type_error(format!("'{key}' is read-only")));
5075            }
5076            let _ = owner;
5077        }
5078        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5079    }
5080
5081    /// The object a `super` operation needs, or the `TypeError` the spec raises.
5082    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5083        match value.as_object() {
5084            Some(object) => Ok(object.clone()),
5085            None => Err(Signal::Throw(
5086                self.make_error("TypeError", "value is not an object"),
5087            )),
5088        }
5089    }
5090
5091    /// Build the class object `define_class` produces.
5092    ///
5093    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5094    /// whose prototype property is a fresh object inheriting from the parent's
5095    /// prototype, and whose own prototype is the parent constructor — which is what makes
5096    /// a static method inherited too.
5097    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5098        let ctor = self.pop();
5099        let parent = self.pop();
5100        let Value::Object(function) = &ctor else {
5101            return Err(Signal::Throw(
5102                self.make_error("TypeError", "class constructor must be a function"),
5103            ));
5104        };
5105        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5106        // but gives the instances no prototype at all.
5107        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5108            match &parent {
5109                Value::Null => (Some(self.realm.function_proto.clone()), None),
5110                Value::Object(parent_class) => {
5111                    if !parent_class.is_callable() {
5112                        return Err(Signal::Throw(
5113                            self.make_error("TypeError", "parent class must be constructor"),
5114                        ));
5115                    }
5116                    let proto = self.get_property(parent_class, "prototype")?;
5117                    match proto {
5118                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5119                        Some(Value::Null) => (Some(parent_class.clone()), None),
5120                        _ => {
5121                            return Err(Signal::Throw(self.make_error(
5122                                "TypeError",
5123                                "parent prototype must be an object or null",
5124                            )));
5125                        }
5126                    }
5127                }
5128                _ => {
5129                    return Err(Signal::Throw(
5130                        self.make_error("TypeError", "parent class must be constructor"),
5131                    ));
5132                }
5133            }
5134        } else {
5135            (
5136                Some(self.realm.function_proto.clone()),
5137                Some(self.realm.object_proto.clone()),
5138            )
5139        };
5140        let proto = self.new_object(parent_proto);
5141        function.set_proto(parent_ctor);
5142        // A class is not callable without `new`, and its `prototype` is not writable —
5143        // both follow from being a class and are what `class A {}; A()` throws on.
5144        function.set_class_constructor(true);
5145        function.set_home_object(None);
5146        self.set_function_name(&ctor, name);
5147        self.define_class_properties(function, &ctor, &proto)?;
5148        Ok((ctor, proto))
5149    }
5150
5151    /// Give the constructor its `prototype` and `length`, and the prototype its
5152    /// `constructor` back-pointer.
5153    fn define_class_properties(
5154        &mut self,
5155        function: &Gc<JsObject>,
5156        ctor: &Value,
5157        proto: &Gc<JsObject>,
5158    ) -> JsResult<()> {
5159        proto.define(
5160            "constructor",
5161            Property::with_attributes(ctor.clone(), true, false),
5162        );
5163        function.define(
5164            "prototype",
5165            Property::prototype_of(Value::Object(proto.clone()), false),
5166        );
5167        if let Some((code, _)) = bytecode_of(function) {
5168            let length = code.code.defined_args;
5169            function.define(
5170                "length",
5171                Property::name_or_length(Value::Int(length as i32)),
5172            );
5173        }
5174        Ok(())
5175    }
5176
5177    /// The own array element `key` names, if this object has one.
5178    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5179        let index = array_index(key)?;
5180        // A typed array's elements live in its buffer, not in a property list: reading one
5181        // goes through the view's element type so a bounds check and a detached buffer are
5182        // both handled there.
5183        if object.typed_array_parts().is_some() {
5184            return object.typed_array_element(index as usize);
5185        }
5186        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5187        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5188        // search early, which is why `Array.prototype[1] = 9` could not be seen through
5189        // `[1,,3][1]`.
5190        match object.array_get(index as usize) {
5191            Some(Value::Hole) | None => None,
5192            other => other,
5193        }
5194    }
5195
5196    /// Store `object[key] = value`, honouring setters and inherited properties.
5197    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5198        self.set_property_with(object, key, value, DeleteFailure::Throw)
5199    }
5200
5201    /// Store a property, choosing what to do when the object refuses.
5202    ///
5203    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5204    /// mode, which is the one place assignment differs by mode. Native code (the array
5205    /// methods, `JSON`) always asks for the throw.
5206    pub fn set_property_with(
5207        &mut self,
5208        object: &Gc<JsObject>,
5209        key: &str,
5210        value: Value,
5211        on_failure: DeleteFailure,
5212    ) -> JsResult<()> {
5213        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5214    }
5215
5216    /// [`Interp::set_property_with`] with a key that may be a symbol.
5217    pub fn set_property_with_key(
5218        &mut self,
5219        object: &Gc<JsObject>,
5220        key: &PropertyKey,
5221        value: Value,
5222        on_failure: DeleteFailure,
5223    ) -> JsResult<()> {
5224        // A proxy's `set` trap decides, and its `false` means the same thing an
5225        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5226        if object.proxy_state().is_some() {
5227            let receiver = Value::Object(object.clone());
5228            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5229                return match (accepted, on_failure) {
5230                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5231                    (false, DeleteFailure::Throw) => {
5232                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5233                    }
5234                };
5235            }
5236        }
5237        // A host class's `set_property` trap decides for itself. `Some(false)` is a
5238        // refusal and means exactly what a proxy's `false` means.
5239        if let Some(exotic) = object.exotic() {
5240            let receiver = Value::Object(object.clone());
5241            if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5242                return match (accepted, on_failure) {
5243                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5244                    (false, DeleteFailure::Throw) => {
5245                        Err(self.type_error(format!("property '{key}' is read-only")))
5246                    }
5247                };
5248            }
5249        }
5250        // The element and `length` shortcuts only exist for string keys: an array
5251        // index has no symbol spelling, and a symbol named `length` is an ordinary
5252        // property.
5253        let text = key.as_str();
5254        // A typed array's elements are a window onto its buffer: the store has to go
5255        // through the view's element type so the value is wrapped (or clamped) and so an
5256        // out-of-range or detached write is a silent no-op, as the spec says.
5257        if let Some(text) = text
5258            && let Some(index) = array_index(text)
5259            && let Some(element) = object.typed_array_element_type()
5260        {
5261            // §10.4.5.5: an out-of-bounds index answers `true` *before* `V` is converted,
5262            // so a `valueOf` with a side effect must not run. Checking the length first is
5263            // what keeps `valueOfCalled` at 0 in `key-is-out-of-bounds-receiver-is-…`.
5264            let length = object.typed_array_length().unwrap_or(0);
5265            if index as usize >= length {
5266                return Ok(());
5267            }
5268            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5269            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5270            // in `Interp`, because it is script-observable and the storage borrow inside
5271            // `typed_array_set` must not be held across it.
5272            let stored = self.element_value(element, value)?;
5273            if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
5274                return Err(self.type_error(reason));
5275            }
5276            return Ok(());
5277        }
5278        if let Some(text) = text
5279            && let Some(index) = array_index(text)
5280            && object.is_array()
5281        {
5282            // An accessor defined on an index lives in the property table while the
5283            // element slot is a hole, so the store has to go through the property first.
5284            // Writing the vector directly skipped the setter entirely.
5285            if let Some(existing) = object.own_property_key(key) {
5286                if existing.is_accessor() {
5287                    return match existing.setter.clone() {
5288                        Some(setter) if !matches!(setter, Value::Undefined) => {
5289                            let receiver = Value::Object(object.clone());
5290                            self.call_value(setter, receiver, vec![value]).map(|_| ())
5291                        }
5292                        _ => match on_failure {
5293                            DeleteFailure::Throw => Err(self.type_error(format!(
5294                                "cannot set property '{text}', it has only a getter"
5295                            ))),
5296                            DeleteFailure::Ignore => Ok(()),
5297                        },
5298                    };
5299                }
5300                if !existing.writable {
5301                    return match on_failure {
5302                        DeleteFailure::Throw => {
5303                            Err(self.type_error(format!("'{text}' is read-only")))
5304                        }
5305                        DeleteFailure::Ignore => Ok(()),
5306                    };
5307                }
5308            }
5309            {
5310                // Growing the array needs a writable `length`.
5311                if (index as usize) >= object.array_length().unwrap_or(0)
5312                    && !object.length_writable()
5313                {
5314                    return match on_failure {
5315                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5316                        DeleteFailure::Ignore => Ok(()),
5317                    };
5318                }
5319                // Adding an index past the end makes the array longer, which a
5320                // non-extensible array refuses.
5321                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5322                    return match on_failure {
5323                        DeleteFailure::Throw => Err(self.type_error(format!(
5324                            "cannot add property '{key}', object is not extensible"
5325                        ))),
5326                        DeleteFailure::Ignore => Ok(()),
5327                    };
5328                }
5329                if object.element_is_locked(index) {
5330                    return match on_failure {
5331                        DeleteFailure::Throw => {
5332                            Err(self.type_error(format!("'{key}' is read-only")))
5333                        }
5334                        DeleteFailure::Ignore => Ok(()),
5335                    };
5336                }
5337                // The element vector is only half of `[[Set]]` for an index: the
5338                // prototype chain is consulted first, and a setter there answers instead
5339                // of the element store. This branch used to write the element directly, so
5340                // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5341                // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5342                // the reference calls the setter and the array keeps no own index.
5343                if let Some((owner, property)) = lookup_key(object, key)
5344                    && !owner.ptr_eq(object)
5345                {
5346                    match &property {
5347                        property if property.is_accessor() => {
5348                            match &property.setter {
5349                                Some(setter) if !matches!(setter, Value::Undefined) => {
5350                                    let receiver = Value::Object(object.clone());
5351                                    self.call_value(setter.clone(), receiver, vec![value])?;
5352                                }
5353                                _ => {
5354                                    return match on_failure {
5355                                        DeleteFailure::Throw => Err(self.type_error(format!(
5356                                            "cannot set property '{text}', it has only a getter"
5357                                        ))),
5358                                        DeleteFailure::Ignore => Ok(()),
5359                                    };
5360                                }
5361                            }
5362                            return Ok(());
5363                        }
5364                        property if !property.writable => {
5365                            return match on_failure {
5366                                DeleteFailure::Throw => {
5367                                    Err(self.type_error(format!("'{text}' is read-only")))
5368                                }
5369                                DeleteFailure::Ignore => Ok(()),
5370                            };
5371                        }
5372                        _ => {}
5373                    }
5374                }
5375                if object.array_set(self.heap, index as usize, value.clone()) {
5376                    return Ok(());
5377                }
5378                // Past the dense limit the slot is too far out to be worth one `Value`
5379                // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
5380                // constant time by keeping the index as an ordinary property. The store
5381                // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
5382                // to a legal program.
5383                object.define_key(key, Property::with_attributes(value, true, true));
5384                // Extend, never shorten: the index may be *inside* the current length (a
5385                // huge `length` with a sparse store), and shortening would delete the
5386                // sparse properties above it — including the one just stored.
5387                if index as usize + 1 > object.array_length().unwrap_or(0) {
5388                    object.array_set_length(self.heap, index as usize + 1);
5389                }
5390                return Ok(());
5391            }
5392        }
5393        if text == Some("length") && object.is_array() {
5394            if !object.length_writable() {
5395                return match on_failure {
5396                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5397                    DeleteFailure::Ignore => Ok(()),
5398                };
5399            }
5400            let length = value.to_number();
5401            if length.is_finite() && length >= 0.0 {
5402                let length = length as usize;
5403                // `a.length = n` with `n` below a non-configurable element cannot
5404                // drop that element, so the whole assignment fails. The spec makes
5405                // this a `TypeError` rather than a silent no-op, in any mode.
5406                if let Some(blocked) = object.first_undeletable_at_or_above(length) {
5407                    // Sloppy mode stops the truncation at the blocking element
5408                    // instead of failing; strict mode raises.
5409                    // Both modes stop at the blocking element; they differ in
5410                    // whether that is reported. The reference truncates *then*
5411                    // throws, so the array is left in the shortened state.
5412                    object.array_truncate(self.heap, blocked + 1);
5413                    return match on_failure {
5414                        DeleteFailure::Throw => {
5415                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
5416                        }
5417                        DeleteFailure::Ignore => Ok(()),
5418                    };
5419                }
5420                object.array_set_length(self.heap, length);
5421                return Ok(());
5422            }
5423        }
5424        if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
5425        {
5426            return match on_failure {
5427                DeleteFailure::Throw => Err(self.type_error(format!(
5428                    "cannot add property {}, object is not extensible",
5429                    key
5430                ))),
5431                DeleteFailure::Ignore => Ok(()),
5432            };
5433        }
5434        if let Some((owner, property)) = self.lookup_for_write(object, key)? {
5435            if property.is_accessor() {
5436                match &property.setter {
5437                    Some(setter) if !matches!(setter, Value::Undefined) => {
5438                        let receiver = Value::Object(object.clone());
5439                        self.call_value(setter.clone(), receiver, vec![value])?;
5440                    }
5441                    // §10.1.9.2 step 3: an accessor with no setter refuses the write.
5442                    // Sloppy code swallows that refusal, strict code raises — the same
5443                    // rule the read-only *data* property below follows, and skipping it
5444                    // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
5445                    // return silently. The reference answers `TypeError: 'x' is
5446                    // read-only`.
5447                    _ => {
5448                        return match on_failure {
5449                            DeleteFailure::Throw => {
5450                                Err(self.type_error(format!("'{key}' is read-only")))
5451                            }
5452                            DeleteFailure::Ignore => Ok(()),
5453                        };
5454                    }
5455                }
5456                return Ok(());
5457            }
5458            // A non-writable data property refuses the write, own **or inherited**: an
5459            // own one stops here because nothing may change it, and an inherited one
5460            // because §10.1.9.2 step 4 refuses to create the shadowing own property.
5461            //
5462            // The `ptr_eq` this used to carry meant an inherited read-only property fell
5463            // through to `define_data_key` and *did* create the shadow — `var o =
5464            // Object.create(Object.freeze({x: 1})); o.x = 9` answered `9` and
5465            // `o.hasOwnProperty('x')` answered `true`, where the reference answers `1`
5466            // and `false`.
5467            if !property.writable {
5468                return match on_failure {
5469                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
5470                    DeleteFailure::Ignore => Ok(()),
5471                };
5472            }
5473            // An existing writable own property keeps its attributes: only the value
5474            // moves. Redefining instead would reset them, which is how a
5475            // non-configurable global `var` used to become deletable.
5476            if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
5477                return Ok(());
5478            }
5479        }
5480        // No own data property: create one, shadowing whatever the prototype holds.
5481        object.define_data_key(key, value);
5482        Ok(())
5483    }
5484
5485    /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
5486    ///
5487    /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
5488    /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
5489    /// a virtual accessor gets its setter run without implementing `set_property` at all.
5490    /// Answering `Some(None)` from the hook does not end the search: the key may still be on
5491    /// the prototype, so the walk resumes above the object.
5492    fn lookup_for_write(
5493        &mut self,
5494        object: &Gc<JsObject>,
5495        key: &PropertyKey,
5496    ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
5497        let Some(exotic) = object.exotic() else {
5498            return Ok(lookup_key(object, key));
5499        };
5500        Ok(match exotic.get_own_property(self, object, key)? {
5501            Some(Some(property)) => Some((object.clone(), property)),
5502            Some(None) => lookup_key_above(object, key),
5503            None => lookup_key(object, key),
5504        })
5505    }
5506
5507    /// Delete `object[key]`.
5508    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
5509        self.delete_property_key(object, &PropertyKey::from(key))
5510    }
5511
5512    /// [`Interp::delete_property`] with a key that may be a symbol.
5513    pub fn delete_property_key(
5514        &mut self,
5515        object: &Gc<JsObject>,
5516        key: &PropertyKey,
5517    ) -> JsResult<bool> {
5518        // A proxy decides for itself, and may even throw; the invariant checks live in
5519        // `proxy_delete`.
5520        if let Some(answer) = self.proxy_delete(object, key)? {
5521            return Ok(answer);
5522        }
5523        // A host class's `delete_property` trap decides; `false` is a refusal, which the
5524        // caller reports as a failed delete.
5525        if let Some(exotic) = object.exotic()
5526            && let Some(answer) = exotic.delete_property(self, object, key)?
5527        {
5528            return Ok(answer);
5529        }
5530        if let Some(index) = key.as_str().and_then(array_index)
5531            && let Some(length) = object.array_length()
5532            && (index as usize) < length
5533        {
5534            // An accessor defined on an index lives in the property table rather than the
5535            // element vector, so both have to be cleared: `delete` after
5536            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
5537            object.delete_key(key);
5538            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
5539            // index stops answering `in`.
5540            if object.element_is_undeletable(index) {
5541                return Ok(false);
5542            }
5543            object.array_set(self.heap, index as usize, Value::Hole);
5544            return Ok(true);
5545        }
5546        Ok(object.delete_key(key))
5547    }
5548
5549    // -- proxy traps --------------------------------------------------------
5550    //
5551    // A proxy's internal methods all look the same: ask the handler for the trap, call it
5552    // with the target and the operation's own arguments, then check the answer against
5553    // the target. The checks are not decoration — they are what stops a proxy from
5554    // reporting a `non-configurable` property as missing, which would let a frozen object
5555    // be rewritten by standing in front of it.
5556
5557    /// The target and handler of `object`, or `None` when it is not a proxy.
5558    ///
5559    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
5560    /// one has to fail: the slots the traps would have been read from are gone.
5561    fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
5562        let Some(state) = object.proxy_state() else {
5563            return Ok(None);
5564        };
5565        let state = state.borrow();
5566        match (&state.target, &state.handler) {
5567            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
5568            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
5569        }
5570    }
5571
5572    /// Call `handler[name]`, or answer `None` when the trap is absent.
5573    ///
5574    /// A trap that is present but not callable is a `TypeError` rather than "no trap":
5575    /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
5576    /// back to the target.
5577    fn proxy_trap(
5578        &mut self,
5579        handler: &Value,
5580        name: &str,
5581        args: Vec<Value>,
5582    ) -> JsResult<Option<Value>> {
5583        let Value::Object(table) = handler else {
5584            return Err(self.type_error("proxy handler is not an object"));
5585        };
5586        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
5587        match trap {
5588            Value::Undefined => Ok(None),
5589            Value::Object(function) if function.is_callable() => {
5590                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
5591                Ok(Some(answer))
5592            }
5593            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
5594        }
5595    }
5596
5597    /// Whether `object`'s own property `key` is one the target refuses to lose.
5598    ///
5599    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
5600    /// its value behind the target's back. This goes through
5601    /// [`Self::ordinary_own_property`] rather than the property table so that an array's
5602    /// elements and its `length` — both fixed, both outside the table — are covered.
5603    fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
5604        Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
5605    }
5606
5607    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
5608    fn proxy_get(
5609        &mut self,
5610        object: &Gc<JsObject>,
5611        receiver: &Value,
5612        key: &PropertyKey,
5613    ) -> JsResult<Option<Value>> {
5614        let Some((target, handler)) = self.proxy_parts(object)? else {
5615            return Ok(None);
5616        };
5617        let key_value = self.key_value(key);
5618        let Some(result) = self.proxy_trap(
5619            &handler,
5620            "get",
5621            vec![Value::Object(target.clone()), key_value, receiver.clone()],
5622        )?
5623        else {
5624            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
5625            // inherited getter still sees the proxy.
5626            return Ok(Some(
5627                self.get_property_key_for(&target, Some(receiver), key)?
5628                    .unwrap_or(Value::Undefined),
5629            ));
5630        };
5631        if let Some(fixed) = Self::is_fixed_property(&target, key) {
5632            if fixed.is_accessor() {
5633                // A fixed accessor with no getter must read as `undefined`.
5634                let has_getter = fixed
5635                    .getter
5636                    .as_ref()
5637                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
5638                if !has_getter && !matches!(result, Value::Undefined) {
5639                    return Err(self.type_error(format!(
5640                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
5641                    )));
5642                }
5643            } else if !fixed.writable {
5644                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5645                if !fixed_value.same_value(&result) {
5646                    return Err(self.type_error(format!(
5647                        "proxy 'get' disagrees with the non-configurable property '{key}'"
5648                    )));
5649                }
5650            }
5651        }
5652        Ok(Some(result))
5653    }
5654
5655    /// `[[Set]]` on a proxy.
5656    ///
5657    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
5658    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
5659    /// read-only store has.
5660    fn proxy_set(
5661        &mut self,
5662        object: &Gc<JsObject>,
5663        key: &PropertyKey,
5664        value: Value,
5665        receiver: &Value,
5666    ) -> JsResult<Option<bool>> {
5667        let Some((target, handler)) = self.proxy_parts(object)? else {
5668            return Ok(None);
5669        };
5670        let key_value = self.key_value(key);
5671        let Some(result) = self.proxy_trap(
5672            &handler,
5673            "set",
5674            vec![
5675                Value::Object(target.clone()),
5676                key_value,
5677                value.clone(),
5678                receiver.clone(),
5679            ],
5680        )?
5681        else {
5682            // No trap: store on the target, which is where an ordinary proxy write lands.
5683            self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
5684            return Ok(Some(true));
5685        };
5686        if !result.to_boolean() {
5687            return Ok(Some(false));
5688        }
5689        if let Some(fixed) = Self::is_fixed_property(&target, key) {
5690            if fixed.is_accessor() {
5691                let has_setter = fixed
5692                    .setter
5693                    .as_ref()
5694                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
5695                if !has_setter {
5696                    return Err(self.type_error(format!(
5697                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
5698                    )));
5699                }
5700            } else if !fixed.writable {
5701                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5702                if !fixed_value.same_value(&value) {
5703                    return Err(self.type_error(format!(
5704                        "proxy 'set' changed the non-configurable property '{key}'"
5705                    )));
5706                }
5707            }
5708        }
5709        // A new property cannot appear on a target that refuses new properties.
5710        if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
5711            return Err(self.type_error(format!(
5712                "proxy 'set' added '{key}' to a non-extensible target"
5713            )));
5714        }
5715        Ok(Some(true))
5716    }
5717
5718    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
5719    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5720        let Some((target, handler)) = self.proxy_parts(object)? else {
5721            return Ok(None);
5722        };
5723        let key_value = self.key_value(key);
5724        let Some(result) = self.proxy_trap(
5725            &handler,
5726            "has",
5727            vec![Value::Object(target.clone()), key_value],
5728        )?
5729        else {
5730            return Ok(Some(self.has_own_or_inherited(&target, key)?));
5731        };
5732        if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5733            return Err(self.type_error(format!(
5734                "proxy 'has' denied the non-configurable property '{key}'"
5735            )));
5736        }
5737        // A non-extensible target cannot grow, so every own property it *has* is fixed.
5738        if !result.to_boolean()
5739            && !target.is_extensible()
5740            && Self::ordinary_own_property(&target, key).is_some()
5741        {
5742            return Err(self.type_error(format!(
5743                "proxy 'has' denied the own property '{key}' of a non-extensible target"
5744            )));
5745        }
5746        Ok(Some(result.to_boolean()))
5747    }
5748
5749    /// `[[Delete]]` on a proxy.
5750    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5751        let Some((target, handler)) = self.proxy_parts(object)? else {
5752            return Ok(None);
5753        };
5754        let key_value = self.key_value(key);
5755        let Some(result) = self.proxy_trap(
5756            &handler,
5757            "deleteProperty",
5758            vec![Value::Object(target.clone()), key_value],
5759        )?
5760        else {
5761            return Ok(Some(self.delete_property_key(&target, key)?));
5762        };
5763        if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5764            return Err(self.type_error(format!(
5765                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
5766            )));
5767        }
5768        if result.to_boolean()
5769            && !target.is_extensible()
5770            && Self::ordinary_own_property(&target, key).is_some()
5771        {
5772            return Err(self.type_error(format!(
5773                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
5774            )));
5775        }
5776        Ok(Some(result.to_boolean()))
5777    }
5778
5779    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
5780    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
5781        let Some((target, handler)) = self.proxy_parts(object)? else {
5782            return Ok(None);
5783        };
5784        let Some(result) =
5785            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
5786        else {
5787            // No trap: the target's own keys, already in the order an object reports.
5788            return Ok(Some(self.object_own_property_keys(&target)?));
5789        };
5790        // `CreateListFromArrayLike` with the string-or-symbol restriction.
5791        let list = self.list_from_array_like(&result, true)?;
5792        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
5793        for value in list {
5794            let key = self.propkey(&value)?;
5795            if keys.contains(&key) {
5796                return Err(self.type_error(format!(
5797                    "proxy 'ownKeys' returned the duplicate key '{key}'"
5798                )));
5799            }
5800            keys.push(key);
5801        }
5802        for (key, property) in target.property_entries() {
5803            if !property.configurable && !keys.contains(&key) {
5804                return Err(self.type_error(format!(
5805                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
5806                )));
5807            }
5808            if !target.is_extensible() && !keys.contains(&key) {
5809                return Err(self.type_error(format!(
5810                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
5811                )));
5812            }
5813        }
5814        if !target.is_extensible() {
5815            let own = target.property_entries().len();
5816            if keys.len() != own {
5817                return Err(
5818                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
5819                );
5820            }
5821        }
5822        Ok(Some(keys))
5823    }
5824
5825    /// `[[GetOwnProperty]]` on a proxy.
5826    fn proxy_get_own_property(
5827        &mut self,
5828        object: &Gc<JsObject>,
5829        key: &PropertyKey,
5830    ) -> JsResult<Option<Option<Property>>> {
5831        let Some((target, handler)) = self.proxy_parts(object)? else {
5832            return Ok(None);
5833        };
5834        let key_value = self.key_value(key);
5835        let Some(result) = self.proxy_trap(
5836            &handler,
5837            "getOwnPropertyDescriptor",
5838            vec![Value::Object(target.clone()), key_value],
5839        )?
5840        else {
5841            // No trap: the target's own descriptor is the answer. This has to go through
5842            // the same synthesis an ordinary object gets, because a proxy's own property
5843            // table is empty by design — reading it directly reported `undefined` for
5844            // every key, including an array's indices and `length`.
5845            return Ok(Some(Self::ordinary_own_property(&target, key)));
5846        };
5847        let answer = if matches!(result, Value::Undefined) {
5848            None
5849        } else {
5850            Some(self.property_from_descriptor(&result)?)
5851        };
5852        let fixed = Self::is_fixed_property(&target, key);
5853        match (&answer, &fixed) {
5854            // A non-configurable property cannot be reported as absent.
5855            (None, Some(_)) => {
5856                return Err(self.type_error(format!(
5857                    "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
5858                )));
5859            }
5860            (Some(descriptor), Some(fixed)) => {
5861                if descriptor.configurable {
5862                    return Err(self.type_error(format!(
5863                        "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
5864                    )));
5865                }
5866                if fixed.is_accessor() != descriptor.is_accessor() {
5867                    return Err(self.type_error(format!(
5868                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
5869                    )));
5870                }
5871                if !fixed.is_accessor() && !fixed.writable {
5872                    let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
5873                    let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
5874                    if !fixed_value.same_value(&reported) {
5875                        return Err(self.type_error(format!(
5876                            "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
5877                        )));
5878                    }
5879                }
5880            }
5881            _ => {}
5882        }
5883        Ok(Some(answer))
5884    }
5885
5886    /// `[[DefineOwnProperty]]` on a proxy.
5887    fn proxy_define_property(
5888        &mut self,
5889        object: &Gc<JsObject>,
5890        key: &PropertyKey,
5891        property: Property,
5892    ) -> JsResult<Option<bool>> {
5893        let Some((target, handler)) = self.proxy_parts(object)? else {
5894            return Ok(None);
5895        };
5896        let key_value = self.key_value(key);
5897        let descriptor = self.descriptor_from_property(&property);
5898        let Some(result) = self.proxy_trap(
5899            &handler,
5900            "defineProperty",
5901            vec![Value::Object(target.clone()), key_value, descriptor],
5902        )?
5903        else {
5904            return Ok(None);
5905        };
5906        if !result.to_boolean() {
5907            return Ok(Some(false));
5908        }
5909        let fixed = Self::is_fixed_property(&target, key);
5910        let creating = Self::ordinary_own_property(&target, key).is_none();
5911        if creating && !target.is_extensible() {
5912            return Err(self.type_error(format!(
5913                "proxy 'defineProperty' added '{key}' to a non-extensible target"
5914            )));
5915        }
5916        if let Some(fixed) = fixed {
5917            if property.configurable {
5918                return Err(self.type_error(format!(
5919                    "proxy 'defineProperty' made the non-configurable '{key}' configurable"
5920                )));
5921            }
5922            if !fixed.writable && property.writable && !fixed.is_accessor() {
5923                return Err(self.type_error(format!(
5924                    "proxy 'defineProperty' made the read-only '{key}' writable"
5925                )));
5926            }
5927        }
5928        Ok(Some(true))
5929    }
5930
5931    /// `[[GetPrototypeOf]]` on a proxy.
5932    fn proxy_get_prototype_of(
5933        &mut self,
5934        object: &Gc<JsObject>,
5935    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
5936        let Some((target, handler)) = self.proxy_parts(object)? else {
5937            return Ok(None);
5938        };
5939        let Some(result) = self.proxy_trap(
5940            &handler,
5941            "getPrototypeOf",
5942            vec![Value::Object(target.clone())],
5943        )?
5944        else {
5945            return Ok(Some(target.proto()));
5946        };
5947        let proto = match &result {
5948            Value::Null => None,
5949            Value::Object(proto) => Some(proto.clone()),
5950            _ => {
5951                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
5952            }
5953        };
5954        if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
5955            return Err(self.type_error(
5956                "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
5957            ));
5958        }
5959        Ok(Some(proto))
5960    }
5961
5962    /// `[[SetPrototypeOf]]` on a proxy.
5963    fn proxy_set_prototype_of(
5964        &mut self,
5965        object: &Gc<JsObject>,
5966        proto: Option<Gc<JsObject>>,
5967    ) -> JsResult<Option<bool>> {
5968        let Some((target, handler)) = self.proxy_parts(object)? else {
5969            return Ok(None);
5970        };
5971        let proto_value = match &proto {
5972            Some(proto) => Value::Object(proto.clone()),
5973            None => Value::Null,
5974        };
5975        let Some(result) = self.proxy_trap(
5976            &handler,
5977            "setPrototypeOf",
5978            vec![Value::Object(target.clone()), proto_value],
5979        )?
5980        else {
5981            target.set_proto(proto);
5982            return Ok(Some(true));
5983        };
5984        if result.to_boolean()
5985            && !target.is_extensible()
5986            && !same_proto(proto.as_ref(), target.proto().as_ref())
5987        {
5988            return Err(self.type_error(
5989                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
5990            ));
5991        }
5992        Ok(Some(result.to_boolean()))
5993    }
5994
5995    /// `[[IsExtensible]]` on a proxy.
5996    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
5997        let Some((target, handler)) = self.proxy_parts(object)? else {
5998            return Ok(None);
5999        };
6000        let Some(result) = self.proxy_trap(
6001            &handler,
6002            "isExtensible",
6003            vec![Value::Object(target.clone())],
6004        )?
6005        else {
6006            return Ok(Some(target.is_extensible()));
6007        };
6008        // The answer is not the proxy's to invent: it must agree with the target, or a
6009        // script could learn `false` while the target keeps accepting new properties.
6010        if result.to_boolean() != target.is_extensible() {
6011            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
6012        }
6013        Ok(Some(result.to_boolean()))
6014    }
6015
6016    /// `[[PreventExtensions]]` on a proxy.
6017    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6018        let Some((target, handler)) = self.proxy_parts(object)? else {
6019            return Ok(None);
6020        };
6021        let Some(result) = self.proxy_trap(
6022            &handler,
6023            "preventExtensions",
6024            vec![Value::Object(target.clone())],
6025        )?
6026        else {
6027            target.set_extensible(false);
6028            return Ok(Some(true));
6029        };
6030        if result.to_boolean() && target.is_extensible() {
6031            return Err(self.type_error(
6032                "proxy 'preventExtensions' reported success but the target is still extensible",
6033            ));
6034        }
6035        Ok(Some(result.to_boolean()))
6036    }
6037
6038    /// `[[Call]]` on a proxy, through the `apply` trap.
6039    fn proxy_apply(
6040        &mut self,
6041        object: &Gc<JsObject>,
6042        this: Value,
6043        args: Vec<Value>,
6044    ) -> JsResult<Option<Value>> {
6045        let Some((target, handler)) = self.proxy_parts(object)? else {
6046            return Ok(None);
6047        };
6048        // The trap gets the arguments as one array, which is the shape the spec passes
6049        // and the shape `apply` traps are written against (`args[0]` is the first one).
6050        let arguments = self.new_array(args.clone());
6051        let this_for_trap = this.clone();
6052        let Some(result) = self.proxy_trap(
6053            &handler,
6054            "apply",
6055            vec![
6056                Value::Object(target.clone()),
6057                this_for_trap,
6058                Value::Object(arguments),
6059            ],
6060        )?
6061        else {
6062            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
6063        };
6064        Ok(Some(result))
6065    }
6066
6067    /// `[[Construct]]` on a proxy, through the `construct` trap.
6068    fn proxy_construct(
6069        &mut self,
6070        object: &Gc<JsObject>,
6071        args: Vec<Value>,
6072        new_target: &Value,
6073    ) -> JsResult<Option<Value>> {
6074        let Some((target, handler)) = self.proxy_parts(object)? else {
6075            return Ok(None);
6076        };
6077        if !target.is_callable() {
6078            return Err(self.type_error("proxy target is not a constructor"));
6079        }
6080        let arguments = self.new_array(args.clone());
6081        let Some(result) = self.proxy_trap(
6082            &handler,
6083            "construct",
6084            vec![
6085                Value::Object(target.clone()),
6086                Value::Object(arguments),
6087                new_target.clone(),
6088            ],
6089        )?
6090        else {
6091            return Ok(Some(self.construct(
6092                Value::Object(target),
6093                new_target.clone(),
6094                args,
6095            )?));
6096        };
6097        if !matches!(result, Value::Object(_)) {
6098            return Err(self.type_error("proxy 'construct' must return an object"));
6099        }
6100        Ok(Some(result))
6101    }
6102
6103    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
6104    pub(crate) fn has_own_or_inherited(
6105        &mut self,
6106        object: &Gc<JsObject>,
6107        key: &PropertyKey,
6108    ) -> JsResult<bool> {
6109        // The object itself first: it may be a proxy, and then the answer is its trap's.
6110        if let Some(answer) = self.proxy_has(object, key)? {
6111            return Ok(answer);
6112        }
6113        // A host class answers `in` for its own keys, which may live nowhere in a property
6114        // table — `"x" in point` is true because the class says so, not because a property
6115        // exists.
6116        if let Some(exotic) = object.exotic()
6117            && let Some(answer) = exotic.has_property(self, object, key)?
6118        {
6119            return Ok(answer);
6120        }
6121        // `has_own` rather than `own_property_key`: an array's elements and its derived
6122        // `length` are invisible to the property table, and `Array.prototype` is an array.
6123        // A host class's `get_own_property` counts too, because the reference's
6124        // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
6125        // lives — a class with only `get_own_property` answers `in` through it.
6126        if self.exotic_has_own(object, key)? {
6127            return Ok(true);
6128        }
6129        // A hole is *not* the end of the search: the chain may still have the key, which
6130        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
6131        for ancestor in object.chain() {
6132            // A proxy further up the chain answers for itself.
6133            if let Some(answer) = self.proxy_has(&ancestor, key)? {
6134                return Ok(answer);
6135            }
6136            // Same for a host class: a prototype may be one, and `in` reaches it.
6137            if let Some(exotic) = ancestor.exotic()
6138                && let Some(answer) = exotic.has_property(self, &ancestor, key)?
6139            {
6140                return Ok(answer);
6141            }
6142            if self.exotic_has_own(&ancestor, key)? {
6143                return Ok(true);
6144            }
6145        }
6146        Ok(false)
6147    }
6148
6149    /// Whether `object` reports `key` as an own property, its class's `get_own_property`
6150    /// trap included.
6151    ///
6152    /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
6153    /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
6154    fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
6155        if let Some(exotic) = object.exotic()
6156            && let Some(answer) = exotic.get_own_property(self, object, key)?
6157        {
6158            return Ok(answer.is_some());
6159        }
6160        Ok(has_own(object, key))
6161    }
6162
6163    /// `CreateListFromArrayLike`, optionally restricted to property keys.
6164    ///
6165    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
6166    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
6167    /// `TypeError` instead of a property named `"1.5"`.
6168    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
6169        let object = self.object_from(value)?;
6170        let length = self
6171            .get_property(&object, "length")?
6172            .map(|value| value.to_number())
6173            .unwrap_or(0.0);
6174        if !length.is_finite() || length < 0.0 {
6175            return Err(self.type_error("invalid array-like length"));
6176        }
6177        let length = length as usize;
6178        let mut items = Vec::with_capacity(length.min(1024));
6179        for index in 0..length {
6180            let item = self
6181                .get_property(&object, &index.to_string())?
6182                .unwrap_or(Value::Undefined);
6183            if keys_only && matches!(&item, Value::Symbol(_)) {
6184                items.push(item);
6185                continue;
6186            }
6187            if keys_only && !matches!(&item, Value::String(_)) {
6188                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
6189            }
6190            items.push(item);
6191        }
6192        Ok(items)
6193    }
6194
6195    /// A `Property` from the descriptor object a trap returned.
6196    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
6197        let object = self.object_from(value)?;
6198        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
6199            interp.get_property(&object, name)
6200        };
6201        let getter = field(self, "get")?;
6202        let setter = field(self, "set")?;
6203        let accessor = getter.is_some() || setter.is_some();
6204        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
6205            Ok(interp
6206                .get_property(&object, name)?
6207                .is_some_and(|value| value.to_boolean()))
6208        };
6209        let enumerable = boolean(self, "enumerable")?;
6210        let configurable = boolean(self, "configurable")?;
6211        if accessor {
6212            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
6213                return Err(
6214                    self.type_error("a descriptor cannot be both a data property and an accessor")
6215                );
6216            }
6217            Ok(Property {
6218                getter: getter.or(Some(Value::Undefined)),
6219                setter: setter.or(Some(Value::Undefined)),
6220                enumerable,
6221                configurable,
6222                writable: false,
6223                value: None,
6224            })
6225        } else {
6226            Ok(Property {
6227                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
6228                writable: boolean(self, "writable")?,
6229                enumerable,
6230                configurable,
6231                getter: None,
6232                setter: None,
6233            })
6234        }
6235    }
6236
6237    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
6238    fn descriptor_from_property(&mut self, property: &Property) -> Value {
6239        let object = self.new_object(None);
6240        if property.is_accessor() {
6241            let getter = property.getter.clone().unwrap_or(Value::Undefined);
6242            let setter = property.setter.clone().unwrap_or(Value::Undefined);
6243            object.define_data("get", getter);
6244            object.define_data("set", setter);
6245        } else {
6246            let value = property.value.clone().unwrap_or(Value::Undefined);
6247            object.define_data("value", value);
6248            object.define_data("writable", Value::Bool(property.writable));
6249        }
6250        object.define_data("enumerable", Value::Bool(property.enumerable));
6251        object.define_data("configurable", Value::Bool(property.configurable));
6252        Value::Object(object)
6253    }
6254
6255    // -- calling ------------------------------------------------------------
6256
6257    /// Call `callee` with `this` and `args`.
6258    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
6259        let Value::Object(function) = &callee else {
6260            // `typeof x === "function"` is not enough to make `x()` legal: only a
6261            // callable object is. `null` and `undefined` need no special wording
6262            // here — their `ToString` already reads the way the reference's does.
6263            let what = format!("{} is not a function", callee.to_js_string());
6264            return Err(Signal::Throw(self.make_error("TypeError", &what)));
6265        };
6266        // A proxy of a function is called through its `apply` trap. It has no
6267        // `ObjectKind::Function` of its own, so this has to come before the dispatch
6268        // below, and a proxy of a non-function has nothing to forward to.
6269        if function.proxy_state().is_some() {
6270            return match self.proxy_apply(function, this, args)? {
6271                Some(result) => Ok(result),
6272                None => Err(Signal::Throw(
6273                    self.make_error("TypeError", "proxy target is not callable"),
6274                )),
6275            };
6276        }
6277        let callable = function.with(|data| match &data.kind {
6278            ObjectKind::Function(callable) => match callable {
6279                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
6280                // The `Rc` is cloned out so the borrow of this object's data is released
6281                // before the closure runs: the closure may touch the same object.
6282                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
6283                Callable::Bound {
6284                    target,
6285                    this,
6286                    args: leading,
6287                } => Some(NativeCall::Bound {
6288                    target: target.clone(),
6289                    this: this.clone(),
6290                    leading: leading.clone(),
6291                }),
6292                Callable::Bytecode { code, env } => {
6293                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
6294                }
6295                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
6296                Callable::PromiseResolve(promise) => {
6297                    Some(NativeCall::PromiseResolve(promise.clone()))
6298                }
6299                Callable::PromiseReject(promise) => {
6300                    Some(NativeCall::PromiseReject(promise.clone()))
6301                }
6302                Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
6303                    state: state.clone(),
6304                }),
6305                Callable::ThenShim {
6306                    handler,
6307                    resolve,
6308                    reject,
6309                    fulfilled,
6310                } => Some(NativeCall::ThenShim {
6311                    handler: handler.clone(),
6312                    resolve: resolve.clone(),
6313                    reject: reject.clone(),
6314                    fulfilled: *fulfilled,
6315                }),
6316                Callable::AwaitResume {
6317                    coroutine,
6318                    promise,
6319                    kind,
6320                } => Some(NativeCall::AwaitResume {
6321                    coroutine: coroutine.clone(),
6322                    promise: promise.clone(),
6323                    kind: *kind,
6324                }),
6325                Callable::CombinatorSettle {
6326                    state,
6327                    index,
6328                    fulfilled,
6329                } => Some(NativeCall::CombinatorSettle {
6330                    state: state.clone(),
6331                    index: *index,
6332                    fulfilled: *fulfilled,
6333                }),
6334                Callable::FinallyShim {
6335                    callback,
6336                    fulfilled,
6337                    constructor,
6338                } => Some(NativeCall::FinallyShim {
6339                    callback: callback.clone(),
6340                    fulfilled: *fulfilled,
6341                    constructor: constructor.clone(),
6342                }),
6343                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
6344                Callable::CompletedReturn {
6345                    generator,
6346                    promise,
6347                    rejected,
6348                } => Some(NativeCall::CompletedReturn {
6349                    generator: generator.clone(),
6350                    promise: promise.clone(),
6351                    rejected: *rejected,
6352                }),
6353                Callable::YieldResult {
6354                    generator,
6355                    promise,
6356                    done,
6357                } => Some(NativeCall::YieldResult {
6358                    generator: generator.clone(),
6359                    promise: promise.clone(),
6360                    done: *done,
6361                }),
6362                Callable::DisposeStep {
6363                    remaining,
6364                    promise,
6365                    error,
6366                    rejected,
6367                } => Some(NativeCall::DisposeStep {
6368                    remaining: remaining.clone(),
6369                    promise: promise.clone(),
6370                    error: error.clone(),
6371                    rejected: *rejected,
6372                }),
6373                Callable::GeneratorResume {
6374                    generator,
6375                    promise,
6376                    kind,
6377                } => Some(NativeCall::GeneratorResume {
6378                    generator: generator.clone(),
6379                    promise: promise.clone(),
6380                    kind: *kind,
6381                }),
6382                Callable::SettlePromise {
6383                    promise,
6384                    value,
6385                    rejected,
6386                } => Some(NativeCall::SettlePromise {
6387                    promise: promise.clone(),
6388                    value: value.clone(),
6389                    rejected: *rejected,
6390                }),
6391            },
6392            _ => None,
6393        });
6394        match callable {
6395            Some(NativeCall::Host(func)) => {
6396                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
6397                // function by name rather than stopping at the caller.
6398                let frame_less = function
6399                    .own_property("_frame_less")
6400                    .and_then(|property| property.value)
6401                    .is_some_and(|value| value.to_boolean());
6402                let outer = if frame_less {
6403                    None
6404                } else {
6405                    self.native_frames
6406                        .push((function.clone(), self.frames.len()));
6407                    Some(self.current_native.replace(function.clone()))
6408                };
6409                let result = {
6410                    let mut body = func.borrow_mut();
6411                    body(self, this, &args)
6412                };
6413                if !frame_less {
6414                    self.native_frames.pop();
6415                    self.current_native = outer.flatten();
6416                }
6417                result
6418            }
6419            Some(NativeCall::Native(func)) => {
6420                // A function marked `_frame_less` is one the reference implements
6421                // without a call frame — `eval` is the only one so far.
6422                let frame_less = function
6423                    .own_property("_frame_less")
6424                    .and_then(|property| property.value)
6425                    .is_some_and(|value| value.to_boolean());
6426                let outer = if frame_less {
6427                    None
6428                } else {
6429                    self.native_frames
6430                        .push((function.clone(), self.frames.len()));
6431                    Some(self.current_native.replace(function.clone()))
6432                };
6433                let result = func(self, this, &args);
6434                if !frame_less {
6435                    self.native_frames.pop();
6436                    self.current_native = outer.flatten();
6437                }
6438                result
6439            }
6440            Some(NativeCall::Revoker(slots)) => {
6441                // Idempotent: revoking twice answers `undefined` again rather than
6442                // complaining, which is what the spec says and what a `finally` block
6443                // relies on.
6444                let mut state = slots.borrow_mut();
6445                state.target = None;
6446                state.handler = None;
6447                Ok(Value::Undefined)
6448            }
6449            Some(NativeCall::PromiseResolve(promise)) => {
6450                // One-shot: a second call is silently ignored, which
6451                // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
6452                let value = args.first().cloned().unwrap_or(Value::Undefined);
6453                self.resolve_promise_with(&promise, value)?;
6454                Ok(Value::Undefined)
6455            }
6456            Some(NativeCall::PromiseReject(promise)) => {
6457                let reason = args.first().cloned().unwrap_or(Value::Undefined);
6458                self.reject_promise(&promise, reason);
6459                Ok(Value::Undefined)
6460            }
6461            Some(NativeCall::ThenShim {
6462                handler,
6463                resolve,
6464                reject,
6465                fulfilled,
6466            }) => {
6467                // `PerformPromiseThen` with a capability: run the handler, then settle
6468                // through the capability's own pair. A throw from the handler is the
6469                // rejection, and a throw from the capability's `resolve` is not caught —
6470                // exactly the spec's `?`.
6471                let value = args.first().cloned().unwrap_or(Value::Undefined);
6472                match handler {
6473                    Some(handler) => {
6474                        match self.call_value(handler, Value::Undefined, vec![value]) {
6475                            Ok(result) => {
6476                                self.call_value(resolve, Value::Undefined, vec![result])?;
6477                            }
6478                            Err(Signal::Throw(reason)) => {
6479                                self.call_value(reject, Value::Undefined, vec![reason])?;
6480                            }
6481                            Err(signal) => return Err(signal),
6482                        }
6483                    }
6484                    None => {
6485                        let handler = if fulfilled { resolve } else { reject };
6486                        self.call_value(handler, Value::Undefined, vec![value])?;
6487                    }
6488                }
6489                Ok(Value::Undefined)
6490            }
6491            Some(NativeCall::CapabilityExecutor { state }) => {
6492                // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
6493                // slot holds a value yet. The test is on the *values*, not on a call count —
6494                // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
6495                // called-twice`'s first case does exactly that), while a second call after a
6496                // real pair is the `TypeError`.
6497                let defined = |name: &str| {
6498                    state
6499                        .own_property(name)
6500                        .and_then(|property| property.value)
6501                        .is_some_and(|value| !matches!(value, Value::Undefined))
6502                };
6503                if defined("resolve") || defined("reject") {
6504                    return Err(self.type_error("promise capability executor called twice"));
6505                }
6506                let resolve = args.first().cloned().unwrap_or(Value::Undefined);
6507                let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
6508                state.define_data("resolve", resolve);
6509                state.define_data("reject", reject);
6510                Ok(Value::Undefined)
6511            }
6512            Some(NativeCall::CombinatorSettle {
6513                state,
6514                index,
6515                fulfilled,
6516            }) => {
6517                let value = args.first().cloned().unwrap_or(Value::Undefined);
6518                self.settle_combinator(&state, index, fulfilled, value)?;
6519                Ok(Value::Undefined)
6520            }
6521            Some(NativeCall::AwaitResume {
6522                coroutine,
6523                promise,
6524                kind,
6525            }) => {
6526                // Resume *inline*, in the reaction that delivered the value. Deferring it
6527                // by another job inserts a tick between every `await` and its
6528                // continuation, which reorders `await` against unrelated `then` chains —
6529                // `f().then(g)` then runs before `f`'s own next statement.
6530                self.drive_async(
6531                    &coroutine,
6532                    &promise,
6533                    kind,
6534                    args.first().cloned().unwrap_or(Value::Undefined),
6535                )
6536                .map(|()| Value::Undefined)
6537            }
6538            Some(NativeCall::FinallyShim {
6539                callback,
6540                fulfilled,
6541                constructor,
6542            }) => {
6543                // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
6544                // that settles with the *original* outcome once the callback's result has
6545                // settled. The callback's own value is discarded — that is the whole
6546                // difference between `finally` and `then`.
6547                let original = args.first().cloned().unwrap_or(Value::Undefined);
6548                let result = match &callback {
6549                    Some(callback) => {
6550                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
6551                    }
6552                    None => Value::Undefined,
6553                };
6554                // `PromiseResolve(C, result)`, not the intrinsic: a `result` that is
6555                // already a promise of this constructor is reused rather than rewrapped.
6556                let resolved = self.promise_resolve_for(&constructor, result)?;
6557                let Value::Object(resolved) = resolved else {
6558                    return Ok(original);
6559                };
6560                // The wait is a chained promise rather than a bare return, so a callback
6561                // that returns a slow promise really does delay the continuation.
6562                let waiting = self.new_promise();
6563                let pass = JsObject::function(
6564                    self.heap,
6565                    Some(self.realm.function_proto.clone()),
6566                    Callable::SettlePromise {
6567                        promise: waiting.clone(),
6568                        value: original,
6569                        rejected: !fulfilled,
6570                    },
6571                );
6572                let pass = Value::Object(pass);
6573                // Whichever way the callback's promise settles, the original outcome wins.
6574                self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
6575                Ok(Value::Object(waiting))
6576            }
6577            Some(NativeCall::DisposeStep {
6578                remaining,
6579                promise,
6580                error,
6581                rejected,
6582            }) => {
6583                let error = if rejected {
6584                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
6585                    self.merge_dispose_error(reason, error)
6586                } else {
6587                    error
6588                };
6589                self.dispose_step(&remaining, &promise, error)?;
6590                Ok(Value::Undefined)
6591            }
6592            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
6593            Some(NativeCall::CompletedReturn {
6594                generator,
6595                promise,
6596                rejected,
6597            }) => {
6598                let value = args.first().cloned().unwrap_or(Value::Undefined);
6599                let outcome = if rejected {
6600                    AsyncOutcome::Error(value)
6601                } else {
6602                    AsyncOutcome::Value(self.iterator_result(value, true)?)
6603                };
6604                self.settle_async_request(&generator, &promise, outcome)?;
6605                Ok(Value::Undefined)
6606            }
6607            Some(NativeCall::YieldResult {
6608                generator,
6609                promise,
6610                done,
6611            }) => {
6612                let value = args.first().cloned().unwrap_or(Value::Undefined);
6613                let result = self.iterator_result(value, done)?;
6614                self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
6615                Ok(Value::Undefined)
6616            }
6617            Some(NativeCall::GeneratorResume {
6618                generator,
6619                promise,
6620                kind,
6621            }) => {
6622                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
6623                // tick and reorders the generator against other chains.
6624                self.step_async_generator(
6625                    &generator,
6626                    &promise,
6627                    kind,
6628                    args.first().cloned().unwrap_or(Value::Undefined),
6629                )
6630                .map(|()| Value::Undefined)
6631            }
6632            Some(NativeCall::SettlePromise {
6633                promise,
6634                value,
6635                rejected,
6636            }) => {
6637                if rejected {
6638                    self.reject_promise(&promise, value);
6639                } else {
6640                    self.fulfill_promise(&promise, value);
6641                }
6642                Ok(Value::Undefined)
6643            }
6644            Some(NativeCall::Bound {
6645                target,
6646                this: bound_this,
6647                leading,
6648            }) => {
6649                let mut all = leading;
6650                all.extend(args);
6651                self.call_value(target, bound_this, all)
6652            }
6653            Some(NativeCall::Bytecode(code, env)) => {
6654                if code.code.kind.is_generator() {
6655                    return self.new_generator(callee, this, args);
6656                }
6657                if code.code.kind.is_async() {
6658                    // Same coroutine machinery as a generator; the difference is only in
6659                    // what the completion does — see `new_async_function`.
6660                    return self.new_async_function(callee, this, args);
6661                }
6662                self.execute(code, env, this, args, callee)
6663            }
6664            None => Err(Signal::Throw(
6665                self.make_error("TypeError", "not a function"),
6666            )),
6667        }
6668    }
6669
6670    /// Give a freshly built function its own `prototype` object.
6671    ///
6672    /// Every function that can be used with `new` carries one, and its
6673    /// `constructor` points back at the function — a reference cycle, which is
6674    /// exactly what the collector's cycle pass exists to reclaim.
6675    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
6676        let prototype = self.new_object(Some(self.realm.object_proto.clone()));
6677        let constructor = Value::Object(function.clone());
6678        prototype.define(
6679            "constructor",
6680            Property::with_attributes(constructor, true, false),
6681        );
6682        let value = Value::Object(prototype);
6683        function.define("prototype", Property::prototype_of(value, true));
6684    }
6685
6686    /// The object `special_object` builds.
6687    ///
6688    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
6689    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
6690    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
6691    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
6692    /// write through `arguments` does not reach the parameter.
6693    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
6694        match magic {
6695            0 | 1 => {
6696                let args = self.frame().passed().to_vec();
6697                let proto = self.realm.object_proto.clone();
6698                let object = self.new_object(Some(proto));
6699                // The marker `Object.prototype.toString` needs: an arguments object is an
6700                // ordinary object apart from reporting `[object Arguments]`, and that has
6701                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
6702                // show up ahead of them in a key listing anyway — it is non-enumerable.
6703                self.internal_set(&object, "_class", self.string("Arguments"));
6704                // `length` is writable and configurable but neither enumerable nor a
6705                // plain data property: `Object.keys(arguments)` lists the indices only,
6706                // which is how `{...arguments}` copies them without the length.
6707                object.define(
6708                    "length",
6709                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
6710                );
6711                for (index, value) in args.into_iter().enumerate() {
6712                    object.define_data(&index.to_string(), value);
6713                }
6714                // An arguments object is iterable: `[...arguments]` and
6715                // `for (const a of arguments)` both work, through the *array* iterator
6716                // because the object is array-like. Without this the whole spread form
6717                // reported "not iterable".
6718                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
6719                let values = self
6720                    .realm
6721                    .array_proto
6722                    .own_property("values")
6723                    .and_then(|property| property.value);
6724                if let Some(values) = values {
6725                    object.define_key(
6726                        &iterator_key,
6727                        Property::with_attributes(values, true, false),
6728                    );
6729                }
6730                Ok(Value::Object(object))
6731            }
6732            // `this.active_func`: the constructor `super()` resolves against.
6733            //
6734            // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
6735            // own, so it inherits this from the function it was written in along with `this`
6736            // — and that is a lexical relationship, not a stack one: an arrow that escaped
6737            // the constructor and is called back later (`iter.return = () => super()`) has
6738            // the constructor nowhere on the stack. The compiler therefore reads it out of
6739            // a closure variable of the enclosing function, exactly as the reference does
6740            // with its `this_active_func` local.
6741            2 => Ok(self
6742                .current_callee()
6743                .map_or(Value::Undefined, Value::Object)),
6744            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
6745            // inherited from the caller inside an `eval`. An arrow has no `new.target` of
6746            // its own either, so the lookup walks out to the nearest non-arrow frame for
6747            // the same reason as `this.active_func` above — without that, `super()` inside
6748            // an arrow passed `undefined` as the new target and the parent constructor was
6749            // then rejected for being invoked without `new`.
6750            3 => Ok(self
6751                .eval_new_target
6752                .clone()
6753                .unwrap_or_else(|| self.frame().new_target.clone())),
6754            // `[[HomeObject]]` of the function being run: what `super` is relative to.
6755            // An arrow has none of its own, so the lookup walks out to the enclosing
6756            // method — which is why `super` works inside an arrow inside a method.
6757            4 => Ok(self
6758                .frames
6759                .iter()
6760                .rev()
6761                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6762                .map_or(Value::Undefined, Value::Object)),
6763            // `import.meta`: the innermost module body's meta object. Outside a module
6764            // the compiler never emits this, so an empty fallback is unreachable rather
6765            // than permissive.
6766            6 => {
6767                let name = self.module_stack.last().cloned();
6768                let meta = name
6769                    .and_then(|name| self.modules.get(&name).cloned())
6770                    .and_then(|module| module.with(|r| r.import_meta.clone()));
6771                Ok(meta.map_or(Value::Undefined, Value::Object))
6772            }
6773            other => Err(Signal::Throw(self.make_error(
6774                "InternalError",
6775                &format!("special_object {other} is not implemented yet"),
6776            ))),
6777        }
6778    }
6779
6780    /// `[[HomeObject]]` of the innermost function that has one, if any.
6781    ///
6782    /// An arrow has none, so the search walks out to the enclosing method — the same
6783    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
6784    /// inside a method.
6785    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
6786        self.frames
6787            .iter()
6788            .rev()
6789            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6790    }
6791
6792    /// The dispose method a `using` declaration should snapshot, or an error.
6793    ///
6794    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
6795    /// is what makes a resource that only knows the synchronous protocol usable in both
6796    /// forms.
6797    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
6798        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
6799        if value.is_nullish() {
6800            return Ok(Value::Undefined);
6801        }
6802        let Some(object) = value.as_object() else {
6803            return Err(self.type_error("not an object"));
6804        };
6805        let mut method = if await_form {
6806            let found = self.get_property_key(
6807                object,
6808                &self.realm.well_known_key(WellKnown::AsyncDisposable),
6809            )?;
6810            match found {
6811                Some(found) if !found.is_nullish() => Some(found),
6812                _ => self
6813                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
6814            }
6815        } else {
6816            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
6817        };
6818        let Some(found) = method.take() else {
6819            return Err(self.type_error("value is not disposable"));
6820        };
6821        if found.is_nullish() {
6822            return Err(self.type_error("value is not disposable"));
6823        }
6824        let callable = found.as_object().is_some_and(|object| object.is_callable());
6825        if !callable {
6826            return Err(self.type_error("dispose method is not a function"));
6827        }
6828        Ok(found)
6829    }
6830
6831    /// Call one resource's disposer, folding a failure into `error_state`.
6832    ///
6833    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
6834    /// because a captured `using` binding lives in its reference cell and the local slot is
6835    /// stale — a closure over the resource is legal and must not change what is disposed.
6836    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
6837        let value = self.get_loc(slot);
6838        let method = self.get_loc(slot + 1);
6839        // A resource that was never initialised — its declaration threw — or that is
6840        // `null`/`undefined` has nothing to dispose.
6841        if value.is_nullish() || matches!(value, Value::Uninitialized) {
6842            return Ok(error_state);
6843        }
6844        if matches!(method, Value::Undefined | Value::Uninitialized) {
6845            return Ok(error_state);
6846        }
6847        match self.call_value(method, value, Vec::new()) {
6848            Ok(_) => Ok(error_state),
6849            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
6850            Err(other) => Err(other),
6851        }
6852    }
6853
6854    /// Combine a disposal failure with whatever was already going wrong.
6855    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
6856        if matches!(error_state, Value::Uninitialized) {
6857            return new_error;
6858        }
6859        self.new_suppressed_error(new_error, error_state)
6860    }
6861
6862    /// A `SuppressedError` instance built straight from its prototype.
6863    ///
6864    /// Not through the constructor: a script that rewrites
6865    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
6866    /// error wrapping.
6867    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
6868        let proto = self
6869            .realm
6870            .suppressed_error_proto
6871            .clone()
6872            .unwrap_or_else(|| self.realm.error_proto.clone());
6873        let object = self.new_object(Some(proto));
6874        object.define("error", Property::with_attributes(error, true, true));
6875        object.define(
6876            "suppressed",
6877            Property::with_attributes(suppressed, true, true),
6878        );
6879        object.define(
6880            "message",
6881            Property::with_attributes(self.string("SuppressedError"), true, true),
6882        );
6883        self.internal_set(&object, "_class", self.string("Error"));
6884        self.add_stack(&object);
6885        Value::Object(object)
6886    }
6887
6888    /// Call `callee`, or push its frame and let the main loop run it.
6889    ///
6890    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
6891    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
6892    /// continues, so `function f(){ return f() }` costs heap and stops at
6893    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
6894    /// is entered directly, and natives do not re-enter JavaScript in this
6895    /// milestone.
6896    ///
6897    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
6898    /// because the returning frame will.
6899    /// The elements of an array-like value, as a call argument list.
6900    ///
6901    /// `apply` accepts any array-like, not only a real array: the reference reads
6902    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
6903    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
6904        let Some(object) = value.as_object().cloned() else {
6905            if value.is_nullish() {
6906                // `f.apply(this, null)` passes no arguments at all.
6907                return Ok(Vec::new());
6908            }
6909            return Err(self.type_error("createListFromArrayLike called on non-object"));
6910        };
6911        let length = match self.get_property(&object, "length")? {
6912            Some(length) => length.to_number(),
6913            None => 0.0,
6914        };
6915        if !length.is_finite() || length <= 0.0 {
6916            return Ok(Vec::new());
6917        }
6918        let length = (length as usize).min(1_000_000);
6919        let mut args = Vec::with_capacity(length);
6920        for index in 0..length {
6921            let element = self.get_property(&object, &index.to_string())?;
6922            args.push(element.unwrap_or(Value::Undefined));
6923        }
6924        Ok(args)
6925    }
6926
6927    /// Turn a call to a generator function into a generator object.
6928    ///
6929    /// The frame is built exactly as an ordinary call would build it, then detached and
6930    /// stored in the generator before any body instruction runs — which is what makes
6931    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
6932    /// is `initial_yield`, the first instruction of every suspending body.
6933    pub fn new_generator(
6934        &mut self,
6935        function: Value,
6936        this: Value,
6937        args: Vec<Value>,
6938    ) -> JsResult<Value> {
6939        let Some(object) = function.as_object().cloned() else {
6940            return Err(self.type_error("not a generator function"));
6941        };
6942        let Some((code, env)) = bytecode_of(&object) else {
6943            return Err(self.type_error("not a generator function"));
6944        };
6945        let is_async = code.code.kind.is_async();
6946        self.push_frame(code, env, this, args, function)?;
6947        let frame = self.frames.pop().expect("push_frame just pushed it");
6948        // A fresh generator is *suspended at start*: the body has not run, so a
6949        // `return`/`throw` on it finishes without executing anything.
6950        let mut state = GeneratorState {
6951            frame: Some(frame),
6952            phase: GeneratorPhase::SuspendedStart,
6953            parked_on_await: false,
6954            parked_on_yield_star: false,
6955            requests: std::collections::VecDeque::new(),
6956            async_busy: false,
6957        };
6958        // Run to the first suspension. For a generator that is `initial_yield`, so no
6959        // body code runs; for a malformed body it would be the first `yield`.
6960        // An `async function*` answers an async generator: same coroutine, but its
6961        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
6962        let proto = if is_async {
6963            self.realm
6964                .async_generator_proto
6965                .clone()
6966                .unwrap_or_else(|| self.realm.generator_proto.clone())
6967        } else {
6968            self.realm.generator_proto.clone()
6969        };
6970        let generator = self.new_object(Some(proto));
6971        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
6972            Ok(_) => {}
6973            Err(error) => return Err(error),
6974        }
6975        generator.with_mut(|data| {
6976            data.kind = ObjectKind::Generator(Box::new(state));
6977        });
6978        Ok(Value::Object(generator))
6979    }
6980
6981    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
6982    ///
6983    /// Returns the `{value, done}` object itself rather than the pair, because a
6984    /// `yield*` suspension already has one — the inner iterator's own result — and the
6985    /// protocol says to hand that straight through rather than nest it.
6986    /// Advance a generator and report *why* it parked.
6987    ///
6988    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
6989    /// "hand this value to the caller" — but an async generator does: an `await` has to
6990    /// settle before it can answer, while a `yield` is the answer.
6991    fn resume_generator_detailed(
6992        &mut self,
6993        generator: &Gc<JsObject>,
6994        kind: ResumeKind,
6995        value: Value,
6996    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
6997        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
6998            ObjectKind::Generator(state) => Some(std::mem::replace(
6999                state.as_mut(),
7000                GeneratorState {
7001                    frame: None,
7002                    phase: GeneratorPhase::Executing,
7003                    parked_on_await: false,
7004                    parked_on_yield_star: false,
7005                    requests: std::collections::VecDeque::new(),
7006                    async_busy: false,
7007                },
7008            )),
7009            _ => None,
7010        }) else {
7011            return Err(self.type_error("not a generator"));
7012        };
7013        let result = self.step_generator(&mut state, kind, value);
7014        generator.with_mut(|data| {
7015            data.kind = ObjectKind::Generator(Box::new(state));
7016        });
7017        result
7018    }
7019
7020    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7021    ///
7022    /// Returns the `{value, done}` object itself rather than the pair, because a
7023    /// `yield*` suspension already has one — the inner iterator's own result — and the
7024    /// protocol says to hand that straight through rather than nest it.
7025    pub fn resume_generator(
7026        &mut self,
7027        generator: &Gc<JsObject>,
7028        kind: ResumeKind,
7029        value: Value,
7030    ) -> JsResult<Value> {
7031        let (value, done, ready, _reason) =
7032            self.resume_generator_detailed(generator, kind, value)?;
7033        if ready {
7034            return Ok(value);
7035        }
7036        self.iterator_result(value, done)
7037    }
7038
7039    /// `next`/`return`/`throw` on an async generator, which answer a promise.
7040    ///
7041    /// The body is the same coroutine a sync generator runs; what changes is that an
7042    /// `await` inside it has to settle before the method can answer, so the step is
7043    /// driven off the job queue rather than returning inline.
7044    pub fn resume_async_generator(
7045        &mut self,
7046        generator: &Gc<JsObject>,
7047        kind: ResumeKind,
7048        value: Value,
7049    ) -> JsResult<Value> {
7050        let promise = self.new_promise();
7051        // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
7052        // that order, and the second value must reach the *second* `yield`.
7053        let idle = generator.with_mut(|data| match &mut data.kind {
7054            ObjectKind::Generator(state) => {
7055                state.requests.push_back(AsyncRequest {
7056                    kind,
7057                    value,
7058                    promise: promise.clone(),
7059                });
7060                !state.async_busy
7061            }
7062            _ => false,
7063        });
7064        if idle {
7065            self.next_async_request(generator)?;
7066        }
7067        Ok(Value::Object(promise))
7068    }
7069
7070    /// Serve the front queued request, if the generator is free to run one.
7071    ///
7072    /// A finished generator answers from the queue without running anything:
7073    /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
7074    /// first, and `throw(e)` rejects.
7075    fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
7076        enum Front {
7077            Idle,
7078            Run(ResumeKind, Value, Gc<JsObject>),
7079            Finished(ResumeKind, Value, Gc<JsObject>),
7080        }
7081        let front = generator.with_mut(|data| match &mut data.kind {
7082            ObjectKind::Generator(state) => {
7083                let Some(request) = state.requests.front() else {
7084                    return Front::Idle;
7085                };
7086                // Busy means a request is still in flight — awaiting inside the body, not
7087                // finished. Serving another now would interleave two requests.
7088                if state.async_busy && state.phase != GeneratorPhase::Completed {
7089                    return Front::Idle;
7090                }
7091                let kind = request.kind;
7092                let value = request.value.clone();
7093                let promise = request.promise.clone();
7094                state.async_busy = true;
7095                if state.phase == GeneratorPhase::Completed {
7096                    Front::Finished(kind, value, promise)
7097                } else {
7098                    Front::Run(kind, value, promise)
7099                }
7100            }
7101            _ => Front::Idle,
7102        });
7103        match front {
7104            Front::Idle => Ok(()),
7105            Front::Run(kind, value, promise) => {
7106                self.step_async_generator(generator, &promise, kind, value)
7107            }
7108            Front::Finished(kind, value, promise) => match kind {
7109                ResumeKind::Throw => {
7110                    self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
7111                }
7112                ResumeKind::Next | ResumeKind::Start => {
7113                    let result = self.iterator_result(Value::Undefined, true)?;
7114                    self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
7115                }
7116                ResumeKind::Return => {
7117                    // `js_async_generator_completed_return`: the value is awaited before it
7118                    // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
7119                    // finished generator answers `1`, not a promise.
7120                    let resolved = match self.promise_resolve_value(value) {
7121                        Ok(resolved) => resolved,
7122                        Err(Signal::Throw(reason)) => {
7123                            return self.settle_async_request(
7124                                generator,
7125                                &promise,
7126                                AsyncOutcome::Error(reason),
7127                            );
7128                        }
7129                        Err(other) => return Err(other),
7130                    };
7131                    let done = JsObject::function(
7132                        self.heap,
7133                        Some(self.realm.function_proto.clone()),
7134                        Callable::CompletedReturn {
7135                            generator: generator.clone(),
7136                            promise: promise.clone(),
7137                            rejected: false,
7138                        },
7139                    );
7140                    let failed = JsObject::function(
7141                        self.heap,
7142                        Some(self.realm.function_proto.clone()),
7143                        Callable::CompletedReturn {
7144                            generator: generator.clone(),
7145                            promise: promise.clone(),
7146                            rejected: true,
7147                        },
7148                    );
7149                    let Value::Object(resolved) = resolved else {
7150                        return self.settle_async_request(
7151                            generator,
7152                            &promise,
7153                            AsyncOutcome::Error(Value::Undefined),
7154                        );
7155                    };
7156                    self.perform_then(
7157                        &resolved,
7158                        Some(Value::Object(done)),
7159                        Some(Value::Object(failed)),
7160                    )?;
7161                    Ok(())
7162                }
7163            },
7164        }
7165    }
7166
7167    /// Settle the front request and start the next one.
7168    ///
7169    /// Every path out of [`Interp::step_async_generator`] goes through here, so the
7170    /// "busy" flag and the queue cannot drift: a promise settled without releasing the
7171    /// generator would strand every later request.
7172    fn settle_async_request(
7173        &mut self,
7174        generator: &Gc<JsObject>,
7175        promise: &Gc<JsObject>,
7176        outcome: AsyncOutcome,
7177    ) -> JsResult<()> {
7178        let settled = generator.with_mut(|data| match &mut data.kind {
7179            ObjectKind::Generator(state) => {
7180                let front = state.requests.front();
7181                debug_assert!(
7182                    front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
7183                    "a request settled outside its turn"
7184                );
7185                state.requests.pop_front();
7186                state.async_busy = false;
7187                true
7188            }
7189            _ => false,
7190        });
7191        if settled {
7192            match outcome {
7193                AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
7194                AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
7195            }
7196        }
7197        self.next_async_request(generator)
7198    }
7199
7200    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
7201    ///
7202    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
7203    /// disposer runs **synchronously** — the reference starts it before returning, which
7204    /// a test can observe by logging after the call — and the rest follow once their
7205    /// predecessor settles.
7206    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
7207        let promise = self.new_promise();
7208        let mut pairs = Vec::with_capacity(resources.len());
7209        for (value, method) in resources {
7210            let pair = self.new_array(vec![value, method]);
7211            pairs.push(Value::Object(pair));
7212        }
7213        let remaining = self.new_array(pairs);
7214        self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
7215        Ok(Value::Object(promise))
7216    }
7217
7218    /// One link of the `disposeAsync` chain.
7219    ///
7220    /// Loops while the disposers finish synchronously, and parks on the first thenable it
7221    /// meets — pushing itself back in as the continuation, with the accumulated error
7222    /// carried along so a later failure can still be folded into the `SuppressedError`.
7223    fn dispose_step(
7224        &mut self,
7225        remaining: &Gc<JsObject>,
7226        promise: &Gc<JsObject>,
7227        mut error: Value,
7228    ) -> JsResult<()> {
7229        loop {
7230            let length = remaining.array_length().unwrap_or(0);
7231            if length == 0 {
7232                if matches!(error, Value::Uninitialized) {
7233                    self.fulfill_promise(promise, Value::Undefined);
7234                } else {
7235                    self.reject_promise(promise, error);
7236                }
7237                return Ok(());
7238            }
7239            let Some(Value::Object(pair)) = remaining
7240                .array_get(length - 1)
7241                .filter(|v| !matches!(v, Value::Hole))
7242            else {
7243                remaining.array_truncate(self.heap, length - 1);
7244                continue;
7245            };
7246            remaining.array_truncate(self.heap, length - 1);
7247            let value = pair.array_get(0).unwrap_or(Value::Undefined);
7248            let Some(Value::Object(method)) = pair.array_get(1) else {
7249                continue;
7250            };
7251            if !method.is_callable() {
7252                continue;
7253            }
7254            match self.call_value(Value::Object(method), value, Vec::new()) {
7255                Ok(result) => {
7256                    if !self.is_thenable(&result)? {
7257                        // Finished synchronously; the next disposer is the next iteration.
7258                        continue;
7259                    }
7260                    let awaited = match self.promise_resolve_value(result) {
7261                        Ok(awaited) => awaited,
7262                        Err(Signal::Throw(reason)) => {
7263                            self.reject_promise(promise, reason);
7264                            return Ok(());
7265                        }
7266                        Err(other) => return Err(other),
7267                    };
7268                    let Value::Object(awaited) = awaited else {
7269                        continue;
7270                    };
7271                    let ok = JsObject::function(
7272                        self.heap,
7273                        Some(self.realm.function_proto.clone()),
7274                        Callable::DisposeStep {
7275                            remaining: remaining.clone(),
7276                            promise: promise.clone(),
7277                            error: error.clone(),
7278                            rejected: false,
7279                        },
7280                    );
7281                    let failed = JsObject::function(
7282                        self.heap,
7283                        Some(self.realm.function_proto.clone()),
7284                        Callable::DisposeStep {
7285                            remaining: remaining.clone(),
7286                            promise: promise.clone(),
7287                            error,
7288                            rejected: true,
7289                        },
7290                    );
7291                    self.perform_then(
7292                        &awaited,
7293                        Some(Value::Object(ok)),
7294                        Some(Value::Object(failed)),
7295                    )?;
7296                    return Ok(());
7297                }
7298                Err(Signal::Throw(thrown)) => {
7299                    error = self.merge_dispose_error(thrown, error);
7300                }
7301                Err(other) => return Err(other),
7302            }
7303        }
7304    }
7305
7306    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
7307    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
7308        let Value::Object(object) = value else {
7309            return Ok(false);
7310        };
7311        Ok(matches!(
7312            self.get_property(object, "then")?,
7313            Some(Value::Object(then)) if then.is_callable()
7314        ))
7315    }
7316
7317    /// One step of an async generator, settling `promise` with an `{value, done}` result.
7318    fn step_async_generator(
7319        &mut self,
7320        generator: &Gc<JsObject>,
7321        promise: &Gc<JsObject>,
7322        kind: ResumeKind,
7323        value: Value,
7324    ) -> JsResult<()> {
7325        let stepped = self.resume_generator_detailed(generator, kind, value);
7326        let (value, done, ready, reason) = match stepped {
7327            Ok(stepped) => stepped,
7328            Err(Signal::Throw(reason)) => {
7329                return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
7330            }
7331            Err(other) => return Err(other),
7332        };
7333        // Only an `await` has to wait before the method can answer.
7334        if !done && reason == Some(SuspendKind::Await) {
7335            let awaited = match self.promise_resolve_value(value) {
7336                Ok(awaited) => awaited,
7337                Err(Signal::Throw(reason)) => {
7338                    return self.settle_async_request(
7339                        generator,
7340                        promise,
7341                        AsyncOutcome::Error(reason),
7342                    );
7343                }
7344                Err(other) => return Err(other),
7345            };
7346            let Value::Object(awaited) = awaited else {
7347                return Ok(());
7348            };
7349            let resumed = JsObject::function(
7350                self.heap,
7351                Some(self.realm.function_proto.clone()),
7352                Callable::GeneratorResume {
7353                    generator: generator.clone(),
7354                    promise: promise.clone(),
7355                    kind: ResumeKind::Next,
7356                },
7357            );
7358            let raised = JsObject::function(
7359                self.heap,
7360                Some(self.realm.function_proto.clone()),
7361                Callable::GeneratorResume {
7362                    generator: generator.clone(),
7363                    promise: promise.clone(),
7364                    kind: ResumeKind::Throw,
7365                },
7366            );
7367            self.perform_then(
7368                &awaited,
7369                Some(Value::Object(resumed)),
7370                Some(Value::Object(raised)),
7371            )?;
7372            return Ok(());
7373        }
7374        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
7375        // completes it — both arrive as the settled value rather than as the promise
7376        // object. A plain value skips the round trip, which is also what keeps `yield 1`
7377        // from costing an extra tick.
7378        let awaits_value = self.is_thenable(&value)?;
7379        if awaits_value {
7380            let awaited = match self.promise_resolve_value(value) {
7381                Ok(awaited) => awaited,
7382                Err(Signal::Throw(reason)) => {
7383                    return self.settle_async_request(
7384                        generator,
7385                        promise,
7386                        AsyncOutcome::Error(reason),
7387                    );
7388                }
7389                Err(other) => return Err(other),
7390            };
7391            let Value::Object(awaited) = awaited else {
7392                return Ok(());
7393            };
7394            // A rejected yield throws *at the yield* inside the body, so the rejection
7395            // resumes the generator rather than the method's promise.
7396            let answer = JsObject::function(
7397                self.heap,
7398                Some(self.realm.function_proto.clone()),
7399                Callable::YieldResult {
7400                    generator: generator.clone(),
7401                    promise: promise.clone(),
7402                    done,
7403                },
7404            );
7405            let raise = JsObject::function(
7406                self.heap,
7407                Some(self.realm.function_proto.clone()),
7408                Callable::GeneratorResume {
7409                    generator: generator.clone(),
7410                    promise: promise.clone(),
7411                    kind: ResumeKind::Throw,
7412                },
7413            );
7414            self.perform_then(
7415                &awaited,
7416                Some(Value::Object(answer)),
7417                Some(Value::Object(raise)),
7418            )?;
7419            return Ok(());
7420        }
7421        let result = if ready {
7422            // `yield*` handed back the inner iterator's own result object.
7423            value
7424        } else {
7425            self.iterator_result(value, done)?
7426        };
7427        self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
7428    }
7429
7430    /// The `{value, done}` object an iterator method answers with.
7431    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
7432        let result = self.new_object(Some(self.realm.object_proto.clone()));
7433        result.define_data("value", value);
7434        result.define_data("done", Value::Bool(done));
7435        Ok(Value::Object(result))
7436    }
7437
7438    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
7439    fn step_generator(
7440        &mut self,
7441        state: &mut GeneratorState,
7442        kind: ResumeKind,
7443        value: Value,
7444    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7445        match state.phase {
7446            GeneratorPhase::Executing => {
7447                return Err(self.type_error("cannot invoke a running generator"));
7448            }
7449            GeneratorPhase::Completed => {
7450                // A finished generator answers every resumption without running.
7451                return Ok(match kind {
7452                    ResumeKind::Throw => return Err(Signal::Throw(value)),
7453                    ResumeKind::Return => (value, true, false, None),
7454                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
7455                });
7456            }
7457            GeneratorPhase::SuspendedStart => {
7458                if kind != ResumeKind::Next && kind != ResumeKind::Start {
7459                    // The body never started, so there is nothing to unwind or return
7460                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
7461                    state.frame = None;
7462                    state.phase = GeneratorPhase::Completed;
7463                    return Ok(match kind {
7464                        ResumeKind::Throw => return Err(Signal::Throw(value)),
7465                        _ => (value, true, false, None),
7466                    });
7467                }
7468            }
7469            GeneratorPhase::SuspendedYield => {}
7470        }
7471
7472        let Some(mut frame) = state.frame.take() else {
7473            return Ok((Value::Undefined, true, false, None));
7474        };
7475        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
7476        // number that says which method resumed it; the emitted `if_false` branches on
7477        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
7478        let mut raised = None;
7479        match kind {
7480            ResumeKind::Next | ResumeKind::Start => {
7481                if state.phase == GeneratorPhase::SuspendedYield {
7482                    frame.stack.push(value);
7483                    // An `await` resumes with its value alone; only a `yield` gets the
7484                    // magic number that says which of `next`/`return` resumed it.
7485                    if !state.parked_on_await {
7486                        frame.stack.push(Value::Int(RESUME_NEXT));
7487                    }
7488                }
7489            }
7490            ResumeKind::Return => {
7491                // A `return` on a not-yet-started generator is handled above, so this is
7492                // always a real resumption.
7493                frame.stack.push(value);
7494                frame.stack.push(Value::Int(RESUME_RETURN));
7495            }
7496            ResumeKind::Throw => {
7497                // At a `yield*` the exception is *data* for the delegation: the compiled
7498                // code resumes with the value and magic `2` and calls the inner iterator's
7499                // `throw`. Everywhere else it is raised at the suspension point, so the
7500                // body's own handler sees it.
7501                if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
7502                    frame.stack.push(value);
7503                    frame.stack.push(Value::Int(RESUME_THROW));
7504                } else {
7505                    raised = Some(value);
7506                }
7507            }
7508        }
7509        state.phase = GeneratorPhase::Executing;
7510
7511        let depth = self.frames.len();
7512        self.frames.push(frame);
7513        // A `throw` unwinds from where the frame parked, exactly as if the exception had
7514        // happened at the `yield`.
7515        if let Some(exception) = raised {
7516            if self.catch_here(exception.clone()).is_none() {
7517                self.pop_frame();
7518                state.phase = GeneratorPhase::Completed;
7519                return Err(Signal::Throw(exception));
7520            }
7521        }
7522
7523        // Only the generator's *own* frame ends the generator. The body may call ordinary
7524        // functions, and those push frames of their own: a `Step::Return` from one of them
7525        // is a nested call finishing, not the generator completing. Miscounting that is
7526        // silent — the generator reports the callee's value as its own result and marks
7527        // itself done — so the depth comparison is load-bearing, not defensive.
7528        let own_frame = depth + 1;
7529        loop {
7530            match self.step() {
7531                Ok(Step::Continue) => {}
7532                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
7533                    let mut frame = self.frames.pop().expect("a frame is live");
7534                    // `yield` left the value on the stack; `initial_yield` left nothing.
7535                    let yielded = if reason == SuspendKind::Initial {
7536                        Value::Undefined
7537                    } else {
7538                        frame.stack.pop().unwrap_or(Value::Undefined)
7539                    };
7540                    state.frame = Some(frame);
7541                    state.parked_on_await = reason == SuspendKind::Await;
7542                    state.parked_on_yield_star =
7543                        matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
7544                    state.phase = if reason == SuspendKind::Initial {
7545                        GeneratorPhase::SuspendedStart
7546                    } else {
7547                        GeneratorPhase::SuspendedYield
7548                    };
7549                    // `yield*` hands the inner iterator's own result object straight
7550                    // back, so the caller sees one `{value, done}` rather than a nested
7551                    // one — which is why the third field says "already a result".
7552                    return Ok((
7553                        yielded,
7554                        false,
7555                        reason == SuspendKind::YieldStar,
7556                        Some(reason),
7557                    ));
7558                }
7559                Ok(Step::Suspend(_)) => {
7560                    // A `yield` in a frame other than the generator's would mean a
7561                    // generator body entered as an ordinary call, which
7562                    // `call_or_push` prevents.
7563                    self.unwind_to(depth);
7564                    state.phase = GeneratorPhase::Completed;
7565                    return Err(Signal::Throw(self.make_error(
7566                        "InternalError",
7567                        "a generator body ran as an ordinary call",
7568                    )));
7569                }
7570                Ok(Step::Return(value)) => {
7571                    self.pop_frame();
7572                    if self.frames.len() > depth {
7573                        // A nested call finished: hand the value back to its caller and
7574                        // keep running the generator body.
7575                        self.frames
7576                            .last_mut()
7577                            .expect("a caller is live")
7578                            .stack
7579                            .push(value);
7580                        continue;
7581                    }
7582                    state.phase = GeneratorPhase::Completed;
7583                    // The reference closes the generator's closure variables here; ours
7584                    // live in cells the frame owned, which the drop below releases.
7585                    return Ok((value, true, false, None));
7586                }
7587                Err(Signal::Throw(exception)) => {
7588                    // The frame that threw gets the first chance to catch, exactly as in
7589                    // the ordinary call loop; a frame above the generator's is popped and
7590                    // the exception carries on down.
7591                    let exception = exception;
7592                    loop {
7593                        if self.frames.len() <= depth {
7594                            // The generator's own frame is gone, so nothing here caught it.
7595                            state.phase = GeneratorPhase::Completed;
7596                            return Err(Signal::Throw(exception));
7597                        }
7598                        if self.catch_here(exception.clone()).is_some() {
7599                            break;
7600                        }
7601                        self.pop_frame();
7602                    }
7603                }
7604                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
7605            }
7606        }
7607    }
7608
7609    /// Pop frames until `depth` are left, keeping their buffers.
7610    fn unwind_to(&mut self, depth: usize) {
7611        while self.frames.len() > depth {
7612            self.pop_frame();
7613        }
7614    }
7615    fn call_or_push(
7616        &mut self,
7617        callee: Value,
7618        this: Value,
7619        args: Vec<Value>,
7620    ) -> JsResult<Option<Value>> {
7621        if let Value::Object(function) = &callee
7622            && let Some((code, env)) = bytecode_of(function)
7623        {
7624            // Calling a generator function does not run anything: it captures the
7625            // arguments in a frame and hands back the generator object.
7626            if code.code.kind.is_generator() {
7627                return self.new_generator(callee, this, args).map(Some);
7628            }
7629            // An async function answers a promise and runs its body as a coroutine, so it
7630            // takes the same path as a plain call into it.
7631            if code.code.kind.is_async() {
7632                return self.new_async_function(callee, this, args).map(Some);
7633            }
7634            self.push_frame(code, env, this, args, callee)?;
7635            return Ok(None);
7636        }
7637        self.call_value(callee, this, args).map(Some)
7638    }
7639
7640    /// `new callee(args)`.
7641    ///
7642    /// A constructor differs from a plain call in three ways: it gets a fresh object
7643    /// as `this` whose prototype is the constructor's `prototype` property, its
7644    /// return value is *replaced* by that object unless it returns an object itself,
7645    /// and a native constructor is expected to initialise the object it is given
7646    /// rather than build one.
7647    pub fn construct(
7648        &mut self,
7649        callee: Value,
7650        new_target: Value,
7651        args: Vec<Value>,
7652    ) -> JsResult<Value> {
7653        // `new` on a bound function constructs its *target*, prepending the arguments
7654        // the bind fixed and ignoring the bound `this` — a bound function is a
7655        // constructor only when its target is one, and `new` always makes a fresh
7656        // object of the target's prototype rather than reusing the bound receiver.
7657        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
7658        // ran the body with `this === null` and threw on `this.x = a`.
7659        let mut callee = callee;
7660        let mut new_target = new_target;
7661        let mut args = args;
7662        loop {
7663            let Some(object) = callee.as_object().cloned() else {
7664                return Err(Signal::Throw(
7665                    self.make_error("TypeError", "not a constructor"),
7666                ));
7667            };
7668            // A proxy of a function constructs through its `construct` trap, and the
7669            // trap's answer is the result directly — no fresh object is made here.
7670            if object.proxy_state().is_some() {
7671                return match self.proxy_construct(&object, args, &new_target)? {
7672                    Some(result) => Ok(result),
7673                    None => Err(Signal::Throw(
7674                        self.make_error("TypeError", "proxy target is not a constructor"),
7675                    )),
7676                };
7677            }
7678            // A generator function has no `[[Construct]]`, and the reference names it in
7679            // the message: `new (function* G(){})()` reports "G is not a constructor".
7680            if object.with(|data| match &data.kind {
7681                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
7682                    code.code.kind.is_generator()
7683                }
7684                _ => false,
7685            }) {
7686                let name = object
7687                    .own_property("name")
7688                    .and_then(|property| property.value)
7689                    .map(|value| value.to_js_string())
7690                    .unwrap_or_default();
7691                return Err(Signal::Throw(
7692                    self.make_error("TypeError", &format!("{name} is not a constructor")),
7693                ));
7694            }
7695            let bound = object.with(|data| match &data.kind {
7696                ObjectKind::Function(Callable::Bound {
7697                    target,
7698                    args: leading,
7699                    ..
7700                }) => Some((target.clone(), leading.clone())),
7701                _ => None,
7702            });
7703            let Some((target, leading)) = bound else {
7704                // Not a bound function, so this object is the callee. §7.2.4
7705                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
7706                // refusals above cover only the built-ins the reference also refuses by
7707                // name. Everything else — a method, an arrow, an async function — has no
7708                // `[[Construct]]` either, and answering "yes" here made
7709                // `new (Array.prototype.map)` build an object instead of throwing.
7710                if !object.is_constructor() {
7711                    let name = object
7712                        .own_property("name")
7713                        .and_then(|property| property.value)
7714                        .map(|value| value.to_js_string())
7715                        .unwrap_or_default();
7716                    return Err(Signal::Throw(
7717                        self.make_error("TypeError", &format!("{name} is not a constructor")),
7718                    ));
7719                }
7720                break;
7721            };
7722            let mut all = leading;
7723            all.extend(args);
7724            args = all;
7725            // A bound function that is its own `new.target` stands in for its target:
7726            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
7727            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
7728            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
7729                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
7730                _ => false,
7731            };
7732            if same_wrapper {
7733                new_target = target.clone();
7734            }
7735            callee = target;
7736        }
7737        let Value::Object(function) = &callee else {
7738            unreachable!("the loop above only breaks on an object");
7739        };
7740        // The fresh object's prototype comes from `new.target`, not from the callee: a
7741        // derived constructor reaches here through `super()`, and the instance must be a
7742        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
7743        // an object inheriting `D.prototype` rather than `C.prototype`.
7744        let prototype_source = match new_target.as_object() {
7745            Some(target) => target.clone(),
7746            None => function.clone(),
7747        };
7748        // A native constructor builds its own instance, through `new_ctor_instance`, once it
7749        // has validated its arguments. Pre-building one here would read
7750        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
7751        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
7752        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
7753        let is_native = function.native_creates_own_instance();
7754        let this = if is_native {
7755            Value::Undefined
7756        } else {
7757            let prototype = self.get_property(&prototype_source, "prototype")?;
7758            let prototype = match prototype {
7759                Some(Value::Object(proto)) => Some(proto),
7760                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
7761                // object, the answer is the realm's *intrinsic* prototype for this
7762                // constructor, not `%Object.prototype%`.
7763                _ => {
7764                    let fallback = self.get_property(function, "prototype")?;
7765                    match fallback {
7766                        Some(Value::Object(proto)) => Some(proto),
7767                        _ => Some(self.realm.object_proto.clone()),
7768                    }
7769                }
7770            };
7771            Value::Object(self.new_object(prototype))
7772        };
7773        // `new.target` inside the body is the constructor that was written, so a bound
7774        // function's target sees itself rather than the bound wrapper.
7775        //
7776        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
7777        // `?`, so assigning `None` after the call would be skipped and the failed
7778        // `new.target` would stay visible to every later native call. The symptom was a
7779        // native constructor refusing a plain call — `var s = Symbol(); new
7780        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
7781        // "FinalizationRegistry is not a constructor".
7782        let outer_new_target = self.pending_new_target.replace(new_target);
7783        let result = self.call_value(callee, this.clone(), args);
7784        self.pending_new_target = outer_new_target;
7785        let result = result?;
7786        // A constructor that returns an object overrides `this`; any other return
7787        // value (including `undefined`) is ignored.
7788        Ok(match result {
7789            Value::Object(_) => result,
7790            _ => this,
7791        })
7792    }
7793
7794    /// `new.target` for the call currently being made.
7795    ///
7796    /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
7797    /// it as `this`), but a *host* constructor that builds its own instance is handed
7798    /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
7799    /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
7800    /// it here.
7801    ///
7802    /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
7803    /// receives for a plain call.
7804    pub fn current_new_target(&self) -> Value {
7805        self.pending_new_target.clone().unwrap_or(Value::Undefined)
7806    }
7807
7808    /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
7809    ///
7810    /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
7811    /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
7812    pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
7813        let constructor = self.realm.errors.get("AggregateError").cloned();
7814        let Some(constructor) = constructor else {
7815            return self.make_error("AggregateError", message);
7816        };
7817        let list = self.new_array(errors);
7818        match self.construct(
7819            Value::Object(constructor.clone()),
7820            Value::Object(constructor),
7821            vec![Value::Object(list), self.string(message)],
7822        ) {
7823            Ok(value) => value,
7824            // A user could have replaced `AggregateError` with something that throws; the
7825            // engine still owes the caller a rejection, so it falls back rather than
7826            // turning `Promise.any`'s rejection into a throw.
7827            Err(_) => self.make_error("AggregateError", message),
7828        }
7829    }
7830
7831    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
7832    ///
7833    /// The error classes themselves arrive with the builtins milestone; what
7834    /// matters here is that the thrown value stringifies the way a script printing
7835    /// the caught value expects.
7836    ///
7837    /// `name` and `message` become own properties, which is what makes `e.name` cheap and
7838    /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
7839    /// rely on when they print a caught value.
7840    pub fn make_error(&self, name: &str, message: &str) -> Value {
7841        let proto = self
7842            .realm
7843            .errors
7844            .get(name)
7845            .map(|constructor| self.prototype_of(constructor))
7846            .unwrap_or_else(|| self.realm.error_proto.clone());
7847        let error = self.new_object(Some(proto));
7848        // `name` and `message` are own properties of the instance, which is what
7849        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
7850        // `Error`.
7851        error.define(
7852            "name",
7853            Property::with_attributes(self.string(name), true, false),
7854        );
7855        error.define(
7856            "message",
7857            Property::with_attributes(self.string(message), true, false),
7858        );
7859        // The internal class, which is what tells a printer this is an error rather than a
7860        // plain object with `name` and `message` properties. The constructor path sets it
7861        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
7862        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
7863        // literally `"Error"` in both places — the *name* is read from `name`, which is why
7864        // a `RangeError` still prints as `RangeError`.
7865        self.internal_set(&error, "_class", self.string("Error"));
7866        // The trace is captured where the error is *made*, which is where the reference
7867        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
7868        // way out, so a caught engine error already has its stack even if the handler
7869        // never rethrows it.
7870        self.add_stack(&error);
7871        Value::Object(error)
7872    }
7873
7874    /// Give an error object its `stack` property, from the current frame stack.
7875    ///
7876    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
7877    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
7878    /// `stack` a script set, is not rewritten.
7879    pub fn add_stack(&self, object: &Gc<JsObject>) {
7880        self.add_stack_skipping(object, 0);
7881    }
7882
7883    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
7884    ///
7885    /// An `Error` constructor passes 1: the reference builds those traces with
7886    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
7887    /// constructor itself, while a `RangeError` raised inside `toISOString` does
7888    /// report `at toISOString (native)`.
7889    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
7890        if object.has_own("stack") {
7891            return;
7892        }
7893        let trace = self.stack_trace_skipping(skip);
7894        let text = self.string(trace);
7895        object.define("stack", Property::with_attributes(text, true, true));
7896    }
7897
7898    /// The function object currently being called, if any.
7899    ///
7900    /// A native function is a bare `fn` pointer, so it cannot capture which class
7901    /// it belongs to; it reads that from the callee instead. This is also what a
7902    /// stack trace would use.
7903    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
7904        match &self.frames.last()?.callee {
7905            Value::Object(object) => Some(object.clone()),
7906            _ => None,
7907        }
7908    }
7909
7910    /// The `prototype` property of a constructor, falling back to
7911    /// `Object.prototype` for anything that is not shaped like one.
7912    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
7913        constructor
7914            .own_property("prototype")
7915            .and_then(|property| property.value)
7916            .and_then(|value| value.as_object().cloned())
7917            .unwrap_or_else(|| self.realm.object_proto.clone())
7918    }
7919
7920    /// Throw a `TypeError` carrying `message`.
7921    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
7922        Signal::Throw(self.make_error("TypeError", message.as_ref()))
7923    }
7924
7925    /// Throw a `RangeError` carrying `message`.
7926    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
7927        Signal::Throw(self.make_error("RangeError", message.as_ref()))
7928    }
7929
7930    /// The `ReferenceError` a read of an uninitialised binding raises.
7931    /// The name of the binding `slot` refers to, for an error message.
7932    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
7933        match kind {
7934            VarSlot::Loc => self
7935                .frame()
7936                .code
7937                .code
7938                .vars
7939                .get(slot)
7940                .map(|v| v.name.clone()),
7941            VarSlot::Closure => self
7942                .frame()
7943                .code
7944                .code
7945                .closure_vars
7946                .get(slot)
7947                .map(|c| c.name.clone()),
7948        }
7949        .unwrap_or_default()
7950    }
7951
7952    /// Whether `slot` names a `const` binding, which rejects every store after its
7953    /// initialiser.
7954    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
7955        match kind {
7956            VarSlot::Loc => self
7957                .frame()
7958                .code
7959                .code
7960                .vars
7961                .get(slot)
7962                .is_some_and(|v| v.is_const),
7963            VarSlot::Closure => self
7964                .frame()
7965                .code
7966                .code
7967                .closure_vars
7968                .get(slot)
7969                .is_some_and(|c| c.is_const),
7970        }
7971    }
7972
7973    /// The `TypeError` a store to a `const` binding raises.
7974    ///
7975    /// `const` is enforced here rather than at compile time because the binding can be
7976    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
7977    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
7978    /// both halves of what "checked store" means: the dead zone is over, and the
7979    /// binding is writable.
7980    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
7981        let name = self.binding_name(slot, kind);
7982        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
7983    }
7984
7985    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
7986        let name = match kind {
7987            VarSlot::Loc => self
7988                .frame()
7989                .code
7990                .code
7991                .vars
7992                .get(slot)
7993                .map(|v| v.name.clone()),
7994            VarSlot::Closure => self
7995                .frame()
7996                .code
7997                .code
7998                .closure_vars
7999                .get(slot)
8000                .map(|c| c.name.clone()),
8001        }
8002        .unwrap_or_default();
8003        Signal::Throw(self.make_error(
8004            "ReferenceError",
8005            &format!("cannot access '{name}' before initialization"),
8006        ))
8007    }
8008
8009    fn throw_reference(&self, name: &str) -> Signal {
8010        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
8011    }
8012
8013    // -- the instruction loop -----------------------------------------------
8014
8015    // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
8016    // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
8017    // measured at 16% of a tight arithmetic loop's total time.
8018    #[inline(always)]
8019    fn step(&mut self) -> JsResult<Step> {
8020        // The instruction is already decoded (see [`crate::insn`]), so this is an index
8021        // and a `Copy` read rather than a table lookup plus a width switch. Only the
8022        // borrow lives across the boundary; nothing is cloned.
8023        // **One** borrow of the frame: fetch the record, then advance in the same scope.
8024        // The obvious version borrowed it three times (`last` to read, `last_mut` to
8025        // write, and once more inside the handler), and each is a bounds check plus an
8026        // `Option` unwrap — on the one path every instruction takes.
8027        let Some((insn, next)) = ({
8028            let frame = self
8029                .frames
8030                .last_mut()
8031                .expect("step() is only called with a live frame");
8032            // Past the last instruction is a normal return: the compiler ends a function
8033            // with `return`, and a jump to the end of a block lands here.
8034            let insn = frame.insns().get(frame.pc).copied();
8035            match insn {
8036                None => None,
8037                Some(insn) => {
8038                    // A fused record stands for the next few instructions, so the next
8039                    // `pc` is its width ahead — the instructions it replaces are never
8040                    // dispatched. `at` is the byte offset a stack trace reports; it stays
8041                    // an offset because the line table is keyed by bytes.
8042                    frame.at = insn.offset as usize;
8043                    frame.pc += insn.width();
8044                    Some((insn, frame.pc))
8045                }
8046            }
8047        }) else {
8048            return Ok(Step::Return(Value::Undefined));
8049        };
8050        self.check_memory()?;
8051        self.check_interrupt()?;
8052        if insn.fused == crate::insn::Fused::None {
8053            self.execute_instruction(insn.op, insn.a, insn.b, next)
8054        } else {
8055            self.execute_fused(insn)
8056        }
8057    }
8058
8059    /// Run a fused instruction: several bytecode instructions in one dispatch.
8060    ///
8061    /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
8062    /// it cannot throw and cannot allocate — and anything else falls back to the real
8063    /// instructions, in their real order, so an exception leaves the operand stack
8064    /// exactly as it would have been.
8065    #[inline]
8066    fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
8067        use crate::insn::Fused;
8068        let slot = insn.a as usize;
8069        match insn.fused {
8070            // `x = k`: `push k; put_loc x`.
8071            Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
8072            // `x += k`: `get_loc x; push k; add; put_loc x`.
8073            Fused::AddImmLoc => {
8074                let delta = insn.b as i32;
8075                match self.get_loc(slot) {
8076                    Value::Int(left) => {
8077                        // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
8078                        // that built two `Value`s, called a function, and matched on them
8079                        // again to reach this same `checked_add`. It is the innermost
8080                        // operation of every accumulator in every program.
8081                        let answer = match left.checked_add(delta) {
8082                            Some(sum) => Value::Int(sum),
8083                            None => Value::Float(left as f64 + delta as f64),
8084                        };
8085                        self.put_loc(slot, answer);
8086                    }
8087                    other => {
8088                        self.push(other);
8089                        self.push(Value::Int(delta));
8090                        self.binary_add()?;
8091                        let value = self.pop();
8092                        self.put_loc(slot, value);
8093                    }
8094                }
8095            }
8096            // `x += "literal"` and `x += y`: the two shapes that can append in place.
8097            Fused::AddAtomLoc => {
8098                let text = self.atom_wtf8(insn.b as usize);
8099                let right = self.string_wtf8(text);
8100                self.add_into_loc(slot, right)?;
8101            }
8102            Fused::AddLocLoc => {
8103                let source = (insn.a & 0xFFFF) as usize;
8104                let target = (insn.a >> 16) as usize;
8105                let right = self.get_loc(source);
8106                self.add_into_loc(target, right)?;
8107            }
8108            Fused::AddArgLoc => {
8109                let source = (insn.a & 0xFFFF) as usize;
8110                let target = (insn.a >> 16) as usize;
8111                let right = self.get_arg(source);
8112                self.add_into_loc(target, right)?;
8113            }
8114            // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
8115            Fused::PostIncLoc => match self.get_loc(slot) {
8116                Value::Int(left) => {
8117                    let answer = match left.checked_add(1) {
8118                        Some(sum) => Value::Int(sum),
8119                        None => Value::Float(left as f64 + 1.0),
8120                    };
8121                    self.put_loc(slot, answer);
8122                }
8123                other => {
8124                    self.push(other);
8125                    let raw = self.pop();
8126                    let (old, updated) = self.advance_numeric(raw, true)?;
8127                    self.push(old);
8128                    self.push(updated);
8129                    let value = self.pop();
8130                    self.put_loc(slot, value);
8131                    self.pop();
8132                }
8133            },
8134            // `if (!(x < arg)) goto target`: a loop header.
8135            //
8136            // The comparison is computed rather than replayed on the operand stack. That
8137            // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
8138            // that throws: the effects happen in the same order, and a handler truncates
8139            // the stack down to its marker, so the intermediate values are unobservable.
8140            Fused::LtLocArgJump => {
8141                let loc = (insn.a >> 16) as usize;
8142                let arg = (insn.a & 0xFFFF) as usize;
8143                let left = self.get_loc(loc);
8144                let right = self.get_arg(arg);
8145                let taken = match (&left, &right) {
8146                    (Value::Int(left), Value::Int(right)) => !(left < right),
8147                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8148                };
8149                if taken {
8150                    self.frame_mut().pc = insn.b as usize;
8151                }
8152            }
8153            // `i < k` in a loop header, where `k` is an integer literal.
8154            Fused::LtLocImmJump => {
8155                let left = self.get_loc(insn.a as usize);
8156                let right = Value::Int(insn.imm as i32);
8157                let taken = match &left {
8158                    Value::Int(left) => !(*left < insn.imm as i32),
8159                    _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8160                };
8161                if taken {
8162                    self.frame_mut().pc = insn.b as usize;
8163                }
8164            }
8165            Fused::None => unreachable!("only called for a fused record"),
8166        }
8167        Ok(Step::Continue)
8168    }
8169
8170    /// Run records that cannot call script, cannot throw and cannot change frames.
8171    ///
8172    /// Returns `Some(value)` when the function ran off the end of its instructions (a
8173    /// normal return), and `None` when it stopped in front of an instruction the slow path
8174    /// has to handle — `pc` is written back either way, so `step` resumes at the right
8175    /// place.
8176    ///
8177    /// **The invariant is the whole point.** Every arm here is restricted to work that
8178    /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
8179    /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
8180    /// that the memory limit has to see. An opcode whose operands turn out to need any of
8181    /// that **stops the loop** instead of trying, so the slow path gets the instruction
8182    /// untouched and with its operands still on the stack. That is why the fallback is a
8183    /// `break` and not a duplicated slow arm: a second implementation of the same
8184    /// semantics is how a wrong answer gets in with no test noticing.
8185    ///
8186    /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
8187    /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
8188    fn run_fast(&mut self) -> JsResult<Option<Value>> {
8189        use crate::insn::Fused;
8190        // The outer loop exists only so a `Call` can come back through here: once a
8191        // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
8192        // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
8193        // frame. Re-entering re-reads both from whichever frame is now on top. Every
8194        // other exit from the inner loop returns, so this costs one loop per call.
8195        'outer: loop {
8196            // One reference-count bump per *slow* instruction (a call, an allocation, a
8197            // property access), never one per instruction — that distinction is worth
8198            // two orders of magnitude and was measured as such.
8199            let (code, mut pc) = {
8200                let frame = self.frame();
8201                (frame.code.clone(), frame.pc)
8202            };
8203            let insns = &code.insns;
8204            loop {
8205                let Some(insn) = insns.get(pc).copied() else {
8206                    self.frame_mut().pc = pc;
8207                    return Ok(Some(Value::Undefined));
8208                };
8209                match insn.fused {
8210                    // `x = k`
8211                    Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
8212                    // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
8213                    // object — stops the loop so `binary_add` can decide.
8214                    Fused::AddImmLoc => {
8215                        let slot = insn.a as usize;
8216                        let delta = insn.b as i32;
8217                        let Value::Int(left) = self.get_loc(slot) else {
8218                            return Ok(self.stop(pc));
8219                        };
8220                        let sum = match left.checked_add(delta) {
8221                            Some(sum) => Value::Int(sum),
8222                            None => Value::Float(left as f64 + delta as f64),
8223                        };
8224                        self.put_loc(slot, sum);
8225                    }
8226                    // `x += "literal"` / `x += y`: the operand is a string, so the append
8227                    // either allocates one or grows one. Both are the slow path's business;
8228                    // the fusion's job is only to make the *slot* the sole owner, which is what
8229                    // `execute_fused` needs and what `get_loc` alone destroys.
8230                    Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
8231                        return Ok(self.stop(pc));
8232                    }
8233                    // `x++` on an integer, old value dropped.
8234                    Fused::PostIncLoc => {
8235                        // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
8236                        // value is read in place and overwritten in place, so the reference
8237                        // count it held is released by the same assignment that stores the
8238                        // new one. `get_loc` plus `put_loc` did two borrows, two table
8239                        // lookups and a clone, and this arm is the whole body of a counting
8240                        // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
8241                        let slot = insn.a as usize;
8242                        let frame = self.frames.last_mut().expect("a frame is live");
8243                        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
8244                        let target = if cell < 0 {
8245                            frame.locals.get_mut(slot)
8246                        } else {
8247                            None
8248                        };
8249                        let Some(target) = target else {
8250                            return Ok(self.stop(pc));
8251                        };
8252                        let Value::Int(left) = *target else {
8253                            return Ok(self.stop(pc));
8254                        };
8255                        *target = match left.checked_add(1) {
8256                            Some(sum) => Value::Int(sum),
8257                            None => Value::Float(left as f64 + 1.0),
8258                        };
8259                    }
8260                    // A loop header, `if (!(x < arg)) goto target`, with both sides already
8261                    // integers — which is every `for (i = 0; i < n; i++)` whose counter and
8262                    // bound stayed small integers.
8263                    Fused::LtLocArgJump => {
8264                        let loc = (insn.a >> 16) as usize;
8265                        let arg = (insn.a & 0xFFFF) as usize;
8266                        // One borrow for both slots: this arm *is* the whole loop of a
8267                        // `for (i = 0; i < n; i++)` with an argument bound, so a second
8268                        // `frames.last()` here is paid on every iteration. Measured 7.5% on
8269                        // `dispatch:empty-loop`.
8270                        let (left, right) = {
8271                            let frame = self.frame();
8272                            (frame.read_loc(loc), frame.read_arg(arg))
8273                        };
8274                        // Heavily measured: the bound is very often a `Float` even when the
8275                        // counter is an `Int` — anything that came from `+scriptArgs[2]`,
8276                        // `JSON.parse` or a division is one — so requiring both sides to be
8277                        // `Int` sent every iteration of those loops down the slow path. The
8278                        // comparison below is the same one `relational` makes for two numbers.
8279                        if !is_number(&left) || !is_number(&right) {
8280                            return Ok(self.stop(pc));
8281                        }
8282                        // `if_false` branches on the comparison being false, which is **not**
8283                        // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
8284                        // `>=` is also false and would keep it running forever. Clippy wants the
8285                        // negation folded; that would be a wrong answer.
8286                        let ordered = left.to_number() < right.to_number();
8287                        let take_branch = !ordered;
8288                        if take_branch {
8289                            pc = insn.b as usize;
8290                            continue;
8291                        }
8292                    }
8293                    // The same header with a literal bound: `if (!(x < k)) goto target`.
8294                    // The bound is an immediate, so only the counter needs a type test.
8295                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
8296                    Fused::LtLocImmJump => {
8297                        let left = self.get_loc(insn.a as usize);
8298                        if !is_number(&left) {
8299                            return Ok(self.stop(pc));
8300                        }
8301                        let take_branch = !(left.to_number() < insn.imm as i32 as f64);
8302                        if take_branch {
8303                            pc = insn.b as usize;
8304                            continue;
8305                        }
8306                    }
8307                    Fused::None => match insn.op {
8308                        // -- branches ---------------------------------------------------
8309                        // A jump is an assignment now, because the target is an instruction
8310                        // index. No arithmetic, no resolution table.
8311                        Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
8312                            let target = insn.a as usize;
8313                            // A **back-edge** is a loop, and it is the only place an
8314                            // instruction-level checkpoint can stop one: `for(;;){}` compiles
8315                            // to a jump to itself and never leaves this loop, so the
8316                            // per-instruction checks in `step` never run. That is exactly the
8317                            // hole this arm closes — a host's `JS_SetInterruptHandler` did
8318                            // nothing to a `for(;;){}` until it did, which is what
8319                            // `tests/c/embed.c` is for.
8320                            //
8321                            // Polling here rather than on every instruction in this loop is
8322                            // also the reference's choice (`OP_goto` calls
8323                            // `js_poll_interrupts`), and it costs one compare per branch
8324                            // instead of one decrement per instruction.
8325                            if target <= pc {
8326                                self.frame_mut().pc = target;
8327                                self.check_memory()?;
8328                                self.check_interrupt()?;
8329                            }
8330                            pc = target;
8331                            continue;
8332                        }
8333                        // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
8334                        Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
8335                            let taken = self.pop().to_boolean();
8336                            let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
8337                            if taken == want {
8338                                pc = insn.a as usize;
8339                                continue;
8340                            }
8341                        }
8342                        // -- slot access -------------------------------------------------
8343                        // A load's slot is already an operand (see `insn::implicit_operand`);
8344                        // a captured one goes through its cell, which runs no script.
8345                        Opcode::GetLoc
8346                        | Opcode::GetLoc8
8347                        | Opcode::GetLoc0
8348                        | Opcode::GetLoc1
8349                        | Opcode::GetLoc2
8350                        | Opcode::GetLoc3 => {
8351                            let value = self.get_loc(insn.a as usize);
8352                            self.push(value);
8353                        }
8354                        Opcode::PutLoc
8355                        | Opcode::PutLoc8
8356                        | Opcode::PutLoc0
8357                        | Opcode::PutLoc1
8358                        | Opcode::PutLoc2
8359                        | Opcode::PutLoc3 => {
8360                            let value = self.pop();
8361                            self.put_loc(insn.a as usize, value);
8362                        }
8363                        Opcode::GetArg
8364                        | Opcode::GetArg0
8365                        | Opcode::GetArg1
8366                        | Opcode::GetArg2
8367                        | Opcode::GetArg3 => {
8368                            let value = self.get_arg(insn.a as usize);
8369                            self.push(value);
8370                        }
8371                        Opcode::PutArg
8372                        | Opcode::PutArg0
8373                        | Opcode::PutArg1
8374                        | Opcode::PutArg2
8375                        | Opcode::PutArg3 => {
8376                            let value = self.pop();
8377                            self.put_arg(insn.a as usize, value);
8378                        }
8379                        // `a[i]` with an integer index on a dense array: see `fast_array_get`
8380                        // for why a non-hole own element is exactly the slow path's answer.
8381                        // The two operands are *peeked*, so a miss leaves the stack as the
8382                        // slow path expects to find it.
8383                        Opcode::GetArrayEl => {
8384                            // One lookup, not two. The guard used `if …is_some()` and the arm
8385                            // then called it again to get the value — two `peek`s, two
8386                            // `array_get`s and two `Value` clones for one element.
8387                            // `fast_array_get` was 13.1% of `array:indexed`, and the same
8388                            // double call was the first version of the `get_field` fast path.
8389                            let Some(value) = self.fast_array_get() else {
8390                                return Ok(self.stop(pc));
8391                            };
8392                            // `a[i]` consumes both operands and leaves the element in their
8393                            // place: one `truncate` and one write, no `pop`/`push` pair.
8394                            let frame = self.frame_mut();
8395                            frame.stack.truncate(frame.stack.len() - 2);
8396                            frame.stack.push(value);
8397                        }
8398                        // `a[i] = v` on a dense array with an integer index: see
8399                        // `fast_array_set` for why the whole store is one step.
8400                        Opcode::PutArrayEl if self.fast_array_set() => {}
8401                        // `o.x` resolved from the inline cache without leaving the loop.
8402                        //
8403                        // The cache is keyed by `(receiver identity, atom, site)` and a
8404                        // monomorphic read re-validates the same chain every iteration, so
8405                        // each one used to cost a `stop(pc)` — a write of `pc` into the
8406                        // frame, a return out of this loop, a re-dispatch through `step` and
8407                        // a re-entry. `property:monomorphic` spent 18% in
8408                        // `read_field_cached` and 21% in `push`, both across that boundary.
8409                        //
8410                        // The site is `pc + width`, which is exactly the `next` the slow arm
8411                        // passes — the two must agree or every fast lookup misses and
8412                        // re-records the same entry forever.
8413                        //
8414                        // A miss leaves the stack untouched (`fast_field_get` peeks) so the
8415                        // slow arm finds the receiver where it expects it.
8416                        // `name` resolved from the global-variable cache inside the loop.
8417                        //
8418                        // Same shape as `get_field` above and for the same reason: `get_var`
8419                        // was not in the fast loop, so reading a global — which `fib` does
8420                        // once per recursive call, for its own name — cost a `stop(pc)`, a
8421                        // return out of the loop, a `step` re-dispatch and a re-entry, before
8422                        // `get_global` even started its `scopes_are_plain` checks.
8423                        //
8424                        // Everything here is exactly `get_global`'s first branch: not lexical,
8425                        // no `eval` scope, cache hit. Anything else leaves the stack untouched
8426                        // and lets the slow arm decide.
8427                        Opcode::GetVar => {
8428                            let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
8429                                return Ok(self.stop(pc));
8430                            };
8431                            self.push(value);
8432                        }
8433                        Opcode::GetField | Opcode::GetField2 => {
8434                            let Some(value) =
8435                                self.fast_field_get(insn.a as usize, pc + insn.width())
8436                            else {
8437                                return Ok(self.stop(pc));
8438                            };
8439                            if insn.op == Opcode::GetField2 {
8440                                // `get_field2` keeps the receiver for the `call_method` that
8441                                // follows.
8442                                self.push(value);
8443                            } else {
8444                                // `get_field` replaces the receiver, so this is one store over
8445                                // the top slot rather than a `pop` and a `push`: the length
8446                                // never changes, so neither `Vec` arm has a capacity check or a
8447                                // drop to run beyond the one the overwrite itself does.
8448                                let frame = self.frame_mut();
8449                                match frame.stack.last_mut() {
8450                                    Some(slot) => *slot = value,
8451                                    None => return Ok(self.stop(pc)),
8452                                }
8453                            }
8454                        }
8455                        // -- constants ---------------------------------------------------
8456                        Opcode::PushMinus1
8457                        | Opcode::Push0
8458                        | Opcode::Push1
8459                        | Opcode::Push2
8460                        | Opcode::Push3
8461                        | Opcode::Push4
8462                        | Opcode::Push5
8463                        | Opcode::Push6
8464                        | Opcode::Push7
8465                        | Opcode::PushI8
8466                        | Opcode::PushI16
8467                        | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
8468                        // -- stack shuffling ---------------------------------------------
8469                        Opcode::Drop => {
8470                            self.pop();
8471                        }
8472                        // -- arithmetic on two integers ----------------------------------
8473                        //
8474                        // The operands are *looked at* before they are popped, so a non-integer
8475                        // pair leaves the stack exactly as the slow path expects to find it.
8476                        Opcode::Add if self.numeric_pair() => {
8477                            let right = self.pop();
8478                            let left = self.pop();
8479                            // Exactly [`add_numbers`], which is what the slow arm reaches.
8480                            let answer = match (&left, &right) {
8481                                (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
8482                                    Some(sum) => Value::Int(sum),
8483                                    None => Value::Float(*a as f64 + *b as f64),
8484                                },
8485                                _ => Value::Float(left.to_number() + right.to_number()),
8486                            };
8487                            self.push(answer);
8488                        }
8489                        Opcode::Sub
8490                        | Opcode::And
8491                        | Opcode::Or
8492                        | Opcode::Xor
8493                        | Opcode::Shl
8494                        | Opcode::Sar
8495                        | Opcode::Shr
8496                            if self.numeric_pair() =>
8497                        {
8498                            let right = self.pop();
8499                            let left = self.pop();
8500                            let answer =
8501                                arithmetic(insn.op, left, right).expect("numbers cannot throw");
8502                            self.push(answer);
8503                        }
8504                        Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
8505                            if self.numeric_pair() =>
8506                        {
8507                            let right = self.pop();
8508                            let left = self.pop();
8509                            let answer = self
8510                                .relational(insn.op, left, right)
8511                                .expect("numbers cannot throw");
8512                            self.push(answer);
8513                        }
8514                        // -- calls -------------------------------------------------------
8515                        //
8516                        // A plain call: `callee(arg0, …, argN) -> result`.
8517                        //
8518                        // This arm exists because of one measurement. `call:recursion` had
8519                        // **20.4% of its profile in `execute_instruction`** — the *slow*
8520                        // executor — and `fib`'s recursive call is the only thing in that
8521                        // function which is not a fast arm. Every call therefore left this
8522                        // loop via `stop()`, went through `step()`'s dispatch and
8523                        // `execute_instruction`'s match over every opcode, and came back here
8524                        // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
8525                        //
8526                        // Two things make it safe to do here rather than only in the slow path:
8527                        //
8528                        // * the caller's `pc` is stored *before* the call, which is what
8529                        //   `step` does too — so when the callee returns, the caller resumes
8530                        //   after the call and not at it;
8531                        // * `check_memory` runs, because `step` calls it once per instruction
8532                        //   and a call allocates a frame, its locals and its cells. Skipping
8533                        //   the checkpoint here would let a `--memory-limit` script overshoot
8534                        //   by one call per instruction.
8535                        Opcode::Call
8536                        | Opcode::Call0
8537                        | Opcode::Call1
8538                        | Opcode::Call2
8539                        | Opcode::Call3 => {
8540                            let argc = self.argc_operand(insn.op, insn.a);
8541                            let next = pc + insn.width();
8542                            {
8543                                let frame = self
8544                                    .frames
8545                                    .last_mut()
8546                                    .expect("run_fast() is only called with a live frame");
8547                                // `at` is what a stack trace reports for this frame, so a throw
8548                                // inside the callee has to see the call site and not whatever
8549                                // the last `stop()` left there.
8550                                frame.at = insn.offset as usize;
8551                                frame.pc = next;
8552                            }
8553                            self.check_memory()?;
8554                            self.check_interrupt()?;
8555                            let args = self.pop_n(argc);
8556                            let callee = self.pop();
8557                            // A plain call has no receiver; the callee decides what to do with
8558                            // `undefined` (a sloppy function substitutes the global object).
8559                            if let Some(result) =
8560                                self.call_or_push(callee, Value::Undefined, args)?
8561                            {
8562                                // Native, host, generator, async, bound — no frame was pushed,
8563                                // so this loop is still describing the right function. `pc`
8564                                // is advanced by the loop tail like every other arm; only the
8565                                // frame's copy had to be written here, and it already was.
8566                                self.push(result);
8567                            } else {
8568                                // A bytecode callee: its frame is on top now, and `insns` and
8569                                // `pc` both belong to the caller. Start over on the new frame.
8570                                continue 'outer;
8571                            }
8572                        }
8573                        // -- return ------------------------------------------------------
8574                        Opcode::Return => {
8575                            let value = self.pop();
8576                            self.frame_mut().pc = pc + insn.width();
8577                            return Ok(Some(value));
8578                        }
8579                        Opcode::ReturnUndef => {
8580                            self.frame_mut().pc = pc + insn.width();
8581                            return Ok(Some(Value::Undefined));
8582                        }
8583                        // Everything else needs the slow path.
8584                        _ => return Ok(self.stop(pc)),
8585                    },
8586                }
8587                pc += insn.width();
8588            }
8589        }
8590    }
8591
8592    /// Whether the top two operand-stack values are both numbers.
8593    ///
8594    /// The guard the fast loop uses before it takes an arithmetic record: two numbers
8595    /// cannot run script, so the arm may not throw and may not change frames.
8596    fn numeric_pair(&self) -> bool {
8597        is_number(&self.peek(0)) && is_number(&self.peek(1))
8598    }
8599
8600    /// `a[i]` for a dense array and an integer index, without the string round trip.
8601    ///
8602    /// The slow path answers this by turning `i` into a string (`propkey` →
8603    /// `number_to_string`) and then parsing it straight back (`read_field_key` →
8604    /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
8605    /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
8606    /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
8607    /// without even the cheap `Int` formatting.
8608    ///
8609    /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
8610    /// unambiguously the one the slow path would give:
8611    ///
8612    /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
8613    ///   `2^32-1` is the length, not an index),
8614    /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
8615    ///   typed array or an ordinary object, all of which have their own rules),
8616    /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
8617    ///   starts walking the prototype chain, and `a[i]` on a hole must find
8618    ///   `Array.prototype[i]` if it exists rather than `undefined`.
8619    ///
8620    /// The last condition is the one that makes this safe rather than merely fast: an own
8621    /// element always wins over the prototype, so a non-hole hit needs no further lookup.
8622    /// `get_var` answered from the global-variable cache, or `None`.
8623    ///
8624    /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
8625    /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
8626    /// records nothing — the slow arm is about to walk the chain and record it.
8627    fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
8628        let frame = self.frame();
8629        let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
8630        // "Lexical" is presence in the realm's table, not the closure var's flag: a
8631        // `GlobalRef` forwarded through a nested function has its flags cleared.
8632        if self.realm.globals.contains_key(name) {
8633            return None;
8634        }
8635        if !self.scopes_are_plain() {
8636            return None;
8637        }
8638        let object = &self.realm.global;
8639        let site = slot & (GLOBAL_CACHE_SLOTS - 1);
8640        let cached = self.global_cache[site].as_ref()?;
8641        if !object.upgrades_to(&cached.object) {
8642            return None;
8643        }
8644        object.data_property_at(cached.index, name)
8645    }
8646
8647    /// `o.x` answered entirely from the inline cache, or `None`.
8648    ///
8649    /// Read-only on purpose: a miss must not record an entry, because the slow arm is
8650    /// about to do exactly that and recording it twice would rebuild the chain for every
8651    /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
8652    /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
8653    fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
8654        // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
8655        // an object receiver is a reference-count bump that the answer never needs.
8656        let frame = self.frame();
8657        let object = frame.stack.last()?;
8658        let Value::Object(target) = object else {
8659            return None;
8660        };
8661        // A proxy traps the lookup, so no cache entry ever describes it.
8662        if target.proxy_state().is_some() {
8663            return None;
8664        }
8665        let key = frame.code.atom_keys.get(atom)?;
8666        let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
8667        if cached.key != *key {
8668            return None;
8669        }
8670        Self::cached_hit(target, cached)
8671    }
8672
8673    fn fast_array_get(&self) -> Option<Value> {
8674        let Value::Int(index) = self.peek(0) else {
8675            return None;
8676        };
8677        // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
8678        // set for an `i32`.
8679        if index < 0 {
8680            return None;
8681        }
8682        let Value::Object(object) = self.peek(1) else {
8683            return None;
8684        };
8685        match object.array_get(index as usize) {
8686            Some(value) if !matches!(value, Value::Hole) => Some(value),
8687            _ => None,
8688        }
8689    }
8690
8691    /// `a[i] = v` on a dense array with an integer index, as one store.
8692    ///
8693    /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
8694    /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
8695    /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
8696    /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
8697    /// reference at the time it was measured (14.7x).
8698    ///
8699    /// Every condition here is one the slow path would also have to satisfy before
8700    /// storing into the element vector:
8701    ///
8702    /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
8703    ///   accepts as an index;
8704    /// * the target is an array whose elements are writable (`Object.freeze` clears it);
8705    /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
8706    ///   one inside a recorded descriptor, reports `false` and the caller stops.
8707    ///
8708    /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
8709    /// writes the own element too once `array_set` says it did.
8710    fn fast_array_set(&mut self) -> bool {
8711        // Every test runs *before* anything is popped: a refusal has to leave the stack
8712        // exactly as the slow path expects to find it. Popping first and reporting the
8713        // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
8714        // then ran the slow path with nothing to write.
8715        let Value::Int(index) = self.peek(1) else {
8716            return false;
8717        };
8718        // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
8719        if index < 0 {
8720            return false;
8721        }
8722        // Only a real array: a typed array's elements live in its buffer, a string-like
8723        // object has no element vector, and `array_set` on either does nothing.
8724        let Value::Object(object) = self.peek(2) else {
8725            return false;
8726        };
8727        if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
8728            return false;
8729        }
8730        // A non-extensible array reports `false` here, but the *slow* path has to decide
8731        // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
8732        // that with the key and the stack still intact.
8733        if !object.is_extensible() {
8734            return false;
8735        }
8736        // Inside the logical length, so the store cannot change `length`. Combined with
8737        // extensibility above, the only growth left for `array_set` is filling a hole in
8738        // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
8739        // shape this fast path exists for. A store past the length would grow the array,
8740        // and whether that is allowed is the slow path's question.
8741        if index as usize >= object.array_length().unwrap_or(0) {
8742            return false;
8743        }
8744        // The bound `array_set` refuses past. Checking it here keeps that arm from having
8745        // to report a failure after the operands are gone.
8746        if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
8747            return false;
8748        }
8749        let value = self.pop();
8750        self.pop();
8751        self.pop();
8752        object.array_store(self.heap, index as usize, value)
8753    }
8754
8755    /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
8756    fn stop(&mut self, pc: usize) -> Option<Value> {
8757        self.frame_mut().pc = pc;
8758        None
8759    }
8760
8761    fn push(&mut self, value: Value) {
8762        self.frame_mut().stack.push(value);
8763    }
8764
8765    fn pop(&mut self) -> Value {
8766        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
8767    }
8768
8769    fn pop_n(&mut self, count: usize) -> Vec<Value> {
8770        let frame = self.frame_mut();
8771        let start = frame.stack.len().saturating_sub(count);
8772        frame.stack.split_off(start)
8773    }
8774
8775    fn peek(&self, back: usize) -> Value {
8776        let frame = self.frame();
8777        frame
8778            .stack
8779            .get(frame.stack.len().wrapping_sub(1 + back))
8780            .cloned()
8781            .unwrap_or(Value::Undefined)
8782    }
8783
8784    #[allow(clippy::too_many_lines)]
8785    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
8786        use Opcode::*;
8787        match op {
8788            // -- constants and stack shuffling -----------------------------
8789            Nop => {}
8790            PushMinus1 => self.push(Value::Int(-1)),
8791            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
8792                let value = match op {
8793                    Push0 => 0,
8794                    Push1 => 1,
8795                    Push2 => 2,
8796                    Push3 => 3,
8797                    Push4 => 4,
8798                    Push5 => 5,
8799                    Push6 => 6,
8800                    _ => 7,
8801                };
8802                self.push(Value::Int(value));
8803            }
8804            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
8805            PushBigintI32 => {
8806                // The immediate form of a `BigInt` literal; the reference has the same
8807                // split between this and a constant-pool entry.
8808                let value = crate::bigint::BigInt::from_i64(a as i64);
8809                self.push(self.bigint(value));
8810            }
8811            PushTrue => self.push(Value::Bool(true)),
8812            PushFalse => self.push(Value::Bool(false)),
8813            PushEmptyString => self.push(self.string("")),
8814            Undefined => self.push(Value::Undefined),
8815            Null => self.push(Value::Null),
8816            Object => {
8817                let proto = self.realm.object_proto.clone();
8818                self.push(Value::Object(self.new_object(Some(proto))));
8819            }
8820            PushThis => {
8821                let this = self.frame().this.clone();
8822                self.push(this);
8823            }
8824            PushConst | PushConst8 => {
8825                let value = self.constant(a as usize)?;
8826                self.push(value);
8827            }
8828            PushAtomValue => {
8829                let text = self.atom_wtf8(a as usize);
8830                self.push(self.string_wtf8(text));
8831            }
8832            Dup => {
8833                let value = self.peek(0);
8834                self.push(value);
8835            }
8836            Dup2 => {
8837                // `a b -> a b a b`
8838                let b = self.peek(0);
8839                let a = self.peek(1);
8840                self.push(a);
8841                self.push(b);
8842            }
8843            Dup3 => {
8844                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
8845                // prototype and key while reading the current value through them.
8846                let c = self.peek(0);
8847                let b = self.peek(1);
8848                let a = self.peek(2);
8849                self.push(a);
8850                self.push(b);
8851                self.push(c);
8852            }
8853            Swap => {
8854                // `a b -> b a`
8855                let bottom = self.pop();
8856                let top = self.pop();
8857                self.push(bottom);
8858                self.push(top);
8859            }
8860            Perm3 => {
8861                // `a b c -> b a c`, the reference's reordering for a spread method
8862                // call: `obj func array` becomes the `func this array` that `apply`
8863                // takes.
8864                let c = self.pop();
8865                let b = self.pop();
8866                let a = self.pop();
8867                self.push(b);
8868                self.push(a);
8869                self.push(c);
8870            }
8871            Dup1 => {
8872                let value = self.peek(1);
8873                self.push(value);
8874            }
8875            Drop => {
8876                self.pop();
8877            }
8878            Nip => {
8879                // `a b -> b`
8880                let top = self.pop();
8881                self.pop();
8882                self.push(top);
8883            }
8884            Perm4 => {
8885                // `obj prop a b -> a obj prop b`, the reference's reordering for a
8886                // postfix update of a computed element: it puts the *old* value
8887                // underneath the receiver and key so `put_array_el` can consume them
8888                // and leave the old value as the expression's result.
8889                let d = self.pop();
8890                let c = self.pop();
8891                let b = self.pop();
8892                let a = self.pop();
8893                self.push(c);
8894                self.push(a);
8895                self.push(b);
8896                self.push(d);
8897            }
8898            Insert2 => {
8899                // `obj a -> a obj a`
8900                let value = self.pop();
8901                let object = self.pop();
8902                self.push(value.clone());
8903                self.push(object);
8904                self.push(value);
8905            }
8906            Insert3 => {
8907                // `obj prop a -> a obj prop a`
8908                let value = self.pop();
8909                let key = self.pop();
8910                let object = self.pop();
8911                self.push(value.clone());
8912                self.push(object);
8913                self.push(key);
8914                self.push(value);
8915            }
8916            Insert4 => {
8917                // `this obj prop a -> a this obj prop a`
8918                //
8919                // `put_super_value` consumes all four and yields nothing, so the copy
8920                // underneath is what leaves the assignment an expression value.
8921                let value = self.pop();
8922                let key = self.pop();
8923                let object = self.pop();
8924                let receiver = self.pop();
8925                self.push(value.clone());
8926                self.push(receiver);
8927                self.push(object);
8928                self.push(key);
8929                self.push(value);
8930            }
8931            Swap2 => {
8932                // `a b c d -> c d a b`
8933                let d = self.pop();
8934                let c = self.pop();
8935                let b = self.pop();
8936                let a = self.pop();
8937                self.push(c);
8938                self.push(d);
8939                self.push(a);
8940                self.push(b);
8941            }
8942            Rot3l => {
8943                // `x a b -> a b x`
8944                let b = self.pop();
8945                let a = self.pop();
8946                let x = self.pop();
8947                self.push(a);
8948                self.push(b);
8949                self.push(x);
8950            }
8951            Rot3r => {
8952                // `a b c -> c a b`
8953                let c = self.pop();
8954                let b = self.pop();
8955                let a_value = self.pop();
8956                self.push(c);
8957                self.push(a_value);
8958                self.push(b);
8959            }
8960
8961            Rest => {
8962                // `...rest` in a parameter list: the arguments from index `a` on, as a
8963                // real array. It takes nothing off the stack — the arguments are in the
8964                // frame, not on it.
8965                let frame = self.frame();
8966                let from = a as usize;
8967                let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
8968                let array = self.new_array(collected);
8969                self.push(Value::Object(array));
8970            }
8971
8972            // -- slots ------------------------------------------------------
8973            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
8974                let slot = self.slot_operand(op, a);
8975                let value = self.get_loc(slot);
8976                self.push(value);
8977            }
8978            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
8979                let slot = self.slot_operand(op, a);
8980                let value = self.pop();
8981                self.put_loc(slot, value);
8982            }
8983            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
8984                let slot = self.slot_operand(op, a);
8985                let value = self.pop();
8986                self.put_loc(slot, value.clone());
8987                self.push(value);
8988            }
8989            // The `_check` forms are the temporal dead zone: they throw when the
8990            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
8991            // *reads*, so only the two writes may pop — mishandling that quietly
8992            // consumes the value the caller pushed just before.
8993            GetLocCheck => {
8994                let slot = self.slot_operand(op, a);
8995                let value = self.get_loc(slot);
8996                if matches!(value, Value::Uninitialized) {
8997                    return Err(self.dead_zone(slot, VarSlot::Loc));
8998                }
8999                self.push(value);
9000            }
9001            PutLocCheck | SetLocCheck => {
9002                let slot = self.slot_operand(op, a);
9003                let value = self.pop();
9004                if matches!(value, Value::Uninitialized) {
9005                    return Err(self.dead_zone(slot, VarSlot::Loc));
9006                }
9007                // The initialiser goes through `put_loc`, not this, so any store that
9008                // reaches here is a later assignment — which a `const` refuses.
9009                if self.is_read_only(slot, VarSlot::Loc) {
9010                    return Err(self.read_only(slot, VarSlot::Loc));
9011                }
9012                if op == SetLocCheck {
9013                    self.put_loc(slot, value.clone());
9014                    self.push(value);
9015                } else {
9016                    self.put_loc(slot, value);
9017                }
9018            }
9019            PutLocCheckInit => {
9020                // The one store that *initialises* a lexical slot: `this` in a derived
9021                // constructor, which only exists after `super()` has run. A second
9022                // initialisation is the error the reference reports as
9023                // "'this' can be initialized only once".
9024                let slot = self.slot_operand(op, a);
9025                let value = self.pop();
9026                if !matches!(self.get_loc(slot), Value::Uninitialized) {
9027                    return Err(Signal::Throw(self.make_error(
9028                        "ReferenceError",
9029                        "'this' can be initialized only once",
9030                    )));
9031                }
9032                self.put_loc(slot, value);
9033            }
9034            CheckCtor => {
9035                // A class constructor may only run under `new`, which is what makes
9036                // `class A {}; A()` a TypeError.
9037                if matches!(self.frame().new_target, Value::Undefined) {
9038                    return Err(Signal::Throw(self.make_error(
9039                        "TypeError",
9040                        "class constructors must be invoked with 'new'",
9041                    )));
9042                }
9043            }
9044            InitCtor => {
9045                // The body a derived class gets when it declares no constructor:
9046                // forward every argument to the parent constructor, keeping `new.target`.
9047                if matches!(self.frame().new_target, Value::Undefined) {
9048                    return Err(Signal::Throw(self.make_error(
9049                        "TypeError",
9050                        "class constructors must be invoked with 'new'",
9051                    )));
9052                }
9053                let Some(callee) = self.current_callee() else {
9054                    return Err(Signal::Throw(
9055                        self.make_error("TypeError", "no constructor to inherit from"),
9056                    ));
9057                };
9058                let parent = callee.proto().map_or(Value::Null, Value::Object);
9059                let new_target = self.frame().new_target.clone();
9060                let args = self.frame().passed().to_vec();
9061                let result = self.construct(parent, new_target, args)?;
9062                self.push(result);
9063            }
9064            SetLocUninitialized => {
9065                let slot = self.slot_operand(op, a);
9066                self.put_loc(slot, Value::Uninitialized);
9067            }
9068            CloseLoc => {
9069                // "Close" a binding: give it a *fresh* cell holding the current
9070                // value. Closures created before this point keep the old cell and the
9071                // ones created after see the new one, which is what makes every
9072                // iteration of `for (let i ...)` capture its own `i`, and what freezes
9073                // a block-scoped binding when the block ends.
9074                //
9075                // Clearing the slot instead (which this used to do) broke both: a
9076                // closure over a captured block variable read `undefined`, and a loop
9077                // terminated after one iteration.
9078                let slot = self.slot_operand(op, a);
9079                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
9080                if index >= 0 {
9081                    let current = self.frame().cells[index as usize].get();
9082                    let fresh = self.new_cell(current);
9083                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
9084                        *cell = fresh;
9085                    }
9086                }
9087            }
9088            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
9089                let slot = self.slot_operand(op, a);
9090                let value = self.get_arg(slot);
9091                self.push(value);
9092            }
9093            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
9094                let slot = self.slot_operand(op, a);
9095                let value = self.pop();
9096                self.put_arg(slot, value);
9097            }
9098            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
9099                let slot = self.slot_operand(op, a);
9100                let value = self.pop();
9101                self.put_arg(slot, value.clone());
9102                self.push(value);
9103            }
9104
9105            // -- closure variables ------------------------------------------
9106            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
9107                let slot = self.slot_operand(op, a);
9108                // A name a direct `eval` created shadows the binding the compiler chose.
9109                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
9110                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
9111                // and only a runtime lookup can know that.
9112                if let Some(cell) = self.eval_created_local(slot) {
9113                    self.push(cell.get());
9114                    return self.step();
9115                }
9116                let value = self.cell_value(slot)?;
9117                self.push(value);
9118            }
9119            GetVarRefCheck => {
9120                let slot = self.slot_operand(op, a);
9121                let value = self.cell_value(slot)?;
9122                if matches!(value, Value::Uninitialized) {
9123                    return Err(self.dead_zone(slot, VarSlot::Closure));
9124                }
9125                self.push(value);
9126            }
9127            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
9128                let slot = self.slot_operand(op, a);
9129                let value = self.pop();
9130                if let Some(cell) = self.eval_created_local(slot) {
9131                    cell.set(value);
9132                    return self.step();
9133                }
9134                // Same rule as `PutLocCheck`: a checked store to a captured binding
9135                // refuses a `const` once its initialiser has run.
9136                if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
9137                    return Err(self.read_only(slot, VarSlot::Closure));
9138                }
9139                self.set_cell(slot, value)?;
9140            }
9141            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
9142                let slot = self.slot_operand(op, a);
9143                let value = self.pop();
9144                if let Some(cell) = self.eval_created_local(slot) {
9145                    cell.set(value.clone());
9146                    self.push(value);
9147                    return self.step();
9148                }
9149                self.set_cell(slot, value.clone())?;
9150                self.push(value);
9151            }
9152
9153            // -- globals ----------------------------------------------------
9154            GetVar => {
9155                let value = self.get_global(a as usize)?;
9156                self.push(value);
9157            }
9158            GetVarUndef => {
9159                let value = self
9160                    .get_global(a as usize)
9161                    .or_else(|_| Ok(Value::Undefined))?;
9162                self.push(value);
9163            }
9164            DeleteVar => {
9165                // `delete name` for a name that is not a declared binding. A lexical
9166                // global lives in the reference table and cannot be deleted; anything
9167                // reachable only as a property of the global object is *implicit* —
9168                // `x = 1` with no declaration — and goes away if it is configurable,
9169                // which is what `delete` on an implicit global answers.
9170                let name = self.atom_text(a as usize);
9171                let global = self.realm.global.clone();
9172                let deleted = if self.realm.globals.contains_key(&name) {
9173                    false
9174                } else if global.own_property(&name).is_some() {
9175                    self.delete_property(&global, &name)?
9176                } else {
9177                    true
9178                };
9179                self.push(Value::Bool(deleted));
9180            }
9181            PutVar => {
9182                let value = self.pop();
9183                self.put_global(a as usize, value)?;
9184            }
9185            PutVarInit => {
9186                let slot = a as usize;
9187                let value = self.pop();
9188                self.init_global(slot, value)?;
9189            }
9190
9191            // -- arithmetic -------------------------------------------------
9192            Add => self.binary_add()?,
9193            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
9194                let raw_right = self.pop();
9195                let raw_left = self.pop();
9196                // BigInt arithmetic is a separate path, and not only for the type of the
9197                // result: `ToNumber` of a bigint throws, so mixing the two must be an error
9198                // rather than a silent conversion.
9199                if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
9200                    let left = self.primitive_of(raw_left)?;
9201                    let right = self.primitive_of(raw_right)?;
9202                    let value = self.bigint_arithmetic(op, left, right)?;
9203                    self.push(value);
9204                } else {
9205                    let right = self.numeric(raw_right)?;
9206                    let left = self.numeric(raw_left)?;
9207                    self.push(arithmetic(op, left, right)?);
9208                }
9209            }
9210            Neg => {
9211                let raw = self.pop();
9212                match raw {
9213                    // A bigint negates exactly, however wide it is.
9214                    Value::BigInt(big) => {
9215                        let negated = big.negate();
9216                        self.push(self.bigint(negated));
9217                    }
9218                    other => {
9219                        let value = self.numeric(other)?;
9220                        self.push(negate(value));
9221                    }
9222                }
9223            }
9224            Plus => {
9225                let value = self.pop();
9226                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
9227                // unary plus is defined to produce a *number*, which a bigint cannot
9228                // become without loss. It used to fall through to `NaN`.
9229                if matches!(value, Value::BigInt(_)) {
9230                    return Err(self.type_error("cannot convert bigint to number"));
9231                }
9232                let numeric = self.numeric_of(value)?;
9233                self.push(numeric);
9234            }
9235            Inc => {
9236                let raw = self.pop();
9237                let (_, updated) = self.advance_numeric(raw, true)?;
9238                self.push(updated);
9239            }
9240            Dec => {
9241                let raw = self.pop();
9242                let (_, updated) = self.advance_numeric(raw, false)?;
9243                self.push(updated);
9244            }
9245            PostInc | PostDec => {
9246                // `x -> x x+1`: the *new* value ends up on top, so the store the
9247                // compiler emits right after (`put_var`) writes the incremented
9248                // one, while the old value stays underneath for the expression's
9249                // own result. Getting this backwards makes `i++` a no-op, which
9250                // turns `while (i < 3)` into an infinite loop.
9251                let raw = self.pop();
9252                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
9253                self.push(old);
9254                self.push(updated);
9255            }
9256            Not => {
9257                let raw = self.pop();
9258                match raw {
9259                    // `~x` on a bigint is `-x - 1`, exact at any width.
9260                    Value::BigInt(big) => {
9261                        let inverted = big.bitnot();
9262                        self.push(self.bigint(inverted));
9263                    }
9264                    other => {
9265                        let value = self.numeric(other)?;
9266                        self.push(Value::Int(!value.to_int32()));
9267                    }
9268                }
9269            }
9270            Lnot => {
9271                let value = self.pop();
9272                self.push(Value::Bool(!value.to_boolean()));
9273            }
9274
9275            // -- comparison -------------------------------------------------
9276            Lt | Lte | Gt | Gte => {
9277                let right = self.pop();
9278                let left = self.pop();
9279                let answer = self.relational(op, left, right)?;
9280                self.push(answer);
9281            }
9282            Eq | Neq => {
9283                let right = self.pop();
9284                let left = self.pop();
9285                let equal = self.abstract_equals(left, right)?;
9286                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
9287            }
9288            StrictEq => {
9289                let right = self.pop();
9290                let left = self.pop();
9291                self.push(Value::Bool(left.strict_equals(&right)));
9292            }
9293            StrictNeq => {
9294                let right = self.pop();
9295                let left = self.pop();
9296                self.push(Value::Bool(!left.strict_equals(&right)));
9297            }
9298            IsUndefined => {
9299                // `=== undefined`, which is what a destructuring default tests. It is
9300                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
9301                let value = self.pop();
9302                self.push(Value::Bool(matches!(value, Value::Undefined)));
9303            }
9304            IsUndefinedOrNull => {
9305                let value = self.pop();
9306                self.push(Value::Bool(value.is_nullish()));
9307            }
9308            Typeof => {
9309                let value = self.pop();
9310                self.push(self.string(value.type_of()));
9311            }
9312            ToObject => {
9313                // A destructuring *object* pattern starts here, which is why
9314                // `var {} = null` throws. Only `undefined` and `null` are refused; a
9315                // primitive is boxed.
9316                let value = self.pop();
9317                let object = self.object_from(&value)?;
9318                self.push(Value::Object(object));
9319            }
9320            Instanceof => {
9321                let constructor = self.pop();
9322                let object = self.pop();
9323                let answer = self.instance_of(&object, &constructor)?;
9324                self.push(Value::Bool(answer));
9325            }
9326            In => {
9327                let object = self.pop();
9328                let key = self.pop();
9329                let answer = self.has_property(&key, &object)?;
9330                self.push(Value::Bool(answer));
9331            }
9332
9333            // -- control flow -----------------------------------------------
9334            Goto | Goto8 | Goto16 => {
9335                self.frame_mut().pc = a as usize;
9336            }
9337            IfTrue | IfTrue8 => {
9338                let value = self.pop();
9339                if value.to_boolean() {
9340                    self.frame_mut().pc = a as usize;
9341                }
9342            }
9343            IfFalse | IfFalse8 => {
9344                let value = self.pop();
9345                if !value.to_boolean() {
9346                    self.frame_mut().pc = a as usize;
9347                }
9348            }
9349            Catch => {
9350                // Pushes the handler target onto the value stack; `unwind` finds it.
9351                self.push(Value::CatchOffset(a));
9352            }
9353            Gosub => {
9354                self.push(Value::ReturnAddress(next as u32));
9355                self.frame_mut().pc = a as usize;
9356            }
9357            Ret => {
9358                let value = self.pop();
9359                match value {
9360                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
9361                    _ => {
9362                        return Err(Signal::Throw(
9363                            self.make_error("InternalError", "invalid return address"),
9364                        ));
9365                    }
9366                }
9367            }
9368            NipCatch => {
9369                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
9370                // including the marker, keeping the top value.
9371                let top = self.pop();
9372                loop {
9373                    match self.pop() {
9374                        Value::CatchOffset(_) | Value::Undefined => break,
9375                        _ => {}
9376                    }
9377                    if self.frame().stack.is_empty() {
9378                        break;
9379                    }
9380                }
9381                self.push(top);
9382            }
9383            Throw => {
9384                let value = self.pop();
9385                return Err(Signal::Throw(value));
9386            }
9387            ThrowError => {
9388                let name = self.atom_text(a as usize);
9389                let (class, message) = match b {
9390                    0 => ("TypeError", format!("'{name}' is read-only")),
9391                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
9392                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
9393                    // `delete super.x` is a syntax-level mistake the reference reports
9394                    // with this wording, not a property-access failure.
9395                    3 => (
9396                        "ReferenceError",
9397                        "unsupported reference to 'super'".to_string(),
9398                    ),
9399                    4 => (
9400                        "TypeError",
9401                        "iterator does not have a throw method".to_string(),
9402                    ),
9403                    5 => (
9404                        "ReferenceError",
9405                        "invalid assignment left-hand side".to_string(),
9406                    ),
9407                    _ => ("TypeError", format!("invalid operation on '{name}'")),
9408                };
9409                return Err(Signal::Throw(self.make_error(class, &message)));
9410            }
9411            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
9412            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
9413            YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
9414            AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
9415            Await => return Ok(Step::Suspend(SuspendKind::Await)),
9416            ReturnAsync => {
9417                // The reference's `return_async` returns `undefined` and lets the resume
9418                // machinery pick the real value off `sp[-1]`, which is how it tells a
9419                // completion from a suspension. Carrying the value explicitly says the
9420                // same thing without the implicit stack slot.
9421                let value = self.pop();
9422                return Ok(Step::Return(value));
9423            }
9424            Return => {
9425                let value = self.pop();
9426                return Ok(Step::Return(value));
9427            }
9428            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
9429
9430            // -- calls ------------------------------------------------------
9431            Call | Call0 | Call1 | Call2 | Call3 => {
9432                let argc = self.argc_operand(op, a);
9433                let args = self.pop_n(argc);
9434                let callee = self.pop();
9435                // A plain call has no receiver; the callee decides what to do with
9436                // `undefined` (a sloppy function substitutes the global object).
9437                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
9438                    self.push(result);
9439                }
9440            }
9441            CallConstructor => {
9442                // `constructor this_obj args… -> object`. The duplicated
9443                // constructor is `new.target`; this milestone does not expose it,
9444                // so the extra copy is simply consumed here.
9445                let argc = a as usize;
9446                let args = self.pop_n(argc);
9447                let new_target = self.pop();
9448                let callee = self.pop();
9449                let result = self.construct(callee, new_target, args)?;
9450                self.push(result);
9451            }
9452            CallMethod => {
9453                let argc = a as usize;
9454                let args = self.pop_n(argc);
9455                let callee = self.pop();
9456                let this = self.pop();
9457                if let Some(result) = self.call_or_push(callee, this, args)? {
9458                    self.push(result);
9459                }
9460            }
9461            Apply => {
9462                // `func this array -> result`, the spread-call form: the compiler
9463                // builds one array of arguments, and all that is left here is to
9464                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
9465                let array = self.pop();
9466                let this = self.pop();
9467                let callee = self.pop();
9468                let args = self.array_like_to_args(&array)?;
9469                if a & 1 != 0 {
9470                    let result = self.construct(callee, this, args)?;
9471                    self.push(result);
9472                } else if let Some(result) = self.call_or_push(callee, this, args)? {
9473                    self.push(result);
9474                }
9475            }
9476            TailCall | TailCallMethod => {
9477                // `tail_call` is `call` whose result is returned immediately — the
9478                // reference jumps straight to `done` instead of storing the value and
9479                // running on. The callee still gets its own frame, so deep tail
9480                // recursion hits the stack limit exactly like plain recursion does;
9481                // marking this frame lets the return path unwind without needing
9482                // instructions after the call.
9483                let argc = if op == TailCallMethod {
9484                    a as usize
9485                } else {
9486                    self.argc_operand(op, a)
9487                };
9488                let args = self.pop_n(argc);
9489                let callee = self.pop();
9490                let this = if op == TailCallMethod {
9491                    self.pop()
9492                } else {
9493                    Value::Undefined
9494                };
9495                if let Value::Object(function) = &callee
9496                    && let Some((code, env)) = bytecode_of(function)
9497                {
9498                    // A generator or async body is not run here at all: calling it only
9499                    // *creates* the generator/coroutine, so it must not inherit this
9500                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
9501                    // onto `f`'s frame, and the first `yield`/`await` then reported
9502                    // "a generator body ran as an ordinary call".
9503                    if code.code.kind.is_generator() || code.code.kind.is_async() {
9504                        let value = self.call_value(callee, this, args)?;
9505                        return Ok(Step::Return(value));
9506                    }
9507                    self.frame_mut().tail = true;
9508                    self.push_frame(code, env, this, args, callee)?;
9509                    return Ok(Step::Continue);
9510                }
9511                // A native callee has no frame to reuse, so its value is simply
9512                // returned.
9513                let value = self.call_value(callee, this, args)?;
9514                return Ok(Step::Return(value));
9515            }
9516
9517            // -- objects ----------------------------------------------------
9518            SpecialObject => {
9519                let value = self.special_object(a)?;
9520                self.push(value);
9521            }
9522            PrivateSymbol => {
9523                // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
9524                // symbol each time it is evaluated, which is why the compiler evaluates it
9525                // once (at class definition) and stores it in a class-scope binding.
9526                let name = self.atom_text(a as usize);
9527                let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
9528                self.push(Value::Symbol(symbol));
9529            }
9530            GetPrivateField => {
9531                // `obj symbol -> value`. A missing private field is a TypeError, which is what
9532                // makes `#x` inaccessible on any object not built by this class.
9533                let symbol = self.pop();
9534                let object = self.pop();
9535                let value = self.read_private_field(&object, &symbol)?;
9536                self.push(value);
9537            }
9538            PutPrivateField => {
9539                // `obj value symbol ->`, and the store is a plain assignment to a property the
9540                // class already created, so there is no setter to consult.
9541                let symbol = self.pop();
9542                let value = self.pop();
9543                let object = self.pop();
9544                self.write_private_field(&object, &symbol, value)?;
9545            }
9546            DefinePrivateField => {
9547                // `obj symbol value -> obj`: a field initialiser creates the property, and
9548                // redefining one is a TypeError ("already exists").
9549                let value = self.pop();
9550                let symbol = self.pop();
9551                let object = self.pop();
9552                self.define_private_field(&object, &symbol, value)?;
9553                self.push(object);
9554            }
9555            PrivateIn => {
9556                // `obj key -> bool`: `#x in o`. The second operand decides which question is
9557                // being asked, which is the reference's `js_operator_private_in`: a *symbol*
9558                // is a field, so this is an own-property test; a *function* is a method or
9559                // accessor, so this is a brand check.
9560                let key = self.pop();
9561                let object = self.pop();
9562                let Some(target) = object.as_object() else {
9563                    return Err(Signal::Throw(
9564                        self.make_error("TypeError", "invalid 'in' operand"),
9565                    ));
9566                };
9567                let present = match &key {
9568                    Value::Object(_) => self.check_brand(target, &key)?,
9569                    _ => target.own_property_key(&self.private_key(&key)?).is_some(),
9570                };
9571                self.push(Value::Bool(present));
9572            }
9573            AddBrand => {
9574                // `obj home ->`: create the class brand on `home` if it has none, then give
9575                // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
9576                // class definition: only the prototype's copy of the symbol is wanted.
9577                let home = self.pop();
9578                let object = self.pop();
9579                self.add_brand(&object, &home)?;
9580            }
9581            CheckBrand => {
9582                // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
9583                // Both stay, because the caller needs them — `nip` halves a read into its
9584                // value and `call_method` uses the pair as receiver and callee.
9585                let function = self.peek(0);
9586                let object = self.peek(1);
9587                let Some(target) = object.as_object() else {
9588                    return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9589                };
9590                if !self.check_brand(target, &function)? {
9591                    return Err(Signal::Throw(
9592                        self.make_error("TypeError", "invalid brand on object"),
9593                    ));
9594                }
9595            }
9596            GetLength => {
9597                // `get_length` is the `.length` read; an array and a string answer
9598                // from their own length, anything else from the property.
9599                let target = self.pop();
9600                let value = match &target {
9601                    Value::Object(object) => match object.array_length() {
9602                        Some(length) => crate::object::length_value(length),
9603                        None => self.read_field(&target, "length")?,
9604                    },
9605                    Value::String(text) => Value::Int(text.utf16_len() as i32),
9606                    _ => self.read_field(&target, "length")?,
9607                };
9608                self.push(value);
9609            }
9610            GetField | GetField2 => {
9611                let object = self.pop();
9612                // Borrowed out of the code object, not cloned: `atom_key` returns an owned
9613                // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
9614                // just below is what lets the borrow outlive the `&mut self` the lookup
9615                // needs — one refcount bump instead of a key clone plus its drop, on the
9616                // hottest property path there is: every `o.x` and every `o.m()` receiver.
9617                let code = self.frame().code.clone();
9618                let key = &code.atom_keys[a as usize];
9619                let value = self.read_field_cached(&object, key, next)?;
9620                if op == GetField2 {
9621                    self.push(object);
9622                }
9623                self.push(value);
9624            }
9625            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
9626                let key = self.pop();
9627                let object = self.pop();
9628                let key = self.propkey(&key)?;
9629                let value = self.read_field_key(&object, &key)?;
9630                if matches!(op, GetArrayEl2 | GetArrayEl3) {
9631                    self.push(object);
9632                }
9633                if op == GetArrayEl3 {
9634                    // The key goes back in its *value* form, which the compiler stores
9635                    // into the target of a destructuring assignment.
9636                    self.push(match &key {
9637                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
9638                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
9639                    });
9640                }
9641                self.push(value);
9642            }
9643            PutField => {
9644                let value = self.pop();
9645                let object = self.pop();
9646                // Borrowed, like the `get_field` arm: `atom_key` would return an owned
9647                // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
9648                // only reads. `this.value = …` is the write half of the hottest loop in
9649                // `property:method-call`, and `own_property_key` was 4.8% of the case.
9650                let code = self.frame().code.clone();
9651                let key = &code.atom_keys[a as usize];
9652                self.write_field_key(&object, key, value)?;
9653            }
9654            PutArrayEl => {
9655                let value = self.pop();
9656                let key = self.pop();
9657                let object = self.pop();
9658                let key = self.propkey(&key)?;
9659                self.write_field_key(&object, &key, value)?;
9660            }
9661            DefineField => {
9662                let value = self.pop();
9663                let object = self.pop();
9664                // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
9665                // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
9666                // three U+FFFD — a property under a different name from the one
9667                // `o["\uD800"]` reads.
9668                let code = self.frame().code.clone();
9669                let key = code.atom_keys[a as usize].clone();
9670                // No naming here. `{m: function(){}}` is named by the *compiler*, which
9671                // emits `set_name` — and only where `NamedEvaluation` applies, so
9672                // `{m: (0, function(){})}` stays anonymous. Naming every function that
9673                // reaches a property definition got that case wrong, and the compiler is
9674                // the only place that can tell the two apart.
9675                if let Some(target) = object.as_object() {
9676                    // Only an *array* stores into the element vector. A numeric key
9677                    // on an ordinary object is an ordinary property, which is what
9678                    // makes `{1: 'a'}` iterate as a key rather than disappear.
9679                    let stored = target.is_array()
9680                        && key.as_str().and_then(array_index).is_some_and(|index| {
9681                            target.array_set(self.heap, index as usize, value.clone())
9682                        });
9683                    if !stored {
9684                        target.define_data_key(&key, value);
9685                    }
9686                }
9687                self.push(object);
9688            }
9689            DefineArrayEl => {
9690                // `obj key value -> obj key`. The *value* form of the key is what goes
9691                // back on the stack — the compiler stores it into the pattern's binding —
9692                // so the symbol is not stringified on the way through.
9693                let value = self.pop();
9694                let key_value = self.pop();
9695                let object = self.peek(0);
9696                let key = self.propkey(&key_value)?;
9697                self.write_field_key(&object, &key, value)?;
9698                self.push(key_value);
9699            }
9700            SetHomeObject => {
9701                // `obj func -> obj func`: records the object a method was defined on so
9702                // `super` inside it resolves against that object's prototype.
9703                let function = self.peek(0);
9704                let home = self.peek(1);
9705                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
9706                    function.set_home_object(Some(home.clone()));
9707                }
9708            }
9709            Regexp => {
9710                // `pattern flags -> regexp`. A literal compiles here rather than through the
9711                // constructor, which is both what the reference's dedicated opcode is for
9712                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
9713                let flags = self.pop();
9714                let pattern = self.pop();
9715                let pattern = self.to_js_string(&pattern)?;
9716                let flags = self.to_js_string(&flags)?;
9717                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
9718                self.push(Value::Object(object));
9719            }
9720            UsingDisposeInit => {
9721                // The error state a disposal accumulates into. Uninitialised means "no
9722                // failure yet"; anything else is the exception being propagated.
9723                self.push(Value::Uninitialized);
9724            }
9725            UsingCheck => {
9726                // `value -> value, method`: validate and snapshot the disposer now, so a
9727                // later change to `Symbol.dispose` cannot change what gets called, and so a
9728                // value that is not disposable fails before the body runs.
9729                let value = self.pop();
9730                let method = self.using_method_for(&value, a as u8 == 1)?;
9731                self.push(value);
9732                self.push(method);
9733            }
9734            UsingDispose => {
9735                // `error_state -> error_state'`: dispose the variable at `slot` — its value
9736                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
9737                // the pending error.
9738                let slot = self.slot_operand(op, a);
9739                let error_state = self.pop();
9740                let merged = self.using_dispose_once(slot, error_state)?;
9741                self.push(merged);
9742            }
9743            UsingDisposeMerge => {
9744                let new_error = self.pop();
9745                let error_state = self.pop();
9746                let merged = self.merge_dispose_error(new_error, error_state);
9747                self.push(merged);
9748            }
9749            UsingDisposeEnd => {
9750                // A disposal that failed replaces the block's normal completion, so the
9751                // error state becomes a real throw here rather than at the call site.
9752                let error_state = self.pop();
9753                if !matches!(error_state, Value::Uninitialized) {
9754                    return Err(Signal::Throw(error_state));
9755                }
9756            }
9757            UsingDisposeAsync => {
9758                // `await using` needs a promise to await and this runtime has no
9759                // `Promise` builtin, so the disposer is called synchronously and its result
9760                // discarded. That is correct for a disposer that returns nothing and is
9761                // reported as a gap rather than silently skipped.
9762                let slot = self.slot_operand(op, a);
9763                let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
9764                self.push(error_state);
9765            }
9766            GetSuper => {
9767                // `obj -> obj's prototype`: the starting point of a `super` lookup.
9768                let object = self.pop();
9769                let proto = match &object {
9770                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
9771                    _ => Value::Null,
9772                };
9773                self.push(proto);
9774            }
9775            GetSuperValue => {
9776                // `receiver proto key -> value`, searching from `proto` but reporting to
9777                // `receiver`, which is what `super.g` must do for a getter to see `this`.
9778                //
9779                // Three values in, one out: the receiver is *consumed*, not left under the
9780                // result. Leaving it there was invisible for `super.x` in `return` or
9781                // statement position (the result is what gets popped) and corrupted the
9782                // frame everywhere else — `print(super.x)` left the class where the call
9783                // opcode looks for the receiver and called the class itself.
9784                let key = self.pop();
9785                let proto = self.pop();
9786                let receiver = self.pop();
9787                let value = self.super_read(&receiver, &proto, &key)?;
9788                self.push(value);
9789            }
9790            PutSuperValue => {
9791                // `receiver proto key value ->`: a store that starts at `proto` but
9792                // assigns to `receiver`.
9793                let value = self.pop();
9794                let key = self.pop();
9795                let proto = self.pop();
9796                let receiver = self.pop();
9797                self.super_write(&receiver, &proto, &key, value)?;
9798            }
9799            DefineClass => {
9800                // `parent ctor -> ctor proto`: the constructor becomes the class and a
9801                // fresh prototype object lands on top for the methods to go on.
9802                let name = self.atom_text(a as usize);
9803                let (ctor, proto) = self.define_class(&name, b)?;
9804                self.push(ctor);
9805                self.push(Value::Object(proto));
9806            }
9807            DefineClassComputed => {
9808                // `parent ctor key -> ctor proto key`: the computed name stays put so
9809                // `define_field`-style consumers can still read it.
9810                let key = self.pop();
9811                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
9812                let (ctor, proto) = self.define_class(&name, b)?;
9813                self.push(ctor);
9814                self.push(Value::Object(proto));
9815                self.push(key);
9816            }
9817            DefineMethod => {
9818                let function = self.pop();
9819                let object = self.pop();
9820                // The exact key, like `define_field`: a quoted method key may hold an
9821                // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
9822                // that `o["\uD800"]` finds.
9823                let code = self.frame().code.clone();
9824                let key = code.atom_keys[a as usize].clone();
9825                // A method's `[[HomeObject]]` is the object it was defined on, which is
9826                // what `super` inside it resolves against.
9827                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
9828                    function.set_home_object(Some(object.clone()));
9829                }
9830                if let Some(text) = key.as_wtf8() {
9831                    self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
9832                } else {
9833                    self.set_function_name(
9834                        &function,
9835                        &key_with_accessor_prefix(&key.to_string(), b),
9836                    );
9837                }
9838                if let Some(array) = object.as_object() {
9839                    define_function_property(array, &key, function, b);
9840                }
9841                self.push(object);
9842            }
9843            DefineMethodComputed => {
9844                let function = self.pop();
9845                let key = self.pop();
9846                let object = self.pop();
9847                let key = self.propkey(&key)?;
9848                // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
9849                // the name: `super` inside a computed method resolves through it. Without
9850                // this, `class B extends A { [k]() { return super.m() } }` read the
9851                // home object as null and threw.
9852                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
9853                    function.set_home_object(Some(object.clone()));
9854                }
9855                match key.as_wtf8() {
9856                    Some(text) => {
9857                        let name = accessor_prefixed(text, a);
9858                        self.set_function_name_wtf8(&function, &name);
9859                    }
9860                    None => self.set_function_name(
9861                        &function,
9862                        &key_with_accessor_prefix(&key.to_string(), a),
9863                    ),
9864                }
9865                if let Some(array) = object.as_object() {
9866                    define_function_property(array, &key, function, a);
9867                }
9868                self.push(object);
9869            }
9870            SetProto => {
9871                let proto = self.pop();
9872                let object = self.pop();
9873                if let Some(target) = object.as_object() {
9874                    target.set_proto(proto.as_object().cloned());
9875                }
9876                self.push(object);
9877            }
9878            CopyDataProperties => {
9879                let exclusion = self.pop();
9880                let source = self.pop();
9881                let target = self.peek(0);
9882                self.copy_properties(&target, &source, &exclusion)?;
9883                self.push(source);
9884                self.push(exclusion);
9885            }
9886            ToPropkey => {
9887                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
9888                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
9889                // ordinary `"Symbol(b)"` property.
9890                let value = self.pop();
9891                let key = match self.propkey(&value)? {
9892                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
9893                    PropertyKey::String(text) => self.string_wtf8(text),
9894                };
9895                self.push(key);
9896            }
9897            SetName => {
9898                let function = self.peek(0);
9899                let name = self.atom_wtf8(a as usize);
9900                self.set_function_name_wtf8(&function, &name);
9901            }
9902            SetNameComputed => {
9903                let key = self.peek(1);
9904                let function = self.peek(0);
9905                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
9906                self.set_function_name(&function, &name);
9907            }
9908
9909            // -- arrays -----------------------------------------------------
9910            ArrayFrom => {
9911                let count = a as usize;
9912                let elements = self.pop_n(count);
9913                let array = self.new_array(elements);
9914                self.push(Value::Object(array));
9915            }
9916            Append => {
9917                // `array index iterable -> array new_index`
9918                let iterable = self.pop();
9919                self.pop();
9920                let array = self.peek(0);
9921                let added = self.append_enumerate(&array, &iterable)?;
9922                self.push(Value::Int(added));
9923            }
9924
9925            // -- iteration --------------------------------------------------
9926            ForInStart => {
9927                let value = self.pop();
9928                let record = self.for_in_record(&value)?;
9929                self.push(Value::Object(record));
9930            }
9931            ForInNext => {
9932                // `record -> record key done`. The flag is *done*, not "found":
9933                // the compiler tests it with `if_false` to jump back into the body,
9934                // so reporting `true` while keys remain would end the loop at once.
9935                let record = self.peek(0);
9936                match self.for_in_advance(&record)? {
9937                    Some(key) => {
9938                        let text = self.string(key);
9939                        self.push(text);
9940                        self.push(Value::Bool(false));
9941                    }
9942                    None => {
9943                        self.push(Value::Undefined);
9944                        self.push(Value::Bool(true));
9945                    }
9946                }
9947            }
9948            ForOfStart => {
9949                let value = self.pop();
9950                let iterator = self.get_iterator(&value)?;
9951                self.push(iterator.object);
9952                self.push(iterator.next);
9953                self.push(Value::CatchOffset(0));
9954            }
9955            ForOfNext => {
9956                // `iter next catch_offset -> iter next catch_offset value done`.
9957                //
9958                // The operand is how many values sit *above* the iterator triple: a
9959                // destructuring rest element keeps its target array and running index
9960                // there while draining the iterator, so the triple is not at the top.
9961                let extra = a as usize;
9962                let iterator_slot = 2 + extra;
9963                // An exhausted iterator is replaced by `undefined` (see below), so a
9964                // second step must not call `next` again — `Array.from` and a
9965                // destructuring pattern both keep stepping past the end.
9966                let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
9967                    (Value::Undefined, true)
9968                } else {
9969                    let iterator = Iterator {
9970                        object: self.peek(iterator_slot),
9971                        next: self.peek(1 + extra),
9972                    };
9973                    self.iterator_step(&iterator)?
9974                };
9975                if done {
9976                    // The result's `value` is meaningless once the iterator is done:
9977                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
9978                    // rather than binding the generator's return value.
9979                    let top = self.frame().stack.len() - 1 - iterator_slot;
9980                    self.frame_mut().stack[top] = Value::Undefined;
9981                    self.push(Value::Undefined);
9982                    self.push(Value::Bool(true));
9983                } else {
9984                    self.push(value);
9985                    self.push(Value::Bool(false));
9986                }
9987            }
9988            IteratorNext => {
9989                // `iter next catch val -> iter next catch val'`: replace the argument with
9990                // the result of `next(val)`. The triple below stays put, which is why the
9991                // three instructions of the `yield*` loop all address the stack the same way.
9992                let value = self.pop();
9993                let object = self.peek(2);
9994                let next = self.peek(1);
9995                let result = self.call_value(next, object, vec![value])?;
9996                self.push(result);
9997            }
9998            IteratorCall => {
9999                // `iter next catch val -> iter next catch val' flag`.
10000                //
10001                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
10002                // The flag is `true` when the method was missing, which is how the
10003                // caller learns that the inner iterator cannot take part in the
10004                // unwinding.
10005                let value = self.pop();
10006                let object = self.peek(2);
10007                let key = if a & 1 != 0 { "throw" } else { "return" };
10008                let method = self.read_field(&object, key)?;
10009                if matches!(method, Value::Undefined | Value::Null) {
10010                    self.push(value);
10011                    self.push(Value::Bool(true));
10012                } else {
10013                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
10014                    let result = self.call_value(method, object, argument)?;
10015                    self.push(result);
10016                    self.push(Value::Bool(false));
10017                }
10018            }
10019            IteratorCheckObject => {
10020                if !matches!(self.peek(0), Value::Object(_)) {
10021                    return Err(Signal::Throw(
10022                        self.make_error("TypeError", "iterator must return an object"),
10023                    ));
10024                }
10025            }
10026            IteratorClose => {
10027                // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
10028                // calling the iterator's `return` so it can release whatever it holds.
10029                //
10030                // The catch offset goes first, so an exception from `return` is not caught
10031                // by the loop being abandoned. This used to pop the three operands and call
10032                // nothing at all, which made `break` out of a `for of` invisible to an
10033                // iterator with a `return` method.
10034                self.pop();
10035                self.pop();
10036                let iterator = self.pop();
10037                if !matches!(iterator, Value::Undefined) {
10038                    let method = self.read_field(&iterator, "return")?;
10039                    if !matches!(method, Value::Undefined | Value::Null) {
10040                        let result = self.call_value(method, iterator.clone(), Vec::new())?;
10041                        // §7.4.6: a `return` that answers a non-object is a TypeError.
10042                        if !matches!(result, Value::Object(_)) {
10043                            return Err(Signal::Throw(
10044                                self.make_error("TypeError", "iterator must return an object"),
10045                            ));
10046                        }
10047                    }
10048                }
10049            }
10050            Import => {
10051                // `import(specifier)`: the options slot is on top and is not read yet.
10052                let _options = self.pop();
10053                let specifier = self.pop();
10054                let promise = self.dynamic_import(specifier)?;
10055                self.push(promise);
10056            }
10057            ForAwaitOfStart => {
10058                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
10059                // `Symbol.iterator` fallback.
10060                let value = self.pop();
10061                let iterator = self.get_async_iterator(&value)?;
10062                self.push(iterator.object);
10063                self.push(iterator.next);
10064                self.push(Value::CatchOffset(0));
10065            }
10066            ForAwaitOfNext => {
10067                // `for await` steps the iterator and leaves the *result* wrapped in a
10068                // promise, so the `await` the compiler emits right after this can suspend
10069                // on it. Unwrapping happens in `iterator_get_value_done`.
10070                let extra = a as usize;
10071                let iterator_slot = 2 + extra;
10072                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
10073                    Value::Undefined
10074                } else {
10075                    let iterator = Iterator {
10076                        object: self.peek(iterator_slot),
10077                        next: self.peek(1 + extra),
10078                    };
10079                    let next = iterator.next.clone();
10080                    self.call_value(next, iterator.object, Vec::new())?
10081                };
10082                let promise = self.promise_resolve_value(result)?;
10083                self.push(promise);
10084            }
10085            IteratorGetValueDone => {
10086                // `result -> value done`. A missing result object means the iterator was
10087                // already exhausted, which the loop treats as `done`.
10088                let result = self.pop();
10089                let done = match &result {
10090                    Value::Object(object) => self
10091                        .get_property(object, "done")?
10092                        .is_some_and(|value| value.to_boolean()),
10093                    _ => true,
10094                };
10095                if done {
10096                    // Clear the iterator object so the `iterator_close` the loop emits on
10097                    // its way out has nothing to close: `AsyncIteratorClose` must *not* run
10098                    // on normal completion, and this is where a normal completion is
10099                    // recognised — the same trick `for_of_next` uses, which also replaces
10100                    // the slot with `undefined`.
10101                    //
10102                    // The layout is fixed because only `for await` emits this opcode:
10103                    // `iter next catch [result]`, so the iterator is three below the top.
10104                    let depth = self.frame().stack.len();
10105                    if depth >= 3 {
10106                        self.frame_mut().stack[depth - 3] = Value::Undefined;
10107                    }
10108                    self.push(Value::Undefined);
10109                    self.push(Value::Bool(true));
10110                } else {
10111                    let Value::Object(object) = &result else {
10112                        self.push(Value::Undefined);
10113                        self.push(Value::Bool(true));
10114                        return Ok(Step::Continue);
10115                    };
10116                    let value = self
10117                        .get_property(object, "value")?
10118                        .unwrap_or(Value::Undefined);
10119                    self.push(value);
10120                    self.push(Value::Bool(false));
10121                }
10122            }
10123
10124            Delete => {
10125                // `delete obj[key]`, where the key was just pushed. Deleting an array
10126                // index leaves a *hole* rather than closing the gap, and a
10127                // non-configurable property answers `false` and stays.
10128                let key = self.pop();
10129                let target = self.pop();
10130                let key = self.propkey(&key)?;
10131                let text_label = key.as_str().unwrap_or("").to_string();
10132                let deleted = match &target {
10133                    Value::Object(object) => {
10134                        let object = object.clone();
10135                        self.delete_property_key(&object, &key)?
10136                    }
10137                    // A string's `length` and its index properties are
10138                    // non-configurable, so deleting one answers `false`.
10139                    Value::String(text) => {
10140                        !(text_label == "length"
10141                            || array_index(&text_label)
10142                                .is_some_and(|index| (index as usize) < text.utf16_len()))
10143                    }
10144                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
10145                    // object to delete from, and only a *boxable* primitive has one.
10146                    Value::Undefined | Value::Null => {
10147                        return Err(Signal::Throw(
10148                            self.make_error("TypeError", "cannot convert to object"),
10149                        ));
10150                    }
10151                    // Any other primitive has no own properties; deleting nothing
10152                    // succeeds.
10153                    _ => true,
10154                };
10155                self.push(Value::Bool(deleted));
10156            }
10157
10158            // -- exceptions and bookkeeping ---------------------------------
10159            Fclosure | Fclosure8 => {
10160                let value = self.closure(a as usize)?;
10161                self.push(value);
10162            }
10163
10164            other => {
10165                let name = other.info().name;
10166                return Err(Signal::Throw(self.make_error(
10167                    "InternalError",
10168                    &format!("{name} is not implemented yet"),
10169                )));
10170            }
10171        }
10172        Ok(Step::Continue)
10173    }
10174
10175    // -- operand helpers ----------------------------------------------------
10176
10177    /// The slot index an operand names, taking short forms into account.
10178    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
10179        use Opcode::*;
10180        match op {
10181            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
10182            | SetVarRef0 => 0,
10183            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
10184            | SetVarRef1 => 1,
10185            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
10186            | SetVarRef2 => 2,
10187            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
10188            | SetVarRef3 => 3,
10189            _ => a as usize,
10190        }
10191    }
10192
10193    /// The argument count of a call, taking `call0`…`call3` into account.
10194    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
10195        use Opcode::*;
10196        match op {
10197            Call0 => 0,
10198            Call1 => 1,
10199            Call2 => 2,
10200            Call3 => 3,
10201            _ => a as usize,
10202        }
10203    }
10204
10205    /// The atom's name as a property key.
10206    ///
10207    /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
10208    /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
10209    /// `String::clone` was a heap allocation and a copy — per property access.
10210    /// The atom at `index`, as a property key.
10211    ///
10212    /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
10213    /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
10214    /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
10215    /// 5.3% of `property:monomorphic`.
10216    /// The atom's text, exactly — including an unpaired surrogate.
10217    ///
10218    /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
10219    /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
10220    /// `atom_text` below is for the other kind of use, where the atom is a key in the
10221    /// engine's own tables.
10222    fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
10223        self.frame()
10224            .code
10225            .code
10226            .atoms
10227            .get(index)
10228            .map(|atom| match atom {
10229                Atom::Str(text) => text.clone(),
10230                Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
10231                // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
10232                Atom::Null => crate::value::Wtf8::new(String::new()),
10233            })
10234            .unwrap_or_default()
10235    }
10236
10237    fn atom_text(&self, index: usize) -> String {
10238        self.frame()
10239            .code
10240            .code
10241            .atoms
10242            .get(index)
10243            .map(|atom| match atom {
10244                // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
10245                // compare it to an identifier, and a surrogate-bearing name is reachable
10246                // through `atom_wtf8` where it matters.
10247                Atom::Str(text) => text.to_string_lossy().into_owned(),
10248                Atom::Index(value) => value.to_string(),
10249                // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
10250                // `throw_error`, `delete super.x`) never read it.
10251                Atom::Null => String::new(),
10252            })
10253            .unwrap_or_default()
10254    }
10255
10256    fn constant(&mut self, index: usize) -> JsResult<Value> {
10257        let constant = self.frame().code.code.cpool.get(index).cloned();
10258        Ok(match &constant {
10259            Some(Constant::Number(number)) => Value::Float(*number),
10260            Some(Constant::String(text)) => self.string_wtf8(text.clone()),
10261            Some(Constant::BigInt { digits, radix }) => {
10262                match crate::bigint::BigInt::from_radix(digits, *radix) {
10263                    Some(big) => self.bigint(big),
10264                    // A literal the parser accepted is always parseable; a failure here
10265                    // would be a compiler bug, so it reads as an `InternalError`.
10266                    None => {
10267                        return Err(Signal::Throw(
10268                            self.make_error("InternalError", "unparseable bigint literal"),
10269                        ));
10270                    }
10271                }
10272            }
10273            Some(Constant::Function(_)) => {
10274                return Err(Signal::Throw(
10275                    self.make_error("InternalError", "a bare function constant"),
10276                ));
10277            }
10278            // A tagged template's call site: a frozen array of the cooked chunks with a
10279            // frozen `raw` array beside it, which is what `String.raw` reads back.
10280            Some(Constant::Template { cooked, raw }) => {
10281                let cooked_values: Vec<Value> = cooked
10282                    .iter()
10283                    .map(|chunk| match chunk {
10284                        Some(text) => self.string_wtf8(text.clone()),
10285                        None => Value::Undefined,
10286                    })
10287                    .collect();
10288                let raw_values: Vec<Value> =
10289                    raw.iter().map(|text| self.string(text.clone())).collect();
10290                let raw_array = self.new_array(raw_values);
10291                raw_array.set_extensible(false);
10292                let template = self.new_array(cooked_values);
10293                template.define(
10294                    "raw",
10295                    Property::with_attributes(Value::Object(raw_array), false, false),
10296                );
10297                template.set_extensible(false);
10298                Value::Object(template)
10299            }
10300            _ => Value::Undefined,
10301        })
10302    }
10303
10304    /// The reference cell a closure-variable slot names.
10305    ///
10306    /// Two kinds of binding share this addressing: a genuine closure variable
10307    /// (captured from an enclosing function) lives in this frame's environment,
10308    /// while a *declared global* lives in the realm so that a script, a function
10309    /// declaration and their uses all see one binding. A plain `Global` — an
10310    /// undeclared name that may be satisfied by the global object — has no cell at
10311    /// all, which is how `typeof x` still works for a name that does not exist.
10312    /// The reference cell a closure-variable slot names.
10313    ///
10314    /// The environment is resolved once, when the closure is built, and this is
10315    /// just the lookup afterwards. A *declared global* is in there too, pointing at
10316    /// the realm's cell, so a script, a hoisted function declaration and their uses
10317    /// all share one binding. A plain `Global` — a name the script never declared —
10318    /// is read and written through `get_var`/`put_var` by name instead, which is
10319    /// what lets the global object satisfy it.
10320    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
10321        self.frame().env.cells.get(slot).cloned()
10322    }
10323
10324    /// Whether `slot` refers to a global binding through the reference table.
10325    ///
10326    /// A global's cell in the closure environment only exists so the slot has
10327    /// something to point at; the binding itself lives on the global object (a `var`)
10328    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
10329    /// be routed, not performed on the placeholder.
10330    fn is_global_slot(&self, slot: usize) -> bool {
10331        self.frame()
10332            .code
10333            .code
10334            .closure_vars
10335            .get(slot)
10336            .is_some_and(|c| {
10337                // A module's declarations and imports are *not* globals: their cells are
10338                // the module environment's, filled by the host, so the placeholder routing
10339                // must not apply to them.
10340                matches!(
10341                    c.closure_type,
10342                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
10343                )
10344            })
10345    }
10346
10347    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
10348        if self.is_global_slot(slot) {
10349            return self.get_global(slot);
10350        }
10351        Ok(self
10352            .var_ref_cell(slot)
10353            .map(|cell| cell.get())
10354            .unwrap_or(Value::Undefined))
10355    }
10356
10357    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
10358        // A function declaration is hoisted by storing into a global reference before
10359        // the body runs, so this path is also what puts it on the global object.
10360        if self.is_global_slot(slot) {
10361            return self.put_global(slot, value);
10362        }
10363        if let Some(cell) = self.var_ref_cell(slot) {
10364            cell.set(value);
10365        }
10366        Ok(())
10367    }
10368
10369    // -- closures -----------------------------------------------------------
10370
10371    /// Build the closure for the function constant `index`.
10372    ///
10373    /// Every entry in the child's closure table names where its binding lives in
10374    /// *this* frame: a local or argument slot that was marked captured, or a cell
10375    /// this frame is itself holding. That is how a variable three functions deep
10376    /// stays one binding.
10377    fn closure(&mut self, index: usize) -> JsResult<Value> {
10378        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
10379        else {
10380            return Err(Signal::Throw(
10381                self.make_error("InternalError", "fclosure of a non-function"),
10382            ));
10383        };
10384        let mut cells = Vec::with_capacity(function.closure_vars.len());
10385        for closure_var in &function.closure_vars {
10386            let cell = match closure_var.closure_type {
10387                ClosureType::Arg => {
10388                    let slot = closure_var.var_idx as usize;
10389                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
10390                }
10391                ClosureType::Local => {
10392                    let slot = closure_var.var_idx as usize;
10393                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
10394                }
10395                ClosureType::Ref | ClosureType::GlobalRef => {
10396                    // A `Ref` names a cell in this frame's own closure table; a
10397                    // `GlobalRef` also starts there, then resolves by name below.
10398                    let slot = closure_var.var_idx as usize;
10399                    if let Some(cell) = self.frame().env.cells.get(slot) {
10400                        cells.push(cell.clone());
10401                        continue;
10402                    }
10403                    -1
10404                }
10405                _ => -1,
10406            };
10407            if cell >= 0 {
10408                let cell = self.frame().cells[cell as usize].clone();
10409                cells.push(cell);
10410                continue;
10411            }
10412            // A global: the cell is created on demand and shared through the realm,
10413            // so every function sees one binding.
10414            let name = closure_var.name.clone();
10415            let cell = match self.realm.globals.get(&name) {
10416                Some(cell) => cell.clone(),
10417                None => {
10418                    let cell = self.new_cell(Value::Undefined);
10419                    self.realm.globals.insert(name.clone(), cell.clone());
10420                    cell
10421                }
10422            };
10423            cells.push(cell);
10424        }
10425        let name = function.name.clone();
10426        // `.length` is the arity before any default or rest parameter, not the number
10427        // of slots a pattern parameter needs.
10428        let length = function.defined_args;
10429        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
10430        // function and an arrow function do not. A *method* also does not, but that is not
10431        // known here — the method is marked when the `[[HomeObject]]` is attached (see
10432        // `set_home_object`), which is the moment it becomes a method.
10433        let function_kind = function.kind;
10434        let constructible =
10435            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
10436        let code = Gc::new(self.heap, CompiledCode::new(*function));
10437        // A closure built inside an `eval` inherits the eval's view of the enclosing
10438        // bindings, so it can still read them once the eval has returned.
10439        let eval_scope = self
10440            .active_eval_scope
10441            .clone()
10442            .or_else(|| self.frame().env.eval_scope.clone());
10443        // A closure sees the variables a direct `eval` declared in the frame it was
10444        // created in — the ones declared before *and after* it, so the same object is
10445        // shared; only the phase bounds which of them are visible.
10446        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
10447        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
10448        let env = Gc::new(
10449            self.heap,
10450            ClosureEnv {
10451                cells,
10452                eval_scope,
10453                local_vars,
10454                local_phase,
10455            },
10456        );
10457        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
10458        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
10459        // the only thing that carries `Symbol.toStringTag`, so without it
10460        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
10461        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
10462        let proto = match function_kind {
10463            js_compile::bytecode::FunctionKind::AsyncGenerator => self
10464                .realm
10465                .async_generator_function_proto
10466                .clone()
10467                .or_else(|| self.realm.function_proto.clone().into()),
10468            js_compile::bytecode::FunctionKind::Generator => self
10469                .realm
10470                .generator_function_proto
10471                .clone()
10472                .or_else(|| self.realm.function_proto.clone().into()),
10473            js_compile::bytecode::FunctionKind::Async => self
10474                .realm
10475                .async_function_proto
10476                .clone()
10477                .or_else(|| self.realm.function_proto.clone().into()),
10478            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
10479        };
10480        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
10481        object.set_constructible(constructible);
10482        object.define(
10483            "length",
10484            Property::name_or_length(Value::Int(length as i32)),
10485        );
10486        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
10487        // that checks the own-property descriptor fails if the property is missing.
10488        object.define("name", Property::name_or_length(self.string(name)));
10489        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
10490        // when `[[Construct]]` is created, so a generator, an async function and an arrow
10491        // function have none of their own. Installing it unconditionally gave
10492        // `Array.fromAsync` (an async function) an own `prototype` property, which
10493        // `builtin.js` checks for absence.
10494        if constructible {
10495            self.install_function_prototype(&object);
10496        }
10497        Ok(Value::Object(object))
10498    }
10499
10500    // -- conversions used by the operators ----------------------------------
10501
10502    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
10503        // `+x` is `ToNumber`, which for a string parses it and for an object runs
10504        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
10505        // string, which then behaves differently in every later comparison.
10506        match value {
10507            Value::Int(_) | Value::Float(_) => Ok(value),
10508            other => Ok(Value::Float(self.to_js_number(&other)?)),
10509        }
10510    }
10511
10512    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
10513    ///
10514    /// Returns the *converted* old value and the new one, because the two callers need
10515    /// different halves: `++x` yields the new value, while `x++` yields the old one and
10516    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
10517    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
10518    /// boolean.
10519    ///
10520    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
10521    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
10522    /// a bigint algorithm then ran exactly once.
10523    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
10524        if let Value::BigInt(big) = &value {
10525            let one = crate::bigint::BigInt::from_i64(1);
10526            let next = if up { big.add(&one) } else { big.sub(&one) };
10527            return Ok((value, self.bigint(next)));
10528        }
10529        let old = self.numeric(value)?;
10530        let new = if up {
10531            increment(old.clone())
10532        } else {
10533            decrement(old.clone())
10534        };
10535        Ok((old, new))
10536    }
10537
10538    fn numeric(&mut self, value: Value) -> JsResult<Value> {
10539        // `ToNumber` on an object runs `ToPrimitive` first, which is how
10540        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
10541        // heard at all. Reading the object's own tag instead (`other.to_number()`)
10542        // turned the whole operand into `NaN` and swallowed the exception.
10543        match value {
10544            Value::Int(_) | Value::Float(_) => Ok(value),
10545            other => Ok(Value::Float(self.to_js_number(&other)?)),
10546        }
10547    }
10548
10549    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
10550    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
10551        match value {
10552            Value::BigInt(big) => Ok((**big).clone()),
10553            // The reference words this the same way for every operator, so a failing
10554            // script reads identically; the operator itself adds nothing a caller can use.
10555            _ => Err(Signal::Throw(
10556                self.make_error("TypeError", "cannot convert bigint to number"),
10557            )),
10558        }
10559    }
10560
10561    /// Arithmetic where at least one operand is a `BigInt`.
10562    ///
10563    /// The two numeric types never mix, so a bigint paired with anything else is an error
10564    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
10565    /// that the relational operators handle it separately.
10566    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10567        use Opcode::*;
10568        let a = self.bigint_operand(&left)?;
10569        let b = self.bigint_operand(&right)?;
10570        let result = match op {
10571            Add => a.add(&b),
10572            Sub => a.sub(&b),
10573            Mul => a.mul(&b),
10574            Div | Mod => {
10575                let Some((quotient, remainder)) = a.div_rem(&b) else {
10576                    return Err(Signal::Throw(
10577                        self.make_error("RangeError", "division by zero"),
10578                    ));
10579                };
10580                if op == Div { quotient } else { remainder }
10581            }
10582            Pow => {
10583                let Some(value) = a.pow(&b) else {
10584                    return Err(Signal::Throw(self.make_error(
10585                        "RangeError",
10586                        "BigInt exponent must be non-negative and not absurdly large",
10587                    )));
10588                };
10589                value
10590            }
10591            And => a.bitand(&b),
10592            Or => a.bitor(&b),
10593            Xor => a.bitxor(&b),
10594            Shl | Sar => {
10595                // A shift count is a `BigInt` here, and both directions are exact; a
10596                // negative count would be the other direction, which the spec forbids.
10597                let Some(count) = b.to_i64() else {
10598                    return Err(Signal::Throw(
10599                        self.make_error("RangeError", "BigInt shift count is too large"),
10600                    ));
10601                };
10602                if count < 0 {
10603                    return Err(Signal::Throw(self.make_error(
10604                        "RangeError",
10605                        "BigInt shift count must be non-negative",
10606                    )));
10607                }
10608                if op == Shl {
10609                    a.shl(count as u64)
10610                } else {
10611                    a.shr(count as u64)
10612                }
10613            }
10614            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
10615            _ => {
10616                return Err(Signal::Throw(self.make_error(
10617                    "TypeError",
10618                    "BigInts have no unsigned right shift, use >> instead",
10619                )));
10620            }
10621        };
10622        Ok(self.bigint(result))
10623    }
10624
10625    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
10626    ///
10627    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
10628    /// is on the mathematical values, and nothing is rounded first.
10629    /// `<`, `<=`, `>`, `>=`.
10630    ///
10631    /// Both operands go through `ToPrimitive` **before** the comparison, which is what
10632    /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
10633    /// It is a `?`-returning function for exactly that reason: an object operand can run
10634    /// script, and script can throw. The old version compared `to_number` of the raw
10635    /// values, which answered `false` for every object instead of calling `valueOf` —
10636    /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
10637    /// never ran.
10638    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10639        // The hot arm first: `i < n` with both sides already integers. No conversion, no
10640        // call, nothing that can throw.
10641        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10642            let ordering = Some(left.cmp(right));
10643            return Ok(ordering_answer(op, ordering));
10644        }
10645        // Anything that can run script has to be converted first, in this order.
10646        let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
10647        {
10648            (
10649                self.to_primitive(left, Hint::Number)?,
10650                self.to_primitive(right, Hint::Number)?,
10651            )
10652        } else {
10653            (left, right)
10654        };
10655        let ordering = match (&left, &right) {
10656            // The loop condition `i < n` is integer against integer, and it runs once
10657            // per iteration of every loop in every program. Without this arm it took the
10658            // `to_number` path twice, which is a `match` plus a conversion each.
10659            (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
10660            (Value::String(a), Value::String(b)) => {
10661                Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
10662            }
10663            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
10664            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
10665            // is true even though `2.5` has no bigint form.
10666            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
10667                let b = other.to_number();
10668                if b.is_nan() {
10669                    None
10670                } else {
10671                    compare_bigint_and_f64(a, b)
10672                }
10673            }
10674            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
10675                let a = other.to_number();
10676                if a.is_nan() {
10677                    None
10678                } else {
10679                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
10680                }
10681            }
10682            _ => left.to_number().partial_cmp(&right.to_number()),
10683        };
10684        Ok(ordering_answer(op, ordering))
10685    }
10686
10687    fn binary_add(&mut self) -> JsResult<()> {
10688        let right = self.pop();
10689        let left = self.pop();
10690        // Two integers add without any of the machinery below: no `ToPrimitive` (an
10691        // `Int` is already primitive), no string check, no bigint check, no allocation.
10692        // `x += 1` in a loop is the single most common instruction sequence in real
10693        // script, and it used to walk every one of those checks before reaching the
10694        // same `checked_add`.
10695        if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10696            self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
10697            return Ok(());
10698        }
10699        let left = self.primitive_of(left)?;
10700        let right = self.primitive_of(right)?;
10701        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
10702        // that check comes before the bigint one: `"" + 1n` is a string, not a
10703        // mixed-type error.
10704        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
10705            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
10706            // `TypeError`, the one place a symbol and a string do not mix.
10707            // Keep the operands as strings rather than as bytes: `JsString::concat` decides
10708            // between a copy and a rope from their lengths, and a rope is what turns
10709            // `text += "abc"` in a loop from quadratic into linear.
10710            if let (Value::String(left), Value::String(right)) = (&left, &right) {
10711                // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
10712                // reports as `InternalError: string too long`.
10713                let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
10714                    return Err(Signal::Throw(
10715                        self.make_error("InternalError", "string too long"),
10716                    ));
10717                };
10718                self.push(Value::String(Gc::new(self.heap, joined)));
10719                return Ok(());
10720            }
10721            // At least one operand was not a string, so `ToString` it. This rejects a
10722            // symbol, which is the one place a symbol and a string do not mix.
10723            let left = self.checked_to_wtf8(&left)?;
10724            let right = self.checked_to_wtf8(&right)?;
10725            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
10726            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
10727            let text = left.concat(&right);
10728            self.push(self.string_wtf8(text));
10729            return Ok(());
10730        }
10731        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
10732        // not a conversion.
10733        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
10734            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
10735            self.push(value);
10736            return Ok(());
10737        }
10738        let left = self.numeric(left)?;
10739        let right = self.numeric(right)?;
10740        self.push(add_numbers(left, right));
10741        Ok(())
10742    }
10743
10744    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
10745        self.to_primitive(value, Hint::Default)
10746    }
10747
10748    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
10749    ///
10750    /// The order depends on the hint: the "number" order tries `valueOf` first and
10751    /// `toString` second, the "string" order the other way round, and the default
10752    /// hint uses the number order. A result that is still an object is a `TypeError`,
10753    /// because no built-in `valueOf`/`toString` returns one.
10754    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
10755        let Value::Object(object) = &value else {
10756            return Ok(value);
10757        };
10758        // A Date overrides the default hint to mean "string", which is what
10759        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
10760        // this, `"" + new Date()` would print the milliseconds, not the date.
10761        let hint = if hint == Hint::Default && is_date_object(self, object) {
10762            Hint::String
10763        } else {
10764            hint
10765        };
10766        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
10767        // handed the hint as a string. This is the hook a Date uses for its default hint
10768        // and a script uses to take over conversion entirely.
10769        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
10770        if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
10771            if !function.is_callable() {
10772                return Err(self.type_error("Symbol.toPrimitive is not a function"));
10773            }
10774            let hint = match hint {
10775                Hint::String => "string",
10776                Hint::Number => "number",
10777                Hint::Default => "default",
10778            };
10779            let hint = self.string(hint);
10780            let result = self.call_value(
10781                Value::Object(function),
10782                Value::Object(object.clone()),
10783                vec![hint],
10784            )?;
10785            if matches!(result, Value::Object(_)) {
10786                return Err(self.type_error("cannot convert object to primitive value"));
10787            }
10788            return Ok(result);
10789        }
10790        let order: [&str; 2] = match hint {
10791            Hint::String => ["toString", "valueOf"],
10792            Hint::Number | Hint::Default => ["valueOf", "toString"],
10793        };
10794        let receiver = object.clone();
10795        for method in order {
10796            if let Some(function) = self.get_property(&receiver, method)?
10797                && matches!(&function, Value::Object(object) if object.is_callable())
10798            {
10799                let result =
10800                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
10801                if !matches!(result, Value::Object(_)) {
10802                    return Ok(result);
10803                }
10804            }
10805        }
10806        Err(self.type_error("cannot convert object to primitive value"))
10807    }
10808
10809    /// `ToString` with the object case going through `ToPrimitive`.
10810    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
10811        if matches!(value, Value::Object(_)) {
10812            let primitive = self.to_primitive(value.clone(), Hint::String)?;
10813            return Ok(primitive.to_js_string());
10814        }
10815        Ok(value.to_js_string())
10816    }
10817
10818    /// `ToString` that keeps the string's code units instead of flattening them.
10819    ///
10820    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
10821    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
10822    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
10823        if matches!(value, Value::Symbol(_)) {
10824            return Err(Signal::Throw(
10825                self.make_error("TypeError", "cannot convert symbol to string"),
10826            ));
10827        }
10828        // An object runs `ToPrimitive` first, which may itself produce a symbol.
10829        let value = self.to_primitive(value.clone(), Hint::String)?;
10830        match value {
10831            Value::Symbol(_) => Err(Signal::Throw(
10832                self.make_error("TypeError", "cannot convert symbol to string"),
10833            )),
10834            Value::String(text) => Ok(text.wtf8().clone()),
10835            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
10836        }
10837    }
10838
10839    /// `ToNumber` with the object case going through `ToPrimitive`.
10840    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
10841        let value = if matches!(value, Value::Object(_)) {
10842            self.to_primitive(value.clone(), Hint::Number)?
10843        } else {
10844            value.clone()
10845        };
10846        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
10847        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
10848        // `NaN` to stay total, and the operators check for the bigint themselves — but
10849        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
10850        // refuse, and answering `NaN` made them silently wrong instead.
10851        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
10852        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
10853        match value {
10854            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
10855            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
10856            other => Ok(other.to_number()),
10857        }
10858    }
10859
10860    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
10861    /// [`ElementType::write`].
10862    ///
10863    /// This is separated from the write because both conversions are observable script —
10864    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
10865    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
10866    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
10867    /// setters, and a plain `a[i] = v`.
10868    pub(crate) fn element_value(
10869        &mut self,
10870        element: crate::builtins::typedarray::ElementType,
10871        value: Value,
10872    ) -> JsResult<Value> {
10873        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
10874        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
10875        let primitive = match &value {
10876            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
10877            _ => value,
10878        };
10879        if element.is_bigint() {
10880            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
10881            Ok(Value::BigInt(Gc::new(self.heap, big)))
10882        } else {
10883            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
10884            Ok(Value::Float(self.to_js_number(&primitive)?))
10885        }
10886    }
10887
10888    /// `ToPropertyKey`: what a computed member access uses as its key.
10889    ///
10890    /// A symbol is returned as itself, never stringified — that is what keeps
10891    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
10892    pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
10893        match value {
10894            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
10895            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
10896            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
10897            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
10898            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
10899                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
10900                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
10901                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
10902                    other.to_js_string(),
10903                ))),
10904            },
10905            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
10906        }
10907    }
10908
10909    /// `ToPropertyKey` for the callers that can only use a string key.
10910    ///
10911    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
10912    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
10913    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
10914    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
10915    /// program continues with a value nobody asked for.
10916    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
10917        use crate::value::Wtf8;
10918        Ok(match value {
10919            // A string key keeps its code units. Going through a lossy `String` would make
10920            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
10921            Value::String(text) => text.wtf8().clone(),
10922            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
10923            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
10924            // falling back to its `ToString` would print `[object Object]`.
10925            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
10926                Value::String(text) => text.wtf8().clone(),
10927                other => Wtf8::new(other.to_js_string()),
10928            },
10929            other => Wtf8::new(other.to_js_string()),
10930        })
10931    }
10932
10933    // -- object operations used by instructions -----------------------------
10934
10935    /// Read `object[key]`, returning `undefined` when the property is missing.
10936    ///
10937    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
10938    /// primitive (looking through its prototype) as well as an object — which is what
10939    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
10940    /// argument needs too.
10941    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
10942        self.read_field_key(object, &PropertyKey::from(key))
10943    }
10944
10945    /// [`Interp::read_field`] with a key that may be a symbol.
10946    ///
10947    /// A symbol key never reaches the string shortcuts: a string's `length` and its
10948    /// indices are string properties, and a symbol named `length` is a different
10949    /// property that a string primitive cannot have.
10950    /// [`Interp::read_field_key`], with an inline cache in front of it.
10951    ///
10952    /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
10953    /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
10954    /// without this the engine walked the chain and compared ~40 property names on each
10955    /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
10956    ///
10957    /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
10958    /// missing property. Those answers depend on running code or on state the guard below
10959    /// does not cover, and a wrong answer here is far more expensive than a lookup.
10960    ///
10961    /// A hit is re-validated against the *whole* walked chain, not just the level that
10962    /// answered: the receiver and every prototype down to that level must still be the same
10963    /// object (weakly, so a collected and reallocated object is a miss) with unchanged
10964    /// property-table *lengths* — which is what catches a property appearing on an
10965    /// intermediate prototype and shadowing the cached one.
10966    pub fn read_field_cached(
10967        &mut self,
10968        object: &Value,
10969        key: &PropertyKey,
10970        slot: usize,
10971    ) -> JsResult<Value> {
10972        let index = Self::field_cache_slot(object, key, slot);
10973        let Value::Object(target) = object else {
10974            return self.read_field_key(object, key);
10975        };
10976        if target.proxy_state().is_some() {
10977            return self.read_field_key(object, key);
10978        }
10979        if let Some(cached) = &self.field_cache[index]
10980            && cached.key == *key
10981            && let Some(value) = Self::cached_hit(target, cached)
10982        {
10983            return Ok(value);
10984        }
10985        let value = self.read_field_key(object, key)?;
10986        self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
10987        Ok(value)
10988    }
10989
10990    /// Whether a cache entry still describes this lookup, and if so the value.
10991    ///
10992    /// The guard is the whole point of the entry: identity plus property-table length for
10993    /// every level walked. Re-checked per level rather than once at the receiving end,
10994    /// because a shadowing property can appear anywhere along the chain.
10995    fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
10996        // Level 0 — the receiver itself answered — without the `Gc` clone this loop
10997        // starts with: a clone is a reference-count bump and a drop, and for
10998        // `property:monomorphic` every single hit takes only this arm.
10999        let (weak, len) = cached.chain[0].as_ref()?;
11000        if !target.upgrades_to(weak) {
11001            return None;
11002        }
11003        if cached.level == 0 {
11004            // Length and key and accessor-ness in one borrow: see `cached_property_at`.
11005            return target.cached_property_at(cached.index, &cached.key, *len);
11006        }
11007        if target.props_len() != *len {
11008            return None;
11009        }
11010        let mut level = 1;
11011        let mut current = target.proto()?;
11012        loop {
11013            let (weak, len) = cached.chain[level].as_ref()?;
11014            if !current.upgrades_to(weak) || current.props_len() != *len {
11015                return None;
11016            }
11017            if level == cached.level as usize {
11018                // The level that answered: the value is only reusable while the key is
11019                // still there and still a plain data property.
11020                return current.cached_data_property(cached.index, &cached.key);
11021            }
11022            current = current.proto()?;
11023            level += 1;
11024        }
11025    }
11026
11027    /// Build a cache entry for a lookup that just went through the slow path.
11028    ///
11029    /// Records the chain only when the answer came from a plain data property at a level
11030    /// the fixed-size array can hold; everything else simply leaves the slot empty, which
11031    /// costs the next lookup the walk it would have cost anyway.
11032    fn record_field_lookup(
11033        target: &Gc<JsObject>,
11034        key: &PropertyKey,
11035        _value: Value,
11036    ) -> Option<FieldCache> {
11037        let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
11038            [None, None, None];
11039        let mut current = target.clone();
11040        for level in 0..MAX_CACHED_CHAIN {
11041            chain[level] = Some((current.downgrade(), current.props_len()));
11042            if let Some((found, _)) = current.own_property_index(key) {
11043                // `own_property_index` declines an accessor and a hole, which is exactly
11044                // the set that must not be cached.
11045                return Some(FieldCache {
11046                    key: key.clone(),
11047                    index: found,
11048                    level: level as u8,
11049                    chain,
11050                });
11051            }
11052            current = current.proto()?;
11053        }
11054        None
11055    }
11056
11057    /// Which cache slot a lookup uses.
11058    ///
11059    /// Mixes the object's address, the name and the site, so that two properties of one
11060    /// object, and one property of two objects, land in different slots — which is what lets
11061    /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
11062    /// other iteration.
11063    fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
11064        let mut hash = match object {
11065            Value::Object(object) => object.address(),
11066            _ => 0,
11067        };
11068        hash = hash
11069            .wrapping_mul(0x9e37_79b9_7f4a_7c15)
11070            .rotate_left(17)
11071            .wrapping_add(key.hash_code());
11072        hash = hash.wrapping_add(site.wrapping_mul(31));
11073        // The table is a power of two, so the low bits are the slot.
11074        hash & (FIELD_CACHE_SLOTS - 1)
11075    }
11076
11077    /// Read `key` from `object`, without the inline cache.
11078    ///
11079    /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
11080    /// prototype chain, while the cached form answers an own data property from memory.
11081    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
11082        let text = key.as_str().unwrap_or("");
11083        let Value::Object(object) = object else {
11084            // Reading a property of `undefined`/`null` is the classic TypeError.
11085            if object.is_nullish() {
11086                return Err(Signal::Throw(self.make_error(
11087                    "TypeError",
11088                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
11089                )));
11090            }
11091            // A string has `length` and index access without being boxed.
11092            if let Value::String(value) = object {
11093                if text == "length" {
11094                    return Ok(Value::Int(value.utf16_len() as i32));
11095                }
11096                if let Some(index) = array_index(text) {
11097                    return Ok(match value.wtf8().unit_at(index as usize) {
11098                        Some(unit) => self.string_wtf8(unit),
11099                        None => Value::Undefined,
11100                    });
11101                }
11102            }
11103            // A property of a primitive is looked up on its prototype: this is what
11104            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
11105            let prototype = match object {
11106                Value::String(_) => self.realm.string_proto.clone(),
11107                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11108                Value::Bool(_) => self.realm.boolean_proto.clone(),
11109                // A symbol's methods live on `Symbol.prototype`, reached the same way —
11110                // `sym.description` reads through the prototype, not off the symbol.
11111                Value::Symbol(_) => self.realm.symbol_proto.clone(),
11112                // …and a bigint's on `BigInt.prototype`, which is how
11113                // `(255n).toString(16)` reaches its method.
11114                Value::BigInt(_) => self.realm.bigint_proto.clone(),
11115                _ => None,
11116            };
11117            if let Some(prototype) = prototype
11118                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
11119            {
11120                return Ok(value);
11121            }
11122            return Ok(Value::Undefined);
11123        };
11124        Ok(self
11125            .get_property_key(object, key)?
11126            .unwrap_or(Value::Undefined))
11127    }
11128
11129    /// The `#name` a private symbol stands for, for error messages.
11130    ///
11131    /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
11132    /// was made from.
11133    fn private_name(symbol: &Value) -> Option<String> {
11134        match symbol {
11135            Value::Symbol(symbol) if symbol.is_private() => Some(
11136                symbol
11137                    .description()
11138                    .map(|text| text.to_string())
11139                    .unwrap_or_default(),
11140            ),
11141            _ => None,
11142        }
11143    }
11144
11145    /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
11146    ///
11147    /// Every private-field opcode takes the symbol the class stored in its own scope; a
11148    /// non-symbol here would be a compiler bug, and the reference guards it with
11149    /// `JS_ThrowTypeErrorNotASymbol`.
11150    fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
11151        match symbol {
11152            Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
11153            _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
11154        }
11155    }
11156
11157    /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
11158    ///
11159    /// Three early errors, all from the reference: a non-object receiver, a non-extensible
11160    /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
11161    /// would hit if the parser did not reject it first.
11162    fn define_private_field(
11163        &mut self,
11164        object: &Value,
11165        symbol: &Value,
11166        value: Value,
11167    ) -> JsResult<()> {
11168        let key = self.private_key(symbol)?;
11169        let Some(target) = object.as_object() else {
11170            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11171        };
11172        if !target.is_extensible() {
11173            return Err(Signal::Throw(
11174                self.make_error("TypeError", "object is not extensible"),
11175            ));
11176        }
11177        if target.own_property_key(&key).is_some() {
11178            let name = Self::private_name(symbol).unwrap_or_default();
11179            return Err(Signal::Throw(self.make_error(
11180                "TypeError",
11181                &format!("private class field '{name}' already exists"),
11182            )));
11183        }
11184        target.define_data_key(&key, value);
11185        Ok(())
11186    }
11187
11188    /// `JS_GetPrivateField`: only an own property, never the prototype chain.
11189    fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
11190        let key = self.private_key(symbol)?;
11191        let Some(target) = object.as_object() else {
11192            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11193        };
11194        match target.own_property_key(&key) {
11195            Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
11196            None => {
11197                let name = Self::private_name(symbol).unwrap_or_default();
11198                Err(Signal::Throw(self.make_error(
11199                    "TypeError",
11200                    &format!("private class field '{name}' does not exist"),
11201                )))
11202            }
11203        }
11204    }
11205
11206    /// `JS_SetPrivateField`: the store half of the same rule.
11207    fn write_private_field(
11208        &mut self,
11209        object: &Value,
11210        symbol: &Value,
11211        value: Value,
11212    ) -> JsResult<()> {
11213        let key = self.private_key(symbol)?;
11214        let Some(target) = object.as_object() else {
11215            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11216        };
11217        if target.write_value_key(&key, value) {
11218            return Ok(());
11219        }
11220        let name = Self::private_name(symbol).unwrap_or_default();
11221        Err(Signal::Throw(self.make_error(
11222            "TypeError",
11223            &format!("private class field '{name}' does not exist"),
11224        )))
11225    }
11226
11227    /// The `in` half: does `object` have this private field?
11228    /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
11229    ///
11230    /// The symbol is created once per class — the first `add_brand` on a given home object
11231    /// makes it, every later one reuses it, which is what ties the prototype, the constructor
11232    /// and each instance to one identity. `obj` being `null` is not an error: the class-level
11233    /// emit for the *instance* brand passes null because all it wants is the symbol.
11234    fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
11235        let Some(home_object) = home.as_object() else {
11236            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11237        };
11238        let symbol = match home_object.private_brand() {
11239            Some(symbol) => symbol,
11240            None => {
11241                let symbol = Gc::new(
11242                    self.heap,
11243                    crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
11244                );
11245                home_object.set_private_brand(symbol.clone());
11246                symbol
11247            }
11248        };
11249        let Some(target) = object.as_object() else {
11250            // Not an object: nothing to brand. The reference does the same, and `undefined`
11251            // here would otherwise turn a field initialiser into a TypeError.
11252            return Ok(());
11253        };
11254        if !target.is_extensible() {
11255            return Err(Signal::Throw(
11256                self.make_error("TypeError", "object is not extensible"),
11257            ));
11258        }
11259        if target.carries_brand(&symbol) {
11260            return Err(Signal::Throw(
11261                self.make_error("TypeError", "private method is already present"),
11262            ));
11263        }
11264        target.add_brand(symbol);
11265        Ok(())
11266    }
11267
11268    /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
11269    ///
11270    /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
11271    /// decides whether to throw.
11272    fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
11273        let Some(function) = function.as_object() else {
11274            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11275        };
11276        let Some(home) = function.home_object() else {
11277            return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11278        };
11279        let Some(brand) = home.private_brand() else {
11280            return Err(Signal::Throw(
11281                self.make_error("TypeError", "expecting <brand> private field"),
11282            ));
11283        };
11284        Ok(object.carries_brand(&brand))
11285    }
11286
11287    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
11288        let Value::Object(object) = object else {
11289            return Err(Signal::Throw(self.make_error(
11290                "TypeError",
11291                &format!("cannot set property '{key}' of {}", object.to_js_string()),
11292            )));
11293        };
11294        // The write half of the property inline cache, in effect: an own, writable,
11295        // non-accessor data property already holds this key, so `[[Set]]` has nothing to
11296        // decide — no prototype walk (an own property shadows the chain before a setter
11297        // there could matter), no extensibility check (the object already has the key),
11298        // and no `[[DefineOwnProperty]]`.
11299        //
11300        // `this.value = …` inside a method is the whole write side of
11301        // `property:method-call`, and it was reaching `set_property_with_key` with its
11302        // proxy test, its typed-array test, its array-index test and finally a linear
11303        // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
11304        //
11305        // Every disqualifier is checked here: a proxy traps the set, an array index and
11306        // `length` live outside the property table, and a typed array's element is stored
11307        // through its view's element type.
11308        if object.proxy_state().is_none()
11309            && !object.is_array()
11310            && object.typed_array_element_type().is_none()
11311            && object.write_value_key(key, value.clone())
11312        {
11313            return Ok(());
11314        }
11315        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
11316        let on_failure = if self.frame().code.code.strict {
11317            DeleteFailure::Throw
11318        } else {
11319            DeleteFailure::Ignore
11320        };
11321        self.set_property_with_key(object, key, value, on_failure)
11322    }
11323
11324    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
11325    ///
11326    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
11327    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
11328    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
11329    /// `Number.parseInt(sym)` — so those callers use this instead.
11330    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
11331        if matches!(value, Value::Symbol(_)) {
11332            return Err(Signal::Throw(
11333                self.make_error("TypeError", "cannot convert symbol to string"),
11334            ));
11335        }
11336        // An object runs `ToPrimitive` first, which may itself produce a symbol —
11337        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
11338        let value = self.to_primitive(value.clone(), Hint::String)?;
11339        if matches!(value, Value::Symbol(_)) {
11340            return Err(Signal::Throw(
11341                self.make_error("TypeError", "cannot convert symbol to string"),
11342            ));
11343        }
11344        Ok(value.to_js_string())
11345    }
11346
11347    /// `ToPropertyKey` for a builtin that takes a key argument.
11348    ///
11349    /// Fallible: a key whose `toString` throws has to propagate that error, both for
11350    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
11351    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
11352    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
11353    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
11354        self.propkey(value)
11355    }
11356
11357    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
11358    ///
11359    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
11360    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
11361    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
11362    /// `RangeError` — and why this cannot be a plain `ToNumber`.
11363    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
11364        let number = match value {
11365            Value::Int(number) => *number as f64,
11366            Value::Float(number) => *number,
11367            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
11368            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
11369            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
11370            // reference answers 0.
11371            Value::Null | Value::Bool(_) => value.to_number(),
11372            _ => {
11373                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
11374                match primitive {
11375                    Value::Int(number) => number as f64,
11376                    Value::Float(number) => number,
11377                    other => {
11378                        // `ToString` then `ToNumber`, so a string length goes through the
11379                        // full numeric-literal grammar: `"0x00B"` is 11 and `"  5  "` is 5.
11380                        // `Value::to_number` on the string already implements exactly that.
11381                        let text = self.to_js_string(&other)?;
11382                        crate::value::string_to_number(&text)
11383                    }
11384                }
11385            }
11386        };
11387        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
11388        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
11389        // is a `RangeError`, not `0`.
11390        if !number.is_finite()
11391            || number.fract() != 0.0
11392            || !(0.0..=u32::MAX as f64).contains(&number)
11393        {
11394            return Err(self.range_error("invalid array length"));
11395        }
11396        Ok(number as u32)
11397    }
11398
11399    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
11400    /// `Object.getOwnPropertySymbols` put in their result array.
11401    pub fn key_value(&self, key: &PropertyKey) -> Value {
11402        match key {
11403            PropertyKey::String(text) => self.string_wtf8(text.clone()),
11404            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11405        }
11406    }
11407
11408    /// Fill in a String exotic object: `_value`, `length` and the index properties.
11409    ///
11410    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
11411    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
11412    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
11413    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
11414    /// the two paths had drifted; this is the one both now use.
11415    ///
11416    /// The indices are *code units*, so an astral character occupies two of them — the
11417    /// same rule `s.length` and `s[i]` follow.
11418    /// Give an already-created object the internal slot that makes it a wrapper of
11419    /// `value`, so the primitive's prototype methods work on it.
11420    ///
11421    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
11422    /// which are wrappers of their own type holding the empty value.
11423    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
11424        self.internal_set(object, "_value", value);
11425    }
11426
11427    pub(crate) fn init_string_wrapper(
11428        &mut self,
11429        object: &Gc<JsObject>,
11430        text: &Gc<crate::value::JsString>,
11431    ) {
11432        object.define(
11433            "length",
11434            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
11435        );
11436        for index in 0..text.utf16_len() {
11437            if let Some(unit) = text.wtf8().unit_at(index) {
11438                object.define(
11439                    &index.to_string(),
11440                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
11441                    Property::with_attributes(self.string_wtf8(unit), false, true),
11442                );
11443            }
11444        }
11445        object.define_key(
11446            &self.internal_slot("_value"),
11447            Property::with_attributes(Value::String(text.clone()), false, false),
11448        );
11449    }
11450
11451    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
11452    ///
11453    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
11454    /// throws. The wrapper carries its primitive in `_value` — the same slot
11455    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
11456    /// on a boxed value no constructor ever built.
11457    pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
11458        let (prototype, primitive) = match value {
11459            Value::Object(object) => return Ok(object.clone()),
11460            Value::String(text) => {
11461                let object = self.new_object(self.realm.string_proto.clone());
11462                self.init_string_wrapper(&object, text);
11463                return Ok(object);
11464            }
11465            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
11466            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
11467            // A symbol and a bigint box into wrappers whose methods live on
11468            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
11469            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
11470            // branch below instead produced an object with *no* prototype, so those
11471            // methods were unreachable on a box.
11472            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
11473            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
11474            Value::Undefined | Value::Null => {
11475                return Err(Signal::Throw(self.make_error(
11476                    "TypeError",
11477                    &format!("cannot convert {} to object", value.to_js_string()),
11478                )));
11479            }
11480            _ => (None, value.clone()),
11481        };
11482        let object = self.new_object(prototype);
11483        self.internal_set(&object, "_value", primitive);
11484        Ok(object)
11485    }
11486
11487    /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
11488    ///
11489    /// Split out for a reader that has to create the object *before* it knows what it wraps:
11490    /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
11491    /// written before its primitive, so the placeholder has to exist first and be filled in
11492    /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
11493    /// than a second in the deserialiser.
11494    pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
11495        let prototype = match value {
11496            Value::String(_) => self.realm.string_proto.clone(),
11497            Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11498            Value::Bool(_) => self.realm.boolean_proto.clone(),
11499            Value::Symbol(_) => self.realm.symbol_proto.clone(),
11500            Value::BigInt(_) => self.realm.bigint_proto.clone(),
11501            _ => {
11502                return Err(Signal::Throw(self.make_error(
11503                    "TypeError",
11504                    &format!("cannot box {}", value.to_js_string()),
11505                )));
11506            }
11507        };
11508        object.set_proto(prototype);
11509        if let Value::String(text) = value {
11510            self.init_string_wrapper(object, text);
11511            return Ok(());
11512        }
11513        self.internal_set(object, "_value", value.clone());
11514        Ok(())
11515    }
11516
11517    /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
11518    ///
11519    /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
11520    /// through the `Symbol` function object, so the registry is reachable as a method rather
11521    /// than only from `builtins::symbol`.
11522    pub fn symbol_for(&mut self, key: &str) -> Value {
11523        if let Some(existing) = self.realm.symbol_registry.get(key) {
11524            return existing.clone();
11525        }
11526        let symbol = crate::builtins::symbol::symbol_value(
11527            self,
11528            crate::value::JsSymbol::registered(key.to_string()),
11529        );
11530        self.realm
11531            .symbol_registry
11532            .insert(key.to_string(), symbol.clone());
11533        symbol
11534    }
11535
11536    /// `a == b`, the coercing comparison.
11537    ///
11538    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
11539    /// which is what makes `[] == ""` true: `[]` becomes `""` via
11540    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
11541    /// because the conversion is allowed to call script code, so the two primitive
11542    /// operands are handed back to it.
11543    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
11544        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
11545            return Ok(left.loose_equals(&right));
11546        }
11547        // `null == undefined` holds even though neither is an object.
11548        if matches!(left, Value::Undefined | Value::Null)
11549            && matches!(right, Value::Undefined | Value::Null)
11550        {
11551            return Ok(true);
11552        }
11553        if matches!(left, Value::Undefined | Value::Null)
11554            || matches!(right, Value::Undefined | Value::Null)
11555        {
11556            return Ok(false);
11557        }
11558        // Two objects compare by identity. Only an object *against a primitive* is
11559        // converted, which is why `{} == {}` is false while `[] == ""` is true.
11560        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
11561            return Ok(a.ptr_eq(b));
11562        }
11563        let left = self.to_primitive(left, Hint::Default)?;
11564        let right = self.to_primitive(right, Hint::Default)?;
11565        Ok(left.loose_equals(&right))
11566    }
11567
11568    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
11569        let Value::Object(object) = object else {
11570            return Err(Signal::Throw(
11571                self.make_error("TypeError", "cannot use 'in' on a non-object"),
11572            ));
11573        };
11574        let key = self.propkey(key)?;
11575        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
11576        // trap. One implementation, so an array's derived `length` and its inherited holes
11577        // cannot be right in one caller and wrong in another.
11578        self.has_own_or_inherited(object, &key)
11579    }
11580
11581    /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
11582    ///
11583    /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
11584    /// whole reason the operator is a hook rather than a prototype walk.
11585    pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11586        if let Value::Object(function) = constructor {
11587            let key = self.realm.well_known_key(WellKnown::HasInstance);
11588            let method = self.get_property_key(function, &key)?;
11589            if let Some(method) = method
11590                && !matches!(method, Value::Undefined)
11591            {
11592                let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
11593                return Ok(answer.to_boolean());
11594            }
11595        }
11596        self.instance_of(object, constructor)
11597    }
11598
11599    /// `OrdinaryHasInstance`: the prototype walk on its own.
11600    pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11601        self.instance_of(object, constructor)
11602    }
11603
11604    /// `IsArray`: an array, or a proxy whose target is one.
11605    ///
11606    /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
11607    /// makes `Array.isArray(new Proxy([], {}))` true.
11608    pub fn is_array_value(&self, value: &Value) -> bool {
11609        match value {
11610            Value::Object(object) => {
11611                if let Some(state) = object.proxy_state() {
11612                    return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
11613                }
11614                object.is_array()
11615            }
11616            _ => false,
11617        }
11618    }
11619
11620    /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
11621    ///
11622    /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
11623    /// in a Rust closure would hide GC values from the collector. A host-supplied job is
11624    /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
11625    /// see [`Interp::enqueue_job_function`].
11626    pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
11627        // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
11628        // the handler is reported rather than lost — the same reason a `then` reaction needs a
11629        // promise to settle.
11630        let promise = self.new_promise();
11631        self.fulfill_promise(&promise, Value::Undefined);
11632        self.jobs.push_back(Job::Reaction {
11633            handler: Some(function),
11634            argument: Value::Undefined,
11635            rejected: false,
11636            promise,
11637        });
11638        Ok(())
11639    }
11640
11641    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11642        let Value::Object(target) = object else {
11643            return Ok(false);
11644        };
11645        let Value::Object(function) = constructor else {
11646            return Err(Signal::Throw(self.make_error(
11647                "TypeError",
11648                "right-hand side of 'instanceof' is not callable",
11649            )));
11650        };
11651        let prototype = self.get_property(function, "prototype")?;
11652        let Some(Value::Object(prototype)) = prototype else {
11653            return Ok(false);
11654        };
11655        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
11656        // which is also what makes `proxyOfInstance instanceof C` work.
11657        let mut current = Some(target.clone());
11658        while let Some(object) = current {
11659            if object.ptr_eq(&prototype) {
11660                return Ok(true);
11661            }
11662            current = self.object_prototype_of(&object)?;
11663        }
11664        Ok(false)
11665    }
11666
11667    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
11668    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
11669        if let Some(proto) = self.proxy_get_prototype_of(object)? {
11670            return Ok(proto);
11671        }
11672        if let Some(exotic) = object.exotic()
11673            && let Some(proto) = exotic.get_prototype(self, object)?
11674        {
11675            return Ok(proto);
11676        }
11677        Ok(object.proto())
11678    }
11679
11680    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
11681    pub fn object_set_prototype_of(
11682        &mut self,
11683        object: &Gc<JsObject>,
11684        proto: Option<Gc<JsObject>>,
11685    ) -> JsResult<bool> {
11686        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
11687            return Ok(answer);
11688        }
11689        if let Some(exotic) = object.exotic()
11690            && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
11691        {
11692            return Ok(answer);
11693        }
11694        // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
11695        // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
11696        // inheriting from itself, which every later prototype walk then had to defend
11697        // against — and `Reflect.setPrototypeOf` reported success for an operation the
11698        // language says is impossible.
11699        if let Some(proto) = &proto {
11700            let mut current = Some(proto.clone());
11701            let mut guard = 0;
11702            while let Some(node) = current {
11703                if node.ptr_eq(object) {
11704                    return Err(Signal::Throw(
11705                        self.make_error("TypeError", "circular prototype chain"),
11706                    ));
11707                }
11708                guard += 1;
11709                if guard > 1000 {
11710                    break;
11711                }
11712                current = node.proto();
11713            }
11714        }
11715        object.set_proto(proto);
11716        Ok(true)
11717    }
11718
11719    /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
11720    ///
11721    /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
11722    /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
11723    /// already one.
11724    pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
11725        let mut current = Some(object.clone());
11726        // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
11727        let mut guard = 0;
11728        while let Some(node) = current {
11729            guard += 1;
11730            if guard > 1000 {
11731                return Ok(false);
11732            }
11733            let own = self.object_get_own_property(&node, key)?;
11734            if own.is_some() {
11735                return Ok(true);
11736            }
11737            current = self.object_prototype_of(&node)?;
11738        }
11739        Ok(false)
11740    }
11741
11742    /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
11743    ///
11744    /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
11745    /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
11746    /// boolean as well, and it needs the receiver to be the one the caller named.
11747    pub fn set_property_with_key_receiver(
11748        &mut self,
11749        object: &Gc<JsObject>,
11750        key: &PropertyKey,
11751        value: Value,
11752        receiver: Option<&Value>,
11753        on_failure: DeleteFailure,
11754    ) -> JsResult<bool> {
11755        let receiver = receiver
11756            .cloned()
11757            .unwrap_or_else(|| Value::Object(object.clone()));
11758        if object.proxy_state().is_some() {
11759            return match self.proxy_set(object, key, value, &receiver)? {
11760                Some(accepted) => Ok(accepted),
11761                None => Ok(true),
11762            };
11763        }
11764        // An own accessor, or one found up the chain, receives the call with `receiver` as
11765        // `this` — which is the whole reason this variant exists.
11766        if let Some(setter) = self.lookup_setter(object, key)? {
11767            self.call_value(setter, receiver, vec![value])?;
11768            return Ok(true);
11769        }
11770        // Otherwise it is an ordinary create-or-write, which the plain path already does.
11771        self.set_property_with_key(object, key, value, on_failure)?;
11772        Ok(true)
11773    }
11774
11775    /// The setter `key` resolves to, if it resolves to an accessor.
11776    fn lookup_setter(
11777        &mut self,
11778        object: &Gc<JsObject>,
11779        key: &PropertyKey,
11780    ) -> JsResult<Option<Value>> {
11781        let mut current = Some(object.clone());
11782        let mut guard = 0;
11783        while let Some(node) = current {
11784            guard += 1;
11785            if guard > 1000 {
11786                return Ok(None);
11787            }
11788            if let Some(property) = self.object_get_own_property(&node, key)? {
11789                if property.is_accessor() {
11790                    return Ok(property.setter);
11791                }
11792                // A data property stops the walk: the store writes here, not further up.
11793                return Ok(None);
11794            }
11795            current = self.object_prototype_of(&node)?;
11796        }
11797        Ok(None)
11798    }
11799
11800    /// `[[IsExtensible]]`, with the proxy trap when there is one.
11801    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
11802        if let Some(answer) = self.proxy_is_extensible(object)? {
11803            return Ok(answer);
11804        }
11805        if let Some(exotic) = object.exotic()
11806            && let Some(answer) = exotic.is_extensible(self, object)?
11807        {
11808            return Ok(answer);
11809        }
11810        Ok(object.is_extensible())
11811    }
11812
11813    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
11814    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
11815        if let Some(answer) = self.proxy_prevent_extensions(object)? {
11816            return Ok(answer);
11817        }
11818        if let Some(exotic) = object.exotic()
11819            && let Some(answer) = exotic.prevent_extensions(self, object)?
11820        {
11821            return Ok(answer);
11822        }
11823        object.set_extensible(false);
11824        Ok(true)
11825    }
11826
11827    fn copy_properties(
11828        &mut self,
11829        target: &Value,
11830        source: &Value,
11831        exclusion: &Value,
11832    ) -> JsResult<()> {
11833        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
11834        // does contribute: its index properties are own, enumerable and writable, which
11835        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
11836        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
11837        // is a no-op.
11838        let Some(target) = target.as_object() else {
11839            return Ok(());
11840        };
11841        let source_object = match source {
11842            Value::Object(object) => object.clone(),
11843            Value::String(text) => {
11844                // Untaken keys are the string's indices, which are code units.
11845                for index in 0..text.utf16_len() {
11846                    if let Some(unit) = text.wtf8().unit_at(index) {
11847                        target.define_data(&index.to_string(), self.string_wtf8(unit));
11848                    }
11849                }
11850                return Ok(());
11851            }
11852            _ => return Ok(()),
11853        };
11854        // An object *rest* element passes the keys already taken by the literal part as
11855        // an array of strings; a spread passes `null`, which excludes nothing. Only the
11856        // string keys of the exclusion array are meaningful, so an array is read by its
11857        // elements rather than by its own property names.
11858        let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
11859        if let Value::Object(list) = exclusion
11860            && let Some(length) = list.array_length()
11861        {
11862            for index in 0..length {
11863                if let Some(value) = list.array_get(index) {
11864                    excluded.push(self.propkey_of(&value)?);
11865                }
11866            }
11867        }
11868        let source = &source_object;
11869        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
11870        // Reading the property table directly made every spread of a proxy empty.
11871        let keys = self.object_own_property_keys(source)?;
11872        for as_key in keys {
11873            if as_key.is_symbol() {
11874                // A spread copies string-keyed properties only.
11875                continue;
11876            }
11877            if excluded.contains(&crate::value::Wtf8::new(
11878                as_key.as_str().unwrap_or_default(),
11879            )) {
11880                continue;
11881            }
11882            let enumerable = self
11883                .object_get_own_property(source, &as_key)?
11884                .is_some_and(|property| property.enumerable);
11885            if !enumerable {
11886                continue;
11887            }
11888            let value = self
11889                .get_property_key(source, &as_key)?
11890                .unwrap_or(Value::Undefined);
11891            target.define_data_key(&as_key, value);
11892        }
11893        Ok(())
11894    }
11895
11896    // -- iteration ---------------------------------------------------------
11897
11898    /// One object's own keys in enumeration order: array indices ascending, then the
11899    /// rest in insertion order.
11900    ///
11901    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
11902    /// whether the key is enumerable, which the caller resolves per key because an
11903    /// array's elements are not in the same store as its named properties.
11904    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
11905        // An index can arrive twice, once from the array's element store and once from
11906        // its property map, so the numeric keys go through a map that keeps the
11907        // enumerable answer if either source gave one.
11908        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
11909        for (key, enumerable) in &own {
11910            if let Some(index) = key.as_str().and_then(array_index) {
11911                let entry = numeric.entry(index).or_insert(false);
11912                *entry = *entry || *enumerable;
11913            }
11914        }
11915        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
11916            .into_iter()
11917            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
11918            .collect();
11919        ordered.extend(
11920            own.into_iter()
11921                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
11922        );
11923        ordered
11924    }
11925
11926    /// Build the key list a `for-in` loop walks.
11927    ///
11928    /// The order is the specification's: own properties before inherited ones, and
11929    /// within one object the integer-like keys in ascending numeric order ahead of the
11930    /// string keys in insertion order. A shadowed key only appears once, and a key that
11931    /// is a non-enumerable own property anywhere nearer is skipped entirely.
11932    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
11933        let record = self.new_object(None);
11934        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
11935        // A proxy supplies its own key list, and — the reason this is not just another
11936        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
11937        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
11938        // descriptor there.
11939        if let Value::Object(object) = value
11940            && object.proxy_state().is_some()
11941        {
11942            let own = self
11943                .proxy_own_keys(object)?
11944                .unwrap_or_else(|| object.own_property_keys());
11945            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
11946            let mut numeric: Vec<u32> = Vec::new();
11947            let mut rest: Vec<PropertyKey> = Vec::new();
11948            for key in own {
11949                match key.as_str().and_then(array_index) {
11950                    Some(index) => numeric.push(index),
11951                    None => rest.push(key),
11952                }
11953            }
11954            numeric.sort_unstable();
11955            ordered.extend(
11956                numeric
11957                    .into_iter()
11958                    .map(|index| PropertyKey::from(index.to_string())),
11959            );
11960            ordered.extend(rest);
11961            for (index, key) in ordered.into_iter().enumerate() {
11962                record.define_data(&index.to_string(), self.key_value(&key));
11963            }
11964            record.define_data("__index", Value::Int(0));
11965            // The mark that makes `for_in_advance` re-ask the proxy per key.
11966            record.define_data("__proxy", Value::Object(object.clone()));
11967            return Ok(record);
11968        }
11969        if let Value::Object(object) = value {
11970            let mut chain = vec![object.clone()];
11971            chain.extend(object.chain());
11972            // Every own string key the walk has seen, enumerable or not. A
11973            // non-enumerable own property still hides a same-named enumerable one
11974            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
11975            // keeps `x` out of the loop even when the prototype has one.
11976            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
11977            for object in chain {
11978                let mut own: Vec<(crate::value::Wtf8, bool)> = object
11979                    .own_property_keys()
11980                    .iter()
11981                    .filter_map(|key| key.as_wtf8().cloned())
11982                    .map(|key| {
11983                        let enumerable = object
11984                            .own_property(&key.to_string_lossy())
11985                            .map(|property| property.enumerable)
11986                            .unwrap_or(false);
11987                        (key, enumerable)
11988                    })
11989                    .collect();
11990                if let Some(length) = object.array_length() {
11991                    own.retain(|(key, _)| key.as_str() != Some("length"));
11992                    for index in 0..length {
11993                        if object.array_get(index).is_some() {
11994                            own.push((crate::value::Wtf8::new(index.to_string()), true));
11995                        }
11996                    }
11997                }
11998                // Integer-like keys come first in ascending order, then the rest in
11999                // insertion order — and the ordering is *per object*, not for the chain
12000                // as a whole: one pass over every collected key lifted a prototype's
12001                // `"4"` above the target's own `x`/`y`, which is not the order
12002                // `for…in` reports.
12003                for (key, enumerable) in Self::order_own_keys(own) {
12004                    if visited.contains(&key) {
12005                        continue;
12006                    }
12007                    visited.push(key.clone());
12008                    if enumerable {
12009                        keys.push(key);
12010                    }
12011                }
12012            }
12013        }
12014        for (index, key) in keys.into_iter().enumerate() {
12015            record.define_data(&index.to_string(), self.string_wtf8(key));
12016        }
12017        record.define_data("__index", Value::Int(0));
12018        Ok(record)
12019    }
12020
12021    /// The next key of a `for…in` record, `None` when the loop is done.
12022    ///
12023    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
12024    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
12025    /// the loop reaches it, so a handler that stops reporting a key partway through drops
12026    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
12027    /// key the handler had already withdrawn.
12028    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
12029        let Value::Object(record) = record else {
12030            return Ok(None);
12031        };
12032        let proxy = record
12033            .own_property("__proxy")
12034            .and_then(|property| property.value);
12035        loop {
12036            let index = record
12037                .own_property("__index")
12038                .and_then(|property| property.value)
12039                .map(|value| value.to_int32())
12040                .unwrap_or(0);
12041            let Some(candidate) = record
12042                .own_property(&index.to_string())
12043                .and_then(|property| property.value)
12044            else {
12045                return Ok(None);
12046            };
12047            record.define_data("__index", Value::Int(index + 1));
12048            let text = candidate.to_js_string();
12049            let Some(Value::Object(proxy)) = &proxy else {
12050                return Ok(Some(text));
12051            };
12052            // The candidate is already a key string here, so the lookup does not need a
12053            // second `ToPropertyKey` conversion.
12054            let key = PropertyKey::from(text.as_str());
12055            let live = match self.proxy_get_own_property(proxy, &key)? {
12056                Some(descriptor) => descriptor,
12057                // Not a proxy after all, or it lost its state: fall back to the target.
12058                None => proxy.own_property_key(&key),
12059            };
12060            if live.is_some_and(|property| property.enumerable) {
12061                return Ok(Some(text));
12062            }
12063            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
12064            // next one.
12065        }
12066    }
12067
12068    /// The iterator for `for-of`: the object and its `next` method.
12069    ///
12070    /// An object that already carries a `next` method is used as it is — that is what
12071    /// `arr.values()` returns — and only arrays and strings get the built-in
12072    /// sequence iterator.
12073    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
12074    ///
12075    /// Callers that must choose between the iterable and the array-like protocol — the
12076    /// typed-array constructor is the main one — need to ask *before* committing to one.
12077    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
12078        let key = self.realm.well_known_key(WellKnown::Iterator);
12079        let method = self.read_field_key(value, &key)?;
12080        if matches!(method, Value::Undefined | Value::Null) {
12081            return Ok(false);
12082        }
12083        if !matches!(&method, Value::Object(object) if object.is_callable()) {
12084            return Err(Signal::Throw(
12085                self.make_error("TypeError", "Symbol.iterator is not callable"),
12086            ));
12087        }
12088        Ok(true)
12089    }
12090
12091    /// Collect everything an iterable yields, closing it if the walk is abandoned.
12092    ///
12093    /// The cap is a guard against a generator that never ends: an unbounded collect would
12094    /// be an out-of-memory abort rather than a catchable error.
12095    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
12096        const MAX_ITEMS: usize = 1 << 24;
12097        let iterator = self.get_iterator(value)?;
12098        let mut out = Vec::new();
12099        loop {
12100            let (element, done) = self.iterator_step(&iterator)?;
12101            if done {
12102                return Ok(out);
12103            }
12104            out.push(element);
12105            if out.len() > MAX_ITEMS {
12106                return Err(self.range_error("iterable is too long to collect"));
12107            }
12108        }
12109    }
12110
12111    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
12112    ///
12113    /// A native constructor calls this once it has validated its arguments, which is the
12114    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
12115    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
12116    /// never reached. The prototype comes from `new.target` when it is an object, and from
12117    /// `default_proto` otherwise.
12118    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12119        let proto = self.ctor_prototype(default_proto)?;
12120        Ok(self.new_object(Some(proto)))
12121    }
12122
12123    /// An **array** whose prototype comes from `new.target`.
12124    ///
12125    /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
12126    /// instance from `new.target.prototype`, and building a plain array instead made every
12127    /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
12128    pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
12129        let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
12130        Ok(JsObject::array(self.heap, Some(proto), 0))
12131    }
12132
12133    /// `new.target.prototype` when this is a construction, or `None` for a plain call.
12134    ///
12135    /// The `Option` form is for the constructors that build their instance in a helper which
12136    /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
12137    /// from `await`'s internal promise, and only the first has a `new.target`.
12138    fn ctor_prototype_opt(
12139        &mut self,
12140        default_proto: Option<Gc<JsObject>>,
12141    ) -> JsResult<Option<Gc<JsObject>>> {
12142        let Some(target) = self.pending_new_target.clone() else {
12143            return Ok(default_proto);
12144        };
12145        let Some(target) = target.as_object().cloned() else {
12146            return Ok(default_proto);
12147        };
12148        match self.get_property(&target, "prototype")? {
12149            Some(Value::Object(proto)) => Ok(Some(proto)),
12150            _ => Ok(default_proto),
12151        }
12152    }
12153
12154    /// `new.target.prototype`, or `default_proto` when this is a plain call.
12155    fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12156        let Some(target) = self.pending_new_target.clone() else {
12157            return Ok(default_proto);
12158        };
12159        let Some(target) = target.as_object().cloned() else {
12160            return Ok(default_proto);
12161        };
12162        match self.get_property(&target, "prototype")? {
12163            Some(Value::Object(proto)) => Ok(proto),
12164            _ => Ok(default_proto),
12165        }
12166    }
12167
12168    /// `CreateDataPropertyOrThrow(O, key, value)`.
12169    ///
12170    /// A *definition*, not an assignment. The difference is visible the moment the target
12171    /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
12172    /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
12173    /// replaces the descriptor. It is a `TypeError` only when the definition itself is
12174    /// refused (`configurable: false`).
12175    ///
12176    /// The fast path exists because this is called once per element by `map`, `filter`,
12177    /// `slice` and friends: a plain array with no custom element descriptors and a writable
12178    /// `length` can store straight into its element vector.
12179    pub fn create_data_property_or_throw(
12180        &mut self,
12181        object: &Gc<JsObject>,
12182        index: usize,
12183        value: Value,
12184    ) -> JsResult<()> {
12185        if object.is_array()
12186            && object.elements_writable()
12187            && !object.has_element_descriptors()
12188            && object.is_extensible()
12189            && object.array_set(self.heap, index, value.clone())
12190        {
12191            return Ok(());
12192        }
12193        let key = PropertyKey::from(index.to_string());
12194        let property = Property {
12195            value: Some(value),
12196            writable: true,
12197            enumerable: true,
12198            configurable: true,
12199            ..Property::default()
12200        };
12201        if self.object_define_own_property(object, &key, property)? {
12202            return Ok(());
12203        }
12204        Err(self.type_error("cannot create the property"))
12205    }
12206
12207    /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
12208    ///
12209    /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
12210    /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
12211    /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
12212    /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
12213    /// run user code and both can throw.
12214    pub fn species_constructor(
12215        &mut self,
12216        object: &Gc<JsObject>,
12217        default: Value,
12218    ) -> JsResult<Value> {
12219        let Some(constructor) = self.get_property(object, "constructor")? else {
12220            return Ok(default);
12221        };
12222        let constructor = match constructor {
12223            Value::Undefined => return Ok(default),
12224            Value::Object(constructor) => constructor,
12225            _ => return Err(self.type_error("constructor is not an object")),
12226        };
12227        let key = self.realm.well_known_key(WellKnown::Species);
12228        let species = self.get_property_key(&constructor, &key)?;
12229        match species {
12230            None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
12231            Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
12232            Some(_) => Err(self.type_error("species is not a constructor")),
12233        }
12234    }
12235
12236    /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
12237    ///
12238    /// The result is an array of `length` holes whose prototype comes from
12239    /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
12240    /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
12241    /// is why the `IsArray` check is the first step and not an optimisation.
12242    pub fn array_species_create(
12243        &mut self,
12244        original: &Value,
12245        length: usize,
12246    ) -> JsResult<Gc<JsObject>> {
12247        let Some(object) = original.as_object().cloned() else {
12248            return Ok(self.new_array_of_length(length));
12249        };
12250        if !object.is_array() {
12251            return Ok(self.new_array_of_length(length));
12252        }
12253        // A `constructor` that *is* this realm's `Array` means "the default", and skipping
12254        // it here is what keeps `Array.prototype.map` from calling `Array` at all.
12255        let Some(constructor) = self.get_property(&object, "constructor")? else {
12256            return Ok(self.new_array_of_length(length));
12257        };
12258        let species = match constructor {
12259            Value::Undefined => return Ok(self.new_array_of_length(length)),
12260            Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
12261                return Ok(self.new_array_of_length(length));
12262            }
12263            Value::Object(constructor) => {
12264                let key = self.realm.well_known_key(WellKnown::Species);
12265                match self.get_property_key(&constructor, &key)? {
12266                    None | Some(Value::Undefined) | Some(Value::Null) => {
12267                        return Ok(self.new_array_of_length(length));
12268                    }
12269                    Some(species) => species,
12270                }
12271            }
12272            _ => return Ok(self.new_array_of_length(length)),
12273        };
12274        // `IsConstructor(species)` decides whether step 7 may construct at all; a species
12275        // that is merely callable is the `create-species-non-ctor` case.
12276        if !matches!(&species, Value::Object(object) if object.is_constructor()) {
12277            return Err(self.type_error("species is not a constructor"));
12278        }
12279        let created = self.construct(species.clone(), species, vec![Value::Int(length as i32)])?;
12280        let Some(created) = created.as_object().cloned() else {
12281            return Err(self.type_error("species constructor did not answer an object"));
12282        };
12283        // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
12284        // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
12285        // object, and `create-species-with-non-writable-property` asserts exactly that.
12286        // The length is set for the array case; the generic case is the caller's
12287        // `Set(A, "length", …)`.
12288        if created.is_array() {
12289            created.array_set_length(self.heap, length);
12290        }
12291        Ok(created)
12292    }
12293
12294    /// Whether `object` is this realm's `%Array%`.
12295    fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
12296        self.realm
12297            .array_constructor
12298            .as_ref()
12299            .is_some_and(|array| array.ptr_eq(object))
12300    }
12301
12302    /// A fresh `length`-hole array with the intrinsic prototype.
12303    pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
12304        let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
12305        array.array_set_length(self.heap, length);
12306        array
12307    }
12308
12309    /// Whether this call is a construction, i.e. `new.target` is defined.
12310    ///
12311    /// A native constructor receives `this = undefined` (it builds its own instance), so it
12312    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
12313    /// The native function currently executing, if any.
12314    pub fn current_native(&self) -> Option<Gc<JsObject>> {
12315        self.current_native.clone()
12316    }
12317
12318    /// Whether this call is a construction, i.e. `new.target` is defined.
12319    pub fn is_constructing(&self) -> bool {
12320        self.pending_new_target.is_some()
12321    }
12322
12323    /// The `TypeError` a constructor too primitive to have a wrapper raises.
12324    ///
12325    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
12326    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
12327    /// happens inside the native function, which is why the trace carries an
12328    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
12329    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
12330    /// constructor`, and an unnamed one reports the leading space of `" is not a
12331    /// constructor"` because the reference formats the empty name as it is.
12332    ///
12333    /// It is also the answer for a `new.target` that cannot be named at all — not a
12334    /// function, or a throwing `name` getter — where the reference falls back to the bare
12335    /// `not a constructor`.
12336    pub fn not_a_constructor_error(&mut self) -> Signal {
12337        let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
12338        self.not_a_constructor_error_for(target)
12339    }
12340
12341    /// The same `TypeError` for an explicit target, for the callers that check
12342    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
12343    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
12344        let target = match target {
12345            Value::Object(target) if target.is_callable() => target,
12346            _ => return self.type_error("not a constructor"),
12347        };
12348        let name = match self.get_property(&target, "name") {
12349            Ok(Some(value)) => value.to_js_string(),
12350            _ => return self.type_error("not a constructor"),
12351        };
12352        self.type_error(format!("{name} is not a constructor"))
12353    }
12354
12355    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
12356    ///
12357    /// True whenever `new.target` is not the callee itself, or when it has no usable
12358    /// `prototype` — the cases where reading the property is observable at all.
12359    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
12360        match &self.pending_new_target {
12361            Some(Value::Object(target)) => !target.ptr_eq(callee),
12362            Some(_) => true,
12363            None => false,
12364        }
12365    }
12366
12367    /// The symbol key for one of the engine's own hidden slots.
12368    ///
12369    /// Cached on the realm, so every object of a kind shares one key and a slot can be
12370    /// read back by name.
12371    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
12372        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
12373            return PropertyKey::Symbol(symbol.clone());
12374        }
12375        let symbol = Gc::new(
12376            self.heap,
12377            crate::value::JsSymbol::new(Some(name.to_string())),
12378        );
12379        self.realm
12380            .internal_slots
12381            .borrow_mut()
12382            .insert(name, Value::Symbol(symbol.clone()));
12383        PropertyKey::Symbol(symbol)
12384    }
12385
12386    /// Read a hidden slot, or `None` when the object has none of that name.
12387    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
12388        let slots = self.realm.internal_slots.borrow();
12389        let Value::Symbol(symbol) = slots.get(name)? else {
12390            return None;
12391        };
12392        object
12393            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
12394            .and_then(|property| property.value)
12395    }
12396
12397    /// Define a hidden slot.
12398    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
12399        let key = self.internal_slot(name);
12400        object.define_key(&key, Property::with_attributes(value, false, false));
12401    }
12402
12403    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
12404    ///
12405    /// The method is looked up on the value (through its prototype), called with no
12406    /// arguments, and its result becomes the iterator. A generator gets here through
12407    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
12408    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
12409    ///
12410    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
12411    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
12412    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
12413    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
12414    /// does, and a user-defined iterable works without a special case.
12415    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
12416    /// `Symbol.iterator`.
12417    ///
12418    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
12419    /// iterable is legal there, and each value it produces is simply already settled by
12420    /// the time the `await` around it runs.
12421    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12422        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
12423        let method = self.read_field_key(value, &async_key)?;
12424        // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
12425        // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
12426        // is *present but not callable* is a TypeError — it does not mean "try the other
12427        // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
12428        // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
12429        // guard is there to catch.
12430        let absent = matches!(method, Value::Undefined | Value::Null);
12431        if !absent {
12432            let Value::Object(object) = &method else {
12433                return Err(Signal::Throw(
12434                    self.make_error("TypeError", "value is not iterable"),
12435                ));
12436            };
12437            if !object.is_callable() {
12438                return Err(Signal::Throw(
12439                    self.make_error("TypeError", "value is not iterable"),
12440                ));
12441            }
12442        }
12443        if absent {
12444            return self.get_iterator(value);
12445        }
12446        let iterator = self.call_value(method, value.clone(), Vec::new())?;
12447        if !matches!(iterator, Value::Object(_)) {
12448            return Err(Signal::Throw(
12449                self.make_error("TypeError", "iterator is not an object"),
12450            ));
12451        }
12452        let next = self.read_field(&iterator, "next")?;
12453        Ok(Iterator {
12454            object: iterator,
12455            next,
12456        })
12457    }
12458
12459    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12460        let key = self.realm.well_known_key(WellKnown::Iterator);
12461        let method = self.read_field_key(value, &key)?;
12462        let Value::Object(function) = &method else {
12463            return Err(Signal::Throw(self.make_error(
12464                "TypeError",
12465                &format!("{} is not iterable", value.to_js_string()),
12466            )));
12467        };
12468        if !function.is_callable() {
12469            return Err(Signal::Throw(self.make_error(
12470                "TypeError",
12471                &format!("{} is not iterable", value.to_js_string()),
12472            )));
12473        }
12474        let iterator = self.call_value(method, value.clone(), Vec::new())?;
12475        // The spec requires an object here; a primitive iterator has no `next` to call
12476        // and would fail one step later with a confusing message.
12477        if !matches!(iterator, Value::Object(_)) {
12478            return Err(Signal::Throw(
12479                self.make_error("TypeError", "iterator is not an object"),
12480            ));
12481        }
12482        let next = self.read_field(&iterator, "next")?;
12483        Ok(Iterator {
12484            object: iterator,
12485            next,
12486        })
12487    }
12488
12489    /// Drain anything with a `Symbol.iterator` method, or answer `None` when the value is
12490    /// not iterable.
12491    ///
12492    /// Shared so that `Array.from`, the `Promise` combinators and `for…of` all agree on
12493    /// what "iterable" means. A `Map` and a `Set` have no `length`, so an array-like-only
12494    /// reader silently produced an empty array for both — `Array.from(new Set([1,2]))`
12495    /// was `[]`.
12496    pub fn iterable_values(&mut self, value: &Value) -> JsResult<Option<Vec<Value>>> {
12497        let key = self.realm.well_known_key(WellKnown::Iterator);
12498        let method = self.read_field_key(value, &key)?;
12499        if !matches!(&method, Value::Object(object) if object.is_callable()) {
12500            return Ok(None);
12501        }
12502        let iterator = self.get_iterator(value)?;
12503        let mut out = Vec::new();
12504        loop {
12505            let (element, done) = self.iterator_step(&iterator)?;
12506            if done {
12507                return Ok(Some(out));
12508            }
12509            out.push(element);
12510        }
12511    }
12512
12513    /// One step of an internal iterator: the value and whether it is exhausted.
12514    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
12515        // A real iterator (`next` is a function) answers with a result object.
12516        if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
12517            let result =
12518                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
12519            let Some(result) = result.as_object().cloned() else {
12520                return Err(self.type_error("iterator result is not an object"));
12521            };
12522            let done = self
12523                .get_property(&result, "done")?
12524                .is_some_and(|value| value.to_boolean());
12525            let value = self
12526                .get_property(&result, "value")?
12527                .unwrap_or(Value::Undefined);
12528            return Ok((value, done));
12529        }
12530        // An iterator whose `next` is not callable is treated as exhausted, which is
12531        // what `for (x of {})` relies on: `for_of_start` has already refused the ones
12532        // that are not iterable at all.
12533        Ok((Value::Undefined, true))
12534    }
12535
12536    /// `[...iterable]`: append everything the iterator yields, and answer the next
12537    /// index.
12538    ///
12539    /// This goes through the same iterator machinery `for-of` uses rather than copying
12540    /// an array's elements, because a spread source is any iterable: a string spreads
12541    /// into its characters and an array iterator spreads into its results. Handling
12542    /// only arrays made `[..."ab"]` come out empty with no error at all.
12543    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
12544        let Some(target) = array.as_object().cloned() else {
12545            return Ok(0);
12546        };
12547        let start = target.array_length().unwrap_or(0);
12548        let mut added = 0;
12549        let iterator = self.get_iterator(iterable)?;
12550        loop {
12551            let (value, done) = self.iterator_step(&iterator)?;
12552            if done {
12553                break;
12554            }
12555            target.array_set(self.heap, start + added, value);
12556            added += 1;
12557        }
12558        Ok((start + added) as i32)
12559    }
12560
12561    /// How an uncaught exception is reported.
12562    ///
12563    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
12564    /// with `ToString` — `js_std_dump_error` is three lines that end in
12565    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
12566    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
12567    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
12568    ///
12569    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
12570    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
12571    /// `toString`"; it does call it, but only for objects of a class it does not know how
12572    /// to walk, and never for errors, arrays or plain objects.
12573    ///
12574    /// A printer that fails must not take the reporter down with it, so that case falls
12575    /// back to the `ToString` rendering.
12576    pub fn describe_exception(&mut self, value: &Value) -> String {
12577        match crate::print::sprint(self, value) {
12578            Ok(text) => text,
12579            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
12580        }
12581    }
12582
12583    /// The file name of whatever is running, innermost frame first.
12584    ///
12585    /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
12586    /// innermost frame's file name, without distinguishing a module body from a plain
12587    /// script. `import()` uses it as the base for a relative specifier, which is why
12588    /// `import('./x.js')` inside a script resolves next to the script and not next to the
12589    /// process's working directory.
12590    pub fn script_or_module_name(&self) -> Option<String> {
12591        self.script_or_module_name_at(0)
12592    }
12593
12594    /// [`Interp::script_or_module_name`] `level` frames further out.
12595    ///
12596    /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
12597    /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
12598    /// frame without a file name is skipped rather than counted, because a native call
12599    /// pushes no frame of its own and so cannot be a level.
12600    pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
12601        self.frames
12602            .iter()
12603            .rev()
12604            .filter_map(|frame| frame.code.code.filename.clone())
12605            .nth(level)
12606    }
12607
12608    /// The current call stack, formatted the way `qjs` prints `error.stack`.
12609    ///
12610    /// One `    at name (file:line:col)` line per active frame, innermost first. The
12611    /// position is the one recorded for the instruction each frame is stopped on, which
12612    /// is why the compiler builds a pc-to-position table per function: without it a
12613    /// trace could only name the function, not the line inside it.
12614    ///
12615    /// A frame whose code has no positions prints just `(file)`, matching the
12616    /// reference's output for stripped bytecode.
12617    pub fn stack_trace(&self) -> String {
12618        self.stack_trace_skipping(0)
12619    }
12620
12621    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
12622    fn stack_trace_skipping(&self, skip: usize) -> String {
12623        // One ordered list, innermost first, so `skip` counts the same thing whether the
12624        // frames it leaves out are native or bytecode. Indices rather than references: a
12625        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
12626        let depth = self.frames.len();
12627        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
12628        // A native entered while `at` bytecode frames were live was called *from* the
12629        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
12630        // entered at the current depth are therefore innermost of all.
12631        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
12632            for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
12633                if *at == wanted {
12634                    order.push((true, index));
12635                }
12636            }
12637        };
12638        push_natives(&mut order, depth);
12639        for index in (0..depth).rev() {
12640            order.push((false, index));
12641            push_natives(&mut order, index);
12642        }
12643        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
12644        // barrier. Natives entered at exactly the barrier depth are the eval entry point
12645        // itself (`evalScript (native)`), and the reference leaves those out too.
12646        if let Some(barrier) = self.trace_barriers.last().copied() {
12647            order.retain(|(is_native, index)| match is_native {
12648                true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
12649                false => *index >= barrier,
12650            });
12651        }
12652
12653        let mut out = String::new();
12654        for (is_native, index) in order.into_iter().skip(skip) {
12655            match is_native {
12656                true => {
12657                    out.push_str("    at ");
12658                    let (native, _) = &self.native_frames[index];
12659                    let name = native
12660                        .own_property("name")
12661                        .and_then(|property| property.value)
12662                        .map(|value| value.to_js_string())
12663                        .unwrap_or_default();
12664                    out.push_str(&name);
12665                    out.push_str(" (native)\n");
12666                }
12667                false => {
12668                    let frame = &self.frames[index];
12669                    let code = &frame.code.code;
12670                    let file = code.filename.as_deref().unwrap_or("<input>");
12671                    // The name comes from the function *object*, not from the compiled code:
12672                    // an anonymous function expression is named by the property it is stored
12673                    // in (`{valueOf: function(){}}`), which only the object knows.
12674                    let bound_name = match &frame.callee {
12675                        Value::Object(object) => {
12676                            object
12677                                .own_property("name")
12678                                .and_then(|property| match property.value {
12679                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
12680                                        Some(text.to_string_lossy().into_owned())
12681                                    }
12682                                    _ => None,
12683                                })
12684                        }
12685                        _ => None,
12686                    };
12687                    // No callee object means the body was entered by the host, so the
12688                    // name has to come from the compiled code. Two cases differ:
12689                    //
12690                    // * an *unnamed* function of any kind — the reference reads the
12691                    //   `name` property, finds it empty, and prints `<anonymous>`;
12692                    // * a *module* body, which has no `name` property at all: the
12693                    //   reference builds that function object with `js_closure2` and
12694                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
12695                    //   so a trace reaching it also prints `<anonymous>` — while a
12696                    //   *script* body prints `<eval>`, its `name`.
12697                    let unnamed = code.name.is_empty() || code.module.is_some();
12698                    out.push_str("    at ");
12699                    match bound_name.as_deref() {
12700                        Some(name) => out.push_str(name),
12701                        None if unnamed => out.push_str("<anonymous>"),
12702                        None => out.push_str(&code.name),
12703                    }
12704                    match code.position_at(frame.at as u32) {
12705                        Some((line, column)) => {
12706                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
12707                        }
12708                        None => out.push_str(&format!(" ({file})\n")),
12709                    }
12710                }
12711            }
12712        }
12713        out
12714    }
12715
12716    /// Give an anonymous function the name of the property it is stored in.
12717    ///
12718    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
12719    /// enumerable and not configurable, and a function that already has a real name
12720    /// keeps it.
12721    ///
12722    /// "Already named" means a *non-empty* name: every function object is created with
12723    /// a `name` of `""` so the property exists on all of them, and treating that empty
12724    /// string as a name left every anonymous function nameless — which is how a stack
12725    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
12726    /// `SetFunctionName`, for a name that came from source text.
12727    fn set_function_name(&mut self, function: &Value, name: &str) {
12728        self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
12729    }
12730
12731    /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
12732    /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
12733    fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
12734        let Value::Object(object) = function else {
12735            return;
12736        };
12737        // `SetFunctionName` applies to *functions* and classes only, and only when they are
12738        // anonymous. Without the callability guard, `{value: someObject}` renamed
12739        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
12740        // on the right-hand side of a property. That is how a `zipKeyed` result object
12741        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
12742        // has no `NamedEvaluation` at all.
12743        if !object.is_callable() {
12744            return;
12745        }
12746        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
12747            && !existing.wtf8().is_empty()
12748        {
12749            return;
12750        }
12751        let text = self.string_wtf8(name.clone());
12752        object.define("name", Property::name_or_length(text));
12753    }
12754
12755    // -- global declarations -----------------------------------------------
12756
12757    /// Declare a global binding, creating its reference cell.
12758    /// Declare a `var` or function global, whose home is the global object.
12759    ///
12760    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
12761    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
12762    /// such as `print`, or a redeclaration — is left alone.
12763    pub fn declare_var_global(&mut self, name: &str) {
12764        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
12765        // global object is exactly the leak `typeof my_var === "undefined"` after
12766        // `eval("var my_var=2")` rules out.
12767        if let Some(scope) = self.eval_scope.as_mut() {
12768            scope.entry(name.to_string()).or_insert(Value::Undefined);
12769            return;
12770        }
12771        // A sloppy direct eval declares into its *caller's* variable environment. Doing
12772        // this on the global object instead made `eval("var c = 1")` inside a parameter
12773        // list overwrite a global `c`, and made two calls to the same function share one
12774        // binding.
12775        if let Some(cell) = self.declare_eval_local(name) {
12776            cell.set(Value::Undefined);
12777            return;
12778        }
12779        let global = self.realm.global.clone();
12780        if global.own_property(name).is_some() {
12781            return;
12782        }
12783        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
12784        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
12785        // whole point of that trick and what lets `Object.defineProperty` reshape it
12786        // afterwards. `eval_scope` is `Some` while an eval is running.
12787        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
12788        global.define(
12789            name,
12790            Property {
12791                value: Some(Value::Undefined),
12792                writable: true,
12793                enumerable: true,
12794                configurable: from_eval,
12795                ..Property::default()
12796            },
12797        );
12798    }
12799
12800    /// Declare a *lexical* global binding, which starts in its dead zone.
12801    ///
12802    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
12803    /// global object and is created when its initialiser runs.
12804    pub fn declare_global(&mut self, name: &str, is_const: bool) {
12805        if is_const {
12806            self.realm.lexical_consts.insert(name.to_string());
12807        }
12808        if !self.realm.globals.contains_key(name) {
12809            // `Uninitialized` rather than `Undefined`: the binding exists but is not
12810            // readable until its initialiser runs, and that is what `let x` before
12811            // `x = 1` has to observe.
12812            let cell = self.new_cell(Value::Uninitialized);
12813            self.realm.globals.insert(name.to_string(), cell);
12814            self.realm.declared.push(name.to_string());
12815        }
12816    }
12817}
12818
12819/// The bytecode and environment of a function object, if it is a bytecode function.
12820///
12821/// Extracted before a call so no borrow of the object is held across it.
12822fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
12823    function.with(|data| match &data.kind {
12824        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
12825        _ => None,
12826    })
12827}
12828
12829/// A native call target, extracted before the call so no borrow is held.
12830enum NativeCall {
12831    Native(NativeFn),
12832    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
12833    /// not hold that object's `RefCell` borrow.
12834    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
12835    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
12836    Bound {
12837        target: Value,
12838        this: Value,
12839        leading: Vec<Value>,
12840    },
12841    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
12842    Revoker(crate::object::ProxyRef),
12843    /// A promise's `resolve`.
12844    PromiseResolve(Gc<JsObject>),
12845    /// A promise's `reject`.
12846    PromiseReject(Gc<JsObject>),
12847    /// The executor `NewPromiseCapability(C)` hands a user constructor.
12848    CapabilityExecutor {
12849        state: Gc<JsObject>,
12850    },
12851    /// One leg of a `then` that settles through a user capability.
12852    ThenShim {
12853        handler: Option<Value>,
12854        resolve: Value,
12855        reject: Value,
12856        fulfilled: bool,
12857    },
12858    /// One continuation of an `await`.
12859    AwaitResume {
12860        coroutine: Gc<JsObject>,
12861        promise: Gc<JsObject>,
12862        kind: ResumeKind,
12863    },
12864    /// One element of a `Promise` combinator settling.
12865    CombinatorSettle {
12866        state: Gc<JsObject>,
12867        index: usize,
12868        fulfilled: bool,
12869    },
12870    /// One of `Promise.prototype.finally`'s two shims.
12871    FinallyShim {
12872        callback: Option<Value>,
12873        fulfilled: bool,
12874        constructor: Value,
12875    },
12876    /// Settle a promise with a fixed outcome.
12877    SettlePromise {
12878        promise: Gc<JsObject>,
12879        value: Value,
12880        rejected: bool,
12881    },
12882    /// Continue an async generator after its `await` settled.
12883    GeneratorResume {
12884        generator: Gc<JsObject>,
12885        promise: Gc<JsObject>,
12886        kind: ResumeKind,
12887    },
12888    /// Read a module namespace's binding out of its cell.
12889    ModuleBinding(Gc<Cell>),
12890    /// Finish a completed async generator's `return(v)` once `v` has settled.
12891    CompletedReturn {
12892        generator: Gc<JsObject>,
12893        promise: Gc<JsObject>,
12894        rejected: bool,
12895    },
12896    /// Answer a pending async-generator method with `{value, done}`.
12897    YieldResult {
12898        generator: Gc<JsObject>,
12899        promise: Gc<JsObject>,
12900        done: bool,
12901    },
12902    /// One step of `AsyncDisposableStack.disposeAsync`.
12903    DisposeStep {
12904        remaining: Gc<JsObject>,
12905        promise: Gc<JsObject>,
12906        error: Value,
12907        rejected: bool,
12908    },
12909}
12910
12911/// What a store does when the object refuses the write.
12912#[derive(Clone, Copy, PartialEq, Eq)]
12913pub enum DeleteFailure {
12914    /// Raise a `TypeError`, which is what strict mode and every built-in does.
12915    Throw,
12916    /// Ignore the write, which is what a sloppy-mode assignment does.
12917    Ignore,
12918}
12919
12920/// Whether `object` is a `Date` instance, by the class tag it carries.
12921///
12922/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
12923/// builtins module depending on the interpreter's conversion order.
12924fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
12925    interp
12926        .internal_get(object, "_class")
12927        .is_some_and(|value| value.to_js_string() == "Date")
12928}
12929
12930/// Which type `ToPrimitive` prefers when it converts an object.
12931#[derive(Clone, Copy, PartialEq, Eq)]
12932pub enum Hint {
12933    /// The default hint, which behaves like [`Hint::Number`].
12934    Default,
12935    /// `Number(obj)` and the arithmetic operators.
12936    Number,
12937    /// `String(obj)` and `ToPropertyKey`.
12938    String,
12939}
12940
12941/// Which table a binding slot indexes, for the messages that name it.
12942#[derive(Clone, Copy)]
12943enum VarSlot {
12944    Loc,
12945    Closure,
12946}
12947
12948/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
12949fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
12950    Ok(this)
12951}
12952
12953/// An internal iterator: the sequence plus a cursor.
12954pub(crate) struct Iterator {
12955    pub(crate) object: Value,
12956    pub(crate) next: Value,
12957}
12958
12959/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
12960/// and plain `a` for a method.
12961///
12962/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
12963/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
12964/// reads `at get a (file:1:2)`.
12965/// The same prefixing, for a name that may hold an unpaired surrogate.
12966fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
12967    let prefix = match flags & 3 {
12968        1 => "get ",
12969        2 => "set ",
12970        _ => return key.clone(),
12971    };
12972    let mut units: Vec<u16> = prefix.encode_utf16().collect();
12973    units.extend_from_slice(&key.to_units());
12974    crate::value::Wtf8::from_units(&units)
12975}
12976
12977fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
12978    match flags & 3 {
12979        1 => format!("get {key}"),
12980        2 => format!("set {key}"),
12981        _ => key.to_string(),
12982    }
12983}
12984
12985/// Define a method or accessor property, per the `define_method` flag byte.
12986///
12987/// The low two bits pick value/getter/setter and bit 2 marks the property
12988/// enumerable.
12989///
12990/// A getter and a setter arrive as two separate `define_method` instructions, and the
12991/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
12992/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
12993/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
12994/// `JS_DefineProperty`, which leaves the other half alone.
12995fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
12996    let enumerable = flags & 4 != 0;
12997    let kind = flags & 3;
12998    let existing = object.own_property_key(key);
12999    let property = match kind {
13000        1 => Property {
13001            getter: Some(function),
13002            // The setter half, if this literal already defined one.
13003            setter: existing
13004                .filter(Property::is_accessor)
13005                .and_then(|p| p.setter),
13006            enumerable,
13007            configurable: true,
13008            ..Property::default()
13009        },
13010        2 => Property {
13011            getter: existing
13012                .filter(Property::is_accessor)
13013                .and_then(|p| p.getter),
13014            setter: Some(function),
13015            enumerable,
13016            configurable: true,
13017            ..Property::default()
13018        },
13019        _ => Property {
13020            value: Some(function),
13021            writable: true,
13022            enumerable,
13023            configurable: true,
13024            ..Property::default()
13025        },
13026    };
13027    object.define_key(key, property);
13028}
13029
13030// ---------------------------------------------------------------------------
13031// Operand decoding
13032// ---------------------------------------------------------------------------
13033
13034/// How `print` renders a value: the reference's `JS_PrintValue`.
13035///
13036/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
13037/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
13038/// The format is reproduced closely because the test suite compares output text:
13039///
13040/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
13041/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
13042/// * a cycle prints `[circular N]` with `N` the stack index of the object;
13043/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
13044///   end print as `<N empty item(s)>`;
13045/// * a string is quoted inside a container but raw at the top level, which is why
13046///   `print("x")` and `print(["x"])` differ.
13047pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
13048    // A string argument is printed raw: `js_print` converts it with `ToString`
13049    // instead of dumping it, and the quoting only appears inside a container.
13050    if let Value::String(text) = value {
13051        return text.to_string_lossy().into_owned();
13052    }
13053    let mut printer = Printer {
13054        interp,
13055        out: String::new(),
13056        stack: Vec::new(),
13057    };
13058    printer.value(value, 0);
13059    printer.out
13060}
13061
13062/// The internal class name an object carries, when it has one.
13063fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
13064    interp
13065        .internal_get(object, "_class")
13066        .map(|value| value.to_js_string())
13067}
13068
13069/// A string property, looked up the way `GetProperty` does: own first, then the
13070/// prototype chain. Needed because the print formatter holds the interpreter
13071/// immutably and so cannot run getters.
13072fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
13073    let mut current = Some(object.clone());
13074    // Bounded, because a prototype cycle would otherwise loop forever.
13075    for _ in 0..100 {
13076        let node = current?;
13077        if let Some(property) = node.own_property(name)
13078            && let Some(value) = property.value
13079        {
13080            return Some(value.to_js_string());
13081        }
13082        current = node.with(|data| data.proto.clone());
13083    }
13084    None
13085}
13086
13087/// The `JS_PrintValue` state: output, and the objects currently being printed.
13088struct Printer<'a, 'rt> {
13089    /// Kept for the class-name lookups that typed arrays and `Date` will need.
13090    #[allow(dead_code)]
13091    interp: &'a Interp<'rt>,
13092    out: String,
13093    stack: Vec<Gc<JsObject>>,
13094}
13095
13096impl Printer<'_, '_> {
13097    /// Depth past which a container is summarised by its class name.
13098    const MAX_DEPTH: usize = 2;
13099
13100    fn value(&mut self, value: &Value, level: usize) {
13101        match value {
13102            Value::Undefined
13103            | Value::Uninitialized
13104            | Value::Hole
13105            | Value::CatchOffset(_)
13106            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
13107            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
13108            // The printer writes a bigint the way the language spells one, so a dump is
13109            // unambiguous about which kind of number it is showing.
13110            Value::BigInt(big) => {
13111                self.out.push_str(&big.to_decimal_string());
13112                self.out.push('n');
13113            }
13114            Value::Null => self.out.push_str("null"),
13115            Value::Bool(true) => self.out.push_str("true"),
13116            Value::Bool(false) => self.out.push_str("false"),
13117            Value::Int(number) => self.out.push_str(&number.to_string()),
13118            Value::Float(number) => {
13119                self.out
13120                    .push_str(&crate::value::number_to_string_for_print(*number));
13121            }
13122            Value::String(text) => self.print_string(&text.to_string_lossy()),
13123            Value::Object(object) => self.object(object, level),
13124        }
13125    }
13126
13127    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
13128        // A cycle is reported rather than followed; the index is where the object
13129        // already sits in the print stack, which is what the reference shows.
13130        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
13131            self.out.push_str(&format!("[circular {index}]"));
13132            return;
13133        }
13134        if object.is_callable() {
13135            let name = object
13136                .own_property("name")
13137                .and_then(|property| property.value)
13138                .map(|value| value.to_js_string())
13139                .unwrap_or_default();
13140            if name.is_empty() {
13141                self.out.push_str("[Function (anonymous)]");
13142            } else {
13143                self.out.push_str(&format!("[Function {name}]"));
13144            }
13145            return;
13146        }
13147        if level >= Self::MAX_DEPTH {
13148            let class = if object.is_array() { "Array" } else { "Object" };
13149            self.out.push_str(&format!("[{class}]"));
13150            return;
13151        }
13152        // `Date` and `Error` print as themselves rather than as bags of properties:
13153        // the ISO string, and `Name: message` followed by the trace.
13154        if let Some(class) = class_of(self.interp, object) {
13155            if class == "Date" {
13156                self.date(object);
13157                return;
13158            }
13159            if class == "Error" {
13160                self.error(object);
13161                return;
13162            }
13163        }
13164        self.stack.push(object.clone());
13165        if object.is_array() {
13166            self.array(object, level);
13167        } else {
13168            self.plain_object(object, level);
13169        }
13170        self.stack.pop();
13171    }
13172
13173    /// A Date prints as its ISO string; an invalid one falls through to the plain
13174    /// object form, the way the reference falls back when `toISOString` throws.
13175    fn date(&mut self, object: &Gc<JsObject>) {
13176        let value = self
13177            .interp
13178            .internal_get(object, "_date_value")
13179            .map(|value| value.to_number());
13180        match value.and_then(crate::builtins::date::iso_string) {
13181            Some(text) => self.out.push_str(&text),
13182            None => self.plain_object(object, 0),
13183        }
13184    }
13185
13186    /// `Name: message`, then the trace with its trailing newline removed.
13187    fn error(&mut self, object: &Gc<JsObject>) {
13188        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
13189        self.out.push_str(&name);
13190        if let Some(message) = inherited(object, "message")
13191            && !message.is_empty()
13192        {
13193            self.out.push_str(": ");
13194            self.out.push_str(&message);
13195        }
13196        if let Some(stack) = inherited(object, "stack") {
13197            self.out.push('\n');
13198            self.out.push_str(stack.trim_end_matches('\n'));
13199        }
13200    }
13201
13202    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
13203        let elements = object.array_elements().unwrap_or_default();
13204        self.out.push_str("[ ");
13205        // An interior hole means the array is "sparse": the reference prints those
13206        // as `index: value` pairs and says nothing about the holes themselves, while
13207        // a hole run at the end becomes a single `<N empty items>` note.
13208        let last_present = elements
13209            .iter()
13210            .rposition(|value| !matches!(value, Value::Hole));
13211        let has_interior_hole = match last_present {
13212            Some(last) => elements[..last]
13213                .iter()
13214                .any(|value| matches!(value, Value::Hole)),
13215            None => false,
13216        };
13217        let mut first = true;
13218        if has_interior_hole {
13219            let mut index = 0;
13220            while index < elements.len() {
13221                let value = &elements[index];
13222                if matches!(value, Value::Hole) {
13223                    index += 1;
13224                    continue;
13225                }
13226                if !first {
13227                    self.out.push_str(", ");
13228                }
13229                first = false;
13230                self.out.push_str(&format!("{index}: "));
13231                self.value(value, level + 1);
13232                index += 1;
13233            }
13234        } else {
13235            for (index, value) in elements.iter().enumerate() {
13236                if matches!(value, Value::Hole) {
13237                    continue;
13238                }
13239                if !first {
13240                    self.out.push_str(", ");
13241                }
13242                first = false;
13243                let _ = index;
13244                self.value(value, level + 1);
13245            }
13246            if let Some(last) = last_present {
13247                let trailing = elements.len() - last - 1;
13248                if trailing > 0 {
13249                    if !first {
13250                        self.out.push_str(", ");
13251                    }
13252                    self.out.push_str(&format!(
13253                        "<{trailing} empty item{}>",
13254                        if trailing > 1 { "s" } else { "" }
13255                    ));
13256                }
13257            } else if !elements.is_empty() {
13258                let count = elements.len();
13259                self.out.push_str(&format!(
13260                    "<{count} empty item{}>",
13261                    if count > 1 { "s" } else { "" }
13262                ));
13263            }
13264        }
13265        self.out.push_str(" ]");
13266    }
13267
13268    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
13269        self.out.push_str("{ ");
13270        let mut first = true;
13271        for key in object.own_keys() {
13272            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
13273                continue;
13274            };
13275            if !property.enumerable {
13276                continue;
13277            }
13278            if !first {
13279                self.out.push_str(", ");
13280            }
13281            first = false;
13282            self.out
13283                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
13284                    &key.to_string_lossy(),
13285                )));
13286            self.out.push_str(": ");
13287            // An accessor has no value to dump; the reference names the half that
13288            // exists instead of calling it.
13289            if property.is_accessor() {
13290                let text = match (property.getter.is_some(), property.setter.is_some()) {
13291                    (true, true) => "[Getter/Setter]",
13292                    (false, true) => "[Setter]",
13293                    _ => "[Getter]",
13294                };
13295                self.out.push_str(text);
13296            } else {
13297                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
13298            }
13299        }
13300        self.out.push_str(" }");
13301    }
13302
13303    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
13304    fn print_string(&mut self, text: &str) {
13305        self.out.push('"');
13306        for character in text.chars() {
13307            match character {
13308                '"' => self.out.push_str("\\\""),
13309                '\\' => self.out.push_str("\\\\"),
13310                '\n' => self.out.push_str("\\n"),
13311                '\r' => self.out.push_str("\\r"),
13312                '\t' => self.out.push_str("\\t"),
13313                c if (c as u32) < 0x20 => {
13314                    self.out.push_str(&format!("\\u{:04x}", c as u32));
13315                }
13316                c => self.out.push(c),
13317            }
13318        }
13319        self.out.push('"');
13320    }
13321}
13322
13323/// How `print` renders a value.
13324///
13325/// `ToString`, except that negative zero keeps its sign — the reference's host
13326/// printer does that while `String(-0)` is `"0"`.
13327pub fn display(value: &Value) -> String {
13328    match value {
13329        Value::Float(number) => crate::value::number_to_string_for_print(*number),
13330        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
13331            "undefined".to_string()
13332        }
13333        other => other.to_js_string(),
13334    }
13335}
13336
13337// ---------------------------------------------------------------------------
13338// Numeric operators
13339// ---------------------------------------------------------------------------
13340
13341/// `a + b` keeping the `Int` representation when it fits.
13342fn add_numbers(left: Value, right: Value) -> Value {
13343    match (&left, &right) {
13344        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
13345            Some(sum) => Value::Int(sum),
13346            None => Value::Float(*a as f64 + *b as f64),
13347        },
13348        _ => Value::Float(left.to_number() + right.to_number()),
13349    }
13350}
13351
13352/// The arithmetic operators other than `+`, which needs string concatenation.
13353fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13354    use Opcode::*;
13355    // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
13356    // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
13357    // *before* the match, so even the arms that never needed `a` or `b` paid for it.
13358    if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
13359        return Ok(match op {
13360            And => Value::Int(x & y),
13361            Or => Value::Int(x | y),
13362            Xor => Value::Int(x ^ y),
13363            Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
13364            Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
13365            Shr => match (*x as u32) >> ((*y as u32) & 31) {
13366                shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
13367                shifted => Value::Float(shifted as f64),
13368            },
13369            Sub => match x.checked_sub(*y) {
13370                Some(value) => Value::Int(value),
13371                None => Value::Float(*x as f64 - *y as f64),
13372            },
13373            _ => return arithmetic_slow(op, left, right),
13374        });
13375    }
13376    arithmetic_slow(op, left, right)
13377}
13378
13379/// [`arithmetic`] for everything the integer fast path above does not take.
13380fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13381    use Opcode::*;
13382    let (a, b) = (left.to_number(), right.to_number());
13383    Ok(match op {
13384        Sub => match (&left, &right) {
13385            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
13386                Some(value) => Value::Int(value),
13387                None => Value::Float(a - b),
13388            },
13389            _ => Value::Float(a - b),
13390        },
13391        Mul => Value::Float(a * b),
13392        Div => Value::Float(a / b),
13393        Mod => Value::Float(js_mod(a, b)),
13394        Pow => Value::Float(a.powf(b)),
13395        And => Value::Int(left.to_int32() & right.to_int32()),
13396        Or => Value::Int(left.to_int32() | right.to_int32()),
13397        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
13398        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
13399        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
13400        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
13401        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
13402        // fits the small-integer representation stays an `Int`; the rest become a
13403        // float, which is how the reference keeps `n >>> 0` non-negative.
13404        Shr => {
13405            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
13406            match i32::try_from(shifted) {
13407                Ok(value) => Value::Int(value),
13408                Err(_) => Value::Float(shifted as f64),
13409            }
13410        }
13411        _ => Value::Float(a),
13412    })
13413}
13414
13415/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
13416///
13417/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
13418/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
13419/// slow path where the rules live.
13420fn is_number(value: &Value) -> bool {
13421    matches!(value, Value::Int(_) | Value::Float(_))
13422}
13423
13424/// The `Value::Bool` a comparison operator answers for `ordering`.
13425///
13426/// `None` is the unordered case — a `NaN` on either side — and every operator answers
13427/// false for it, including `<=` and `>=`.
13428fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
13429    use Opcode::*;
13430    let answer = match (op, ordering) {
13431        (_, None) => false,
13432        (Lt, Some(ordering)) => ordering.is_lt(),
13433        (Lte, Some(ordering)) => ordering.is_le(),
13434        (Gt, Some(ordering)) => ordering.is_gt(),
13435        (Gte, Some(ordering)) => ordering.is_ge(),
13436        _ => false,
13437    };
13438    Value::Bool(answer)
13439}
13440
13441/// `%`, which follows the sign of the dividend rather than Rust's.
13442fn js_mod(left: f64, right: f64) -> f64 {
13443    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
13444        return f64::NAN;
13445    }
13446    if right.is_infinite() {
13447        return left;
13448    }
13449    let remainder = left % right;
13450    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
13451    // the spec makes the sign match the dividend.
13452    if remainder == 0.0 {
13453        0.0f64.copysign(left)
13454    } else {
13455        remainder
13456    }
13457}
13458
13459fn negate(value: Value) -> Value {
13460    match value {
13461        Value::Int(0) => Value::Float(-0.0),
13462        Value::Int(i) => Value::Int(-i),
13463        other => Value::Float(-other.to_number()),
13464    }
13465}
13466
13467fn increment(value: Value) -> Value {
13468    match value {
13469        Value::Int(i) => match i.checked_add(1) {
13470            Some(next) => Value::Int(next),
13471            None => Value::Float(i as f64 + 1.0),
13472        },
13473        other => Value::Float(other.to_number() + 1.0),
13474    }
13475}
13476
13477fn decrement(value: Value) -> Value {
13478    match value {
13479        Value::Int(i) => match i.checked_sub(1) {
13480            Some(next) => Value::Int(next),
13481            None => Value::Float(i as f64 - 1.0),
13482        },
13483        other => Value::Float(other.to_number() - 1.0),
13484    }
13485}
13486
13487/// Compare a `BigInt` with an `f64` on their mathematical values.
13488///
13489/// Neither side is rounded to the other's precision: the number is split into its integer
13490/// part (compared as an exact bigint) and its fraction, which is what decides the answer
13491/// when the integer parts are equal. An infinite value is larger than every bigint.
13492fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
13493    use std::cmp::Ordering;
13494    if number.is_nan() {
13495        return None;
13496    }
13497    if number.is_infinite() {
13498        return Some(if number > 0.0 {
13499            Ordering::Less
13500        } else {
13501            Ordering::Greater
13502        });
13503    }
13504    let truncated = number.trunc();
13505    // A number wider than `i128` still has an exact integer part, but no bigint form we can
13506    // build cheaply; the sign of the difference is all that is needed, so compare against
13507    // the bigint's own magnitude instead.
13508    if truncated.abs() >= 1.7e38 {
13509        let big_as_f64 = big.to_f64();
13510        return big_as_f64.partial_cmp(&number);
13511    }
13512    let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
13513    match big.cmp(&integer) {
13514        Ordering::Equal => {
13515            // Same integer part: the fraction decides, and a negative number's fraction is
13516            // below the integer (`-1.5` truncates to `-1`).
13517            if number > truncated {
13518                Some(Ordering::Less)
13519            } else if number < truncated {
13520                Some(Ordering::Greater)
13521            } else {
13522                Some(Ordering::Equal)
13523            }
13524        }
13525        other => Some(other),
13526    }
13527}