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::{OpFormat, Opcode};
22use js_gc::{Gc, Heap, WeakGc};
23
24use crate::object::{
25    Callable, ClosureEnv, CompiledCode, EvalScope, JsObject, LocalVars, NativeFn, ObjectKind,
26    Property, PropertyKey, array_index, has_own, lookup_key, same_proto,
27};
28use crate::value::{Cell, Value, number_to_string};
29
30/// Why execution stopped.
31#[derive(Debug, Clone)]
32pub enum Signal {
33    /// A JavaScript exception carrying the thrown value.
34    Throw(Value),
35    /// The runtime ran out of memory.
36    OutOfMemory,
37}
38
39/// What an execution step produced.
40pub type JsResult<T> = std::result::Result<T, Signal>;
41
42/// The result of one instruction.
43enum Step {
44    /// Keep executing the current frame.
45    Continue,
46    /// The current frame returned this value.
47    Return(Value),
48    /// The frame parked at a suspension point, with the yielded value on its stack.
49    ///
50    /// Only a generator or an async function can produce this, and only its own frame —
51    /// a nested ordinary call cannot contain a `yield`. The frame is not popped: it is
52    /// detached and handed to the generator object, which is what lets it resume later
53    /// with its locals and operand stack intact.
54    Suspend(SuspendKind),
55}
56
57/// Why a frame parked, which decides how the resumption is delivered.
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum SuspendKind {
60    /// `initial_yield`: the body has not started. The first `next()` resumes *after* it
61    /// without passing a value, because there is no `yield` expression to receive one.
62    Initial,
63    /// `yield expr`: the value is on the stack and the caller gets `{value, done:false}`.
64    Yield,
65    /// `yield* expr`: like `Yield`, but the value is already an `{value, done}` object
66    /// from the inner iterator and is handed straight back.
67    YieldStar,
68    /// `await expr`: the value is a promise the async machinery has to settle first.
69    Await,
70}
71
72/// Everything one JavaScript realm owns.
73///
74/// A realm is the set of objects a script can reach without naming them: the global
75/// object, the prototype chain roots, and the global binding cells.
76pub struct Realm {
77    /// The global object.
78    pub global: Gc<JsObject>,
79    /// `Object.prototype`.
80    pub object_proto: Gc<JsObject>,
81    /// `Function.prototype`, which is itself callable.
82    pub function_proto: Gc<JsObject>,
83    /// `Array.prototype`.
84    pub array_proto: Gc<JsObject>,
85    /// Reference cells for globals declared by the script.
86    ///
87    /// A declared global is read with `get_var` (by name) but written with
88    /// `put_var_ref` (through the cell), so the cell is what makes a function
89    /// declaration and its uses agree on one binding.
90    pub globals: BTreeMap<String, Gc<Cell>>,
91    /// Names of the globals that came from a *declaration*, which are
92    /// non-configurable properties of the global object.
93    pub declared: Vec<String>,
94    /// Names among the lexical globals that are `const`.
95    ///
96    /// `const`-ness cannot be read back off the bytecode in every case: a closure that
97    /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
98    /// path does not carry, so a store through it would look like a plain `let`. The
99    /// realm records it once, at declaration, and answers for every reader.
100    pub lexical_consts: BTreeSet<String>,
101    /// The error constructors by class name, so a runtime error can throw a real
102    /// `TypeError` instance rather than a look-alike object.
103    pub errors: BTreeMap<&'static str, Gc<JsObject>>,
104    /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
105    pub string_proto: Option<Gc<JsObject>>,
106    /// `Number.prototype`.
107    pub number_proto: Option<Gc<JsObject>>,
108    /// `Boolean.prototype`.
109    pub boolean_proto: Option<Gc<JsObject>>,
110    /// `BigInt.prototype`.
111    pub bigint_proto: Option<Gc<JsObject>>,
112    /// `Error.prototype`, the prototype of every error instance.
113    pub error_proto: Gc<JsObject>,
114    /// `Date.prototype`, so the constructor can build an instance in the
115    /// function-call form (`Date()` returns a string) without going through `new`.
116    pub date_proto: Gc<JsObject>,
117    /// `%GeneratorPrototype%`, the prototype of every generator object.
118    pub generator_proto: Gc<JsObject>,
119    /// `Promise.prototype`, the prototype of every promise.
120    pub promise_proto: Option<Gc<JsObject>>,
121    /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
122    pub async_generator_proto: Option<Gc<JsObject>>,
123    /// `Symbol.prototype`.
124    pub symbol_proto: Option<Gc<JsObject>>,
125    /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
126    /// `_date_value`.
127    ///
128    /// These are *symbol* keys on purpose. A `"_value"` property is visible to
129    /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
130    /// language does not have and `new Error()` listed `_class` beside `message` and
131    /// `stack` — and a caller that copies every own property (which
132    /// `Object.create(null, props)` effectively does) tried to write an internal name and
133    /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
134    /// and `JSON.stringify`, while remaining an ordinary traced property.
135    ///
136    /// `RefCell` because interning is memoisation rather than observable state: filling the
137    /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
138    /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
139    /// built while reporting a failure must not require an exclusive borrow.
140    pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
141
142    /// The `Symbol.for` registry: `key -> symbol`.
143    ///
144    /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
145    /// symbol every time within one script while a fresh realm starts empty.
146    pub symbol_registry: BTreeMap<String, Value>,
147    /// `RegExp.prototype`, filled in by the `RegExp` builtin.
148    pub regexp_proto: Option<Gc<JsObject>>,
149    /// The `RegExp` constructor.
150    pub regexp_ctor: Option<Gc<JsObject>>,
151    /// `SuppressedError.prototype`, which `using` builds its aggregates from.
152    ///
153    /// The prototype rather than the constructor on purpose: a script that replaces
154    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
155    /// error wrapping, which the `using` test suite checks explicitly.
156    pub suppressed_error_proto: Option<Gc<JsObject>>,
157    /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
158    pub disposable_stack_proto: Option<Gc<JsObject>>,
159    /// `Map.prototype`.
160    pub map_proto: Option<Gc<JsObject>>,
161    /// `Set.prototype`.
162    pub set_proto: Option<Gc<JsObject>>,
163    /// Every live `FinalizationRegistry`, held weakly.
164    ///
165    /// The cleanup callback has to run from a *safe point* — a place where script is not
166    /// already executing and no engine borrow is held — and the collector cannot enumerate
167    /// heap objects by type. Registering each registry here gives the drain a list to walk.
168    ///
169    /// The handles are weak on purpose: a registry the script dropped must be collectable,
170    /// and it must not be resurrected merely because the drain knew about it. Entries whose
171    /// target has expired are swept out as the drain walks, so the vector does not grow
172    /// without bound in a program that creates many short-lived registries.
173    pub finalization_registries: Vec<WeakGc<JsObject>>,
174    /// `ArrayBuffer.prototype`.
175    pub array_buffer_proto: Option<Gc<JsObject>>,
176    /// `%TypedArray%.prototype`, the prototype every view type inherits from.
177    pub typed_array_proto: Option<Gc<JsObject>>,
178    /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
179    ///
180    /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
181    /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
182    /// `"Object"` and `r instanceof Int32Array` is false.
183    pub typed_array_protos: Vec<Gc<JsObject>>,
184    /// `DataView.prototype`.
185    pub data_view_proto: Option<Gc<JsObject>>,
186    /// The `AsyncDisposableStack` prototype.
187    pub async_disposable_stack_proto: Option<Gc<JsObject>>,
188    /// `Iterator.prototype`.
189    pub iterator_proto: Option<Gc<JsObject>>,
190    /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
191    ///
192    /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
193    /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
194    /// `[object Iterator Helper]`).
195    pub iterator_helper_proto: Option<Gc<JsObject>>,
196    /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
197    /// that was not already an `Iterator`.
198    ///
199    /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
200    /// untouched and does *not* override `@@toStringTag`, so
201    /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
202    pub iterator_wrap_proto: Option<Gc<JsObject>>,
203    /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
204    pub generator_function_proto: Option<Gc<JsObject>>,
205    /// `%AsyncFunction.prototype%`.
206    pub async_function_proto: Option<Gc<JsObject>>,
207    /// `%AsyncGeneratorFunction.prototype%`.
208    pub async_generator_function_proto: Option<Gc<JsObject>>,
209    /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
210    ///
211    /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
212    /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
213    /// prototype per iterator made every array iterator's prototype distinct.
214    pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
215    /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
216    ///
217    /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
218    /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
219    /// both faster and impossible to break from a script.
220    well_known_symbols: WellKnownSymbols,
221}
222
223/// One binding of the frame that called `eval`, so the eval'd code can read and
224/// write it by name.
225struct EvalBinding {
226    /// The name it was declared with.
227    name: String,
228    /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
229    /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
230    /// a function that declares `a` must find that `a`.
231    frame: usize,
232    /// Which table of that frame it lives in.
233    slot: EvalSlot,
234    /// The slot index within that table.
235    index: usize,
236}
237
238/// Which table of a frame an [`EvalBinding`] indexes.
239#[derive(Clone, Copy)]
240enum EvalSlot {
241    Arg,
242    Local,
243}
244
245/// One activation record.
246struct Frame {
247    /// The bytecode being run.
248    code: Gc<CompiledCode>,
249    /// The cells this closure captured.
250    env: Gc<ClosureEnv>,
251    /// The `this` binding.
252    this: Value,
253    /// Argument slots, sized to the declared parameter count.
254    args: Vec<Value>,
255    /// The values the caller actually passed, which is what `arguments` exposes.
256    passed: Vec<Value>,
257    /// Local slots.
258    locals: Vec<Value>,
259    /// Reference cells for this frame's own captured bindings.
260    cells: Vec<Gc<Cell>>,
261    /// The operand stack.
262    stack: Vec<Value>,
263    /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
264    local_vars: Option<Gc<LocalVars>>,
265
266    /// Byte offset of the next instruction.
267    pc: usize,
268    /// Byte offset of the instruction being executed, which is what a stack trace
269    /// reports. `pc` has already moved past it by the time an instruction runs.
270    at: usize,
271    /// The callee, so a native builtin can tell which constructor it is.
272    callee: Value,
273    /// `new.target`: the constructor under `new`, `undefined` for a plain call.
274    new_target: Value,
275    /// Whether this frame's body ended in a `tail_call`.
276    ///
277    /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
278    /// with its own frame just like `call` does and only skips storing the result
279    /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
280    /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
281    /// pushed as usual, and this marker makes its return value the *caller's* return
282    /// value without running the instructions after the call.
283    tail: bool,
284}
285
286impl js_gc::Trace for Frame {
287    fn trace(&self, tracer: &mut js_gc::Tracer) {
288        self.code.trace(tracer);
289        self.env.trace(tracer);
290        self.this.trace(tracer);
291        for value in &self.args {
292            value.trace(tracer);
293        }
294        for value in &self.passed {
295            value.trace(tracer);
296        }
297        for value in &self.locals {
298            value.trace(tracer);
299        }
300        for cell in &self.cells {
301            cell.trace(tracer);
302        }
303        if let Some(local_vars) = &self.local_vars {
304            tracer.visit(local_vars);
305        }
306        for value in &self.stack {
307            value.trace(tracer);
308        }
309        self.callee.trace(tracer);
310        self.new_target.trace(tracer);
311    }
312}
313
314/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
315/// emitted `if_false` treats as "keep going".
316const RESUME_NEXT: i32 = 0;
317/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
318/// generator fall into its `return_async`.
319const RESUME_RETURN: i32 = 1;
320
321/// One microtask.
322///
323/// The queue holds *data* rather than closures because its contents are GC values: a
324/// closure would be invisible to the collector, and a pending reaction is exactly the
325/// kind of thing that must keep its handlers and its promise alive.
326pub enum Job {
327    /// A `then` reaction about to run.
328    Reaction {
329        /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
330        handler: Option<Value>,
331        /// The value or reason to call it with.
332        argument: Value,
333        /// Whether the source promise rejected, which decides the pass-through kind.
334        rejected: bool,
335        /// The promise the answer settles.
336        promise: Gc<JsObject>,
337    },
338    /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
339    Thenable {
340        /// The `then` that was found on the value.
341        then: Value,
342        /// The thenable itself, which becomes `then`'s `this`.
343        value: Value,
344        /// The promise being resolved.
345        promise: Gc<JsObject>,
346    },
347    /// A pending `import(specifier)`.
348    Import {
349        /// The specifier, already converted to a string.
350        specifier: String,
351        /// The module that asked, which the specifier resolves against.
352        referrer: String,
353        /// The promise `import()` handed back.
354        promise: Gc<JsObject>,
355    },
356    /// An async generator resuming after the value it awaited settled.
357    GeneratorResume {
358        /// The async generator to continue.
359        generator: Gc<JsObject>,
360        /// The promise the pending method returned.
361        promise: Gc<JsObject>,
362        /// Whether this delivers the value or raises the reason.
363        kind: ResumeKind,
364        /// The settled value, or the rejection reason.
365        value: Value,
366    },
367    /// An async function resuming after the value it awaited settled.
368    Resume {
369        /// The body, parked in a coroutine.
370        coroutine: Gc<JsObject>,
371        /// The promise the async function handed its caller.
372        promise: Gc<JsObject>,
373        /// Whether this resumption delivers a value or raises one.
374        kind: ResumeKind,
375        /// The settled value, or the rejection reason.
376        value: Value,
377    },
378}
379
380/// One macro-task: work the event loop owes the script but has not run yet.
381///
382/// The microtask queue ([`Job`]) is different: those run before the host regains control.
383/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
384/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
385/// logic: the engine decides *what* is due, the host decides *how to wait*.
386///
387/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
388/// reference counting even though nothing else references it — the same rule the `HostFn`
389/// documentation states from the other side (a host closure must not hold a `Gc`, so the
390/// `Gc` lives here instead).
391pub enum Task {
392    /// A `setTimeout` that is due at `due_at`.
393    ///
394    /// There is no `setInterval` variant because the reference has no `os.setInterval` at
395    /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
396    /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
397    /// would give this engine a timer the reference cannot produce, with nothing to
398    /// compare it against.
399    Timer {
400        /// The id `setTimeout` returned, for `clearTimeout`.
401        id: i32,
402        /// What to call when it fires.
403        callback: Value,
404        /// When it becomes runnable, as a monotonic instant.
405        due_at: std::time::Instant,
406    },
407}
408
409/// A descriptor the host has to poll, and which directions have a handler.
410///
411/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
412/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
413/// blocks on it, and the host reports back through [`Interp::fire_fd`].
414#[derive(Debug, Clone, Copy, PartialEq, Eq)]
415pub struct FdInterest {
416    /// The descriptor to watch.
417    pub fd: i32,
418    /// Whether `os.setReadHandler` registered a callback.
419    pub read: bool,
420    /// Whether `os.setWriteHandler` registered a callback.
421    pub write: bool,
422}
423
424/// The callbacks registered for one descriptor, per direction.
425#[derive(Default)]
426pub(crate) struct FdHandlers {
427    /// `os.setReadHandler`'s callback.
428    pub read: Option<Value>,
429    /// `os.setWriteHandler`'s callback.
430    pub write: Option<Value>,
431}
432
433/// The file name `eval` reports, which the reference does not inherit from the caller.
434///
435/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
436/// reference and the names show up in stack traces.
437const EVAL_FILE: &str = "<input>";
438
439/// The file name `std.evalScript` reports.
440const EVAL_SCRIPT_FILE: &str = "<evalScript>";
441
442/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
443///
444/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
445/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
446fn clamp_delay(delay_ms: f64) -> std::time::Duration {
447    // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
448    // on a float, which reads as a typo even when it is deliberate. Both NaN and a
449    // non-positive delay mean "due now".
450    if delay_ms.is_nan() || delay_ms <= 0.0 {
451        return std::time::Duration::ZERO;
452    }
453    std::time::Duration::from_secs_f64(delay_ms / 1000.0)
454}
455
456impl js_gc::Trace for Task {
457    fn trace(&self, tracer: &mut js_gc::Tracer) {
458        let Task::Timer { callback, .. } = self;
459        callback.trace(tracer);
460    }
461}
462
463/// What one turn of the event loop did, so the caller cannot spin by accident.
464///
465/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
466/// core until the timer is due. Naming the three cases makes the wait explicit.
467#[derive(Debug, Clone, Copy, PartialEq, Eq)]
468pub enum Turn {
469    /// Something ran. Call again immediately — there may be more ready work.
470    Ran,
471    /// Nothing is runnable, but descriptors are registered: the host must poll
472    /// [`Interp::pending_fds`] for at most this long, then report readiness with
473    /// [`Interp::fire_fd`].
474    ///
475    /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
476    /// the failure this project treats as worst — a handler that silently never fires —
477    /// so the two cannot be confused by accident.
478    Poll(std::time::Duration),
479    /// Nothing is runnable yet, but something is pending. Block at most this long, then
480    /// call again.
481    Wait(std::time::Duration),
482    /// Nothing is pending at all: the loop is done.
483    Done,
484}
485
486impl js_gc::Trace for Job {
487    fn trace(&self, tracer: &mut js_gc::Tracer) {
488        match self {
489            Job::Reaction {
490                handler,
491                argument,
492                promise,
493                ..
494            } => {
495                if let Some(handler) = handler {
496                    handler.trace(tracer);
497                }
498                argument.trace(tracer);
499                tracer.visit(promise);
500            }
501            Job::Thenable {
502                then,
503                value,
504                promise,
505            } => {
506                then.trace(tracer);
507                value.trace(tracer);
508                tracer.visit(promise);
509            }
510            Job::Resume {
511                coroutine,
512                promise,
513                value,
514                ..
515            } => {
516                tracer.visit(coroutine);
517                tracer.visit(promise);
518                value.trace(tracer);
519            }
520            Job::Import { promise, .. } => tracer.visit(promise),
521            Job::GeneratorResume {
522                generator,
523                promise,
524                value,
525                ..
526            } => {
527                tracer.visit(generator);
528                tracer.visit(promise);
529                value.trace(tracer);
530            }
531        }
532    }
533}
534
535/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
536#[derive(Debug, Clone, Copy, PartialEq, Eq)]
537pub enum ResumeKind {
538    /// The generator was just created and is being run to its first suspension.
539    Start,
540    /// `next(v)`.
541    Next,
542    /// `return(v)`.
543    Return,
544    /// `throw(e)`.
545    Throw,
546}
547
548/// A generator object's saved execution.
549///
550/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
551/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
552/// separately allocated buffers.
553pub struct GeneratorState {
554    /// The detached frame, or `None` once the generator has finished or while it runs.
555    frame: Option<Frame>,
556    /// How far it got.
557    phase: GeneratorPhase,
558    /// Whether the last suspension was an `await` rather than a `yield`.
559    ///
560    /// The two resume with *different stack shapes*: a `yield` is re-entered with the
561    /// value and a magic number, because the emitted code branches on which method
562    /// resumed it, while an `await` simply continues with its value. Getting this wrong
563    /// leaves an extra value on the operand stack that the next instruction then
564    /// consumes — a wrong answer rather than a crash.
565    parked_on_await: bool,
566}
567
568/// Which of §27.5.3.3's states a generator is in.
569#[derive(Debug, Clone, Copy, PartialEq, Eq)]
570enum GeneratorPhase {
571    /// Created, `initial_yield` reached, body not entered.
572    SuspendedStart,
573    /// Parked at a `yield`.
574    SuspendedYield,
575    /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
576    Executing,
577    /// Finished; the frame is gone.
578    Completed,
579}
580
581impl js_gc::Trace for GeneratorState {
582    fn trace(&self, tracer: &mut js_gc::Tracer) {
583        if let Some(frame) = &self.frame {
584            frame.trace(tracer);
585        }
586    }
587}
588
589/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
590/// them in.
591///
592/// Each is a field rather than a map entry because the runtime reads them on hot paths
593/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
594/// failure — reaching a default here means the builtin did not install, and every
595/// accessor panics rather than silently answering `undefined`.
596///
597/// [`builtins::symbol`]: crate::builtins::symbol
598#[derive(Default)]
599pub struct WellKnownSymbols {
600    /// The symbol values, positionally. Empty until `Symbol` installs.
601    symbols: Vec<Value>,
602}
603
604/// Which well-known symbol a caller wants.
605///
606/// A typed accessor beats passing a name around: a typo is a compile error rather than
607/// an `undefined` key that quietly matches nothing.
608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub enum WellKnown {
610    /// `Symbol.toPrimitive`.
611    ToPrimitive,
612    /// `Symbol.iterator`.
613    Iterator,
614    /// `Symbol.match`.
615    Match,
616    /// `Symbol.matchAll`.
617    MatchAll,
618    /// `Symbol.replace`.
619    Replace,
620    /// `Symbol.search`.
621    Search,
622    /// `Symbol.split`.
623    Split,
624    /// `Symbol.toStringTag`.
625    ToStringTag,
626    /// `Symbol.isConcatSpreadable`.
627    IsConcatSpreadable,
628    /// `Symbol.hasInstance`.
629    HasInstance,
630    /// `Symbol.species`.
631    Species,
632    /// `Symbol.unscopables`.
633    Unscopables,
634    /// `Symbol.asyncIterator`.
635    AsyncIterator,
636    /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
637    Disposable,
638    /// `Symbol.asyncDispose` — the awaited form.
639    AsyncDisposable,
640}
641
642impl WellKnown {
643    /// The index `Symbol`'s installer creates this symbol at.
644    fn index(self) -> usize {
645        match self {
646            WellKnown::ToPrimitive => 0,
647            WellKnown::Iterator => 1,
648            WellKnown::Match => 2,
649            WellKnown::MatchAll => 3,
650            WellKnown::Replace => 4,
651            WellKnown::Search => 5,
652            WellKnown::Split => 6,
653            WellKnown::ToStringTag => 7,
654            WellKnown::IsConcatSpreadable => 8,
655            WellKnown::HasInstance => 9,
656            WellKnown::Species => 10,
657            WellKnown::Unscopables => 11,
658            WellKnown::AsyncIterator => 12,
659            WellKnown::Disposable => 13,
660            WellKnown::AsyncDisposable => 14,
661        }
662    }
663}
664
665impl Realm {
666    /// Record the well-known symbols, in the order `Symbol`'s installer made them.
667    pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
668        self.well_known_symbols.symbols = symbols;
669    }
670
671    /// A well-known symbol.
672    pub fn well_known(&self, which: WellKnown) -> Value {
673        self.well_known_symbols
674            .symbols
675            .get(which.index())
676            .cloned()
677            .unwrap_or(Value::Undefined)
678    }
679
680    /// The well-known symbol as a property key.
681    pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
682        match self.well_known(which) {
683            Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
684            // Unreachable once `Symbol` has installed; an empty string key matches
685            // nothing, which degrades to "the object has no such method".
686            _ => PropertyKey::from(String::new()),
687        }
688    }
689}
690
691/// The interpreter: a realm plus a frame stack.
692pub struct Interp<'a> {
693    /// The heap everything is allocated on.
694    pub heap: &'a Heap,
695    /// The realm.
696    pub realm: Realm,
697    /// Active frames, outermost first.
698    frames: Vec<Frame>,
699    /// A strict-mode `eval`'s own variable scope, while its script runs.
700    ///
701    /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
702    /// become a global. Name lookups still fall through to the realm, which is why
703    /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
704    eval_scope: Option<BTreeMap<String, Value>>,
705    /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
706    /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
707    eval_depth: usize,
708    /// The calling frame's own bindings, which the running `eval` can read and write.
709    ///
710    /// Held separately from [`Interp::eval_scope`] because these already exist: reads
711    /// come from the frame, and a write is applied back to the frame (or to the cell
712    /// the frame captured) when the eval finishes. That is what makes
713    /// `f("a = 3")` visible to the caller as `a === 3`.
714    eval_bindings: Vec<EvalBinding>,
715    /// The calling frame's `arguments`, while an `eval` runs.
716    ///
717    /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
718    /// own yet still has to see the caller's `arguments`.
719    eval_arguments: Option<Value>,
720    /// The `with` objects live at the moment the running `eval` started, innermost first.
721    ///
722    /// `None` outside an eval, which is what keeps a finished block's object from
723    /// shadowing ordinary bytecode reads.
724    eval_with: Option<Vec<Gc<JsObject>>>,
725    /// The bindings the running direct `eval` makes visible, as name → cell.
726    ///
727    /// Set for the duration of an eval and then restored, but every closure created
728    /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
729    /// `eval("f = () => i")` work after the eval has returned.
730    active_eval_scope: Option<Gc<EvalScope>>,
731    /// The frame that called the direct `eval` currently running, if any.
732    ///
733    /// A sloppy eval declares its `var`s in that frame's variable environment rather than
734    /// on the global object, which is what keeps
735    /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
736    /// gives each call its own `x`.
737    eval_caller: Option<Option<usize>>,
738    /// The caller's `new.target`, while an `eval` runs.
739    ///
740    /// The eval'd code is a script with no constructor of its own, so it inherits the
741    /// one the enclosing function was called with.
742    eval_new_target: Option<Value>,
743    /// `new.target` for the frame about to be pushed.
744    ///
745    /// `construct` parks the constructor here and `push_frame` takes it, which is how the
746    /// value reaches the frame without threading a parameter through every call site.
747    pending_new_target: Option<Value>,
748    /// Names of the native functions currently executing, outermost first.
749    ///
750    /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
751    /// trace still names it with `(native)` instead of a position, so the names are
752    /// tracked separately and stitched into [`Interp::stack_trace`].
753    ///
754    /// The third field is how many bytecode frames were live when the native was entered,
755    /// which is what places it *among* them rather than before all of them. Native
756    /// functions used to be emitted up front on the grounds that they never re-enter
757    /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
758    native_frames: Vec<(String, Gc<JsObject>, usize)>,
759    /// The native function currently executing, for the ones that have to know *which*
760    /// function they are — a typed-array constructor reads its element type off itself.
761    ///
762    /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
763    /// reports whatever the enclosing bytecode frame was called with.
764    current_native: Option<Gc<JsObject>>,
765    /// Text written by `print` and friends, in order.
766    ///
767    /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
768    /// once at the end, which is also when upstream's line buffering becomes
769    /// visible for the cases compared here.
770    pub output: String,
771    /// Where `print` also writes, as it goes. `output` keeps the full log for
772    /// [`crate::Context::output`]; this is the live copy, flushed per line.
773    ///
774    /// Both exist on purpose. A host that gives a script a sink sees output *when it
775    /// happens* — which is what a timer callback's `console.log` has to do, and what the
776    /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
777    /// this repository keep reading the accumulated `String`. Buffering only (no sink)
778    /// would show a script's output all at once when it finished.
779    pub output_sink: Option<Box<dyn std::io::Write>>,
780    /// The most frames that may be live at once.
781    pub max_frames: usize,
782    /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
783    ///
784    /// Script execution does not return until this has drained, which is what makes
785    /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
786    /// than never. Reactions append to it while it drains, so the loop is a `while` and
787    /// not a `for`.
788    pub(crate) jobs: std::collections::VecDeque<Job>,
789    /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
790    ///
791    /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
792    /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
793    pub(crate) tasks: Vec<Task>,
794    /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
795    /// barrier'd evaluation started.
796    ///
797    /// A trace is truncated to the frames at or inside the innermost barrier, which is what
798    /// lets a REPL report an error from the line it just evaluated without also reporting
799    /// its own readline loop.
800    trace_barriers: Vec<usize>,
801    /// `os.signal` handlers, keyed by signal number.
802    ///
803    /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
804    /// a handler cannot be freed while it is still registered.
805    pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
806    /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
807    ///
808    /// Kept here rather than in a closure so the collector walks the callbacks: a handler
809    /// that is only reachable from a host closure could be freed while still registered.
810    pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
811    /// The next timer id.
812    ///
813    /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
814    /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
815    next_timer_id: i32,
816    /// Errors thrown by timer callbacks, already rendered.
817    ///
818    /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
819    /// that throws has no promise behind it. Both are reported by the host at the end of
820    /// the loop, but only one is fixed up by a later `.catch`.
821    timer_errors: Vec<String>,
822    /// The module registry, keyed by canonical name.
823    pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
824    /// How the host turns a specifier into bytes.
825    pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
826    /// The module the host was asked to run, for `import.meta.main`.
827    pub main_module_name: Option<String>,
828    /// Module bodies currently running, innermost last.
829    ///
830    /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
831    /// this is the only place that knows which module that is.
832    pub module_stack: Vec<String>,
833    /// Rejections that no handler has claimed, with the promise they belong to.
834    ///
835    /// A `then` registered later prunes its entry, which is why the promise is kept: the
836    /// reason alone cannot say whether somebody eventually listened.
837    unhandled: Vec<(Gc<JsObject>, Value)>,
838}
839
840impl<'a> Interp<'a> {
841    /// Build an interpreter over `heap`, with a fresh realm.
842    pub fn new(heap: &'a Heap) -> Interp<'a> {
843        let object_proto = JsObject::ordinary(heap, None);
844        let function_proto = JsObject::function(
845            heap,
846            Some(object_proto.clone()),
847            Callable::Native {
848                func: |_, _, _| Ok(Value::Undefined),
849                own_instance: false,
850            },
851        );
852        let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
853        let global = JsObject::ordinary(heap, Some(object_proto.clone()));
854        let mut interp = Interp {
855            heap,
856            realm: Realm {
857                global,
858                object_proto,
859                function_proto,
860                array_proto,
861                globals: BTreeMap::new(),
862                declared: Vec::new(),
863                lexical_consts: BTreeSet::new(),
864                errors: BTreeMap::new(),
865                string_proto: None,
866                number_proto: None,
867                boolean_proto: None,
868                bigint_proto: None,
869                error_proto: JsObject::ordinary(heap, None),
870                date_proto: JsObject::ordinary(heap, None),
871                generator_proto: JsObject::ordinary(heap, None),
872                promise_proto: None,
873                async_generator_proto: None,
874                symbol_proto: None,
875                symbol_registry: BTreeMap::new(),
876                internal_slots: std::cell::RefCell::new(BTreeMap::new()),
877                regexp_proto: None,
878                regexp_ctor: None,
879                suppressed_error_proto: None,
880                disposable_stack_proto: None,
881                map_proto: None,
882                set_proto: None,
883                finalization_registries: Vec::new(),
884                array_buffer_proto: None,
885                typed_array_proto: None,
886                typed_array_protos: Vec::new(),
887                data_view_proto: None,
888                async_disposable_stack_proto: None,
889                iterator_proto: None,
890                iterator_helper_proto: None,
891                iterator_wrap_proto: None,
892                generator_function_proto: None,
893                async_function_proto: None,
894                async_generator_function_proto: None,
895                iterator_protos: std::collections::BTreeMap::new(),
896                well_known_symbols: WellKnownSymbols::default(),
897            },
898            frames: Vec::new(),
899            eval_scope: None,
900            eval_depth: 0,
901            eval_bindings: Vec::new(),
902            eval_arguments: None,
903            eval_with: None,
904            active_eval_scope: None,
905            eval_caller: None,
906            pending_new_target: None,
907            eval_new_target: None,
908            native_frames: Vec::new(),
909            current_native: None,
910            output: String::new(),
911            output_sink: None,
912            max_frames: 4096,
913            jobs: std::collections::VecDeque::new(),
914            tasks: Vec::new(),
915            trace_barriers: Vec::new(),
916            signal_handlers: std::collections::BTreeMap::new(),
917            fd_handlers: std::collections::BTreeMap::new(),
918            next_timer_id: 1,
919            timer_errors: Vec::new(),
920            modules: std::collections::BTreeMap::new(),
921            module_loader: None,
922            main_module_name: None,
923            module_stack: Vec::new(),
924            unhandled: Vec::new(),
925        };
926        crate::builtins::install(&mut interp);
927        interp
928    }
929
930    // -- allocation helpers -------------------------------------------------
931
932    /// A new string value.
933    /// A `BigInt` value from a computed big integer.
934    pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
935        Value::BigInt(Gc::new(self.heap, value))
936    }
937
938    /// A string value from bytes that are already WTF-8, which is how a string with an
939    /// unpaired surrogate reaches a `Value`.
940    pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
941        Value::string_wtf8(self.heap, text)
942    }
943
944    /// A new string value, from text that is valid UTF-8.
945    pub fn string(&self, text: impl Into<String>) -> Value {
946        Value::string(self.heap, text)
947    }
948
949    /// A new ordinary object with the given prototype.
950    pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
951        JsObject::ordinary(self.heap, proto)
952    }
953
954    /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
955    ///
956    /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
957    /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
958    /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
959    /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
960    /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
961    /// said `[object Object]` instead of `[object Array Iterator]`.
962    ///
963    /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
964    /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
965    /// its own.
966    pub fn new_iterator_prototype(
967        &mut self,
968        tag: &str,
969        next: crate::object::NativeFn,
970    ) -> Gc<JsObject> {
971        if let Some(existing) = self.realm.iterator_protos.get(tag) {
972            return existing.clone();
973        }
974        let parent = self.realm.iterator_proto.clone();
975        let proto = self.new_object(parent);
976        let next = self.new_native("next", 0, next);
977        proto.define(
978            "next",
979            Property::with_attributes(Value::Object(next), true, false),
980        );
981        let key = self.realm.well_known_key(WellKnown::Iterator);
982        let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
983        proto.define_key(
984            &key,
985            Property::with_attributes(Value::Object(identity), true, false),
986        );
987        let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
988        let tag_value = self.string(tag);
989        proto.define_key(&tag_key, Property::with_attributes(tag_value, false, false));
990        self.realm
991            .iterator_protos
992            .insert(tag.to_string(), proto.clone());
993        proto
994    }
995
996    /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
997    ///
998    /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
999    /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1000    /// produced. That is why the two branches are not merged.
1001    pub fn object_own_property_keys(
1002        &mut self,
1003        object: &Gc<JsObject>,
1004    ) -> JsResult<Vec<PropertyKey>> {
1005        if let Some(keys) = self.proxy_own_keys(object)? {
1006            return Ok(keys);
1007        }
1008        // Integer-like keys ascending, then the string keys in insertion order, then the
1009        // symbols — the order every schema that walks an object expects.
1010        let entries = object.property_entries();
1011        let mut numeric: Vec<u32> = Vec::new();
1012        let mut strings: Vec<PropertyKey> = Vec::new();
1013        let mut symbols: Vec<PropertyKey> = Vec::new();
1014        for (key, _) in entries {
1015            match &key {
1016                PropertyKey::Symbol(_) => symbols.push(key),
1017                PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1018                    Some(index) => {
1019                        if !numeric.contains(&index) {
1020                            numeric.push(index);
1021                        }
1022                    }
1023                    None => strings.push(key),
1024                },
1025            }
1026        }
1027        numeric.sort_unstable();
1028        let mut keys: Vec<PropertyKey> = numeric
1029            .into_iter()
1030            .map(|index| PropertyKey::from(index.to_string()))
1031            .collect();
1032        keys.extend(strings);
1033        keys.extend(symbols);
1034        Ok(keys)
1035    }
1036
1037    /// The state behind a promise object, or `None` when `object` is not one.
1038    pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1039        object.with(|data| match &data.kind {
1040            ObjectKind::Promise(state) => Some(state.clone()),
1041            _ => None,
1042        })
1043    }
1044
1045    /// A new pending promise.
1046    pub fn new_promise(&mut self) -> Gc<JsObject> {
1047        let proto = self.realm.promise_proto.clone();
1048        let promise = JsObject::ordinary(self.heap, proto);
1049        promise.with_mut(|data| {
1050            data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1051                crate::object::PromiseState::default(),
1052            )));
1053        });
1054        promise
1055    }
1056
1057    /// Fulfil `promise`, unless it has already settled.
1058    ///
1059    /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1060    /// after `reject`, changes nothing.
1061    pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1062        let Some(state) = self.promise_state(promise) else {
1063            return;
1064        };
1065        let reactions = {
1066            let mut state = state.borrow_mut();
1067            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1068                return;
1069            }
1070            state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1071            std::mem::take(&mut state.reactions)
1072        };
1073        self.queue_reactions(reactions, value, false);
1074    }
1075
1076    /// Reject `promise`, unless it has already settled.
1077    pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1078        let Some(state) = self.promise_state(promise) else {
1079            return;
1080        };
1081        let reactions = {
1082            let mut state = state.borrow_mut();
1083            if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1084                return;
1085            }
1086            state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1087            std::mem::take(&mut state.reactions)
1088        };
1089        // Remember it only when nothing is listening *now*; a `then` registered later
1090        // prunes the entry in `perform_then`.
1091        if reactions.is_empty() {
1092            self.unhandled.push((promise.clone(), reason.clone()));
1093        }
1094        self.queue_reactions(reactions, reason, true);
1095    }
1096
1097    /// Queue one job per reaction.
1098    ///
1099    /// This is what makes `then` asynchronous even on an already-settled promise:
1100    /// `p.then(f); g()` calls `g` first.
1101    fn queue_reactions(
1102        &mut self,
1103        reactions: Vec<crate::object::PromiseReaction>,
1104        argument: Value,
1105        rejected: bool,
1106    ) {
1107        for reaction in reactions {
1108            let handler = if rejected {
1109                reaction.on_rejected.clone()
1110            } else {
1111                reaction.on_fulfilled.clone()
1112            };
1113            self.jobs.push_back(Job::Reaction {
1114                handler,
1115                argument: argument.clone(),
1116                rejected,
1117                promise: reaction.promise,
1118            });
1119        }
1120    }
1121
1122    /// `NewPromiseCapability` as the executor receives it: the promise plus its
1123    /// resolve/reject pair.
1124    ///
1125    /// The pair are callable objects rather than Rust closures, because the script gets
1126    /// them and may stash them for later.
1127    pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1128        let promise = self.new_promise();
1129        let resolve = JsObject::function(
1130            self.heap,
1131            Some(self.realm.function_proto.clone()),
1132            Callable::PromiseResolve(promise.clone()),
1133        );
1134        let reject = JsObject::function(
1135            self.heap,
1136            Some(self.realm.function_proto.clone()),
1137            Callable::PromiseReject(promise.clone()),
1138        );
1139        (promise, Value::Object(resolve), Value::Object(reject))
1140    }
1141
1142    /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1143    /// promise, as `{ value: completion }`.
1144    ///
1145    /// The three cases are the reference's, and they differ on purpose:
1146    ///
1147    /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1148    ///   exception before any promise exists;
1149    /// * a **runtime** error rejects the returned promise;
1150    /// * success resolves it with `{ value }`, where the value is the script's completion
1151    ///   value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1152    ///   {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1153    ///   `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1154    ///   `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1155    ///
1156    /// # What this does not do
1157    ///
1158    /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1159    /// is evaluated in an async context, so `await` outside a function is legal. That needs
1160    /// the parser and the suspension machinery to accept a suspended top-level script, and
1161    /// is not implemented — such source is a syntax error here. Everything else about the
1162    /// flag is reproduced.
1163    pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1164        // The barrier goes up before compiling: a *parse* failure is reported with a trace
1165        // too, and the reference truncates that one at the same place as a runtime failure.
1166        if barrier {
1167            let depth = self.frames.len();
1168            self.trace_barriers.push(depth);
1169        }
1170        // Compiled before the promise exists, so a parse failure propagates as a throw
1171        // instead of being folded into a rejection.
1172        let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1173            Ok(compiled) => compiled,
1174            Err(error) => {
1175                if barrier {
1176                    self.trace_barriers.pop();
1177                }
1178                return Err(error);
1179            }
1180        };
1181        // An async body answers its own promise, and that promise is what the reference
1182        // hands back — the same object, not a wrapper around it. Its resolution value is
1183        // the `{value}` object the compiled epilogue built.
1184        if compiled.kind.is_async() {
1185            let strict = compiled.strict;
1186            let promise = self.run_eval_script(compiled, strict)?;
1187            if barrier {
1188                self.trace_barriers.pop();
1189            }
1190            return Ok(promise);
1191        }
1192        let (promise, resolve, reject) = self.new_promise_capability();
1193        let strict = compiled.strict;
1194        match self.run_eval_script(compiled, strict) {
1195            Ok(value) => {
1196                // `{ value }` is a plain object, so resolving with it adopts nothing even
1197                // when the completion value is itself a promise.
1198                let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1199                self.set_property(&wrapped, "value", value)?;
1200                self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1201            }
1202            Err(Signal::Throw(error)) => {
1203                self.call_value(reject, Value::Undefined, vec![error])?;
1204            }
1205            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1206        }
1207        if barrier {
1208            self.trace_barriers.pop();
1209        }
1210        Ok(Value::Object(promise))
1211    }
1212
1213    /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1214    ///
1215    /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1216    /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1217    /// timer table, where the collector already scans it.
1218    pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1219        let (promise, resolve, _reject) = self.new_promise_capability();
1220        let resolve = self.new_host_function(
1221            "resolve",
1222            1,
1223            Box::new(
1224                move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1225                    let value = args.first().cloned().unwrap_or(Value::Undefined);
1226                    interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1227                },
1228            ),
1229        );
1230        // The timer keeps the resolver alive: it is a property of the timer entry, and the
1231        // timer table is part of what the collector walks.
1232        self.schedule_timer(Value::Object(resolve), delay_ms);
1233        Ok(Value::Object(promise))
1234    }
1235
1236    /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1237    /// new promise resolved with it.
1238    pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1239        if let Value::Object(object) = &value
1240            && self.promise_state(object).is_some()
1241        {
1242            return Ok(value);
1243        }
1244        let promise = self.new_promise();
1245        self.resolve_promise_with(&promise, value)?;
1246        Ok(Value::Object(promise))
1247    }
1248
1249    /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1250    pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1251        // Resolving a promise with itself is a `TypeError`. The check exists because the
1252        // alternative is a chain of self-reactions that never settles.
1253        if let Value::Object(object) = &value
1254            && object.ptr_eq(promise)
1255        {
1256            // The spec rejects *and* throws, so both the promise and the caller see it.
1257            let thrown = self.type_error("cannot resolve a promise with itself");
1258            let Signal::Throw(error) = thrown.clone() else {
1259                unreachable!("type_error always throws")
1260            };
1261            self.reject_promise(promise, error);
1262            return Err(thrown);
1263        }
1264        let then = match &value {
1265            Value::Object(object) => self.get_property(object, "then")?,
1266            _ => None,
1267        };
1268        let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1269        if !callable_then {
1270            // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1271            self.fulfill_promise(promise, value);
1272            return Ok(());
1273        }
1274        // Adopting a thenable is asynchronous — `then` is called from a job, never from
1275        // inside `resolve`, so a script cannot make a promise settle synchronously.
1276        self.jobs.push_back(Job::Thenable {
1277            then: then.expect("checked callable"),
1278            value,
1279            promise: promise.clone(),
1280        });
1281        Ok(())
1282    }
1283
1284    /// `Promise.prototype.then`: register a reaction and answer the derived promise.
1285    pub fn perform_then(
1286        &mut self,
1287        promise: &Gc<JsObject>,
1288        on_fulfilled: Option<Value>,
1289        on_rejected: Option<Value>,
1290    ) -> JsResult<Value> {
1291        let Some(state) = self.promise_state(promise) else {
1292            return Err(self.type_error("not a promise"));
1293        };
1294        // Whether a rejection handler is being attached decides whether a recorded
1295        // rejection stops being unhandled, so it is read before the values are moved.
1296        let has_rejection_handler = on_rejected.is_some();
1297        let derived = self.new_promise();
1298        let reaction = crate::object::PromiseReaction {
1299            on_fulfilled,
1300            on_rejected,
1301            promise: derived.clone(),
1302        };
1303        let settled = {
1304            let mut state = state.borrow_mut();
1305            // A rejection somebody reacts to is no longer unhandled.
1306            state.handled = true;
1307            match &state.status {
1308                crate::object::PromiseStatus::Pending => {
1309                    state.reactions.push(reaction.clone());
1310                    None
1311                }
1312                crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
1313                crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
1314            }
1315        };
1316        // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
1317        // later, means somebody is listening after all.
1318        if has_rejection_handler {
1319            self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
1320        }
1321        if let Some((argument, rejected)) = settled {
1322            let handler = if rejected {
1323                reaction.on_rejected
1324            } else {
1325                reaction.on_fulfilled
1326            };
1327            self.jobs.push_back(Job::Reaction {
1328                handler,
1329                argument,
1330                rejected,
1331                promise: reaction.promise,
1332            });
1333        }
1334        Ok(Value::Object(derived))
1335    }
1336
1337    /// The rejections nobody listened to, formatted the way the reference reports them.
1338    ///
1339    /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
1340    /// when there is one. The adjective is the reference's: a rejection is only *possibly*
1341    /// unhandled at the point the queue drains, because a `then` may still be attached
1342    /// before the host acts on it.
1343    pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
1344        let entries = std::mem::take(&mut self.unhandled);
1345        // Somebody may have attached a handler after the rejection was recorded, so the
1346        // promise is the authority rather than the list.
1347        let still_unhandled: Vec<Value> = entries
1348            .into_iter()
1349            .filter_map(|(promise, reason)| {
1350                let handled = self
1351                    .promise_state(&promise)
1352                    .map(|state| state.borrow().handled)
1353                    .unwrap_or(true);
1354                (!handled).then_some(reason)
1355            })
1356            .collect();
1357        still_unhandled
1358            .into_iter()
1359            .map(|reason| {
1360                let text = self.describe_exception(&reason);
1361                let stack = match &reason {
1362                    Value::Object(object) => self
1363                        .get_property(object, "stack")
1364                        .ok()
1365                        .flatten()
1366                        .map(|value| value.to_js_string())
1367                        // `stack` carries a trailing newline of its own, which would leave
1368                        // a blank line between two reported rejections.
1369                        .map(|text| text.trim_end().to_string())
1370                        .unwrap_or_default(),
1371                    _ => String::new(),
1372                };
1373                if stack.is_empty() {
1374                    format!("Possibly unhandled promise rejection: {text}")
1375                } else {
1376                    format!("Possibly unhandled promise rejection: {text}\n{stack}")
1377                }
1378            })
1379            .collect()
1380    }
1381
1382    /// Run the microtask queue to exhaustion.
1383    ///
1384    /// Jobs queued while draining run in the same drain, FIFO, which is what makes
1385    /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
1386    /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
1387    ///
1388    /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
1389    /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
1390    /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
1391    pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
1392        crate::builtins::json::parse_text(self, text, true)
1393    }
1394
1395    /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
1396    ///
1397    /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
1398    /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
1399    /// immediately, and `setTimeout(f, -1)` is ordinary code.
1400    ///
1401    /// The callback is called with **no arguments**. The reference stores only the function
1402    /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
1403    /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
1404    /// extra arguments arrive as `undefined`.
1405    pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
1406        let id = self.next_timer_id;
1407        // Wrap rather than grow: the id reaches the script as an `Int32`.
1408        self.next_timer_id = if self.next_timer_id == i32::MAX {
1409            1
1410        } else {
1411            self.next_timer_id + 1
1412        };
1413        let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
1414        self.tasks.push(Task::Timer {
1415            id,
1416            callback,
1417            due_at,
1418        });
1419        id
1420    }
1421
1422    /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
1423    /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
1424    pub fn cancel_timer(&mut self, id: i32) -> bool {
1425        let before = self.tasks.len();
1426        self.tasks.retain(|task| match task {
1427            Task::Timer { id: task_id, .. } => *task_id != id,
1428        });
1429        self.tasks.len() != before
1430    }
1431
1432    /// How long until the earliest pending timer, or `None` when none is pending.
1433    pub fn next_timeout(&self) -> Option<std::time::Duration> {
1434        let now = std::time::Instant::now();
1435        self.tasks
1436            .iter()
1437            .map(|task| match task {
1438                Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
1439            })
1440            .min()
1441    }
1442
1443    /// Run one turn of the event loop.
1444    ///
1445    /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
1446    /// run at most one due timer, then drain again. The blocking belongs to the caller
1447    /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
1448    /// is how it asks.
1449    ///
1450    /// One timer per turn rather than all of them: a timer callback may schedule another
1451    /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
1452    /// starve the microtask queue.
1453    pub fn run_one_turn(&mut self) -> JsResult<Turn> {
1454        self.drain_jobs()?;
1455        let now = std::time::Instant::now();
1456        // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
1457        // followed by `setTimeout(g, 1)` must run `g` first.
1458        let due = self
1459            .tasks
1460            .iter()
1461            .enumerate()
1462            .filter(|(_, task)| match task {
1463                Task::Timer { due_at, .. } => *due_at <= now,
1464            })
1465            .min_by_key(|(_, task)| match task {
1466                Task::Timer { due_at, .. } => *due_at,
1467            })
1468            .map(|(index, _)| index);
1469        let Some(index) = due else {
1470            // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
1471            // descriptor is registered but no timer is closer, so a script that never
1472            // touches the descriptor still gets control back. Without a cap a handler on a
1473            // descriptor that is never ready would block for as long as the host allows.
1474            let timeout = self
1475                .next_timeout()
1476                .unwrap_or(std::time::Duration::from_secs(10))
1477                .min(std::time::Duration::from_secs(10));
1478            if !self.fd_handlers.is_empty() {
1479                // Blocking on a timer while descriptors are registered would starve them,
1480                // and blocking on the descriptors while a timer is due would delay it; the
1481                // host polls with the earlier of the two deadlines, which this timeout is.
1482                return Ok(Turn::Poll(timeout));
1483            }
1484            return Ok(match self.next_timeout() {
1485                Some(wait) => Turn::Wait(wait),
1486                None => Turn::Done,
1487            });
1488        };
1489        let Task::Timer { callback, .. } = self.tasks.remove(index);
1490        let this = Value::Undefined;
1491        // A throwing timer callback must not stop the loop: the reference reports it and
1492        // keeps going, because the alternative is that one bad timer silently stops every
1493        // later one.
1494        // No arguments: see `schedule_timer` — the reference calls the callback bare.
1495        match self.call_value(callback, this, Vec::new()) {
1496            Ok(_) => {}
1497            Err(Signal::Throw(value)) => {
1498                let text = self.describe_exception(&value);
1499                self.timer_errors.push(text);
1500            }
1501            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1502        }
1503        self.drain_jobs()?;
1504        Ok(Turn::Ran)
1505    }
1506
1507    /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
1508    ///
1509    /// `callback` of `None` unregisters that direction, and an entry with neither direction
1510    /// left is removed — the reference does the same, so a script can rely on
1511    /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
1512    pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
1513        let entry = self.fd_handlers.entry(fd).or_default();
1514        if readable {
1515            entry.read = callback;
1516        } else {
1517            entry.write = callback;
1518        }
1519        if entry.read.is_none() && entry.write.is_none() {
1520            self.fd_handlers.remove(&fd);
1521        }
1522    }
1523
1524    /// Register or clear an `os.signal` handler.
1525    ///
1526    /// `None` removes it; the host separately restores the default disposition or sets
1527    /// ignore, because which of those happened is the script's choice (`null` versus
1528    /// `undefined`) and not something this table can express.
1529    pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
1530        match handler {
1531            Some(handler) => {
1532                self.signal_handlers.insert(signal, handler);
1533            }
1534            None => {
1535                self.signal_handlers.remove(&signal);
1536            }
1537        }
1538    }
1539
1540    /// Run the handler for `signal`, reporting whether one ran.
1541    ///
1542    /// A throwing handler is reported and the loop continues, like a timer's.
1543    pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
1544        let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
1545            return Ok(false);
1546        };
1547        match self.call_value(handler, Value::Undefined, Vec::new()) {
1548            Ok(_) => {}
1549            Err(Signal::Throw(value)) => {
1550                let text = self.describe_exception(&value);
1551                self.timer_errors.push(text);
1552            }
1553            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1554        }
1555        self.drain_jobs()?;
1556        Ok(true)
1557    }
1558
1559    /// The descriptors the host has to poll, and in which direction.
1560    ///
1561    /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
1562    /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
1563    /// `os_poll` asks for.
1564    pub fn pending_fds(&self) -> Vec<FdInterest> {
1565        self.fd_handlers
1566            .iter()
1567            .map(|(fd, entry)| FdInterest {
1568                fd: *fd,
1569                read: entry.read.is_some(),
1570                write: entry.write.is_some(),
1571            })
1572            .collect()
1573    }
1574
1575    /// Call the handler registered for `fd`, reporting whether one ran.
1576    ///
1577    /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
1578    /// poll iteration and then restarts the loop, because the handler may have changed the
1579    /// registration list underneath it; doing the same here keeps a handler that
1580    /// unregisters itself from being called with stale state.
1581    ///
1582    /// A throwing handler is reported and the loop continues — a bad handler must not stop
1583    /// every later one, exactly as with timers.
1584    pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
1585        let Some(entry) = self.fd_handlers.get(&fd) else {
1586            return Ok(false);
1587        };
1588        let callback = if readable {
1589            entry.read.clone()
1590        } else if writable {
1591            entry.write.clone()
1592        } else {
1593            None
1594        };
1595        let Some(callback) = callback else {
1596            return Ok(false);
1597        };
1598        self.drain_jobs()?;
1599        match self.call_value(callback, Value::Undefined, Vec::new()) {
1600            Ok(_) => {}
1601            Err(Signal::Throw(value)) => {
1602                let text = self.describe_exception(&value);
1603                self.timer_errors.push(text);
1604            }
1605            Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1606        }
1607        self.drain_jobs()?;
1608        Ok(true)
1609    }
1610
1611    /// Take the errors timer callbacks threw, leaving the list empty.
1612    pub fn take_timer_errors(&mut self) -> Vec<String> {
1613        std::mem::take(&mut self.timer_errors)
1614    }
1615
1616    /// Whether anything is still pending: a microtask or a timer.
1617    pub fn has_pending_work(&self) -> bool {
1618        !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
1619    }
1620
1621    /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
1622    pub fn has_pending_timers_or_jobs(&self) -> bool {
1623        !self.jobs.is_empty() || !self.tasks.is_empty()
1624    }
1625
1626    /// Run every queued microtask, including ones queued while draining.
1627    pub fn drain_jobs(&mut self) -> JsResult<()> {
1628        // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
1629        // would spin forever, so the drain is bounded the way the call stack is.
1630        let mut budget = 1_000_000usize;
1631        while let Some(job) = self.jobs.pop_front() {
1632            if budget == 0 {
1633                return Err(Signal::Throw(
1634                    self.make_error("InternalError", "promise job queue did not drain"),
1635                ));
1636            }
1637            budget -= 1;
1638            self.run_job(job)?;
1639            // `FinalizationRegistry` at the job boundary: this is the safe point where the
1640            // engine may run script that the script itself did not ask for. Doing it here
1641            // rather than from a drop hook is what keeps the callback out of arbitrary
1642            // engine bookkeeping — see `builtins::weak`'s header.
1643            crate::builtins::weak::drain_finalizers(self)?;
1644        }
1645        // A script that queued no jobs may still have dropped targets, so the checkpoint
1646        // runs once more after the queue empties.
1647        crate::builtins::weak::drain_finalizers(self)?;
1648        Ok(())
1649    }
1650
1651    /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
1652    ///
1653    /// The registry list is weak, so a registry the script dropped answers `upgrade` with
1654    /// `None` and is swept out here. This is also where the realm learns that a registry
1655    /// died, which is why it is a mutation rather than a read.
1656    pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
1657        let handles = std::mem::take(&mut self.realm.finalization_registries);
1658        let mut live = Vec::with_capacity(handles.len());
1659        for handle in handles {
1660            let Some(object) = handle.upgrade() else {
1661                continue;
1662            };
1663            let Some(state) = object.finalization_state() else {
1664                continue;
1665            };
1666            live.push((object.clone(), *state));
1667            self.realm.finalization_registries.push(object.downgrade());
1668        }
1669        live
1670    }
1671
1672    /// Run one microtask.
1673    fn run_job(&mut self, job: Job) -> JsResult<()> {
1674        match job {
1675            Job::Reaction {
1676                handler: None,
1677                argument,
1678                rejected,
1679                promise,
1680            } => {
1681                // No handler: the settlement passes straight through to the derived
1682                // promise, which is why `p.catch(f)` ignores fulfilments.
1683                if rejected {
1684                    self.reject_promise(&promise, argument);
1685                } else {
1686                    self.fulfill_promise(&promise, argument);
1687                }
1688                Ok(())
1689            }
1690            Job::Reaction {
1691                handler: Some(handler),
1692                argument,
1693                promise,
1694                ..
1695            } => match self.call_value(handler, Value::Undefined, vec![argument]) {
1696                Ok(answer) => {
1697                    if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
1698                        self.reject_promise(&promise, error);
1699                    }
1700                    Ok(())
1701                }
1702                Err(Signal::Throw(reason)) => {
1703                    self.reject_promise(&promise, reason);
1704                    Ok(())
1705                }
1706                Err(other) => Err(other),
1707            },
1708            Job::Thenable {
1709                then,
1710                value,
1711                promise,
1712            } => {
1713                // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
1714                // the value it produces settles `promise`.
1715                // The thenable's `then` gets this promise's own pair, so whatever it
1716                // produces settles `promise`.
1717                let resolve = JsObject::function(
1718                    self.heap,
1719                    Some(self.realm.function_proto.clone()),
1720                    Callable::PromiseResolve(promise.clone()),
1721                );
1722                let reject = JsObject::function(
1723                    self.heap,
1724                    Some(self.realm.function_proto.clone()),
1725                    Callable::PromiseReject(promise.clone()),
1726                );
1727                match self.call_value(
1728                    then,
1729                    value,
1730                    vec![Value::Object(resolve), Value::Object(reject)],
1731                ) {
1732                    Ok(_) => Ok(()),
1733                    Err(Signal::Throw(reason)) => {
1734                        self.reject_promise(&promise, reason);
1735                        Ok(())
1736                    }
1737                    Err(other) => Err(other),
1738                }
1739            }
1740            Job::Resume {
1741                coroutine,
1742                promise,
1743                kind,
1744                value,
1745            } => self.drive_async(&coroutine, &promise, kind, value),
1746            Job::GeneratorResume {
1747                generator,
1748                promise,
1749                kind,
1750                value,
1751            } => self.step_async_generator(&generator, &promise, kind, value),
1752            Job::Import {
1753                specifier,
1754                referrer,
1755                promise,
1756            } => {
1757                self.run_dynamic_import(&specifier, &referrer, &promise);
1758                Ok(())
1759            }
1760        }
1761    }
1762
1763    /// One element of a `Promise` combinator settled.
1764    ///
1765    /// The shared state object holds the results array, the number still outstanding, and
1766    /// the combinator's own resolve/reject pair. `all` fills by index so the answer keeps
1767    /// the input order; `race` settles on the first element and ignores the rest, which a
1768    /// one-shot settle gives for free.
1769    fn settle_combinator(
1770        &mut self,
1771        state: &Gc<JsObject>,
1772        index: usize,
1773        fulfilled: bool,
1774        value: Value,
1775    ) -> JsResult<()> {
1776        let kind = state
1777            .own_property("kind")
1778            .and_then(|property| property.value)
1779            .map(|value| value.to_int32())
1780            .unwrap_or(0);
1781        let outcome = state
1782            .own_property("outcome")
1783            .and_then(|property| property.value);
1784        let Some(Value::Object(outcome)) = outcome else {
1785            return Ok(());
1786        };
1787        if kind == 3 {
1788            // `race`: the first settlement wins; the rest are ignored by the one-shot rule.
1789            if fulfilled {
1790                self.resolve_promise_with(&outcome, value)?;
1791            } else {
1792                self.reject_promise(&outcome, value);
1793            }
1794            return Ok(());
1795        }
1796        let results = state
1797            .own_property("results")
1798            .and_then(|property| property.value)
1799            .and_then(|value| value.as_object().cloned());
1800        let remaining = state
1801            .own_property("remaining")
1802            .and_then(|property| property.value)
1803            .map(|value| value.to_int32())
1804            .unwrap_or(0);
1805        match kind {
1806            0 => {
1807                // `all`: the first rejection wins outright.
1808                if !fulfilled {
1809                    self.reject_promise(&outcome, value);
1810                    return Ok(());
1811                }
1812                let Some(results) = &results else {
1813                    return Ok(());
1814                };
1815                results.array_set(index, value);
1816            }
1817            1 => {
1818                // `allSettled`: never rejects; each slot records what happened.
1819                let Some(results) = &results else {
1820                    return Ok(());
1821                };
1822                let record = self.new_object(Some(self.realm.object_proto.clone()));
1823                if fulfilled {
1824                    record.define_data("status", self.string("fulfilled"));
1825                    record.define_data("value", value);
1826                } else {
1827                    record.define_data("status", self.string("rejected"));
1828                    record.define_data("reason", value);
1829                }
1830                results.array_set(index, Value::Object(record));
1831            }
1832            2 => {
1833                // `any`: the first fulfilment wins; a full sweep of rejections does not
1834                // settle here — it is handled by the count below.
1835                if fulfilled {
1836                    self.resolve_promise_with(&outcome, value)?;
1837                    return Ok(());
1838                }
1839            }
1840            _ => {}
1841        }
1842        let left = remaining - 1;
1843        state.define_data("remaining", Value::Int(left));
1844        if left != 0 {
1845            return Ok(());
1846        }
1847        match kind {
1848            0 | 1 => {
1849                let Some(results) = results else {
1850                    return Ok(());
1851                };
1852                self.resolve_promise_with(&outcome, Value::Object(results))?;
1853            }
1854            2 => {
1855                let error = self.make_error("AggregateError", "all promises were rejected");
1856                self.reject_promise(&outcome, error);
1857            }
1858            _ => {}
1859        }
1860        Ok(())
1861    }
1862
1863    /// Build an async function's result: a promise whose body runs as a coroutine.
1864    pub fn new_async_function(
1865        &mut self,
1866        function: Value,
1867        this: Value,
1868        args: Vec<Value>,
1869    ) -> JsResult<Value> {
1870        let promise = self.new_promise();
1871        let coroutine = self.new_coroutine(function, this, args)?;
1872        if let Err(Signal::Throw(reason)) =
1873            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
1874        {
1875            self.reject_promise(&promise, reason);
1876        }
1877        Ok(Value::Object(promise))
1878    }
1879
1880    /// The coroutine an async body runs in.
1881    ///
1882    /// Generator-shaped and never exposed to the script: what makes `await` work is the
1883    /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
1884    /// than growing a second state machine. The difference is only in the ending — a
1885    /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
1886    /// Run `code` as an async function body, answering the promise it settles.
1887    ///
1888    /// Used for a module with top-level `await`: its body is an async function whose
1889    /// caller is the host, so there is no function object to pass through
1890    /// [`Interp::new_async_function`].
1891    pub fn run_async_body(
1892        &mut self,
1893        code: Gc<CompiledCode>,
1894        env: Gc<ClosureEnv>,
1895        this: Value,
1896    ) -> JsResult<Value> {
1897        let promise = self.new_promise();
1898        let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
1899        if let Err(Signal::Throw(reason)) =
1900            self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
1901        {
1902            self.reject_promise(&promise, reason);
1903        }
1904        Ok(Value::Object(promise))
1905    }
1906
1907    fn new_coroutine(
1908        &mut self,
1909        function: Value,
1910        this: Value,
1911        args: Vec<Value>,
1912    ) -> JsResult<Gc<JsObject>> {
1913        let Some(object) = function.as_object().cloned() else {
1914            return Err(self.type_error("not a function"));
1915        };
1916        let Some((code, env)) = bytecode_of(&object) else {
1917            return Err(self.type_error("not a function"));
1918        };
1919        self.new_coroutine_from(code, env, this, args)
1920    }
1921
1922    /// Build a coroutine over an already-resolved body.
1923    fn new_coroutine_from(
1924        &mut self,
1925        code: Gc<CompiledCode>,
1926        env: Gc<ClosureEnv>,
1927        this: Value,
1928        args: Vec<Value>,
1929    ) -> JsResult<Gc<JsObject>> {
1930        let function = Value::Undefined;
1931        self.push_frame(code, env, this, args, function)?;
1932        let frame = self.frames.pop().expect("push_frame just pushed it");
1933        let state = GeneratorState {
1934            frame: Some(frame),
1935            phase: GeneratorPhase::SuspendedStart,
1936            parked_on_await: false,
1937        };
1938        let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
1939        coroutine.with_mut(|data| {
1940            data.kind = ObjectKind::Generator(Box::new(state));
1941        });
1942        Ok(coroutine)
1943    }
1944
1945    /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
1946    /// `await` and `value` is what it awaited.
1947    fn resume_coroutine(
1948        &mut self,
1949        coroutine: &Gc<JsObject>,
1950        kind: ResumeKind,
1951        value: Value,
1952    ) -> JsResult<(Value, bool)> {
1953        let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
1954            ObjectKind::Generator(state) => Some(std::mem::replace(
1955                state.as_mut(),
1956                GeneratorState {
1957                    frame: None,
1958                    phase: GeneratorPhase::Executing,
1959                    parked_on_await: false,
1960                },
1961            )),
1962            _ => None,
1963        }) else {
1964            return Err(self.type_error("not a coroutine"));
1965        };
1966        let result = self.step_generator(&mut state, kind, value);
1967        coroutine.with_mut(|data| {
1968            data.kind = ObjectKind::Generator(Box::new(state));
1969        });
1970        let (value, done, _ready, _reason) = result?;
1971        Ok((value, done))
1972    }
1973
1974    /// Advance an async body and settle its promise with the outcome.
1975    fn drive_async(
1976        &mut self,
1977        coroutine: &Gc<JsObject>,
1978        promise: &Gc<JsObject>,
1979        kind: ResumeKind,
1980        value: Value,
1981    ) -> JsResult<()> {
1982        match self.resume_coroutine(coroutine, kind, value) {
1983            Ok((value, true)) => {
1984                // `Ok` with `done` means the body finished *normally*, even when it was
1985                // resumed by a `throw` — `try { await p } catch {}` completes by
1986                // returning. Only the `Err` arm below is a rejection.
1987                //
1988                // Resolving rather than fulfilling matters: `return promise` in an async
1989                // body adopts the inner promise, so `async function f(){ return
1990                // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
1991                // promise.
1992                if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
1993                    self.reject_promise(promise, reason);
1994                }
1995                Ok(())
1996            }
1997            Ok((value, false)) => {
1998                // Parked on `await`: follow what it awaited and resume with the outcome.
1999                let awaited = match self.promise_resolve_value(value) {
2000                    Ok(awaited) => awaited,
2001                    Err(Signal::Throw(error)) => {
2002                        self.reject_promise(promise, error);
2003                        return Ok(());
2004                    }
2005                    Err(other) => return Err(other),
2006                };
2007                self.hook_await(awaited, coroutine, promise)
2008            }
2009            Err(Signal::Throw(reason)) => {
2010                self.reject_promise(promise, reason);
2011                Ok(())
2012            }
2013            Err(other) => Err(other),
2014        }
2015    }
2016
2017    /// Arrange for `coroutine` to resume when `awaited` settles.
2018    fn hook_await(
2019        &mut self,
2020        awaited: Value,
2021        coroutine: &Gc<JsObject>,
2022        promise: &Gc<JsObject>,
2023    ) -> JsResult<()> {
2024        let resumed = JsObject::function(
2025            self.heap,
2026            Some(self.realm.function_proto.clone()),
2027            Callable::AwaitResume {
2028                coroutine: coroutine.clone(),
2029                promise: promise.clone(),
2030                kind: ResumeKind::Next,
2031            },
2032        );
2033        let raised = JsObject::function(
2034            self.heap,
2035            Some(self.realm.function_proto.clone()),
2036            Callable::AwaitResume {
2037                coroutine: coroutine.clone(),
2038                promise: promise.clone(),
2039                kind: ResumeKind::Throw,
2040            },
2041        );
2042        // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2043        // guarantees one; the fallback keeps a mis-shaped value from panicking.
2044        let Value::Object(awaited) = &awaited else {
2045            self.jobs.push_back(Job::Resume {
2046                coroutine: coroutine.clone(),
2047                promise: promise.clone(),
2048                kind: ResumeKind::Next,
2049                value: awaited,
2050            });
2051            return Ok(());
2052        };
2053        self.perform_then(
2054            awaited,
2055            Some(Value::Object(resumed)),
2056            Some(Value::Object(raised)),
2057        )?;
2058        Ok(())
2059    }
2060
2061    /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2062    /// things an engine keeps outside it — array elements and an array's `length`.
2063    fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2064        if let Some(property) = object.own_property_key(key) {
2065            return Some(property);
2066        }
2067        // An array's elements live in their own vector rather than the property table, so
2068        // a descriptor for one has to be synthesized — with the attributes an element has.
2069        if let Some(index) = key.as_str().and_then(array_index)
2070            && let Some(value) = object.array_get(index as usize)
2071            && !matches!(value, Value::Hole)
2072        {
2073            return Some(Property::data(value));
2074        }
2075        // `length` is an own property of an array that is not in its property table
2076        // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2077        // and non-enumerable.
2078        if key.as_str() == Some("length")
2079            && let Some(length) = object.array_length()
2080        {
2081            return Some(Property {
2082                value: Some(crate::object::length_value(length)),
2083                writable: object.length_writable(),
2084                enumerable: false,
2085                configurable: false,
2086                getter: None,
2087                setter: None,
2088            });
2089        }
2090        None
2091    }
2092
2093    /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2094    pub fn object_get_own_property(
2095        &mut self,
2096        object: &Gc<JsObject>,
2097        key: &PropertyKey,
2098    ) -> JsResult<Option<Property>> {
2099        if let Some(answer) = self.proxy_get_own_property(object, key)? {
2100            return Ok(answer);
2101        }
2102        Ok(Self::ordinary_own_property(object, key))
2103    }
2104
2105    /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
2106    pub fn object_define_own_property(
2107        &mut self,
2108        object: &Gc<JsObject>,
2109        key: &PropertyKey,
2110        property: Property,
2111    ) -> JsResult<bool> {
2112        if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
2113            return Ok(accepted);
2114        }
2115        // An array index is stored in the element vector, which can hold a plain value and
2116        // nothing else. An accessor — or a data property with non-default attributes —
2117        // therefore has to live in the property table, and the element slot is blanked so
2118        // the table is what a read finds. Without this `Object.defineProperty(a, "0",
2119        // {get})` stored the accessor where no read ever looked, and the array kept
2120        // answering its old value.
2121        // An array's `length` is not stored in the property table, so defining it has to
2122        // run `ArraySetLength`: it truncates or extends the element vector and refuses a
2123        // value that is not a valid index. Without this `Object.defineProperty(a, "length",
2124        // {value: 1})` reported success and changed nothing.
2125        if key.as_str() == Some("length") && object.is_array() {
2126            // `{writable: false}` on `length` does not change the length, but it does make
2127            // it read-only — after which neither a later `{writable: true}` nor a store
2128            // past the end may succeed.
2129            if property.value.is_none() {
2130                if !object.length_writable() && property.writable {
2131                    return Ok(false);
2132                }
2133                object.set_length_writable(property.writable);
2134                return Ok(true);
2135            }
2136            if !object.length_writable() {
2137                return Ok(false);
2138            }
2139        }
2140        if key.as_str() == Some("length")
2141            && object.is_array()
2142            && let Some(value) = property.value.clone()
2143        {
2144            let requested = value.to_number();
2145            let valid = requested.is_finite()
2146                && requested >= 0.0
2147                && requested.fract() == 0.0
2148                && requested <= u32::MAX as f64;
2149            if !valid {
2150                return Err(self.range_error("invalid array length"));
2151            }
2152            // Truncating deletes the elements above the new length, and a non-configurable
2153            // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
2154            // makes `a.length = 2` fail rather than quietly drop it.
2155            let current = object.array_length().unwrap_or(0);
2156            let requested = requested as usize;
2157            if requested < current
2158                && (requested..current).any(|index| object.element_is_undeletable(index as u32))
2159            {
2160                return Ok(false);
2161            }
2162            object.array_set_length(requested);
2163            return Ok(true);
2164        }
2165        let plain = property.writable
2166            && property.enumerable
2167            && property.configurable
2168            && !property.is_accessor();
2169        if let Some(index) = key.as_str().and_then(array_index)
2170            && object.is_array()
2171        {
2172            // Growing the array needs a writable `length`: after
2173            // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
2174            // be added.
2175            if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
2176                return Ok(false);
2177            }
2178            if plain && let Some(value) = property.value {
2179                // An ordinary element: the vector is where a read looks first, so it has
2180                // to be the vector that changes.
2181                object.delete_key(key);
2182                object.array_set(index as usize, value);
2183                return Ok(true);
2184            }
2185            object.define_key(key, property);
2186            // The slot stays, so `length` does not shrink; a hole is not an element, so
2187            // the table entry is now what a read finds.
2188            object.array_set(index as usize, Value::Hole);
2189            return Ok(true);
2190        }
2191        object.define_key(key, property);
2192        Ok(true)
2193    }
2194
2195    /// Build a proxy object over `target`, with its traps read from `handler`.
2196    pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
2197        JsObject::proxy(self.heap, target, handler)
2198    }
2199
2200    /// The `revoke` function for a proxy's slots.
2201    pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
2202        JsObject::function(
2203            self.heap,
2204            Some(self.realm.function_proto.clone()),
2205            Callable::Revoker(slots),
2206        )
2207    }
2208
2209    /// A new array.
2210    pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
2211        let array = JsObject::array(
2212            self.heap,
2213            Some(self.realm.array_proto.clone()),
2214            elements.len(),
2215        );
2216        for (index, element) in elements.into_iter().enumerate() {
2217            array.array_set(index, element);
2218        }
2219        array
2220    }
2221
2222    /// A new native function object.
2223    ///
2224    /// The observable `name` and `length` are installed as properties here, which is
2225    /// what `Function.prototype.name` and `.length` read; nothing else stores them,
2226    /// so `f.name = "x"` behaves like the writable property it is.
2227    /// A native constructor that builds its own instance after validating its arguments.
2228    ///
2229    /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
2230    /// check runs before `new.target.prototype` is read.
2231    pub fn new_native_ctor(
2232        &self,
2233        name: impl Into<String>,
2234        length: u32,
2235        func: NativeFn,
2236    ) -> Gc<JsObject> {
2237        let function = JsObject::function(
2238            self.heap,
2239            Some(self.realm.function_proto.clone()),
2240            Callable::Native {
2241                func,
2242                own_instance: true,
2243            },
2244        );
2245        function.set_constructible(true);
2246        function.define(
2247            "length",
2248            Property::name_or_length(Value::Int(length as i32)),
2249        );
2250        function.define("name", Property::name_or_length(self.string(name)));
2251        function
2252    }
2253
2254    /// A native constructor that lets `new` build the instance first.
2255    ///
2256    /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
2257    /// validation that must precede reading `new.target.prototype`, so the object can be
2258    /// created before the implementation runs. Distinct from [`Interp::new_native`],
2259    /// which makes a *method* and therefore not a constructor at all.
2260    pub fn new_native_constructor(
2261        &self,
2262        name: impl Into<String>,
2263        length: u32,
2264        func: NativeFn,
2265    ) -> Gc<JsObject> {
2266        let function = self.new_native(name, length, func);
2267        function.set_constructible(true);
2268        function
2269    }
2270
2271    /// A new host function object: a native closure that carries its own state.
2272    ///
2273    /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
2274    /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
2275    /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
2276    /// this safe: the closure must not capture a `Gc`.
2277    pub fn new_host_function(
2278        &self,
2279        name: impl Into<String>,
2280        length: u32,
2281        func: crate::object::HostFn,
2282    ) -> Gc<JsObject> {
2283        self.new_host_inner(name.into(), length, func, false)
2284    }
2285
2286    /// A host constructor: `new` hands it `this = undefined`, so it validates its
2287    /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
2288    pub fn new_host_ctor(
2289        &self,
2290        name: impl Into<String>,
2291        length: u32,
2292        func: crate::object::HostFn,
2293    ) -> Gc<JsObject> {
2294        let function = self.new_host_inner(name.into(), length, func, true);
2295        function.set_constructible(true);
2296        // A constructor needs a `prototype` for `new` and for `instanceof`; the body
2297        // installs its own methods on it, so it starts as a plain object.
2298        let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
2299        function.define(
2300            "prototype",
2301            Property {
2302                value: Some(Value::Object(proto)),
2303                writable: true,
2304                enumerable: false,
2305                configurable: false,
2306                ..Property::default()
2307            },
2308        );
2309        function
2310    }
2311
2312    fn new_host_inner(
2313        &self,
2314        name: String,
2315        length: u32,
2316        func: crate::object::HostFn,
2317        own_instance: bool,
2318    ) -> Gc<JsObject> {
2319        let function = JsObject::function(
2320            self.heap,
2321            Some(self.realm.function_proto.clone()),
2322            Callable::Host {
2323                func: std::rc::Rc::new(std::cell::RefCell::new(func)),
2324                own_instance,
2325            },
2326        );
2327        function.define(
2328            "length",
2329            Property::name_or_length(Value::Int(length as i32)),
2330        );
2331        function.define("name", Property::name_or_length(self.string(name)));
2332        function
2333    }
2334
2335    /// A new native function object.
2336    pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
2337        let function = JsObject::function(
2338            self.heap,
2339            Some(self.realm.function_proto.clone()),
2340            Callable::Native {
2341                func,
2342                own_instance: false,
2343            },
2344        );
2345        // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
2346        // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
2347        // `length,name` and this listed `name,length`. A bytecode function already gets it
2348        // the right way round; only native ones were built backwards.
2349        function.define(
2350            "length",
2351            Property::name_or_length(Value::Int(length as i32)),
2352        );
2353        function.define("name", Property::name_or_length(self.string(name)));
2354        function
2355    }
2356
2357    /// A new bound function.
2358    pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
2359        // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
2360        // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
2361        // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
2362        let constructible = target
2363            .as_object()
2364            .is_some_and(|target| target.is_constructor());
2365        let bound = JsObject::function(
2366            self.heap,
2367            Some(self.realm.function_proto.clone()),
2368            Callable::Bound { target, this, args },
2369        );
2370        bound.set_constructible(constructible);
2371        bound
2372    }
2373
2374    /// A new reference cell.
2375    pub fn new_cell(&self, value: Value) -> Gc<Cell> {
2376        Gc::new(self.heap, Cell::new(value))
2377    }
2378
2379    // -- running ------------------------------------------------------------
2380
2381    /// Evaluate `code` as a script body and return its completion value.
2382    /// Compile and run `source` for the engine's own use, returning its completion value.
2383    ///
2384    /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
2385    /// needs to be a real async function, and the engine already runs those as coroutines,
2386    /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
2387    ///
2388    /// Differences from [`Self::eval_in_global`], both deliberate:
2389    ///
2390    /// * It does **not** drain the microtask queue. Install runs while the realm is still
2391    ///   being built, and the source is an IIFE that only constructs a closure, so there
2392    ///   is nothing to drain — and draining here would run script-queued jobs in the
2393    ///   middle of `install`.
2394    /// * It reports a syntax error as an `InternalError` throw rather than as the usual
2395    ///   `SyntaxError` with a position: a malformed builtin source is this crate's bug,
2396    ///   and it should not look like the user wrote something wrong.
2397    pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
2398        let program = match js_parse::parse_script(source) {
2399            Ok(program) => program,
2400            Err(error) => {
2401                let message = format!("builtin source does not parse: {error}");
2402                return Err(Signal::Throw(self.make_error("InternalError", &message)));
2403            }
2404        };
2405        let mut code = match js_compile::compile_script(&program) {
2406            Ok(code) => code,
2407            Err(error) => {
2408                let message = format!("builtin source does not compile: {}", error.message);
2409                return Err(Signal::Throw(self.make_error("InternalError", &message)));
2410            }
2411        };
2412        // The frame has to name something, and `<builtin>` is what a stack trace through
2413        // this code should say.
2414        code.set_filename("<builtin>");
2415        let compiled = Gc::new(self.heap, CompiledCode::new(code));
2416        let closure_vars = compiled.code.closure_vars.clone();
2417        let env = self.global_env(&closure_vars);
2418        let this = Value::Object(self.realm.global.clone());
2419        self.execute(compiled, env, this, Vec::new(), Value::Undefined)
2420    }
2421
2422    /// Run an already-parsed script and drain the microtasks it queued.
2423    ///
2424    /// The drain is what lets an `async` function's body advance past its first `await`
2425    /// before the host sees the result: nothing else pumps the job queue.
2426    pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
2427        let compiled = Gc::new(self.heap, CompiledCode::new(code));
2428        let closure_vars = compiled.code.closure_vars.clone();
2429        let env = self.global_env(&closure_vars);
2430        let this = Value::Object(self.realm.global.clone());
2431        let callee = Value::Undefined;
2432        let result = self.execute(compiled, env, this, Vec::new(), callee)?;
2433        // The script is done, so the microtasks it queued run before the host sees the
2434        // result. Without this an `async` function's body would never advance past its
2435        // first `await`, because nothing else drains the queue.
2436        self.drain_jobs()?;
2437        Ok(result)
2438    }
2439
2440    /// Compile and run `source` in global scope, returning its completion value.
2441    ///
2442    /// This is what `eval` and `new Function` use. Running it as a script means it
2443    /// sees the global object and nothing else, which is right for `eval("1+1")` and
2444    /// for a `Function` body; a *direct* eval that reads a local variable would need
2445    /// the compiler to hand its variable environment over, which is not implemented.
2446    pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
2447        self.eval_in_global_named(source, EVAL_FILE, false)
2448    }
2449
2450    /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
2451    ///
2452    /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
2453    /// shows `<evalScript>` — and the name is visible in every stack trace that passes
2454    /// through the code, so they cannot share one constant.
2455    pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
2456        self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
2457    }
2458
2459    fn eval_in_global_named(&mut self, source: &str, file: &str, barrier: bool) -> JsResult<Value> {
2460        // Marked for the duration, so `declare_var_global` knows a `var` from here is an
2461        // eval-created global binding — configurable, unlike a script's own `var`.
2462        self.eval_depth += 1;
2463        if barrier {
2464            let depth = self.frames.len();
2465            self.trace_barriers.push(depth);
2466        }
2467        let result = self.eval_in_global_inner(source, file);
2468        if barrier {
2469            self.trace_barriers.pop();
2470        }
2471        self.eval_depth -= 1;
2472        result
2473    }
2474
2475    fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
2476        let compiled = self.compile_global_script(source, file, false)?;
2477        let strict = compiled.strict;
2478        self.run_eval_script(compiled, strict)
2479    }
2480
2481    /// Parse and compile `source` as a global script, without running it.
2482    ///
2483    /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
2484    /// before a promise exists to reject — while still evaluating in the same eval context
2485    /// (direct-eval strictness, `new.target`, `super`).
2486    fn compile_global_script(
2487        &mut self,
2488        source: &str,
2489        file: &str,
2490        async_body: bool,
2491    ) -> JsResult<CompiledFunction> {
2492        // A *direct* eval inherits the strictness of the code that called it, which is
2493        // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
2494        // implicit global. The caller's frame is the innermost one here, because a
2495        // native function does not push a frame of its own.
2496        let strict = self.current_strict();
2497        // `eval` runs in the caller's function context, so `new.target` is legal here
2498        // even though the source is a bare script — and so is `super.x` when the caller
2499        // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
2500        // caller's, which is what `special_object 4` already does.
2501        let context = js_parse::EvalContext {
2502            in_method: self.enclosing_home_object().is_some(),
2503            // `super()` belongs to a derived constructor, and an eval'd body is not a
2504            // constructor at all: the caller frame's `this` is already built.
2505            in_derived_constructor: false,
2506        };
2507        // A *global* eval is not a function body: `new.target` and `super` are out of
2508        // reach there. Its `{async: true}` form differs in the other direction — the body
2509        // may `await` — so the two flags are independent and the reference sets both from
2510        // the eval type rather than from the caller.
2511        let parsed = if async_body {
2512            js_parse::parse_suspensible_global_eval(source, strict)
2513        } else {
2514            js_parse::parse_eval_script_in(source, strict, context)
2515        };
2516        let program = match parsed {
2517            Ok(program) => program,
2518            Err(error) => {
2519                // The message is bare: the position lives in `fileName`,
2520                // `lineNumber`, `columnNumber` and the stack frame above, which is where
2521                // the reference puts it. An `invalid source: L:C: ` prefix made
2522                // `e.message` differ from the reference while the stack already agreed.
2523                return Err(Signal::Throw(self.syntax_error_at(
2524                    file,
2525                    error.span.start.line,
2526                    error.span.start.column,
2527                    &error.message,
2528                )));
2529            }
2530        };
2531        let mut compiled = match if async_body {
2532            js_compile::compile_script_suspensible(&program)
2533        } else {
2534            js_compile::compile_script(&program)
2535        } {
2536            Ok(compiled) => compiled,
2537            // A construct the compiler does not handle yet is reported the same way a
2538            // parse error is: it happens before anything runs, so the trace is the
2539            // position in the source followed by the caller.
2540            Err(error) => {
2541                return Err(Signal::Throw(self.syntax_error_at(
2542                    file,
2543                    error.span.start.line,
2544                    error.span.start.column,
2545                    &error.message,
2546                )));
2547            }
2548        };
2549        compiled.set_filename(file);
2550        Ok(compiled)
2551    }
2552
2553    /// Run an `eval`'d script in the caller's scope.
2554    ///
2555    /// Three things have to come from the calling frame, because the eval'd code is a
2556    /// script and would otherwise see only the global object:
2557    ///
2558    /// * `this`, so `f.call(1, "this")` evaluates to `1`;
2559    /// * `arguments`, exposed as a binding of the eval's own scope, so
2560    ///   `f("arguments.length", 1)` sees the caller's arguments;
2561    /// * a fresh variable environment for `var`, so a strict `eval` does not leak
2562    ///   `eval("var v = 1")` into the global object.
2563    ///
2564    /// Locals of the calling function are *not* reachable: that needs the compiler to
2565    /// hand its variable environment over, which this milestone does not do.
2566    fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
2567        // `this` and `arguments` come from the innermost frame only — those are not
2568        // lexical — while the name bindings come from the whole chain of frames, part
2569        // of it being ordinary scope resolution.
2570        // An arrow has no `this` of its own, so an `eval` inside one inherits the
2571        // enclosing function's receiver — the lexical `this` the arrow was compiled to
2572        // read from its closure.
2573        // `this` and `arguments` come from the innermost *non-arrow* frame, but the
2574        // variable environment is the innermost frame of all: an arrow's own body is where
2575        // `var`s declared by an `eval` inside it belong.
2576        let caller_index = self
2577            .frames
2578            .iter()
2579            .rposition(|frame| !frame.code.code.is_arrow)
2580            .or_else(|| self.frames.len().checked_sub(1));
2581        let env_index = self.frames.len().checked_sub(1);
2582        let caller = caller_index.and_then(|index| self.frames.get(index));
2583        let (this, passed) = match caller {
2584            Some(frame) => (frame.this.clone(), frame.passed.clone()),
2585            // No frame at all: the eval is running at the top level, so there is
2586            // nothing to inherit and the global receiver is right.
2587            None => (Value::Object(self.realm.global.clone()), Vec::new()),
2588        };
2589        // Innermost frame first, so the first binding found for a name is the one that
2590        // shadows the rest. A script frame (`<eval>`) contributes nothing.
2591        let mut bindings: Vec<EvalBinding> = Vec::new();
2592        // The calling function's own bindings, resolved by the compiler at the call
2593        // site. That table is the only reliable answer when a name is declared twice in
2594        // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
2595        // body means, and guessing by declaration order picks the wrong one as soon as
2596        // two loops in a row use the same name.
2597        // Only a *direct* eval sees the caller's scope. The compiler records a site for
2598        // every direct call — a bare `eval(...)` callee — so finding one at the current
2599        // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
2600        // callee to a value first and leave no site behind.
2601        let mut direct = false;
2602        let mut resolved_here = false;
2603        if let Some(frame) = self.frames.last() {
2604            let (line, column) = frame
2605                .code
2606                .code
2607                .position_at(frame.at as u32)
2608                .unwrap_or_default();
2609            // The nearest site at or before the current position, not an exact match:
2610            // the recorded position of the `call` instruction is the callee's, which
2611            // sits a few columns inside the call expression the compiler recorded. A
2612            // site is unique per call, so "the closest one behind us" identifies it.
2613            if let Some(site) = frame
2614                .code
2615                .code
2616                .eval_sites
2617                .iter()
2618                .filter(|site| (site.line, site.column) <= (line, column))
2619                .max_by_key(|site| (site.line, site.column))
2620            {
2621                direct = true;
2622                resolved_here = true;
2623                for binding in &site.bindings {
2624                    // An enclosing function's frame sits `owner` levels below the one
2625                    // running the call.
2626                    let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
2627                    else {
2628                        continue;
2629                    };
2630                    bindings.push(EvalBinding {
2631                        name: binding.name.clone(),
2632                        frame,
2633                        slot: if binding.is_arg {
2634                            EvalSlot::Arg
2635                        } else {
2636                            EvalSlot::Local
2637                        },
2638                        index: binding.index as usize,
2639                    });
2640                }
2641            }
2642        }
2643        for frame_index in (0..self.frames.len()).rev() {
2644            // Skip the innermost frame's flat scan when the compiler already answered
2645            // for it; an enclosing frame still needs one, because the eval resolves
2646            // those names dynamically.
2647            if resolved_here && frame_index == self.frames.len() - 1 {
2648                continue;
2649            }
2650            let frame = &self.frames[frame_index];
2651            for (index, arg) in frame.code.code.args.iter().enumerate() {
2652                bindings.push(EvalBinding {
2653                    name: arg.name.clone(),
2654                    frame: frame_index,
2655                    slot: EvalSlot::Arg,
2656                    index,
2657                });
2658            }
2659            for (index, local) in frame.code.code.vars.iter().enumerate() {
2660                bindings.push(EvalBinding {
2661                    name: local.name.clone(),
2662                    frame: frame_index,
2663                    slot: EvalSlot::Local,
2664                    index,
2665                });
2666            }
2667        }
2668        let mut seen = BTreeSet::new();
2669        bindings.retain(|binding| seen.insert(binding.name.clone()));
2670
2671        // The caller's `arguments`, as an array-like. Reading `length` and the indexed
2672        // elements is all the spec's ordinary uses need.
2673        //
2674        // Known divergence: this is bound for a *global* eval too, where there is no
2675        // caller and the reference throws `'arguments' is not defined`. Deciding properly
2676        // needs "does the calling frame have an `arguments` of its own", which is not
2677        // recorded anywhere the runtime can see — the caller of a direct eval has one, a
2678        // script or eval body does not, and `eval(b)` passes the callee as a value so even
2679        // the call-site detection does not answer it. Modelled as a binding in the caller's
2680        // variable environment, this would fall out; that is a larger change than the one
2681        // this comment is attached to.
2682        let arguments = Value::Object(self.new_array(passed));
2683
2684        // Only a *strict* eval gets a variable environment of its own. A sloppy one
2685        // declares its `var`s in the caller's — which for a top-level eval is the global
2686        // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
2687        // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
2688        // vanish into a scope nobody reads back from.
2689        let previous_scope = if code_strict {
2690            self.eval_scope.replace(BTreeMap::new())
2691        } else {
2692            None
2693        };
2694        let previous_arguments = self.eval_arguments.replace(arguments);
2695        let previous_with = self.eval_with.replace(self.with_objects());
2696        let inherited_new_target = self
2697            .frames
2698            .iter()
2699            .rev()
2700            .find(|frame| !frame.code.code.is_arrow)
2701            .map(|frame| frame.new_target.clone());
2702        let previous_new_target = self
2703            .eval_new_target
2704            .replace(inherited_new_target.unwrap_or(Value::Undefined));
2705        let eval_cells = self.eval_cells_for(&bindings);
2706        let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
2707        // A sloppy direct eval declares its `var`s in the caller's variable environment;
2708        // `declare_eval_local` needs to know which frame that is.
2709        // An indirect eval gets the global environment, so nothing of the caller's is
2710        // recorded as the place its `var`s belong.
2711        let previous_caller = self
2712            .eval_caller
2713            .replace(if direct { env_index } else { None });
2714        // The cell-based view of the same bindings, which is what a closure created
2715        // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
2716        // whose compiler did not put a binding in a cell simply does not appear here —
2717        // reads and writes still work through `eval_bindings`, they just cannot outlive
2718        // the eval.
2719        let previous_eval_scope = self
2720            .active_eval_scope
2721            .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
2722        let compiled = Gc::new(self.heap, CompiledCode::new(code));
2723        let closure_vars = compiled.code.closure_vars.clone();
2724        let env = self.global_env(&closure_vars);
2725        let callee = Value::Undefined;
2726        // An async body does not run here: it becomes a coroutine and answers a promise,
2727        // which is what makes `await` legal in it. `this` still has to be the caller's
2728        // (for a global eval, the global object), because `this` is not part of `await`.
2729        let result = if compiled.code.kind.is_async() {
2730            self.run_async_body(compiled, env, this)
2731        } else {
2732            self.execute(compiled, env, this, Vec::new(), callee)
2733        };
2734        self.eval_scope = previous_scope;
2735        self.eval_arguments = previous_arguments;
2736        self.eval_with = previous_with;
2737        self.eval_new_target = previous_new_target;
2738        self.eval_bindings = previous_bindings;
2739        self.eval_caller = previous_caller;
2740        self.active_eval_scope = previous_eval_scope;
2741        result
2742    }
2743
2744    /// The cell-backed subset of `bindings`, in the same priority order.
2745    ///
2746    /// Both lookup routes have to agree — the eval's own reads go through
2747    /// [`Interp::eval_binding_value`] and the closures it builds go through
2748    /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
2749    /// scanning the frames twice and disagreeing about a shadowed name. A binding that
2750    /// is not in a cell simply does not appear: reads and writes still work, they just
2751    /// cannot be handed to a closure that outlives the eval.
2752    fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
2753        let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
2754        for binding in bindings {
2755            let Some(frame) = self.frames.get(binding.frame) else {
2756                continue;
2757            };
2758            let cell = match binding.slot {
2759                EvalSlot::Arg => frame
2760                    .code
2761                    .arg_cell
2762                    .get(binding.index)
2763                    .copied()
2764                    .unwrap_or(-1),
2765                EvalSlot::Local => frame
2766                    .code
2767                    .loc_cell
2768                    .get(binding.index)
2769                    .copied()
2770                    .unwrap_or(-1),
2771            };
2772            if cell < 0 {
2773                continue;
2774            }
2775            if let Some(cell) = frame.cells.get(cell as usize) {
2776                names.push((binding.name.clone(), cell.clone()));
2777            }
2778        }
2779        names
2780    }
2781
2782    /// A `SyntaxError` that reports where in the source it happened.
2783    ///
2784    /// Compile-time failures never run, so they have no frame of their own; the
2785    /// reference still puts the position first in the trace, with no function name and
2786    /// no parentheses, and the caller's frames after it. It also defines `fileName`,
2787    /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
2788    /// reference borrows), which is how a script reads the position without parsing
2789    /// the trace.
2790    /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
2791    ///
2792    /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
2793    /// `columnNumber`, which is how the reference prints one. A positionless error
2794    /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
2795    /// the reference raises it from `js_resolve_module`, where there is no position.
2796    pub(crate) fn syntax_error_plain(
2797        &mut self,
2798        error: &js_parse::SyntaxError,
2799        file: &str,
2800    ) -> Value {
2801        if error.positionless {
2802            return self.make_error("SyntaxError", &error.message);
2803        }
2804        self.syntax_error_at(
2805            file,
2806            error.span.start.line,
2807            error.span.start.column,
2808            &error.message,
2809        )
2810    }
2811
2812    fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
2813        let blamed = format!("    at {file}:{line}:{column}\n{}", self.stack_trace());
2814        let value = self.make_error("SyntaxError", message);
2815        if let Value::Object(object) = &value {
2816            let text = self.string(blamed);
2817            object.define("stack", Property::with_attributes(text, true, true));
2818            let name = self.string(file);
2819            object.define("fileName", Property::with_attributes(name, true, true));
2820            object.define(
2821                "lineNumber",
2822                Property::with_attributes(Value::Int(line as i32), true, true),
2823            );
2824            object.define(
2825                "columnNumber",
2826                Property::with_attributes(Value::Int(column as i32), true, true),
2827            );
2828        }
2829        value
2830    }
2831
2832    /// Run a compiled script whose completion value is a function, returning it.
2833    ///
2834    /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
2835    /// get the closure out, which keeps the constant-pool plumbing in one place.
2836    pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
2837        self.run_script(code)
2838    }
2839
2840    /// The environment of a script or of any function compiled at global scope:
2841    /// every entry is a global binding, so each one resolves to the realm's cell.
2842    fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
2843        let mut cells = Vec::with_capacity(closure_vars.len());
2844        for closure_var in closure_vars {
2845            let cell = match closure_var.closure_type {
2846                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
2847                    if closure_var.is_lexical =>
2848                {
2849                    // A lexical declaration: the cell is created here holding the
2850                    // dead-zone marker, which is what makes the binding exist and
2851                    // unreadable before its initialiser runs.
2852                    self.declare_global(&closure_var.name, closure_var.is_const);
2853                    self.realm.globals[&closure_var.name].clone()
2854                }
2855                ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
2856                    // A `var` or function declaration becomes a property of the global
2857                    // object, and it exists from here on — which is why
2858                    // `print(v); var v = 1` prints `undefined` instead of raising.
2859                    // Declaring it at instantiation time (rather than at the
2860                    // initialiser) is also what makes it non-configurable: the store
2861                    // then lands on an existing property instead of creating one.
2862                    self.declare_var_global(&closure_var.name);
2863                    // The cell is a placeholder that nothing indexes; it cannot be
2864                    // omitted because the slot has to hold something.
2865                    self.new_cell(Value::Undefined)
2866                }
2867                _ => {
2868                    // An undeclared global is read by name; the cell is a
2869                    // placeholder that nothing indexes.
2870                    self.new_cell(Value::Undefined)
2871                }
2872            };
2873            cells.push(cell);
2874        }
2875        Gc::new(
2876            self.heap,
2877            ClosureEnv {
2878                cells,
2879                eval_scope: None,
2880                local_vars: None,
2881                local_phase: 1,
2882            },
2883        )
2884    }
2885
2886    /// Push a frame and run until it returns.
2887    pub(crate) fn execute(
2888        &mut self,
2889        code: Gc<CompiledCode>,
2890        env: Gc<ClosureEnv>,
2891        this: Value,
2892        args: Vec<Value>,
2893        callee: Value,
2894    ) -> JsResult<Value> {
2895        let depth = self.frames.len();
2896        self.push_frame(code, env, this, args, callee)?;
2897        loop {
2898            match self.step() {
2899                Ok(Step::Continue) => {}
2900                Ok(Step::Return(value)) => {
2901                    self.frames.pop();
2902                    // A frame that ended in a `tail_call` hands its value straight to
2903                    // its caller: nothing after the call can run, so every frame above
2904                    // the callee unwinds with the same value. See [`Frame::tail`] —
2905                    // the reference does not reuse frames either, so recursion depth
2906                    // and the stack-overflow limit behave the same way.
2907                    while self.frames.len() > depth && self.frame().tail {
2908                        self.frames.pop();
2909                    }
2910                    if self.frames.len() == depth {
2911                        return Ok(value);
2912                    }
2913                    // The caller resumes with the value on its stack.
2914                    self.frames
2915                        .last_mut()
2916                        .expect("a caller is live")
2917                        .stack
2918                        .push(value);
2919                }
2920                Err(Signal::Throw(value)) => {
2921                    // A handler lives on the stack of the frame that is throwing —
2922                    // `catch` pushed it there — so this frame gets the first chance
2923                    // to catch before it is popped.
2924                    let value = value;
2925                    loop {
2926                        if self.frames.len() <= depth {
2927                            return Err(Signal::Throw(value));
2928                        }
2929                        if self.catch_here(value.clone()).is_some() {
2930                            break;
2931                        }
2932                        self.frames.pop();
2933                    }
2934                }
2935                // A `yield` in a frame that `execute` is running directly means a
2936                // generator body was entered as an ordinary call, which only happens if
2937                // the generator check in `call_or_push` was bypassed.
2938                Ok(Step::Suspend(_)) => {
2939                    return Err(Signal::Throw(self.make_error(
2940                        "InternalError",
2941                        "a generator body ran as an ordinary call",
2942                    )));
2943                }
2944                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2945            }
2946        }
2947    }
2948
2949    /// Install a handler for `value` if this frame has one, resuming at it.
2950    ///
2951    /// The scan is the reference's: walk the frame's stack downwards looking for the
2952    /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
2953    /// `0` is an enumerator marker rather than a handler — it exists so that a
2954    /// `break` out of a `for-of` can find and close the iterator — so it is skipped
2955    /// here and the unwinding continues.
2956    fn catch_here(&mut self, value: Value) -> Option<()> {
2957        let frame = self.frames.last_mut()?;
2958        while let Some(top) = frame.stack.pop() {
2959            if let Value::CatchOffset(offset) = top {
2960                if offset == 0 {
2961                    continue;
2962                }
2963                frame.stack.push(value);
2964                frame.pc = offset as usize;
2965                return Some(());
2966            }
2967        }
2968        None
2969    }
2970
2971    fn push_frame(
2972        &mut self,
2973        code: Gc<CompiledCode>,
2974        env: Gc<ClosureEnv>,
2975        this: Value,
2976        mut args: Vec<Value>,
2977        callee: Value,
2978    ) -> JsResult<()> {
2979        if self.frames.len() >= self.max_frames {
2980            return Err(Signal::Throw(
2981                self.string("Maximum call stack size exceeded"),
2982            ));
2983        }
2984        let arg_count = code.code.args.len();
2985        // How many were actually passed, which `arguments.length` reports and
2986        // `assert(x)` depends on: a call with one argument must not look like a call
2987        // with one argument and an explicit `undefined`.
2988        let passed = args.len();
2989        // Missing arguments are `undefined` in their slots; extra ones are dropped
2990        // from the slots but still reachable through `arguments`.
2991        let mut passed_values = args.clone();
2992        args.resize(arg_count, Value::Undefined);
2993        args.truncate(arg_count);
2994        let cell_count = code.code.var_ref_count as usize;
2995        let mut cells = Vec::with_capacity(cell_count);
2996        for _ in 0..cell_count {
2997            cells.push(self.new_cell(Value::Undefined));
2998        }
2999        let locals = vec![Value::Undefined; code.code.vars.len()];
3000        // A captured argument lives in its cell, not in the argument slot, so the
3001        // incoming value has to be moved there before the body runs.
3002        for (slot, cell) in code.arg_cell.iter().enumerate() {
3003            if *cell >= 0
3004                && let Some(value) = args.get(slot).cloned()
3005            {
3006                cells[*cell as usize].set(value);
3007            }
3008        }
3009        // Sloppy mode substitutes the global object for a missing receiver and boxes a
3010        // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
3011        // reports `object`. Strict mode passes the value through untouched.
3012        let this = if code.code.strict {
3013            this
3014        } else if this.is_nullish() {
3015            Value::Object(self.realm.global.clone())
3016        } else if matches!(this, Value::Object(_)) {
3017            this
3018        } else {
3019            match crate::builtins::this_object(self, &this) {
3020                Ok(boxed) => Value::Object(boxed),
3021                Err(_) => this,
3022            }
3023        };
3024        self.frames.push(Frame {
3025            code,
3026            env,
3027            this,
3028            args,
3029            passed: passed_values.drain(..passed).collect(),
3030            locals,
3031            cells,
3032            local_vars: None,
3033            stack: Vec::with_capacity(16),
3034            pc: 0,
3035            at: 0,
3036            callee,
3037            new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
3038            tail: false,
3039        });
3040        Ok(())
3041    }
3042
3043    /// The cell a direct `eval` created for the closure entry at `slot`, if any.
3044    ///
3045    /// Only names the eval created are here: a name the frame already declared statically
3046    /// is written through to its own slot instead, so this cannot shadow a real local.
3047    fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
3048        let name = &self.frame().code.code.closure_vars.get(slot)?.name;
3049        let (local_vars, phase) = self.visible_local_vars()?;
3050        if !local_vars.contains(name) {
3051            return None;
3052        }
3053        local_vars.get(name, phase)
3054    }
3055
3056    /// The variables a direct `eval` declared, as the code currently running sees them.
3057    ///
3058    /// Inside an eval that is the *caller's* set — the eval's own variable environment
3059    /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
3060    /// else it is the current frame's, falling back to the frame the closure was created
3061    /// in.
3062    fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
3063        // While an `eval` runs, its own frame is on top but its variable environment is
3064        // the *caller's* — so the caller is what the lookup has to start from.
3065        let (index, phase) = match self.eval_caller.flatten() {
3066            Some(caller) => (
3067                caller,
3068                if self.in_parameter_list_at(caller) {
3069                    0
3070                } else {
3071                    1
3072                },
3073            ),
3074            None => (
3075                self.frames.len().checked_sub(1)?,
3076                if self.in_parameter_list() { 0 } else { 1 },
3077            ),
3078        };
3079        let frame = self.frames.get(index)?;
3080        // The frame's own variables, or — for an arrow, which has no variable environment
3081        // of its own — the one it was created in, which `ClosureEnv` carries.
3082        if let Some(local_vars) = frame.local_vars.clone() {
3083            return Some((local_vars, phase));
3084        }
3085        frame
3086            .env
3087            .local_vars
3088            .clone()
3089            .map(|local_vars| (local_vars, frame.env.local_phase))
3090    }
3091
3092    /// Whether the innermost frame is still evaluating its parameter list.
3093    ///
3094    /// A direct `eval` that runs there declares its `var`s in the parameter environment,
3095    /// and a closure created there may only see that much of [`LocalVars`].
3096    fn in_parameter_list(&self) -> bool {
3097        self.in_parameter_list_at(self.frames.len().saturating_sub(1))
3098    }
3099
3100    /// [`Interp::in_parameter_list`] for a specific frame.
3101    fn in_parameter_list_at(&self, frame: usize) -> bool {
3102        let Some(frame) = self.frames.get(frame) else {
3103            return false;
3104        };
3105        let code = &frame.code.code;
3106        if !code.has_parameter_expressions {
3107            return false;
3108        }
3109        // `(0, 0)` means the compiler did not record a boundary, so treat the whole
3110        // function as its body and let a direct `eval` act accordingly.
3111        if code.body_start == (0, 0) {
3112            return false;
3113        }
3114        match code.position_at(frame.at as u32) {
3115            Some(position) => position < code.body_start,
3116            None => false,
3117        }
3118    }
3119
3120    fn frame(&self) -> &Frame {
3121        self.frames.last().expect("a frame is live")
3122    }
3123
3124    fn frame_mut(&mut self) -> &mut Frame {
3125        self.frames.last_mut().expect("a frame is live")
3126    }
3127
3128    // -- slot access --------------------------------------------------------
3129
3130    fn read_slot(&self, cell: i32, value: &Value) -> Value {
3131        match cell {
3132            -1 => value.clone(),
3133            index => self
3134                .frame()
3135                .cells
3136                .get(index as usize)
3137                .expect("a cell index in range")
3138                .get(),
3139        }
3140    }
3141
3142    fn get_arg(&self, slot: usize) -> Value {
3143        let frame = self.frame();
3144        let cell = frame.code.arg_cell.get(slot).copied().unwrap_or(-1);
3145        let value = frame.args.get(slot).cloned().unwrap_or(Value::Undefined);
3146        self.read_slot(cell, &value)
3147    }
3148
3149    fn put_arg(&mut self, slot: usize, value: Value) {
3150        let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
3151        if cell == -1 {
3152            if let Some(slot) = self.frame_mut().args.get_mut(slot) {
3153                *slot = value;
3154            }
3155        } else {
3156            self.frame().cells[cell as usize].set(value);
3157        }
3158    }
3159
3160    fn get_loc(&self, slot: usize) -> Value {
3161        let frame = self.frame();
3162        let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
3163        let value = frame.locals.get(slot).cloned().unwrap_or(Value::Undefined);
3164        self.read_slot(cell, &value)
3165    }
3166
3167    fn put_loc(&mut self, slot: usize, value: Value) {
3168        let cell = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
3169        if cell == -1 {
3170            if let Some(slot) = self.frame_mut().locals.get_mut(slot) {
3171                *slot = value;
3172            }
3173        } else {
3174            self.frame().cells[cell as usize].set(value);
3175        }
3176    }
3177
3178    // -- globals ------------------------------------------------------------
3179
3180    /// The name a global-slot operand refers to.
3181    fn global_name(&self, slot: usize) -> String {
3182        self.frame()
3183            .code
3184            .code
3185            .closure_vars
3186            .get(slot)
3187            .map(|c| c.name.clone())
3188            .unwrap_or_default()
3189    }
3190
3191    /// The facts about a global binding that decide where it lives.
3192    ///
3193    /// A script's globals split in two, and the split is observable: `var` and
3194    /// function declarations become properties of the global object (`globalThis.v`
3195    /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
3196    /// declarations live in the global *lexical* environment and are invisible there
3197    /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
3198    /// `is_lexical` flag means the answer is already in the bytecode.
3199    fn global_binding(&self, slot: usize) -> (String, bool, bool) {
3200        let name = self.global_name(slot);
3201        // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
3202        // while forwarding a reference through a nested function is built with the
3203        // flags cleared, so `const c` would look like an ordinary `var` from inside a
3204        // closure. Presence in the realm's lexical table is the same fact, recorded
3205        // once, and every slot sees it.
3206        let lexical = self.realm.globals.contains_key(&name);
3207        let is_const = self.realm.lexical_consts.contains(&name);
3208        (name, lexical, is_const)
3209    }
3210
3211    /// The value of `name` in the innermost active `with` object, if any.
3212    ///
3213    /// The active objects are the [`VarKind::With`] locals of every frame still running,
3214    /// innermost frame first and innermost block first within one. Walking frames rather
3215    /// than keeping a separate stack is what makes a closure called from inside a `with`
3216    /// see it, and what keeps the object alive only as long as the block is.
3217    /// The innermost active `with` object that has `name`, if any.
3218    fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
3219        let objects = self.eval_with.clone().unwrap_or_default();
3220        for object in objects {
3221            let key = self.string(name.to_string());
3222            if self
3223                .has_property(&key, &Value::Object(object.clone()))
3224                .ok()?
3225            {
3226                return Some(object);
3227            }
3228        }
3229        None
3230    }
3231
3232    /// Every active `with` object, innermost first.
3233    fn with_objects(&self) -> Vec<Gc<JsObject>> {
3234        let mut objects = Vec::new();
3235        for frame in self.frames.iter().rev() {
3236            for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
3237                if var.kind != js_compile::VarKind::With {
3238                    continue;
3239                }
3240                // A captured binding lives in its cell and not in the slot list, so the
3241                // cell is consulted first — a closure created inside the block is exactly
3242                // what makes the object captured. Before the store runs the slot still
3243                // holds `undefined`, and a `with` object is always boxed, so a non-object
3244                // entry is simply not in scope yet.
3245                let value = frame
3246                    .code
3247                    .loc_cell
3248                    .get(index)
3249                    .copied()
3250                    .filter(|cell| *cell >= 0)
3251                    .and_then(|cell| frame.cells.get(cell as usize))
3252                    .map(|cell| cell.get())
3253                    .or_else(|| frame.locals.get(index).cloned());
3254                if let Some(Value::Object(object)) = value {
3255                    objects.push(object);
3256                }
3257            }
3258        }
3259        objects
3260    }
3261
3262    fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
3263        for object in self.eval_with.clone().unwrap_or_default() {
3264            let key = self.string(name.to_string());
3265            if self.has_property(&key, &Value::Object(object.clone()))? {
3266                return Ok(Some(self.read_field(&Value::Object(object), name)?));
3267            }
3268        }
3269        Ok(None)
3270    }
3271
3272    fn get_global(&mut self, slot: usize) -> JsResult<Value> {
3273        let (name, lexical, _) = self.global_binding(slot);
3274        if name == "arguments"
3275            && let Some(arguments) = &self.eval_arguments
3276        {
3277            return Ok(arguments.clone());
3278        }
3279        // A `with` block around the *call site* is part of the scope an `eval` sees, so
3280        // the objects live when the eval started are consulted before anything else. The
3281        // snapshot is taken at entry rather than scanning the frames on every read: a
3282        // block that has already finished still leaves its object in the slot, and a
3283        // bytecode read outside the block must not see it.
3284        if let Some(value) = self.with_lookup(&name)? {
3285            return Ok(value);
3286        }
3287        // A variable a direct `eval` declared shadows everything the compiler resolved,
3288        // including an enclosing function's binding: the eval put it in the caller's own
3289        // variable environment, which is nearer than any captured scope.
3290        if let Some((local_vars, phase)) = self.visible_local_vars()
3291            && let Some(cell) = local_vars.get(&name, phase)
3292        {
3293            return Ok(cell.get());
3294        }
3295        // The frame that called `eval` is the innermost scope the eval'd code sees, so
3296        // its local `a` wins over a global `a`.
3297        if let Some(value) = self.eval_binding_value(&name) {
3298            return Ok(value);
3299        }
3300        // A closure created by an `eval` resolves its free names against the bindings
3301        // that eval saw, even after the eval (and its frames) are gone.
3302        if let Some(cell) = self
3303            .frame()
3304            .env
3305            .eval_scope
3306            .as_ref()
3307            .and_then(|scope| scope.get(&name))
3308        {
3309            let value = cell.get();
3310            if matches!(value, Value::Uninitialized) {
3311                return Err(self.throw_reference(&name));
3312            }
3313            return Ok(value);
3314        }
3315        // A binding declared by the strict `eval` currently running shadows anything
3316        // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
3317        if let Some(scope) = &self.eval_scope
3318            && let Some(value) = scope.get(&name)
3319        {
3320            return Ok(value.clone());
3321        }
3322        if lexical {
3323            // A lexical global is a binding in a side table, so the dead zone is
3324            // visible and it is nowhere on the global object.
3325            if let Some(cell) = self.realm.globals.get(&name) {
3326                let value = cell.get();
3327                if matches!(value, Value::Uninitialized) {
3328                    return Err(self.throw_reference(&name));
3329                }
3330                return Ok(value);
3331            }
3332            return Err(self.throw_reference(&name));
3333        }
3334        // A `var` global is an ordinary property, so the prototype chain and the
3335        // global object's own builtins are all reachable through it.
3336        match self.get_property(&self.realm.global.clone(), &name)? {
3337            Some(value) => Ok(value),
3338            None => Err(self.throw_reference(&name)),
3339        }
3340    }
3341
3342    /// Store to a global binding.
3343    ///
3344    /// Returns a signal when the store is refused: a `const` global may only be
3345    /// written by its initialiser, and a non-configurable `var` global may not be
3346    /// deleted but is always writable.
3347    fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
3348        let (name, lexical, is_const) = self.global_binding(slot);
3349
3350        // An assignment inside a `with` writes through to the object that supplies the
3351        // name, which for an `eval` means consulting the same chain `get_global` does.
3352        if let Some(owner) = self.with_owner(&name) {
3353            self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
3354            return Ok(());
3355        }
3356        // A variable the running eval *declared* takes the write before any caller
3357        // binding: `eval("var c = 1")` creates `c` in the eval's own variable
3358        // environment even when an enclosing function has a `var c` of its own.
3359        if self.eval_caller.flatten().is_some()
3360            && let Some((local_vars, phase)) = self.visible_local_vars()
3361            && local_vars.contains(&name)
3362            && let Some(cell) = local_vars.get(&name, phase)
3363        {
3364            cell.set(value);
3365            return Ok(());
3366        }
3367        // A binding of the frame that called `eval` takes the write, which is what
3368        // makes `f("a = 3")` change the caller's `a`.
3369        if self.set_eval_binding(&name, &value)? {
3370            return Ok(());
3371        }
3372        // A closure that outlived its `eval` writes through to the same cell it reads.
3373        if let Some(cell) = self
3374            .frame()
3375            .env
3376            .eval_scope
3377            .as_ref()
3378            .and_then(|scope| scope.get(&name))
3379            .cloned()
3380        {
3381            cell.set(value);
3382            return Ok(());
3383        }
3384        // Inside a strict `eval`, a name it declared itself is stored there. An
3385        // *assignment* to a name nobody declared is not a declaration, so it falls
3386        // through: strict mode raises `ReferenceError` for it, which is what
3387        // `eval("1 + (@not_def = 1)")` has to do.
3388        if let Some(scope) = self.eval_scope.as_mut()
3389            && scope.contains_key(&name)
3390        {
3391            scope.insert(name, value);
3392            return Ok(());
3393        }
3394        if lexical {
3395            if let Some(cell) = self.realm.globals.get(&name).cloned() {
3396                if is_const && !matches!(cell.get(), Value::Uninitialized) {
3397                    return Err(self.read_only_global(&name));
3398                }
3399                cell.set(value);
3400                return Ok(());
3401            }
3402            // Writing an undeclared lexical global is a `ReferenceError` in strict
3403            // mode and a silent global creation otherwise; creating the cell here
3404            // keeps both paths from losing the value.
3405            let cell = self.new_cell(value);
3406            self.realm.globals.insert(name, cell);
3407            return Ok(());
3408        }
3409        // A variable a direct `eval` declared in this call shadows the global object, even
3410        // when the global already has a property of that name — `var c = "global"` at the
3411        // top level must not capture `eval("var c = 1")` inside a function.
3412        if let Some((local_vars, phase)) = self.visible_local_vars()
3413            && local_vars.contains(&name)
3414            && let Some(cell) = local_vars.get(&name, phase)
3415        {
3416            cell.set(value);
3417            return Ok(());
3418        }
3419        let global = self.realm.global.clone();
3420        match global.own_property(&name) {
3421            // A `var` global is writable, so the store goes straight through — but
3422            // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
3423            // store (a non-writable or accessor-without-setter global) is a silent
3424            // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
3425            // split every other assignment has.
3426            Some(_) => {
3427                let on_failure = if self.current_strict() {
3428                    DeleteFailure::Throw
3429                } else {
3430                    DeleteFailure::Ignore
3431                };
3432                self.set_property_with(&global, &name, value, on_failure)
3433            }
3434            // Only an implicit global reaches here. In sloppy mode `x = 1` with no
3435            // declaration creates a *configurable* property, which is what makes it
3436            // deletable and is the one way a global differs from a declared `var`.
3437            // In strict mode the same store is a `ReferenceError` instead: that is the
3438            // whole point of strict mode, and creating the global silently meant
3439            // `"use strict"; x = 1` looked like it worked.
3440            None => {
3441                if self.current_strict() {
3442                    return Err(self.throw_reference(&name));
3443                }
3444                // A direct eval declares here rather than on the global object: its
3445                // `var`s belong to the caller's variable environment. `declare_eval_local`
3446                // also covers a plain assignment to a variable an earlier eval made.
3447                if let Some(cell) = self.declare_eval_local(&name) {
3448                    cell.set(value);
3449                    return Ok(());
3450                }
3451                global.define_data(&name, value);
3452                Ok(())
3453            }
3454        }
3455    }
3456
3457    /// The value of a binding of the frame that called `eval`, if there is one.
3458    fn eval_binding_value(&self, name: &str) -> Option<Value> {
3459        let binding = self
3460            .eval_bindings
3461            .iter()
3462            .find(|binding| binding.name == name)?;
3463        let owner = self.frames.get(binding.frame)?;
3464        let (slot, index) = (binding.slot, binding.index);
3465        Some(match slot {
3466            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
3467                cell if cell >= 0 => owner
3468                    .cells
3469                    .get(cell as usize)
3470                    .map(|cell| cell.get())
3471                    .unwrap_or(Value::Undefined),
3472                _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
3473            },
3474            EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
3475                cell if cell >= 0 => owner
3476                    .cells
3477                    .get(cell as usize)
3478                    .map(|cell| cell.get())
3479                    .unwrap_or(Value::Undefined),
3480                _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
3481            },
3482        })
3483    }
3484
3485    /// Write to a binding of the frame that called `eval`.
3486    ///
3487    /// `Ok(false)` means no binding matched and the caller should keep looking. A
3488    /// matched binding can still refuse the store, which is why this is fallible: a
3489    /// `const` is read-only everywhere, and a named function expression's own name is
3490    /// read-only in strict mode.
3491    fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
3492        let Some(binding) = self
3493            .eval_bindings
3494            .iter()
3495            .find(|binding| binding.name == name)
3496        else {
3497            return Ok(false);
3498        };
3499        let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
3500        let strict = self.current_strict();
3501        let Some(owner) = self.frames.get_mut(frame) else {
3502            return Ok(false);
3503        };
3504        match slot {
3505            EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
3506                cell if cell >= 0 => {
3507                    if let Some(cell) = owner.cells.get(cell as usize) {
3508                        cell.set(value.clone());
3509                    }
3510                }
3511                _ => {
3512                    if let Some(slot) = owner.args.get_mut(index) {
3513                        *slot = value.clone();
3514                    }
3515                }
3516            },
3517            EvalSlot::Local => {
3518                let declared = owner.code.code.vars.get(index);
3519                // A `const` is read-only even through `eval`. The realm records this for
3520                // globals (see `lexical_consts`), but a local's `const`-ness is only in
3521                // the bytecode, so this is where it has to be enforced.
3522                if declared.is_some_and(|var| var.is_const) {
3523                    return Err(self.read_only_local(name));
3524                }
3525                // The name of a named function expression is read-only too, but only
3526                // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
3527                // such a name is ignored, the same as a direct store would be.
3528                if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
3529                    return if strict {
3530                        Err(self.read_only_local(name))
3531                    } else {
3532                        Ok(true)
3533                    };
3534                }
3535                match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
3536                    cell if cell >= 0 => {
3537                        if let Some(cell) = owner.cells.get(cell as usize) {
3538                            cell.set(value.clone());
3539                        }
3540                    }
3541                    _ => {
3542                        if let Some(slot) = owner.locals.get_mut(index) {
3543                            *slot = value.clone();
3544                        }
3545                    }
3546                }
3547            }
3548        }
3549        Ok(true)
3550    }
3551
3552    /// The `TypeError` an assignment to a read-only binding raises.
3553    fn read_only_local(&self, name: &str) -> Signal {
3554        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
3555    }
3556
3557    /// Declare `name` as a variable of the frame that called the running `eval`.
3558    ///
3559    /// `None` when there is no direct eval in progress, or it was called from the top
3560    /// level — then the caller's variable environment *is* the global one and the
3561    /// existing path is right.
3562    fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
3563        let caller = self.eval_caller.flatten()?;
3564        // The bottom frame is the top-level script, whose variable environment *is* the
3565        // global one — so `eval("var x = 1")` at the top level still creates a global.
3566        if caller == 0 {
3567            return None;
3568        }
3569        // A name the eval's *own* variable environment already binds is not a new
3570        // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
3571        // `arguments`, and creating a second binding would leave the first — the one
3572        // closures read — untouched. A binding of an *outer* frame does not count: a
3573        // declaration shadows it rather than writing through.
3574        if self
3575            .eval_bindings
3576            .iter()
3577            .any(|binding| binding.name == name && binding.frame == caller)
3578        {
3579            return None;
3580        }
3581        let phase = if self.in_parameter_list_at(caller) {
3582            0
3583        } else {
3584            1
3585        };
3586        self.frame_local_vars(caller)?;
3587        let local_vars = self.frames.get(caller)?.local_vars.clone()?;
3588        if let Some(cell) = local_vars.get(name, 1) {
3589            return Some(cell);
3590        }
3591        let cell = self.new_cell(Value::Undefined);
3592        Some(local_vars.declare(name, phase, cell))
3593    }
3594
3595    /// Make sure `frame` has a `LocalVars`, creating it on demand.
3596    fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
3597        if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
3598            return Some(local_vars.clone());
3599        }
3600        let local_vars = Gc::new(self.heap, LocalVars::new());
3601        self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
3602        Some(local_vars)
3603    }
3604
3605    /// Whether the realm already has a binding for `name`, lexically or as an *own*
3606    /// property of the global object. Used to decide whether a store inside an
3607    /// `eval` writes through to the realm or declares a binding of its own.
3608    ///
3609    /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
3610    /// write to `Object.prototype.toString`, and must not shadow it either.
3611    fn global_knows(&mut self, name: &str) -> bool {
3612        if self.realm.globals.contains_key(name) {
3613            return true;
3614        }
3615        self.realm.global.own_property(name).is_some()
3616    }
3617
3618    /// Whether the code currently running is strict.
3619    ///
3620    /// Read off the frame's function, which is where the parser's answer ended up; a
3621    /// native function never runs strict-only checks, and there is no frame at all
3622    /// before the first script.
3623    pub fn current_strict(&self) -> bool {
3624        self.frames
3625            .last()
3626            .is_some_and(|frame| frame.code.code.strict)
3627    }
3628
3629    /// Initialise a declared global, which is what ends its dead zone.
3630    ///
3631    /// A `var` global becomes a property of the global object: writable, so a later
3632    /// assignment goes through, and non-configurable, so `delete` refuses.
3633    fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
3634        let (name, lexical, _) = self.global_binding(slot);
3635        // A `var` declared by the strict `eval` currently running belongs to the
3636        // eval's scope, not to the global object: `eval("var v = 1")` must not make
3637        // `typeof v` answer `"number"` afterwards. A name the realm already has is
3638        // initialised in place, which is what a re-declaration inside eval does.
3639        if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
3640            self.eval_scope
3641                .as_mut()
3642                .expect("checked above")
3643                .insert(name, value);
3644            return Ok(());
3645        }
3646        if let Some(scope) = self.eval_scope.as_mut()
3647            && scope.contains_key(&name)
3648        {
3649            scope.insert(name, value);
3650            return Ok(());
3651        }
3652        if lexical {
3653            // The cell exists (created at declaration time) holding the dead-zone
3654            // marker; storing the value is what makes the binding readable.
3655            if let Some(cell) = self.realm.globals.get(&name).cloned() {
3656                cell.set(value);
3657                return Ok(());
3658            }
3659            let cell = self.new_cell(value);
3660            self.realm.globals.insert(name, cell);
3661            return Ok(());
3662        }
3663        let global = self.realm.global.clone();
3664        // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
3665        // to answer `false` and leave the binding in place. `with_attributes` ties
3666        // `configurable` to `writable`, so the property is built field by field.
3667        global.define(
3668            &name,
3669            Property {
3670                value: Some(value),
3671                writable: true,
3672                enumerable: true,
3673                configurable: false,
3674                ..Property::default()
3675            },
3676        );
3677        Ok(())
3678    }
3679
3680    /// The `TypeError` a store to a `const` global raises.
3681    fn read_only_global(&self, name: &str) -> Signal {
3682        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
3683    }
3684
3685    // -- properties ---------------------------------------------------------
3686
3687    /// Read `object[key]`, following the prototype chain.
3688    ///
3689    /// An inherited accessor runs with the *receiver* as `this`, which is why the
3690    /// lookup returns the owner rather than just the value.
3691    pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
3692        self.get_property_key(object, &PropertyKey::from(key))
3693    }
3694
3695    /// [`Interp::get_property`] with a key that may be a symbol.
3696    pub fn get_property_key(
3697        &mut self,
3698        object: &Gc<JsObject>,
3699        key: &PropertyKey,
3700    ) -> JsResult<Option<Value>> {
3701        self.get_property_key_for(object, None, key)
3702    }
3703
3704    /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
3705    ///
3706    /// The receiver matters when the property is found on a *prototype*: a getter has to
3707    /// see the object the read started from. For a primitive that is the primitive
3708    /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
3709    /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
3710    /// the owner.
3711    pub fn get_property_key_for(
3712        &mut self,
3713        object: &Gc<JsObject>,
3714        receiver: Option<&Value>,
3715        key: &PropertyKey,
3716    ) -> JsResult<Option<Value>> {
3717        // A proxy answers for itself, before any of the shortcuts below: `new
3718        // Proxy([], {get: …})` must not read `length` out of an element vector it does not
3719        // have.
3720        if object.proxy_state().is_some() {
3721            let receiver = receiver
3722                .cloned()
3723                .unwrap_or_else(|| Value::Object(object.clone()));
3724            return self.proxy_get(object, &receiver, key);
3725        }
3726        // The element-vector and `length` shortcuts are string-only: an array index
3727        // has no symbol spelling.
3728        if let Some(text) = key.as_str() {
3729            if let Some(value) = self.own_element(object, text) {
3730                return Ok(Some(value));
3731            }
3732            // `length` is not stored as a property: an array's length is its element
3733            // count, and keeping one copy of it is what makes `push`/`pop` and
3734            // `a.length = n` agree.
3735            if let Some(length) = object.array_length()
3736                && text == "length"
3737            {
3738                // Not `Value::Int(length as i32)`: see [`length_value`].
3739                return Ok(Some(crate::object::length_value(length)));
3740            }
3741        }
3742        match lookup_key(object, key) {
3743            Some((_, property)) => {
3744                if property.is_accessor() {
3745                    match &property.getter {
3746                        Some(getter) if !matches!(getter, Value::Undefined) => {
3747                            let receiver = receiver
3748                                .cloned()
3749                                .unwrap_or_else(|| Value::Object(object.clone()));
3750                            self.call_value(getter.clone(), receiver, Vec::new())
3751                                .map(Some)
3752                        }
3753                        // An accessor with no getter reads as `undefined`.
3754                        _ => Ok(Some(Value::Undefined)),
3755                    }
3756                } else {
3757                    Ok(property.value)
3758                }
3759            }
3760            None => Ok(None),
3761        }
3762    }
3763
3764    /// `super.key` — start the search at `proto`, but report to `receiver`.
3765    ///
3766    /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
3767    /// found on the prototype of a class has to see the *instance* as `this`, and a
3768    /// plain property read off `proto` would lose that.
3769    fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
3770        let start = self.require_object(proto)?;
3771        let key = self.propkey(key)?;
3772        // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
3773        if matches!(proto, Value::Null) {
3774            return Ok(Value::Undefined);
3775        }
3776        match lookup_key(&start, &key) {
3777            Some((_, property)) if property.is_accessor() => match &property.getter {
3778                Some(getter) if !matches!(getter, Value::Undefined) => {
3779                    self.call_value(getter.clone(), receiver.clone(), Vec::new())
3780                }
3781                _ => Ok(Value::Undefined),
3782            },
3783            Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
3784            None => Ok(Value::Undefined),
3785        }
3786    }
3787
3788    /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
3789    ///
3790    /// A setter found on the prototype runs with `receiver` as `this`; a data property
3791    /// is shadowed by a new own property on the receiver, the same rule an ordinary
3792    /// assignment follows.
3793    fn super_write(
3794        &mut self,
3795        receiver: &Value,
3796        proto: &Value,
3797        key: &Value,
3798        value: Value,
3799    ) -> JsResult<()> {
3800        let target = self.require_object(receiver)?;
3801        let key = self.propkey(key)?;
3802        if !matches!(proto, Value::Null)
3803            && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
3804        {
3805            if property.is_accessor() {
3806                if let Some(setter) = &property.setter
3807                    && !matches!(setter, Value::Undefined)
3808                {
3809                    self.call_value(setter.clone(), receiver.clone(), vec![value])?;
3810                }
3811                return Ok(());
3812            }
3813            // A data property on the prototype is writable or not; reading `owner` at
3814            // all is only for the attribute check.
3815            if !property.writable {
3816                return Err(self.type_error(format!("'{key}' is read-only")));
3817            }
3818            let _ = owner;
3819        }
3820        self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
3821    }
3822
3823    /// The object a `super` operation needs, or the `TypeError` the spec raises.
3824    fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
3825        match value.as_object() {
3826            Some(object) => Ok(object.clone()),
3827            None => Err(Signal::Throw(
3828                self.make_error("TypeError", "value is not an object"),
3829            )),
3830        }
3831    }
3832
3833    /// Build the class object `define_class` produces.
3834    ///
3835    /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
3836    /// whose prototype property is a fresh object inheriting from the parent's
3837    /// prototype, and whose own prototype is the parent constructor — which is what makes
3838    /// a static method inherited too.
3839    fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
3840        let ctor = self.pop();
3841        let parent = self.pop();
3842        let Value::Object(function) = &ctor else {
3843            return Err(Signal::Throw(
3844                self.make_error("TypeError", "class constructor must be a function"),
3845            ));
3846        };
3847        // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
3848        // but gives the instances no prototype at all.
3849        let (parent_ctor, parent_proto) = if flags & 1 != 0 {
3850            match &parent {
3851                Value::Null => (Some(self.realm.function_proto.clone()), None),
3852                Value::Object(parent_class) => {
3853                    if !parent_class.is_callable() {
3854                        return Err(Signal::Throw(
3855                            self.make_error("TypeError", "parent class must be constructor"),
3856                        ));
3857                    }
3858                    let proto = self.get_property(parent_class, "prototype")?;
3859                    match proto {
3860                        Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
3861                        Some(Value::Null) => (Some(parent_class.clone()), None),
3862                        _ => {
3863                            return Err(Signal::Throw(self.make_error(
3864                                "TypeError",
3865                                "parent prototype must be an object or null",
3866                            )));
3867                        }
3868                    }
3869                }
3870                _ => {
3871                    return Err(Signal::Throw(
3872                        self.make_error("TypeError", "parent class must be constructor"),
3873                    ));
3874                }
3875            }
3876        } else {
3877            (
3878                Some(self.realm.function_proto.clone()),
3879                Some(self.realm.object_proto.clone()),
3880            )
3881        };
3882        let proto = self.new_object(parent_proto);
3883        function.set_proto(parent_ctor);
3884        // A class is not callable without `new`, and its `prototype` is not writable —
3885        // both follow from being a class and are what `class A {}; A()` throws on.
3886        function.set_class_constructor(true);
3887        function.set_home_object(None);
3888        self.set_function_name(&ctor, name);
3889        self.define_class_properties(function, &ctor, &proto)?;
3890        Ok((ctor, proto))
3891    }
3892
3893    /// Give the constructor its `prototype` and `length`, and the prototype its
3894    /// `constructor` back-pointer.
3895    fn define_class_properties(
3896        &mut self,
3897        function: &Gc<JsObject>,
3898        ctor: &Value,
3899        proto: &Gc<JsObject>,
3900    ) -> JsResult<()> {
3901        proto.define(
3902            "constructor",
3903            Property::with_attributes(ctor.clone(), true, false),
3904        );
3905        function.define(
3906            "prototype",
3907            Property::prototype_of(Value::Object(proto.clone()), false),
3908        );
3909        if let Some((code, _)) = bytecode_of(function) {
3910            let length = code.code.defined_args;
3911            function.define(
3912                "length",
3913                Property::name_or_length(Value::Int(length as i32)),
3914            );
3915        }
3916        Ok(())
3917    }
3918
3919    /// The own array element `key` names, if this object has one.
3920    fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
3921        let index = array_index(key)?;
3922        // A typed array's elements live in its buffer, not in a property list: reading one
3923        // goes through the view's element type so a bounds check and a detached buffer are
3924        // both handled there.
3925        if object.typed_array_parts().is_some() {
3926            return object.typed_array_element(index as usize);
3927        }
3928        // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
3929        // has to continue up the prototype chain. Mapping it to `undefined` here ended the
3930        // search early, which is why `Array.prototype[1] = 9` could not be seen through
3931        // `[1,,3][1]`.
3932        match object.array_get(index as usize) {
3933            Some(Value::Hole) | None => None,
3934            other => other,
3935        }
3936    }
3937
3938    /// Store `object[key] = value`, honouring setters and inherited properties.
3939    pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
3940        self.set_property_with(object, key, value, DeleteFailure::Throw)
3941    }
3942
3943    /// Store a property, choosing what to do when the object refuses.
3944    ///
3945    /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
3946    /// mode, which is the one place assignment differs by mode. Native code (the array
3947    /// methods, `JSON`) always asks for the throw.
3948    pub fn set_property_with(
3949        &mut self,
3950        object: &Gc<JsObject>,
3951        key: &str,
3952        value: Value,
3953        on_failure: DeleteFailure,
3954    ) -> JsResult<()> {
3955        self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
3956    }
3957
3958    /// [`Interp::set_property_with`] with a key that may be a symbol.
3959    pub fn set_property_with_key(
3960        &mut self,
3961        object: &Gc<JsObject>,
3962        key: &PropertyKey,
3963        value: Value,
3964        on_failure: DeleteFailure,
3965    ) -> JsResult<()> {
3966        // A proxy's `set` trap decides, and its `false` means the same thing an
3967        // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
3968        if object.proxy_state().is_some() {
3969            let receiver = Value::Object(object.clone());
3970            if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
3971                return match (accepted, on_failure) {
3972                    (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
3973                    (false, DeleteFailure::Throw) => {
3974                        Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
3975                    }
3976                };
3977            }
3978        }
3979        // The element and `length` shortcuts only exist for string keys: an array
3980        // index has no symbol spelling, and a symbol named `length` is an ordinary
3981        // property.
3982        let text = key.as_str();
3983        // A typed array's elements are a window onto its buffer: the store has to go
3984        // through the view's element type so the value is wrapped (or clamped) and so an
3985        // out-of-range or detached write is a silent no-op, as the spec says.
3986        if let Some(text) = text
3987            && let Some(index) = array_index(text)
3988            && let Some(element) = object.typed_array_element_type()
3989        {
3990            // §10.4.5.5: an out-of-bounds index answers `true` *before* `V` is converted,
3991            // so a `valueOf` with a side effect must not run. Checking the length first is
3992            // what keeps `valueOfCalled` at 0 in `key-is-out-of-bounds-receiver-is-…`.
3993            let length = object.typed_array_length().unwrap_or(0);
3994            if index as usize >= length {
3995                return Ok(());
3996            }
3997            // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
3998            // makes both a `TypeError` rather than a silent skip. The conversion runs here,
3999            // in `Interp`, because it is script-observable and the storage borrow inside
4000            // `typed_array_set` must not be held across it.
4001            let stored = self.element_value(element, value)?;
4002            if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
4003                return Err(self.type_error(reason));
4004            }
4005            return Ok(());
4006        }
4007        if let Some(text) = text
4008            && let Some(index) = array_index(text)
4009            && object.is_array()
4010        {
4011            // An accessor defined on an index lives in the property table while the
4012            // element slot is a hole, so the store has to go through the property first.
4013            // Writing the vector directly skipped the setter entirely.
4014            if let Some(existing) = object.own_property_key(key) {
4015                if existing.is_accessor() {
4016                    return match existing.setter.clone() {
4017                        Some(setter) if !matches!(setter, Value::Undefined) => {
4018                            let receiver = Value::Object(object.clone());
4019                            self.call_value(setter, receiver, vec![value]).map(|_| ())
4020                        }
4021                        _ => match on_failure {
4022                            DeleteFailure::Throw => Err(self.type_error(format!(
4023                                "cannot set property '{text}', it has only a getter"
4024                            ))),
4025                            DeleteFailure::Ignore => Ok(()),
4026                        },
4027                    };
4028                }
4029                if !existing.writable {
4030                    return match on_failure {
4031                        DeleteFailure::Throw => {
4032                            Err(self.type_error(format!("'{text}' is read-only")))
4033                        }
4034                        DeleteFailure::Ignore => Ok(()),
4035                    };
4036                }
4037            }
4038            {
4039                // Growing the array needs a writable `length`.
4040                if (index as usize) >= object.array_length().unwrap_or(0)
4041                    && !object.length_writable()
4042                {
4043                    return match on_failure {
4044                        DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
4045                        DeleteFailure::Ignore => Ok(()),
4046                    };
4047                }
4048                // Adding an index past the end makes the array longer, which a
4049                // non-extensible array refuses.
4050                if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
4051                    return match on_failure {
4052                        DeleteFailure::Throw => Err(self.type_error(format!(
4053                            "cannot add property '{key}', object is not extensible"
4054                        ))),
4055                        DeleteFailure::Ignore => Ok(()),
4056                    };
4057                }
4058                if object.element_is_locked(index) {
4059                    return match on_failure {
4060                        DeleteFailure::Throw => {
4061                            Err(self.type_error(format!("'{key}' is read-only")))
4062                        }
4063                        DeleteFailure::Ignore => Ok(()),
4064                    };
4065                }
4066                object.array_set(index as usize, value);
4067                return Ok(());
4068            }
4069        }
4070        if text == Some("length") && object.is_array() {
4071            if !object.length_writable() {
4072                return match on_failure {
4073                    DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
4074                    DeleteFailure::Ignore => Ok(()),
4075                };
4076            }
4077            let length = value.to_number();
4078            if length.is_finite() && length >= 0.0 {
4079                let length = length as usize;
4080                // `a.length = n` with `n` below a non-configurable element cannot
4081                // drop that element, so the whole assignment fails. The spec makes
4082                // this a `TypeError` rather than a silent no-op, in any mode.
4083                if let Some(blocked) = (length..object.array_length().unwrap_or(0))
4084                    .find(|index| object.element_is_undeletable(*index as u32))
4085                {
4086                    // Sloppy mode stops the truncation at the blocking element
4087                    // instead of failing; strict mode raises.
4088                    // Both modes stop at the blocking element; they differ in
4089                    // whether that is reported. The reference truncates *then*
4090                    // throws, so the array is left in the shortened state.
4091                    object.array_truncate(blocked + 1);
4092                    return match on_failure {
4093                        DeleteFailure::Throw => {
4094                            Err(self.type_error(format!("cannot delete property '{blocked}'")))
4095                        }
4096                        DeleteFailure::Ignore => Ok(()),
4097                    };
4098                }
4099                object.array_set_length(length);
4100                return Ok(());
4101            }
4102        }
4103        if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
4104        {
4105            return match on_failure {
4106                DeleteFailure::Throw => Err(self.type_error(format!(
4107                    "cannot add property {}, object is not extensible",
4108                    key
4109                ))),
4110                DeleteFailure::Ignore => Ok(()),
4111            };
4112        }
4113        if let Some((owner, property)) = lookup_key(object, key) {
4114            if property.is_accessor() {
4115                if let Some(setter) = &property.setter
4116                    && !matches!(setter, Value::Undefined)
4117                {
4118                    let receiver = Value::Object(object.clone());
4119                    self.call_value(setter.clone(), receiver, vec![value])?;
4120                }
4121                return Ok(());
4122            }
4123            // An inherited *data* property is shadowed by an own property on the
4124            // receiver; a non-writable one is not.
4125            if owner.ptr_eq(object) && !property.writable {
4126                return match on_failure {
4127                    DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
4128                    DeleteFailure::Ignore => Ok(()),
4129                };
4130            }
4131            // An existing writable own property keeps its attributes: only the value
4132            // moves. Redefining instead would reset them, which is how a
4133            // non-configurable global `var` used to become deletable.
4134            if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
4135                return Ok(());
4136            }
4137        }
4138        // No own data property: create one, shadowing whatever the prototype holds.
4139        object.define_data_key(key, value);
4140        Ok(())
4141    }
4142
4143    /// Delete `object[key]`.
4144    pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
4145        self.delete_property_key(object, &PropertyKey::from(key))
4146    }
4147
4148    /// [`Interp::delete_property`] with a key that may be a symbol.
4149    pub fn delete_property_key(
4150        &mut self,
4151        object: &Gc<JsObject>,
4152        key: &PropertyKey,
4153    ) -> JsResult<bool> {
4154        // A proxy decides for itself, and may even throw; the invariant checks live in
4155        // `proxy_delete`.
4156        if let Some(answer) = self.proxy_delete(object, key)? {
4157            return Ok(answer);
4158        }
4159        if let Some(index) = key.as_str().and_then(array_index)
4160            && let Some(length) = object.array_length()
4161            && (index as usize) < length
4162        {
4163            // An accessor defined on an index lives in the property table rather than the
4164            // element vector, so both have to be cleared: `delete` after
4165            // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
4166            object.delete_key(key);
4167            // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
4168            // index stops answering `in`.
4169            if object.element_is_undeletable(index) {
4170                return Ok(false);
4171            }
4172            object.array_set(index as usize, Value::Hole);
4173            return Ok(true);
4174        }
4175        Ok(object.delete_key(key))
4176    }
4177
4178    // -- proxy traps --------------------------------------------------------
4179    //
4180    // A proxy's internal methods all look the same: ask the handler for the trap, call it
4181    // with the target and the operation's own arguments, then check the answer against
4182    // the target. The checks are not decoration — they are what stops a proxy from
4183    // reporting a `non-configurable` property as missing, which would let a frozen object
4184    // be rewritten by standing in front of it.
4185
4186    /// The target and handler of `object`, or `None` when it is not a proxy.
4187    ///
4188    /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
4189    /// one has to fail: the slots the traps would have been read from are gone.
4190    fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
4191        let Some(state) = object.proxy_state() else {
4192            return Ok(None);
4193        };
4194        let state = state.borrow();
4195        match (&state.target, &state.handler) {
4196            (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
4197            _ => Err(self.type_error("cannot use a proxy that has been revoked")),
4198        }
4199    }
4200
4201    /// Call `handler[name]`, or answer `None` when the trap is absent.
4202    ///
4203    /// A trap that is present but not callable is a `TypeError` rather than "no trap":
4204    /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
4205    /// back to the target.
4206    fn proxy_trap(
4207        &mut self,
4208        handler: &Value,
4209        name: &str,
4210        args: Vec<Value>,
4211    ) -> JsResult<Option<Value>> {
4212        let Value::Object(table) = handler else {
4213            return Err(self.type_error("proxy handler is not an object"));
4214        };
4215        let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
4216        match trap {
4217            Value::Undefined => Ok(None),
4218            Value::Object(function) if function.is_callable() => {
4219                let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
4220                Ok(Some(answer))
4221            }
4222            _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
4223        }
4224    }
4225
4226    /// Whether `object`'s own property `key` is one the target refuses to lose.
4227    ///
4228    /// A non-configurable property is fixed: no trap may hide it, delete it, or change
4229    /// its value behind the target's back. This goes through
4230    /// [`Self::ordinary_own_property`] rather than the property table so that an array's
4231    /// elements and its `length` — both fixed, both outside the table — are covered.
4232    fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
4233        Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
4234    }
4235
4236    /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
4237    fn proxy_get(
4238        &mut self,
4239        object: &Gc<JsObject>,
4240        receiver: &Value,
4241        key: &PropertyKey,
4242    ) -> JsResult<Option<Value>> {
4243        let Some((target, handler)) = self.proxy_parts(object)? else {
4244            return Ok(None);
4245        };
4246        let key_value = self.key_value(key);
4247        let Some(result) = self.proxy_trap(
4248            &handler,
4249            "get",
4250            vec![Value::Object(target.clone()), key_value, receiver.clone()],
4251        )?
4252        else {
4253            // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
4254            // inherited getter still sees the proxy.
4255            return Ok(Some(
4256                self.get_property_key_for(&target, Some(receiver), key)?
4257                    .unwrap_or(Value::Undefined),
4258            ));
4259        };
4260        if let Some(fixed) = Self::is_fixed_property(&target, key) {
4261            if fixed.is_accessor() {
4262                // A fixed accessor with no getter must read as `undefined`.
4263                let has_getter = fixed
4264                    .getter
4265                    .as_ref()
4266                    .is_some_and(|getter| !matches!(getter, Value::Undefined));
4267                if !has_getter && !matches!(result, Value::Undefined) {
4268                    return Err(self.type_error(format!(
4269                        "proxy 'get' must report undefined for the non-configurable property '{key}'"
4270                    )));
4271                }
4272            } else if !fixed.writable {
4273                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
4274                if !fixed_value.same_value(&result) {
4275                    return Err(self.type_error(format!(
4276                        "proxy 'get' disagrees with the non-configurable property '{key}'"
4277                    )));
4278                }
4279            }
4280        }
4281        Ok(Some(result))
4282    }
4283
4284    /// `[[Set]]` on a proxy.
4285    ///
4286    /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
4287    /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
4288    /// read-only store has.
4289    fn proxy_set(
4290        &mut self,
4291        object: &Gc<JsObject>,
4292        key: &PropertyKey,
4293        value: Value,
4294        receiver: &Value,
4295    ) -> JsResult<Option<bool>> {
4296        let Some((target, handler)) = self.proxy_parts(object)? else {
4297            return Ok(None);
4298        };
4299        let key_value = self.key_value(key);
4300        let Some(result) = self.proxy_trap(
4301            &handler,
4302            "set",
4303            vec![
4304                Value::Object(target.clone()),
4305                key_value,
4306                value.clone(),
4307                receiver.clone(),
4308            ],
4309        )?
4310        else {
4311            // No trap: store on the target, which is where an ordinary proxy write lands.
4312            self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
4313            return Ok(Some(true));
4314        };
4315        if !result.to_boolean() {
4316            return Ok(Some(false));
4317        }
4318        if let Some(fixed) = Self::is_fixed_property(&target, key) {
4319            if fixed.is_accessor() {
4320                let has_setter = fixed
4321                    .setter
4322                    .as_ref()
4323                    .is_some_and(|setter| !matches!(setter, Value::Undefined));
4324                if !has_setter {
4325                    return Err(self.type_error(format!(
4326                        "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
4327                    )));
4328                }
4329            } else if !fixed.writable {
4330                let fixed_value = fixed.value.unwrap_or(Value::Undefined);
4331                if !fixed_value.same_value(&value) {
4332                    return Err(self.type_error(format!(
4333                        "proxy 'set' changed the non-configurable property '{key}'"
4334                    )));
4335                }
4336            }
4337        }
4338        // A new property cannot appear on a target that refuses new properties.
4339        if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
4340            return Err(self.type_error(format!(
4341                "proxy 'set' added '{key}' to a non-extensible target"
4342            )));
4343        }
4344        Ok(Some(true))
4345    }
4346
4347    /// `[[HasProperty]]` on a proxy, which is the `in` operator.
4348    fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
4349        let Some((target, handler)) = self.proxy_parts(object)? else {
4350            return Ok(None);
4351        };
4352        let key_value = self.key_value(key);
4353        let Some(result) = self.proxy_trap(
4354            &handler,
4355            "has",
4356            vec![Value::Object(target.clone()), key_value],
4357        )?
4358        else {
4359            return Ok(Some(self.has_own_or_inherited(&target, key)?));
4360        };
4361        if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
4362            return Err(self.type_error(format!(
4363                "proxy 'has' denied the non-configurable property '{key}'"
4364            )));
4365        }
4366        // A non-extensible target cannot grow, so every own property it *has* is fixed.
4367        if !result.to_boolean()
4368            && !target.is_extensible()
4369            && Self::ordinary_own_property(&target, key).is_some()
4370        {
4371            return Err(self.type_error(format!(
4372                "proxy 'has' denied the own property '{key}' of a non-extensible target"
4373            )));
4374        }
4375        Ok(Some(result.to_boolean()))
4376    }
4377
4378    /// `[[Delete]]` on a proxy.
4379    fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
4380        let Some((target, handler)) = self.proxy_parts(object)? else {
4381            return Ok(None);
4382        };
4383        let key_value = self.key_value(key);
4384        let Some(result) = self.proxy_trap(
4385            &handler,
4386            "deleteProperty",
4387            vec![Value::Object(target.clone()), key_value],
4388        )?
4389        else {
4390            return Ok(Some(self.delete_property_key(&target, key)?));
4391        };
4392        if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
4393            return Err(self.type_error(format!(
4394                "proxy 'deleteProperty' removed the non-configurable property '{key}'"
4395            )));
4396        }
4397        if result.to_boolean()
4398            && !target.is_extensible()
4399            && Self::ordinary_own_property(&target, key).is_some()
4400        {
4401            return Err(self.type_error(format!(
4402                "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
4403            )));
4404        }
4405        Ok(Some(result.to_boolean()))
4406    }
4407
4408    /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
4409    fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
4410        let Some((target, handler)) = self.proxy_parts(object)? else {
4411            return Ok(None);
4412        };
4413        let Some(result) =
4414            self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
4415        else {
4416            // No trap: the target's own keys, already in the order an object reports.
4417            return Ok(Some(self.object_own_property_keys(&target)?));
4418        };
4419        // `CreateListFromArrayLike` with the string-or-symbol restriction.
4420        let list = self.list_from_array_like(&result, true)?;
4421        let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
4422        for value in list {
4423            let key = self.propkey(&value)?;
4424            if keys.contains(&key) {
4425                return Err(self.type_error(format!(
4426                    "proxy 'ownKeys' returned the duplicate key '{key}'"
4427                )));
4428            }
4429            keys.push(key);
4430        }
4431        for (key, property) in target.property_entries() {
4432            if !property.configurable && !keys.contains(&key) {
4433                return Err(self.type_error(format!(
4434                    "proxy 'ownKeys' dropped the non-configurable key '{key}'"
4435                )));
4436            }
4437            if !target.is_extensible() && !keys.contains(&key) {
4438                return Err(self.type_error(format!(
4439                    "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
4440                )));
4441            }
4442        }
4443        if !target.is_extensible() {
4444            let own = target.property_entries().len();
4445            if keys.len() != own {
4446                return Err(
4447                    self.type_error("proxy 'ownKeys' does not match its non-extensible target")
4448                );
4449            }
4450        }
4451        Ok(Some(keys))
4452    }
4453
4454    /// `[[GetOwnProperty]]` on a proxy.
4455    fn proxy_get_own_property(
4456        &mut self,
4457        object: &Gc<JsObject>,
4458        key: &PropertyKey,
4459    ) -> JsResult<Option<Option<Property>>> {
4460        let Some((target, handler)) = self.proxy_parts(object)? else {
4461            return Ok(None);
4462        };
4463        let key_value = self.key_value(key);
4464        let Some(result) = self.proxy_trap(
4465            &handler,
4466            "getOwnPropertyDescriptor",
4467            vec![Value::Object(target.clone()), key_value],
4468        )?
4469        else {
4470            // No trap: the target's own descriptor is the answer. This has to go through
4471            // the same synthesis an ordinary object gets, because a proxy's own property
4472            // table is empty by design — reading it directly reported `undefined` for
4473            // every key, including an array's indices and `length`.
4474            return Ok(Some(Self::ordinary_own_property(&target, key)));
4475        };
4476        let answer = if matches!(result, Value::Undefined) {
4477            None
4478        } else {
4479            Some(self.property_from_descriptor(&result)?)
4480        };
4481        let fixed = Self::is_fixed_property(&target, key);
4482        match (&answer, &fixed) {
4483            // A non-configurable property cannot be reported as absent.
4484            (None, Some(_)) => {
4485                return Err(self.type_error(format!(
4486                    "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
4487                )));
4488            }
4489            (Some(descriptor), Some(fixed)) => {
4490                if descriptor.configurable {
4491                    return Err(self.type_error(format!(
4492                        "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
4493                    )));
4494                }
4495                if fixed.is_accessor() != descriptor.is_accessor() {
4496                    return Err(self.type_error(format!(
4497                        "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
4498                    )));
4499                }
4500                if !fixed.is_accessor() && !fixed.writable {
4501                    let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
4502                    let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
4503                    if !fixed_value.same_value(&reported) {
4504                        return Err(self.type_error(format!(
4505                            "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
4506                        )));
4507                    }
4508                }
4509            }
4510            _ => {}
4511        }
4512        Ok(Some(answer))
4513    }
4514
4515    /// `[[DefineOwnProperty]]` on a proxy.
4516    fn proxy_define_property(
4517        &mut self,
4518        object: &Gc<JsObject>,
4519        key: &PropertyKey,
4520        property: Property,
4521    ) -> JsResult<Option<bool>> {
4522        let Some((target, handler)) = self.proxy_parts(object)? else {
4523            return Ok(None);
4524        };
4525        let key_value = self.key_value(key);
4526        let descriptor = self.descriptor_from_property(&property);
4527        let Some(result) = self.proxy_trap(
4528            &handler,
4529            "defineProperty",
4530            vec![Value::Object(target.clone()), key_value, descriptor],
4531        )?
4532        else {
4533            return Ok(None);
4534        };
4535        if !result.to_boolean() {
4536            return Ok(Some(false));
4537        }
4538        let fixed = Self::is_fixed_property(&target, key);
4539        let creating = Self::ordinary_own_property(&target, key).is_none();
4540        if creating && !target.is_extensible() {
4541            return Err(self.type_error(format!(
4542                "proxy 'defineProperty' added '{key}' to a non-extensible target"
4543            )));
4544        }
4545        if let Some(fixed) = fixed {
4546            if property.configurable {
4547                return Err(self.type_error(format!(
4548                    "proxy 'defineProperty' made the non-configurable '{key}' configurable"
4549                )));
4550            }
4551            if !fixed.writable && property.writable && !fixed.is_accessor() {
4552                return Err(self.type_error(format!(
4553                    "proxy 'defineProperty' made the read-only '{key}' writable"
4554                )));
4555            }
4556        }
4557        Ok(Some(true))
4558    }
4559
4560    /// `[[GetPrototypeOf]]` on a proxy.
4561    fn proxy_get_prototype_of(
4562        &mut self,
4563        object: &Gc<JsObject>,
4564    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
4565        let Some((target, handler)) = self.proxy_parts(object)? else {
4566            return Ok(None);
4567        };
4568        let Some(result) = self.proxy_trap(
4569            &handler,
4570            "getPrototypeOf",
4571            vec![Value::Object(target.clone())],
4572        )?
4573        else {
4574            return Ok(Some(target.proto()));
4575        };
4576        let proto = match &result {
4577            Value::Null => None,
4578            Value::Object(proto) => Some(proto.clone()),
4579            _ => {
4580                return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
4581            }
4582        };
4583        if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
4584            return Err(self.type_error(
4585                "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
4586            ));
4587        }
4588        Ok(Some(proto))
4589    }
4590
4591    /// `[[SetPrototypeOf]]` on a proxy.
4592    fn proxy_set_prototype_of(
4593        &mut self,
4594        object: &Gc<JsObject>,
4595        proto: Option<Gc<JsObject>>,
4596    ) -> JsResult<Option<bool>> {
4597        let Some((target, handler)) = self.proxy_parts(object)? else {
4598            return Ok(None);
4599        };
4600        let proto_value = match &proto {
4601            Some(proto) => Value::Object(proto.clone()),
4602            None => Value::Null,
4603        };
4604        let Some(result) = self.proxy_trap(
4605            &handler,
4606            "setPrototypeOf",
4607            vec![Value::Object(target.clone()), proto_value],
4608        )?
4609        else {
4610            target.set_proto(proto);
4611            return Ok(Some(true));
4612        };
4613        if result.to_boolean()
4614            && !target.is_extensible()
4615            && !same_proto(proto.as_ref(), target.proto().as_ref())
4616        {
4617            return Err(self.type_error(
4618                "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
4619            ));
4620        }
4621        Ok(Some(result.to_boolean()))
4622    }
4623
4624    /// `[[IsExtensible]]` on a proxy.
4625    fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
4626        let Some((target, handler)) = self.proxy_parts(object)? else {
4627            return Ok(None);
4628        };
4629        let Some(result) = self.proxy_trap(
4630            &handler,
4631            "isExtensible",
4632            vec![Value::Object(target.clone())],
4633        )?
4634        else {
4635            return Ok(Some(target.is_extensible()));
4636        };
4637        // The answer is not the proxy's to invent: it must agree with the target, or a
4638        // script could learn `false` while the target keeps accepting new properties.
4639        if result.to_boolean() != target.is_extensible() {
4640            return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
4641        }
4642        Ok(Some(result.to_boolean()))
4643    }
4644
4645    /// `[[PreventExtensions]]` on a proxy.
4646    fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
4647        let Some((target, handler)) = self.proxy_parts(object)? else {
4648            return Ok(None);
4649        };
4650        let Some(result) = self.proxy_trap(
4651            &handler,
4652            "preventExtensions",
4653            vec![Value::Object(target.clone())],
4654        )?
4655        else {
4656            target.set_extensible(false);
4657            return Ok(Some(true));
4658        };
4659        if result.to_boolean() && target.is_extensible() {
4660            return Err(self.type_error(
4661                "proxy 'preventExtensions' reported success but the target is still extensible",
4662            ));
4663        }
4664        Ok(Some(result.to_boolean()))
4665    }
4666
4667    /// `[[Call]]` on a proxy, through the `apply` trap.
4668    fn proxy_apply(
4669        &mut self,
4670        object: &Gc<JsObject>,
4671        this: Value,
4672        args: Vec<Value>,
4673    ) -> JsResult<Option<Value>> {
4674        let Some((target, handler)) = self.proxy_parts(object)? else {
4675            return Ok(None);
4676        };
4677        // The trap gets the arguments as one array, which is the shape the spec passes
4678        // and the shape `apply` traps are written against (`args[0]` is the first one).
4679        let arguments = self.new_array(args.clone());
4680        let this_for_trap = this.clone();
4681        let Some(result) = self.proxy_trap(
4682            &handler,
4683            "apply",
4684            vec![
4685                Value::Object(target.clone()),
4686                this_for_trap,
4687                Value::Object(arguments),
4688            ],
4689        )?
4690        else {
4691            return Ok(Some(self.call_value(Value::Object(target), this, args)?));
4692        };
4693        Ok(Some(result))
4694    }
4695
4696    /// `[[Construct]]` on a proxy, through the `construct` trap.
4697    fn proxy_construct(
4698        &mut self,
4699        object: &Gc<JsObject>,
4700        args: Vec<Value>,
4701        new_target: &Value,
4702    ) -> JsResult<Option<Value>> {
4703        let Some((target, handler)) = self.proxy_parts(object)? else {
4704            return Ok(None);
4705        };
4706        if !target.is_callable() {
4707            return Err(self.type_error("proxy target is not a constructor"));
4708        }
4709        let arguments = self.new_array(args.clone());
4710        let Some(result) = self.proxy_trap(
4711            &handler,
4712            "construct",
4713            vec![
4714                Value::Object(target.clone()),
4715                Value::Object(arguments),
4716                new_target.clone(),
4717            ],
4718        )?
4719        else {
4720            return Ok(Some(self.construct(
4721                Value::Object(target),
4722                new_target.clone(),
4723                args,
4724            )?));
4725        };
4726        if !matches!(result, Value::Object(_)) {
4727            return Err(self.type_error("proxy 'construct' must return an object"));
4728        }
4729        Ok(Some(result))
4730    }
4731
4732    /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
4733    pub(crate) fn has_own_or_inherited(
4734        &mut self,
4735        object: &Gc<JsObject>,
4736        key: &PropertyKey,
4737    ) -> JsResult<bool> {
4738        // The object itself first: it may be a proxy, and then the answer is its trap's.
4739        if let Some(answer) = self.proxy_has(object, key)? {
4740            return Ok(answer);
4741        }
4742        // `has_own` rather than `own_property_key`: an array's elements and its derived
4743        // `length` are invisible to the property table, and `Array.prototype` is an array.
4744        if has_own(object, key) {
4745            return Ok(true);
4746        }
4747        // A hole is *not* the end of the search: the chain may still have the key, which
4748        // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
4749        for ancestor in object.chain() {
4750            // A proxy further up the chain answers for itself.
4751            if let Some(answer) = self.proxy_has(&ancestor, key)? {
4752                return Ok(answer);
4753            }
4754            if has_own(&ancestor, key) {
4755                return Ok(true);
4756            }
4757        }
4758        Ok(false)
4759    }
4760
4761    /// `CreateListFromArrayLike`, optionally restricted to property keys.
4762    ///
4763    /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
4764    /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
4765    /// `TypeError` instead of a property named `"1.5"`.
4766    fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
4767        let object = self.object_from(value)?;
4768        let length = self
4769            .get_property(&object, "length")?
4770            .map(|value| value.to_number())
4771            .unwrap_or(0.0);
4772        if !length.is_finite() || length < 0.0 {
4773            return Err(self.type_error("invalid array-like length"));
4774        }
4775        let length = length as usize;
4776        let mut items = Vec::with_capacity(length.min(1024));
4777        for index in 0..length {
4778            let item = self
4779                .get_property(&object, &index.to_string())?
4780                .unwrap_or(Value::Undefined);
4781            if keys_only && matches!(&item, Value::Symbol(_)) {
4782                items.push(item);
4783                continue;
4784            }
4785            if keys_only && !matches!(&item, Value::String(_)) {
4786                return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
4787            }
4788            items.push(item);
4789        }
4790        Ok(items)
4791    }
4792
4793    /// A `Property` from the descriptor object a trap returned.
4794    fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
4795        let object = self.object_from(value)?;
4796        let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
4797            interp.get_property(&object, name)
4798        };
4799        let getter = field(self, "get")?;
4800        let setter = field(self, "set")?;
4801        let accessor = getter.is_some() || setter.is_some();
4802        let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
4803            Ok(interp
4804                .get_property(&object, name)?
4805                .is_some_and(|value| value.to_boolean()))
4806        };
4807        let enumerable = boolean(self, "enumerable")?;
4808        let configurable = boolean(self, "configurable")?;
4809        if accessor {
4810            if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
4811                return Err(
4812                    self.type_error("a descriptor cannot be both a data property and an accessor")
4813                );
4814            }
4815            Ok(Property {
4816                getter: getter.or(Some(Value::Undefined)),
4817                setter: setter.or(Some(Value::Undefined)),
4818                enumerable,
4819                configurable,
4820                writable: false,
4821                value: None,
4822            })
4823        } else {
4824            Ok(Property {
4825                value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
4826                writable: boolean(self, "writable")?,
4827                enumerable,
4828                configurable,
4829                getter: None,
4830                setter: None,
4831            })
4832        }
4833    }
4834
4835    /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
4836    fn descriptor_from_property(&mut self, property: &Property) -> Value {
4837        let object = self.new_object(None);
4838        if property.is_accessor() {
4839            let getter = property.getter.clone().unwrap_or(Value::Undefined);
4840            let setter = property.setter.clone().unwrap_or(Value::Undefined);
4841            object.define_data("get", getter);
4842            object.define_data("set", setter);
4843        } else {
4844            let value = property.value.clone().unwrap_or(Value::Undefined);
4845            object.define_data("value", value);
4846            object.define_data("writable", Value::Bool(property.writable));
4847        }
4848        object.define_data("enumerable", Value::Bool(property.enumerable));
4849        object.define_data("configurable", Value::Bool(property.configurable));
4850        Value::Object(object)
4851    }
4852
4853    // -- calling ------------------------------------------------------------
4854
4855    /// Call `callee` with `this` and `args`.
4856    pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
4857        let Value::Object(function) = &callee else {
4858            // `typeof x === "function"` is not enough to make `x()` legal: only a
4859            // callable object is. `null` and `undefined` need no special wording
4860            // here — their `ToString` already reads the way the reference's does.
4861            let what = format!("{} is not a function", callee.to_js_string());
4862            return Err(Signal::Throw(self.make_error("TypeError", &what)));
4863        };
4864        // A proxy of a function is called through its `apply` trap. It has no
4865        // `ObjectKind::Function` of its own, so this has to come before the dispatch
4866        // below, and a proxy of a non-function has nothing to forward to.
4867        if function.proxy_state().is_some() {
4868            return match self.proxy_apply(function, this, args)? {
4869                Some(result) => Ok(result),
4870                None => Err(Signal::Throw(
4871                    self.make_error("TypeError", "proxy target is not callable"),
4872                )),
4873            };
4874        }
4875        let callable = function.with(|data| match &data.kind {
4876            ObjectKind::Function(callable) => match callable {
4877                Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
4878                // The `Rc` is cloned out so the borrow of this object's data is released
4879                // before the closure runs: the closure may touch the same object.
4880                Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
4881                Callable::Bound {
4882                    target,
4883                    this,
4884                    args: leading,
4885                } => Some(NativeCall::Bound {
4886                    target: target.clone(),
4887                    this: this.clone(),
4888                    leading: leading.clone(),
4889                }),
4890                Callable::Bytecode { code, env } => {
4891                    Some(NativeCall::Bytecode(code.clone(), env.clone()))
4892                }
4893                Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
4894                Callable::PromiseResolve(promise) => {
4895                    Some(NativeCall::PromiseResolve(promise.clone()))
4896                }
4897                Callable::PromiseReject(promise) => {
4898                    Some(NativeCall::PromiseReject(promise.clone()))
4899                }
4900                Callable::AwaitResume {
4901                    coroutine,
4902                    promise,
4903                    kind,
4904                } => Some(NativeCall::AwaitResume {
4905                    coroutine: coroutine.clone(),
4906                    promise: promise.clone(),
4907                    kind: *kind,
4908                }),
4909                Callable::CombinatorSettle {
4910                    state,
4911                    index,
4912                    fulfilled,
4913                } => Some(NativeCall::CombinatorSettle {
4914                    state: state.clone(),
4915                    index: *index,
4916                    fulfilled: *fulfilled,
4917                }),
4918                Callable::FinallyShim {
4919                    callback,
4920                    fulfilled,
4921                } => Some(NativeCall::FinallyShim {
4922                    callback: callback.clone(),
4923                    fulfilled: *fulfilled,
4924                }),
4925                Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
4926                Callable::YieldResult { promise, done } => Some(NativeCall::YieldResult {
4927                    promise: promise.clone(),
4928                    done: *done,
4929                }),
4930                Callable::DisposeStep {
4931                    remaining,
4932                    promise,
4933                    error,
4934                    rejected,
4935                } => Some(NativeCall::DisposeStep {
4936                    remaining: remaining.clone(),
4937                    promise: promise.clone(),
4938                    error: error.clone(),
4939                    rejected: *rejected,
4940                }),
4941                Callable::GeneratorResume {
4942                    generator,
4943                    promise,
4944                    kind,
4945                } => Some(NativeCall::GeneratorResume {
4946                    generator: generator.clone(),
4947                    promise: promise.clone(),
4948                    kind: *kind,
4949                }),
4950                Callable::SettlePromise {
4951                    promise,
4952                    value,
4953                    rejected,
4954                } => Some(NativeCall::SettlePromise {
4955                    promise: promise.clone(),
4956                    value: value.clone(),
4957                    rejected: *rejected,
4958                }),
4959            },
4960            _ => None,
4961        });
4962        match callable {
4963            Some(NativeCall::Host(func)) => {
4964                // Same frame bookkeeping as a `Native`, so a stack trace shows the host
4965                // function by name rather than stopping at the caller.
4966                let frame_less = function
4967                    .own_property("_frame_less")
4968                    .and_then(|property| property.value)
4969                    .is_some_and(|value| value.to_boolean());
4970                let name = function
4971                    .own_property("name")
4972                    .and_then(|property| property.value)
4973                    .map(|value| value.to_js_string())
4974                    .unwrap_or_default();
4975                let outer = if frame_less {
4976                    None
4977                } else {
4978                    self.native_frames
4979                        .push((name, function.clone(), self.frames.len()));
4980                    Some(self.current_native.replace(function.clone()))
4981                };
4982                let result = {
4983                    let mut body = func.borrow_mut();
4984                    body(self, this, &args)
4985                };
4986                if !frame_less {
4987                    self.native_frames.pop();
4988                    self.current_native = outer.flatten();
4989                }
4990                result
4991            }
4992            Some(NativeCall::Native(func)) => {
4993                // A function marked `_frame_less` is one the reference implements
4994                // without a call frame — `eval` is the only one so far.
4995                let frame_less = function
4996                    .own_property("_frame_less")
4997                    .and_then(|property| property.value)
4998                    .is_some_and(|value| value.to_boolean());
4999                let name = function
5000                    .own_property("name")
5001                    .and_then(|property| property.value)
5002                    .map(|value| value.to_js_string())
5003                    .unwrap_or_default();
5004                let outer = if frame_less {
5005                    None
5006                } else {
5007                    self.native_frames
5008                        .push((name, function.clone(), self.frames.len()));
5009                    Some(self.current_native.replace(function.clone()))
5010                };
5011                let result = func(self, this, &args);
5012                if !frame_less {
5013                    self.native_frames.pop();
5014                    self.current_native = outer.flatten();
5015                }
5016                result
5017            }
5018            Some(NativeCall::Revoker(slots)) => {
5019                // Idempotent: revoking twice answers `undefined` again rather than
5020                // complaining, which is what the spec says and what a `finally` block
5021                // relies on.
5022                let mut state = slots.borrow_mut();
5023                state.target = None;
5024                state.handler = None;
5025                Ok(Value::Undefined)
5026            }
5027            Some(NativeCall::PromiseResolve(promise)) => {
5028                // One-shot: a second call is silently ignored, which
5029                // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
5030                let value = args.first().cloned().unwrap_or(Value::Undefined);
5031                self.resolve_promise_with(&promise, value)?;
5032                Ok(Value::Undefined)
5033            }
5034            Some(NativeCall::PromiseReject(promise)) => {
5035                let reason = args.first().cloned().unwrap_or(Value::Undefined);
5036                self.reject_promise(&promise, reason);
5037                Ok(Value::Undefined)
5038            }
5039            Some(NativeCall::CombinatorSettle {
5040                state,
5041                index,
5042                fulfilled,
5043            }) => {
5044                let value = args.first().cloned().unwrap_or(Value::Undefined);
5045                self.settle_combinator(&state, index, fulfilled, value)?;
5046                Ok(Value::Undefined)
5047            }
5048            Some(NativeCall::AwaitResume {
5049                coroutine,
5050                promise,
5051                kind,
5052            }) => {
5053                // Resume *inline*, in the reaction that delivered the value. Deferring it
5054                // by another job inserts a tick between every `await` and its
5055                // continuation, which reorders `await` against unrelated `then` chains —
5056                // `f().then(g)` then runs before `f`'s own next statement.
5057                self.drive_async(
5058                    &coroutine,
5059                    &promise,
5060                    kind,
5061                    args.first().cloned().unwrap_or(Value::Undefined),
5062                )
5063                .map(|()| Value::Undefined)
5064            }
5065            Some(NativeCall::FinallyShim {
5066                callback,
5067                fulfilled,
5068            }) => {
5069                // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
5070                // that settles with the *original* outcome once the callback's result has
5071                // settled. The callback's own value is discarded — that is the whole
5072                // difference between `finally` and `then`.
5073                let original = args.first().cloned().unwrap_or(Value::Undefined);
5074                let result = match &callback {
5075                    Some(callback) => {
5076                        self.call_value(callback.clone(), Value::Undefined, Vec::new())?
5077                    }
5078                    None => Value::Undefined,
5079                };
5080                let resolved = self.promise_resolve_value(result)?;
5081                let Value::Object(resolved) = resolved else {
5082                    return Ok(original);
5083                };
5084                // The wait is a chained promise rather than a bare return, so a callback
5085                // that returns a slow promise really does delay the continuation.
5086                let waiting = self.new_promise();
5087                let pass = JsObject::function(
5088                    self.heap,
5089                    Some(self.realm.function_proto.clone()),
5090                    Callable::SettlePromise {
5091                        promise: waiting.clone(),
5092                        value: original,
5093                        rejected: !fulfilled,
5094                    },
5095                );
5096                let pass = Value::Object(pass);
5097                // Whichever way the callback's promise settles, the original outcome wins.
5098                self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
5099                Ok(Value::Object(waiting))
5100            }
5101            Some(NativeCall::DisposeStep {
5102                remaining,
5103                promise,
5104                error,
5105                rejected,
5106            }) => {
5107                let error = if rejected {
5108                    let reason = args.first().cloned().unwrap_or(Value::Undefined);
5109                    self.merge_dispose_error(reason, error)
5110                } else {
5111                    error
5112                };
5113                self.dispose_step(&remaining, &promise, error)?;
5114                Ok(Value::Undefined)
5115            }
5116            Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
5117            Some(NativeCall::YieldResult { promise, done }) => {
5118                let value = args.first().cloned().unwrap_or(Value::Undefined);
5119                let result = self.iterator_result(value, done)?;
5120                self.fulfill_promise(&promise, result);
5121                Ok(Value::Undefined)
5122            }
5123            Some(NativeCall::GeneratorResume {
5124                generator,
5125                promise,
5126                kind,
5127            }) => {
5128                // Inline for the same reason as `AwaitResume`: a deferred resume adds a
5129                // tick and reorders the generator against other chains.
5130                self.step_async_generator(
5131                    &generator,
5132                    &promise,
5133                    kind,
5134                    args.first().cloned().unwrap_or(Value::Undefined),
5135                )
5136                .map(|()| Value::Undefined)
5137            }
5138            Some(NativeCall::SettlePromise {
5139                promise,
5140                value,
5141                rejected,
5142            }) => {
5143                if rejected {
5144                    self.reject_promise(&promise, value);
5145                } else {
5146                    self.fulfill_promise(&promise, value);
5147                }
5148                Ok(Value::Undefined)
5149            }
5150            Some(NativeCall::Bound {
5151                target,
5152                this: bound_this,
5153                leading,
5154            }) => {
5155                let mut all = leading;
5156                all.extend(args);
5157                self.call_value(target, bound_this, all)
5158            }
5159            Some(NativeCall::Bytecode(code, env)) => {
5160                if code.code.kind.is_generator() {
5161                    return self.new_generator(callee, this, args);
5162                }
5163                if code.code.kind.is_async() {
5164                    // Same coroutine machinery as a generator; the difference is only in
5165                    // what the completion does — see `new_async_function`.
5166                    return self.new_async_function(callee, this, args);
5167                }
5168                self.execute(code, env, this, args, callee)
5169            }
5170            None => Err(Signal::Throw(
5171                self.make_error("TypeError", "not a function"),
5172            )),
5173        }
5174    }
5175
5176    /// Give a freshly built function its own `prototype` object.
5177    ///
5178    /// Every function that can be used with `new` carries one, and its
5179    /// `constructor` points back at the function — a reference cycle, which is
5180    /// exactly what the collector's cycle pass exists to reclaim.
5181    fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
5182        let prototype = self.new_object(Some(self.realm.object_proto.clone()));
5183        let constructor = Value::Object(function.clone());
5184        prototype.define(
5185            "constructor",
5186            Property::with_attributes(constructor, true, false),
5187        );
5188        let value = Value::Object(prototype);
5189        function.define("prototype", Property::prototype_of(value, true));
5190    }
5191
5192    /// The object `special_object` builds.
5193    ///
5194    /// Only `arguments` is implemented. It is an ordinary object with a `length` and
5195    /// one property per passed argument, which is what `typeof`, `arguments[i]` and
5196    /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
5197    /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
5198    /// write through `arguments` does not reach the parameter.
5199    fn special_object(&mut self, magic: u32) -> JsResult<Value> {
5200        match magic {
5201            0 | 1 => {
5202                let args = self.frame().passed.clone();
5203                let proto = self.realm.object_proto.clone();
5204                let object = self.new_object(Some(proto));
5205                // The marker `Object.prototype.toString` needs: an arguments object is an
5206                // ordinary object apart from reporting `[object Arguments]`, and that has
5207                // no `Symbol.toStringTag` of its own. Set before the indices so it does not
5208                // show up ahead of them in a key listing anyway — it is non-enumerable.
5209                self.internal_set(&object, "_class", self.string("Arguments"));
5210                // `length` is writable and configurable but neither enumerable nor a
5211                // plain data property: `Object.keys(arguments)` lists the indices only,
5212                // which is how `{...arguments}` copies them without the length.
5213                object.define(
5214                    "length",
5215                    Property::with_attributes(Value::Int(args.len() as i32), true, false),
5216                );
5217                for (index, value) in args.into_iter().enumerate() {
5218                    object.define_data(&index.to_string(), value);
5219                }
5220                // An arguments object is iterable: `[...arguments]` and
5221                // `for (const a of arguments)` both work, through the *array* iterator
5222                // because the object is array-like. Without this the whole spread form
5223                // reported "not iterable".
5224                let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
5225                let values = self
5226                    .realm
5227                    .array_proto
5228                    .own_property("values")
5229                    .and_then(|property| property.value);
5230                if let Some(values) = values {
5231                    object.define_key(
5232                        &iterator_key,
5233                        Property::with_attributes(values, true, false),
5234                    );
5235                }
5236                Ok(Value::Object(object))
5237            }
5238            // `this function`: what a named function expression binds its own name to.
5239            2 => Ok(self
5240                .current_callee()
5241                .map_or(Value::Undefined, Value::Object)),
5242            // `new.target`: set by `construct`, `undefined` for an ordinary call, and
5243            // inherited from the caller inside an `eval`.
5244            3 => Ok(self
5245                .eval_new_target
5246                .clone()
5247                .unwrap_or_else(|| self.frame().new_target.clone())),
5248            // `[[HomeObject]]` of the function being run: what `super` is relative to.
5249            // An arrow has none of its own, so the lookup walks out to the enclosing
5250            // method — which is why `super` works inside an arrow inside a method.
5251            4 => Ok(self
5252                .frames
5253                .iter()
5254                .rev()
5255                .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
5256                .map_or(Value::Undefined, Value::Object)),
5257            // `import.meta`: the innermost module body's meta object. Outside a module
5258            // the compiler never emits this, so an empty fallback is unreachable rather
5259            // than permissive.
5260            6 => {
5261                let name = self.module_stack.last().cloned();
5262                let meta = name
5263                    .and_then(|name| self.modules.get(&name).cloned())
5264                    .and_then(|module| module.with(|r| r.import_meta.clone()));
5265                Ok(meta.map_or(Value::Undefined, Value::Object))
5266            }
5267            other => Err(Signal::Throw(self.make_error(
5268                "InternalError",
5269                &format!("special_object {other} is not implemented yet"),
5270            ))),
5271        }
5272    }
5273
5274    /// `[[HomeObject]]` of the innermost function that has one, if any.
5275    ///
5276    /// An arrow has none, so the search walks out to the enclosing method — the same
5277    /// rule `special_object 4` follows, and the reason `super` works inside an arrow
5278    /// inside a method.
5279    fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
5280        self.frames
5281            .iter()
5282            .rev()
5283            .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
5284    }
5285
5286    /// The dispose method a `using` declaration should snapshot, or an error.
5287    ///
5288    /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
5289    /// is what makes a resource that only knows the synchronous protocol usable in both
5290    /// forms.
5291    pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
5292        // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
5293        if value.is_nullish() {
5294            return Ok(Value::Undefined);
5295        }
5296        let Some(object) = value.as_object() else {
5297            return Err(self.type_error("not an object"));
5298        };
5299        let mut method = if await_form {
5300            let found = self.get_property_key(
5301                object,
5302                &self.realm.well_known_key(WellKnown::AsyncDisposable),
5303            )?;
5304            match found {
5305                Some(found) if !found.is_nullish() => Some(found),
5306                _ => self
5307                    .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
5308            }
5309        } else {
5310            self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
5311        };
5312        let Some(found) = method.take() else {
5313            return Err(self.type_error("value is not disposable"));
5314        };
5315        if found.is_nullish() {
5316            return Err(self.type_error("value is not disposable"));
5317        }
5318        let callable = found.as_object().is_some_and(|object| object.is_callable());
5319        if !callable {
5320            return Err(self.type_error("dispose method is not a function"));
5321        }
5322        Ok(found)
5323    }
5324
5325    /// Call one resource's disposer, folding a failure into `error_state`.
5326    ///
5327    /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
5328    /// because a captured `using` binding lives in its reference cell and the local slot is
5329    /// stale — a closure over the resource is legal and must not change what is disposed.
5330    fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
5331        let value = self.get_loc(slot);
5332        let method = self.get_loc(slot + 1);
5333        // A resource that was never initialised — its declaration threw — or that is
5334        // `null`/`undefined` has nothing to dispose.
5335        if value.is_nullish() || matches!(value, Value::Uninitialized) {
5336            return Ok(error_state);
5337        }
5338        if matches!(method, Value::Undefined | Value::Uninitialized) {
5339            return Ok(error_state);
5340        }
5341        match self.call_value(method, value, Vec::new()) {
5342            Ok(_) => Ok(error_state),
5343            Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
5344            Err(other) => Err(other),
5345        }
5346    }
5347
5348    /// Combine a disposal failure with whatever was already going wrong.
5349    pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
5350        if matches!(error_state, Value::Uninitialized) {
5351            return new_error;
5352        }
5353        self.new_suppressed_error(new_error, error_state)
5354    }
5355
5356    /// A `SuppressedError` instance built straight from its prototype.
5357    ///
5358    /// Not through the constructor: a script that rewrites
5359    /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
5360    /// error wrapping.
5361    pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
5362        let proto = self
5363            .realm
5364            .suppressed_error_proto
5365            .clone()
5366            .unwrap_or_else(|| self.realm.error_proto.clone());
5367        let object = self.new_object(Some(proto));
5368        object.define("error", Property::with_attributes(error, true, true));
5369        object.define(
5370            "suppressed",
5371            Property::with_attributes(suppressed, true, true),
5372        );
5373        object.define(
5374            "message",
5375            Property::with_attributes(self.string("SuppressedError"), true, true),
5376        );
5377        self.internal_set(&object, "_class", self.string("Error"));
5378        self.add_stack(&object);
5379        Value::Object(object)
5380    }
5381
5382    /// Call `callee`, or push its frame and let the main loop run it.
5383    ///
5384    /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
5385    /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
5386    /// continues, so `function f(){ return f() }` costs heap and stops at
5387    /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
5388    /// is entered directly, and natives do not re-enter JavaScript in this
5389    /// milestone.
5390    ///
5391    /// `Ok(None)` means a frame was pushed: the caller must not push a result,
5392    /// because the returning frame will.
5393    /// The elements of an array-like value, as a call argument list.
5394    ///
5395    /// `apply` accepts any array-like, not only a real array: the reference reads
5396    /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
5397    pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
5398        let Some(object) = value.as_object().cloned() else {
5399            if value.is_nullish() {
5400                // `f.apply(this, null)` passes no arguments at all.
5401                return Ok(Vec::new());
5402            }
5403            return Err(self.type_error("createListFromArrayLike called on non-object"));
5404        };
5405        let length = match self.get_property(&object, "length")? {
5406            Some(length) => length.to_number(),
5407            None => 0.0,
5408        };
5409        if !length.is_finite() || length <= 0.0 {
5410            return Ok(Vec::new());
5411        }
5412        let length = (length as usize).min(1_000_000);
5413        let mut args = Vec::with_capacity(length);
5414        for index in 0..length {
5415            let element = self.get_property(&object, &index.to_string())?;
5416            args.push(element.unwrap_or(Value::Undefined));
5417        }
5418        Ok(args)
5419    }
5420
5421    /// Turn a call to a generator function into a generator object.
5422    ///
5423    /// The frame is built exactly as an ordinary call would build it, then detached and
5424    /// stored in the generator before any body instruction runs — which is what makes
5425    /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
5426    /// is `initial_yield`, the first instruction of every suspending body.
5427    pub fn new_generator(
5428        &mut self,
5429        function: Value,
5430        this: Value,
5431        args: Vec<Value>,
5432    ) -> JsResult<Value> {
5433        let Some(object) = function.as_object().cloned() else {
5434            return Err(self.type_error("not a generator function"));
5435        };
5436        let Some((code, env)) = bytecode_of(&object) else {
5437            return Err(self.type_error("not a generator function"));
5438        };
5439        let is_async = code.code.kind.is_async();
5440        self.push_frame(code, env, this, args, function)?;
5441        let frame = self.frames.pop().expect("push_frame just pushed it");
5442        // A fresh generator is *suspended at start*: the body has not run, so a
5443        // `return`/`throw` on it finishes without executing anything.
5444        let mut state = GeneratorState {
5445            frame: Some(frame),
5446            phase: GeneratorPhase::SuspendedStart,
5447            parked_on_await: false,
5448        };
5449        // Run to the first suspension. For a generator that is `initial_yield`, so no
5450        // body code runs; for a malformed body it would be the first `yield`.
5451        // An `async function*` answers an async generator: same coroutine, but its
5452        // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
5453        let proto = if is_async {
5454            self.realm
5455                .async_generator_proto
5456                .clone()
5457                .unwrap_or_else(|| self.realm.generator_proto.clone())
5458        } else {
5459            self.realm.generator_proto.clone()
5460        };
5461        let generator = self.new_object(Some(proto));
5462        match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
5463            Ok(_) => {}
5464            Err(error) => return Err(error),
5465        }
5466        generator.with_mut(|data| {
5467            data.kind = ObjectKind::Generator(Box::new(state));
5468        });
5469        Ok(Value::Object(generator))
5470    }
5471
5472    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
5473    ///
5474    /// Returns the `{value, done}` object itself rather than the pair, because a
5475    /// `yield*` suspension already has one — the inner iterator's own result — and the
5476    /// protocol says to hand that straight through rather than nest it.
5477    /// Advance a generator and report *why* it parked.
5478    ///
5479    /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
5480    /// "hand this value to the caller" — but an async generator does: an `await` has to
5481    /// settle before it can answer, while a `yield` is the answer.
5482    fn resume_generator_detailed(
5483        &mut self,
5484        generator: &Gc<JsObject>,
5485        kind: ResumeKind,
5486        value: Value,
5487    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
5488        let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
5489            ObjectKind::Generator(state) => Some(std::mem::replace(
5490                state.as_mut(),
5491                GeneratorState {
5492                    frame: None,
5493                    phase: GeneratorPhase::Executing,
5494                    parked_on_await: false,
5495                },
5496            )),
5497            _ => None,
5498        }) else {
5499            return Err(self.type_error("not a generator"));
5500        };
5501        let result = self.step_generator(&mut state, kind, value);
5502        generator.with_mut(|data| {
5503            data.kind = ObjectKind::Generator(Box::new(state));
5504        });
5505        result
5506    }
5507
5508    /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
5509    ///
5510    /// Returns the `{value, done}` object itself rather than the pair, because a
5511    /// `yield*` suspension already has one — the inner iterator's own result — and the
5512    /// protocol says to hand that straight through rather than nest it.
5513    pub fn resume_generator(
5514        &mut self,
5515        generator: &Gc<JsObject>,
5516        kind: ResumeKind,
5517        value: Value,
5518    ) -> JsResult<Value> {
5519        let (value, done, ready, _reason) =
5520            self.resume_generator_detailed(generator, kind, value)?;
5521        if ready {
5522            return Ok(value);
5523        }
5524        self.iterator_result(value, done)
5525    }
5526
5527    /// `next`/`return`/`throw` on an async generator, which answer a promise.
5528    ///
5529    /// The body is the same coroutine a sync generator runs; what changes is that an
5530    /// `await` inside it has to settle before the method can answer, so the step is
5531    /// driven off the job queue rather than returning inline.
5532    pub fn resume_async_generator(
5533        &mut self,
5534        generator: &Gc<JsObject>,
5535        kind: ResumeKind,
5536        value: Value,
5537    ) -> JsResult<Value> {
5538        let promise = self.new_promise();
5539        self.step_async_generator(generator, &promise, kind, value)?;
5540        Ok(Value::Object(promise))
5541    }
5542
5543    /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
5544    ///
5545    /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
5546    /// disposer runs **synchronously** — the reference starts it before returning, which
5547    /// a test can observe by logging after the call — and the rest follow once their
5548    /// predecessor settles.
5549    pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
5550        let promise = self.new_promise();
5551        let mut pairs = Vec::with_capacity(resources.len());
5552        for (value, method) in resources {
5553            let pair = self.new_array(vec![value, method]);
5554            pairs.push(Value::Object(pair));
5555        }
5556        let remaining = self.new_array(pairs);
5557        self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
5558        Ok(Value::Object(promise))
5559    }
5560
5561    /// One link of the `disposeAsync` chain.
5562    ///
5563    /// Loops while the disposers finish synchronously, and parks on the first thenable it
5564    /// meets — pushing itself back in as the continuation, with the accumulated error
5565    /// carried along so a later failure can still be folded into the `SuppressedError`.
5566    fn dispose_step(
5567        &mut self,
5568        remaining: &Gc<JsObject>,
5569        promise: &Gc<JsObject>,
5570        mut error: Value,
5571    ) -> JsResult<()> {
5572        loop {
5573            let length = remaining.array_length().unwrap_or(0);
5574            if length == 0 {
5575                if matches!(error, Value::Uninitialized) {
5576                    self.fulfill_promise(promise, Value::Undefined);
5577                } else {
5578                    self.reject_promise(promise, error);
5579                }
5580                return Ok(());
5581            }
5582            let Some(Value::Object(pair)) = remaining
5583                .array_get(length - 1)
5584                .filter(|v| !matches!(v, Value::Hole))
5585            else {
5586                remaining.array_truncate(length - 1);
5587                continue;
5588            };
5589            remaining.array_truncate(length - 1);
5590            let value = pair.array_get(0).unwrap_or(Value::Undefined);
5591            let Some(Value::Object(method)) = pair.array_get(1) else {
5592                continue;
5593            };
5594            if !method.is_callable() {
5595                continue;
5596            }
5597            match self.call_value(Value::Object(method), value, Vec::new()) {
5598                Ok(result) => {
5599                    if !self.is_thenable(&result)? {
5600                        // Finished synchronously; the next disposer is the next iteration.
5601                        continue;
5602                    }
5603                    let awaited = match self.promise_resolve_value(result) {
5604                        Ok(awaited) => awaited,
5605                        Err(Signal::Throw(reason)) => {
5606                            self.reject_promise(promise, reason);
5607                            return Ok(());
5608                        }
5609                        Err(other) => return Err(other),
5610                    };
5611                    let Value::Object(awaited) = awaited else {
5612                        continue;
5613                    };
5614                    let ok = JsObject::function(
5615                        self.heap,
5616                        Some(self.realm.function_proto.clone()),
5617                        Callable::DisposeStep {
5618                            remaining: remaining.clone(),
5619                            promise: promise.clone(),
5620                            error: error.clone(),
5621                            rejected: false,
5622                        },
5623                    );
5624                    let failed = JsObject::function(
5625                        self.heap,
5626                        Some(self.realm.function_proto.clone()),
5627                        Callable::DisposeStep {
5628                            remaining: remaining.clone(),
5629                            promise: promise.clone(),
5630                            error,
5631                            rejected: true,
5632                        },
5633                    );
5634                    self.perform_then(
5635                        &awaited,
5636                        Some(Value::Object(ok)),
5637                        Some(Value::Object(failed)),
5638                    )?;
5639                    return Ok(());
5640                }
5641                Err(Signal::Throw(thrown)) => {
5642                    error = self.merge_dispose_error(thrown, error);
5643                }
5644                Err(other) => return Err(other),
5645            }
5646        }
5647    }
5648
5649    /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
5650    fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
5651        let Value::Object(object) = value else {
5652            return Ok(false);
5653        };
5654        Ok(matches!(
5655            self.get_property(object, "then")?,
5656            Some(Value::Object(then)) if then.is_callable()
5657        ))
5658    }
5659
5660    /// One step of an async generator, settling `promise` with an `{value, done}` result.
5661    fn step_async_generator(
5662        &mut self,
5663        generator: &Gc<JsObject>,
5664        promise: &Gc<JsObject>,
5665        kind: ResumeKind,
5666        value: Value,
5667    ) -> JsResult<()> {
5668        let stepped = self.resume_generator_detailed(generator, kind, value);
5669        let (value, done, ready, reason) = match stepped {
5670            Ok(stepped) => stepped,
5671            Err(Signal::Throw(reason)) => {
5672                self.reject_promise(promise, reason);
5673                return Ok(());
5674            }
5675            Err(other) => return Err(other),
5676        };
5677        // Only an `await` has to wait before the method can answer.
5678        if !done && reason == Some(SuspendKind::Await) {
5679            let awaited = match self.promise_resolve_value(value) {
5680                Ok(awaited) => awaited,
5681                Err(Signal::Throw(reason)) => {
5682                    self.reject_promise(promise, reason);
5683                    return Ok(());
5684                }
5685                Err(other) => return Err(other),
5686            };
5687            let Value::Object(awaited) = awaited else {
5688                return Ok(());
5689            };
5690            let resumed = JsObject::function(
5691                self.heap,
5692                Some(self.realm.function_proto.clone()),
5693                Callable::GeneratorResume {
5694                    generator: generator.clone(),
5695                    promise: promise.clone(),
5696                    kind: ResumeKind::Next,
5697                },
5698            );
5699            let raised = JsObject::function(
5700                self.heap,
5701                Some(self.realm.function_proto.clone()),
5702                Callable::GeneratorResume {
5703                    generator: generator.clone(),
5704                    promise: promise.clone(),
5705                    kind: ResumeKind::Throw,
5706                },
5707            );
5708            self.perform_then(
5709                &awaited,
5710                Some(Value::Object(resumed)),
5711                Some(Value::Object(raised)),
5712            )?;
5713            return Ok(());
5714        }
5715        // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
5716        // completes it — both arrive as the settled value rather than as the promise
5717        // object. A plain value skips the round trip, which is also what keeps `yield 1`
5718        // from costing an extra tick.
5719        let awaits_value = self.is_thenable(&value)?;
5720        if awaits_value {
5721            let awaited = match self.promise_resolve_value(value) {
5722                Ok(awaited) => awaited,
5723                Err(Signal::Throw(reason)) => {
5724                    self.reject_promise(promise, reason);
5725                    return Ok(());
5726                }
5727                Err(other) => return Err(other),
5728            };
5729            let Value::Object(awaited) = awaited else {
5730                return Ok(());
5731            };
5732            // A rejected yield throws *at the yield* inside the body, so the rejection
5733            // resumes the generator rather than the method's promise.
5734            let answer = JsObject::function(
5735                self.heap,
5736                Some(self.realm.function_proto.clone()),
5737                Callable::YieldResult {
5738                    promise: promise.clone(),
5739                    done,
5740                },
5741            );
5742            let raise = JsObject::function(
5743                self.heap,
5744                Some(self.realm.function_proto.clone()),
5745                Callable::GeneratorResume {
5746                    generator: generator.clone(),
5747                    promise: promise.clone(),
5748                    kind: ResumeKind::Throw,
5749                },
5750            );
5751            self.perform_then(
5752                &awaited,
5753                Some(Value::Object(answer)),
5754                Some(Value::Object(raise)),
5755            )?;
5756            return Ok(());
5757        }
5758        let result = if ready {
5759            // `yield*` handed back the inner iterator's own result object.
5760            value
5761        } else {
5762            self.iterator_result(value, done)?
5763        };
5764        self.fulfill_promise(promise, result);
5765        Ok(())
5766    }
5767
5768    /// The `{value, done}` object an iterator method answers with.
5769    pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
5770        let result = self.new_object(Some(self.realm.object_proto.clone()));
5771        result.define_data("value", value);
5772        result.define_data("done", Value::Bool(done));
5773        Ok(Value::Object(result))
5774    }
5775
5776    /// Advance a generator, returning the `{value, done}` pair the protocol wants.
5777    fn step_generator(
5778        &mut self,
5779        state: &mut GeneratorState,
5780        kind: ResumeKind,
5781        value: Value,
5782    ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
5783        match state.phase {
5784            GeneratorPhase::Executing => {
5785                return Err(self.type_error("cannot invoke a running generator"));
5786            }
5787            GeneratorPhase::Completed => {
5788                // A finished generator answers every resumption without running.
5789                return Ok(match kind {
5790                    ResumeKind::Throw => return Err(Signal::Throw(value)),
5791                    ResumeKind::Return => (value, true, false, None),
5792                    ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
5793                });
5794            }
5795            GeneratorPhase::SuspendedStart => {
5796                if kind != ResumeKind::Next && kind != ResumeKind::Start {
5797                    // The body never started, so there is nothing to unwind or return
5798                    // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
5799                    state.frame = None;
5800                    state.phase = GeneratorPhase::Completed;
5801                    return Ok(match kind {
5802                        ResumeKind::Throw => return Err(Signal::Throw(value)),
5803                        _ => (value, true, false, None),
5804                    });
5805                }
5806            }
5807            GeneratorPhase::SuspendedYield => {}
5808        }
5809
5810        let Some(mut frame) = state.frame.take() else {
5811            return Ok((Value::Undefined, true, false, None));
5812        };
5813        // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
5814        // number that says which method resumed it; the emitted `if_false` branches on
5815        // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
5816        let mut raised = None;
5817        match kind {
5818            ResumeKind::Next | ResumeKind::Start => {
5819                if state.phase == GeneratorPhase::SuspendedYield {
5820                    frame.stack.push(value);
5821                    // An `await` resumes with its value alone; only a `yield` gets the
5822                    // magic number that says which of `next`/`return` resumed it.
5823                    if !state.parked_on_await {
5824                        frame.stack.push(Value::Int(RESUME_NEXT));
5825                    }
5826                }
5827            }
5828            ResumeKind::Return => {
5829                // A `return` on a not-yet-started generator is handled above, so this is
5830                // always a real resumption.
5831                frame.stack.push(value);
5832                frame.stack.push(Value::Int(RESUME_RETURN));
5833            }
5834            ResumeKind::Throw => raised = Some(value),
5835        }
5836        state.phase = GeneratorPhase::Executing;
5837
5838        let depth = self.frames.len();
5839        self.frames.push(frame);
5840        // A `throw` unwinds from where the frame parked, exactly as if the exception had
5841        // happened at the `yield`.
5842        if let Some(exception) = raised {
5843            if self.catch_here(exception.clone()).is_none() {
5844                self.frames.pop();
5845                state.phase = GeneratorPhase::Completed;
5846                return Err(Signal::Throw(exception));
5847            }
5848        }
5849
5850        // Only the generator's *own* frame ends the generator. The body may call ordinary
5851        // functions, and those push frames of their own: a `Step::Return` from one of them
5852        // is a nested call finishing, not the generator completing. Miscounting that is
5853        // silent — the generator reports the callee's value as its own result and marks
5854        // itself done — so the depth comparison is load-bearing, not defensive.
5855        let own_frame = depth + 1;
5856        loop {
5857            match self.step() {
5858                Ok(Step::Continue) => {}
5859                Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
5860                    let mut frame = self.frames.pop().expect("a frame is live");
5861                    // `yield` left the value on the stack; `initial_yield` left nothing.
5862                    let yielded = if reason == SuspendKind::Initial {
5863                        Value::Undefined
5864                    } else {
5865                        frame.stack.pop().unwrap_or(Value::Undefined)
5866                    };
5867                    state.frame = Some(frame);
5868                    state.parked_on_await = reason == SuspendKind::Await;
5869                    state.phase = if reason == SuspendKind::Initial {
5870                        GeneratorPhase::SuspendedStart
5871                    } else {
5872                        GeneratorPhase::SuspendedYield
5873                    };
5874                    // `yield*` hands the inner iterator's own result object straight
5875                    // back, so the caller sees one `{value, done}` rather than a nested
5876                    // one — which is why the third field says "already a result".
5877                    return Ok((
5878                        yielded,
5879                        false,
5880                        reason == SuspendKind::YieldStar,
5881                        Some(reason),
5882                    ));
5883                }
5884                Ok(Step::Suspend(_)) => {
5885                    // A `yield` in a frame other than the generator's would mean a
5886                    // generator body entered as an ordinary call, which
5887                    // `call_or_push` prevents.
5888                    self.unwind_to(depth);
5889                    state.phase = GeneratorPhase::Completed;
5890                    return Err(Signal::Throw(self.make_error(
5891                        "InternalError",
5892                        "a generator body ran as an ordinary call",
5893                    )));
5894                }
5895                Ok(Step::Return(value)) => {
5896                    self.frames.pop();
5897                    if self.frames.len() > depth {
5898                        // A nested call finished: hand the value back to its caller and
5899                        // keep running the generator body.
5900                        self.frames
5901                            .last_mut()
5902                            .expect("a caller is live")
5903                            .stack
5904                            .push(value);
5905                        continue;
5906                    }
5907                    state.phase = GeneratorPhase::Completed;
5908                    // The reference closes the generator's closure variables here; ours
5909                    // live in cells the frame owned, which the drop below releases.
5910                    return Ok((value, true, false, None));
5911                }
5912                Err(Signal::Throw(exception)) => {
5913                    // The frame that threw gets the first chance to catch, exactly as in
5914                    // the ordinary call loop; a frame above the generator's is popped and
5915                    // the exception carries on down.
5916                    let exception = exception;
5917                    loop {
5918                        if self.frames.len() <= depth {
5919                            // The generator's own frame is gone, so nothing here caught it.
5920                            state.phase = GeneratorPhase::Completed;
5921                            return Err(Signal::Throw(exception));
5922                        }
5923                        if self.catch_here(exception.clone()).is_some() {
5924                            break;
5925                        }
5926                        self.frames.pop();
5927                    }
5928                }
5929                Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
5930            }
5931        }
5932    }
5933
5934    /// Pop frames until `depth` are left.
5935    fn unwind_to(&mut self, depth: usize) {
5936        self.frames.truncate(depth);
5937    }
5938    fn call_or_push(
5939        &mut self,
5940        callee: Value,
5941        this: Value,
5942        args: Vec<Value>,
5943    ) -> JsResult<Option<Value>> {
5944        if let Value::Object(function) = &callee
5945            && let Some((code, env)) = bytecode_of(function)
5946        {
5947            // Calling a generator function does not run anything: it captures the
5948            // arguments in a frame and hands back the generator object.
5949            if code.code.kind.is_generator() {
5950                return self.new_generator(callee, this, args).map(Some);
5951            }
5952            // An async function answers a promise and runs its body as a coroutine, so it
5953            // takes the same path as a plain call into it.
5954            if code.code.kind.is_async() {
5955                return self.new_async_function(callee, this, args).map(Some);
5956            }
5957            self.push_frame(code, env, this, args, callee)?;
5958            return Ok(None);
5959        }
5960        self.call_value(callee, this, args).map(Some)
5961    }
5962
5963    /// `new callee(args)`.
5964    ///
5965    /// A constructor differs from a plain call in three ways: it gets a fresh object
5966    /// as `this` whose prototype is the constructor's `prototype` property, its
5967    /// return value is *replaced* by that object unless it returns an object itself,
5968    /// and a native constructor is expected to initialise the object it is given
5969    /// rather than build one.
5970    pub fn construct(
5971        &mut self,
5972        callee: Value,
5973        new_target: Value,
5974        args: Vec<Value>,
5975    ) -> JsResult<Value> {
5976        // `new` on a bound function constructs its *target*, prepending the arguments
5977        // the bind fixed and ignoring the bound `this` — a bound function is a
5978        // constructor only when its target is one, and `new` always makes a fresh
5979        // object of the target's prototype rather than reusing the bound receiver.
5980        // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
5981        // ran the body with `this === null` and threw on `this.x = a`.
5982        let mut callee = callee;
5983        let mut new_target = new_target;
5984        let mut args = args;
5985        loop {
5986            let Some(object) = callee.as_object().cloned() else {
5987                return Err(Signal::Throw(
5988                    self.make_error("TypeError", "not a constructor"),
5989                ));
5990            };
5991            // A proxy of a function constructs through its `construct` trap, and the
5992            // trap's answer is the result directly — no fresh object is made here.
5993            if object.proxy_state().is_some() {
5994                return match self.proxy_construct(&object, args, &new_target)? {
5995                    Some(result) => Ok(result),
5996                    None => Err(Signal::Throw(
5997                        self.make_error("TypeError", "proxy target is not a constructor"),
5998                    )),
5999                };
6000            }
6001            // A generator function has no `[[Construct]]`, and the reference names it in
6002            // the message: `new (function* G(){})()` reports "G is not a constructor".
6003            if object.with(|data| match &data.kind {
6004                ObjectKind::Function(Callable::Bytecode { code, .. }) => {
6005                    code.code.kind.is_generator()
6006                }
6007                _ => false,
6008            }) {
6009                let name = object
6010                    .own_property("name")
6011                    .and_then(|property| property.value)
6012                    .map(|value| value.to_js_string())
6013                    .unwrap_or_default();
6014                return Err(Signal::Throw(
6015                    self.make_error("TypeError", &format!("{name} is not a constructor")),
6016                ));
6017            }
6018            let bound = object.with(|data| match &data.kind {
6019                ObjectKind::Function(Callable::Bound {
6020                    target,
6021                    args: leading,
6022                    ..
6023                }) => Some((target.clone(), leading.clone())),
6024                _ => None,
6025            });
6026            let Some((target, leading)) = bound else {
6027                // Not a bound function, so this object is the callee. §7.2.4
6028                // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
6029                // refusals above cover only the built-ins the reference also refuses by
6030                // name. Everything else — a method, an arrow, an async function — has no
6031                // `[[Construct]]` either, and answering "yes" here made
6032                // `new (Array.prototype.map)` build an object instead of throwing.
6033                if !object.is_constructor() {
6034                    let name = object
6035                        .own_property("name")
6036                        .and_then(|property| property.value)
6037                        .map(|value| value.to_js_string())
6038                        .unwrap_or_default();
6039                    return Err(Signal::Throw(
6040                        self.make_error("TypeError", &format!("{name} is not a constructor")),
6041                    ));
6042                }
6043                break;
6044            };
6045            let mut all = leading;
6046            all.extend(args);
6047            args = all;
6048            // A bound function that is its own `new.target` stands in for its target:
6049            // `new (C.bind(null))()` makes a `C` instance, so the object has to come
6050            // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
6051            let same_wrapper = match (new_target.as_object(), callee.as_object()) {
6052                (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
6053                _ => false,
6054            };
6055            if same_wrapper {
6056                new_target = target.clone();
6057            }
6058            callee = target;
6059        }
6060        let Value::Object(function) = &callee else {
6061            unreachable!("the loop above only breaks on an object");
6062        };
6063        // The fresh object's prototype comes from `new.target`, not from the callee: a
6064        // derived constructor reaches here through `super()`, and the instance must be a
6065        // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
6066        // an object inheriting `D.prototype` rather than `C.prototype`.
6067        let prototype_source = match new_target.as_object() {
6068            Some(target) => target.clone(),
6069            None => function.clone(),
6070        };
6071        // A native constructor builds its own instance, through `new_ctor_instance`, once it
6072        // has validated its arguments. Pre-building one here would read
6073        // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
6074        // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
6075        // getter runs, and `new DataView(detached, …)` likewise for the detached check.
6076        let is_native = function.native_creates_own_instance();
6077        let this = if is_native {
6078            Value::Undefined
6079        } else {
6080            let prototype = self.get_property(&prototype_source, "prototype")?;
6081            let prototype = match prototype {
6082                Some(Value::Object(proto)) => Some(proto),
6083                // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
6084                // object, the answer is the realm's *intrinsic* prototype for this
6085                // constructor, not `%Object.prototype%`.
6086                _ => {
6087                    let fallback = self.get_property(function, "prototype")?;
6088                    match fallback {
6089                        Some(Value::Object(proto)) => Some(proto),
6090                        _ => Some(self.realm.object_proto.clone()),
6091                    }
6092                }
6093            };
6094            Value::Object(self.new_object(prototype))
6095        };
6096        // `new.target` inside the body is the constructor that was written, so a bound
6097        // function's target sees itself rather than the bound wrapper.
6098        //
6099        // The save/restore is not cosmetic: a constructor that *throws* leaves through the
6100        // `?`, so assigning `None` after the call would be skipped and the failed
6101        // `new.target` would stay visible to every later native call. The symptom was a
6102        // native constructor refusing a plain call — `var s = Symbol(); new
6103        // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
6104        // "FinalizationRegistry is not a constructor".
6105        let outer_new_target = self.pending_new_target.replace(new_target);
6106        let result = self.call_value(callee, this.clone(), args);
6107        self.pending_new_target = outer_new_target;
6108        let result = result?;
6109        // A constructor that returns an object overrides `this`; any other return
6110        // value (including `undefined`) is ignored.
6111        Ok(match result {
6112            Value::Object(_) => result,
6113            _ => this,
6114        })
6115    }
6116
6117    /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
6118    ///
6119    /// The error classes themselves arrive with the builtins milestone; what
6120    /// matters here is that the thrown value stringifies the way a script printing
6121    /// the caught value expects.
6122    pub fn make_error(&self, name: &str, message: &str) -> Value {
6123        let proto = self
6124            .realm
6125            .errors
6126            .get(name)
6127            .map(|constructor| self.prototype_of(constructor))
6128            .unwrap_or_else(|| self.realm.error_proto.clone());
6129        let error = self.new_object(Some(proto));
6130        // `name` and `message` are own properties of the instance, which is what
6131        // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
6132        // `Error`.
6133        error.define(
6134            "name",
6135            Property::with_attributes(self.string(name), true, false),
6136        );
6137        error.define(
6138            "message",
6139            Property::with_attributes(self.string(message), true, false),
6140        );
6141        // The internal class, which is what tells a printer this is an error rather than a
6142        // plain object with `name` and `message` properties. The constructor path sets it
6143        // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
6144        // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
6145        // literally `"Error"` in both places — the *name* is read from `name`, which is why
6146        // a `RangeError` still prints as `RangeError`.
6147        self.internal_set(&error, "_class", self.string("Error"));
6148        // The trace is captured where the error is *made*, which is where the reference
6149        // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
6150        // way out, so a caught engine error already has its stack even if the handler
6151        // never rethrows it.
6152        self.add_stack(&error);
6153        Value::Object(error)
6154    }
6155
6156    /// Give an error object its `stack` property, from the current frame stack.
6157    ///
6158    /// Only objects get one — `throw 42` has no stack anywhere — and an object that
6159    /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
6160    /// `stack` a script set, is not rewritten.
6161    pub fn add_stack(&self, object: &Gc<JsObject>) {
6162        self.add_stack_skipping(object, 0);
6163    }
6164
6165    /// [`Interp::add_stack`], omitting the `skip` innermost frames.
6166    ///
6167    /// An `Error` constructor passes 1: the reference builds those traces with
6168    /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
6169    /// constructor itself, while a `RangeError` raised inside `toISOString` does
6170    /// report `at toISOString (native)`.
6171    pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
6172        if object.has_own("stack") {
6173            return;
6174        }
6175        let trace = self.stack_trace_skipping(skip);
6176        let text = self.string(trace);
6177        object.define("stack", Property::with_attributes(text, true, true));
6178    }
6179
6180    /// The function object currently being called, if any.
6181    ///
6182    /// A native function is a bare `fn` pointer, so it cannot capture which class
6183    /// it belongs to; it reads that from the callee instead. This is also what a
6184    /// stack trace would use.
6185    pub fn current_callee(&self) -> Option<Gc<JsObject>> {
6186        match &self.frames.last()?.callee {
6187            Value::Object(object) => Some(object.clone()),
6188            _ => None,
6189        }
6190    }
6191
6192    /// The `prototype` property of a constructor, falling back to
6193    /// `Object.prototype` for anything that is not shaped like one.
6194    pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
6195        constructor
6196            .own_property("prototype")
6197            .and_then(|property| property.value)
6198            .and_then(|value| value.as_object().cloned())
6199            .unwrap_or_else(|| self.realm.object_proto.clone())
6200    }
6201
6202    /// Throw a `TypeError` carrying `message`.
6203    pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
6204        Signal::Throw(self.make_error("TypeError", message.as_ref()))
6205    }
6206
6207    /// Throw a `RangeError` carrying `message`.
6208    pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
6209        Signal::Throw(self.make_error("RangeError", message.as_ref()))
6210    }
6211
6212    /// The `ReferenceError` a read of an uninitialised binding raises.
6213    /// The name of the binding `slot` refers to, for an error message.
6214    fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
6215        match kind {
6216            VarSlot::Loc => self
6217                .frame()
6218                .code
6219                .code
6220                .vars
6221                .get(slot)
6222                .map(|v| v.name.clone()),
6223            VarSlot::Closure => self
6224                .frame()
6225                .code
6226                .code
6227                .closure_vars
6228                .get(slot)
6229                .map(|c| c.name.clone()),
6230        }
6231        .unwrap_or_default()
6232    }
6233
6234    /// Whether `slot` names a `const` binding, which rejects every store after its
6235    /// initialiser.
6236    fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
6237        match kind {
6238            VarSlot::Loc => self
6239                .frame()
6240                .code
6241                .code
6242                .vars
6243                .get(slot)
6244                .is_some_and(|v| v.is_const),
6245            VarSlot::Closure => self
6246                .frame()
6247                .code
6248                .code
6249                .closure_vars
6250                .get(slot)
6251                .is_some_and(|c| c.is_const),
6252        }
6253    }
6254
6255    /// The `TypeError` a store to a `const` binding raises.
6256    ///
6257    /// `const` is enforced here rather than at compile time because the binding can be
6258    /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
6259    /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
6260    /// both halves of what "checked store" means: the dead zone is over, and the
6261    /// binding is writable.
6262    fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
6263        let name = self.binding_name(slot, kind);
6264        Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
6265    }
6266
6267    fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
6268        let name = match kind {
6269            VarSlot::Loc => self
6270                .frame()
6271                .code
6272                .code
6273                .vars
6274                .get(slot)
6275                .map(|v| v.name.clone()),
6276            VarSlot::Closure => self
6277                .frame()
6278                .code
6279                .code
6280                .closure_vars
6281                .get(slot)
6282                .map(|c| c.name.clone()),
6283        }
6284        .unwrap_or_default();
6285        Signal::Throw(self.make_error(
6286            "ReferenceError",
6287            &format!("cannot access '{name}' before initialization"),
6288        ))
6289    }
6290
6291    fn throw_reference(&self, name: &str) -> Signal {
6292        Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
6293    }
6294
6295    // -- the instruction loop -----------------------------------------------
6296
6297    fn step(&mut self) -> JsResult<Step> {
6298        let pc = self.frame().pc;
6299        let code = self.frame().code.clone();
6300        let bytes = &code.code.code;
6301        if pc >= bytes.len() {
6302            return Ok(Step::Return(Value::Undefined));
6303        }
6304        let Some(decoded) = decode(bytes, pc) else {
6305            return Err(Signal::Throw(
6306                self.make_error("InternalError", "undecodable bytecode"),
6307            ));
6308        };
6309        let (op, a, b, next) = decoded;
6310        self.frame_mut().at = pc;
6311        self.frame_mut().pc = next;
6312        self.execute_instruction(op, a, b, next)
6313    }
6314
6315    fn push(&mut self, value: Value) {
6316        self.frame_mut().stack.push(value);
6317    }
6318
6319    fn pop(&mut self) -> Value {
6320        self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
6321    }
6322
6323    fn pop_n(&mut self, count: usize) -> Vec<Value> {
6324        let frame = self.frame_mut();
6325        let start = frame.stack.len().saturating_sub(count);
6326        frame.stack.split_off(start)
6327    }
6328
6329    fn peek(&self, back: usize) -> Value {
6330        let frame = self.frame();
6331        frame
6332            .stack
6333            .get(frame.stack.len().wrapping_sub(1 + back))
6334            .cloned()
6335            .unwrap_or(Value::Undefined)
6336    }
6337
6338    #[allow(clippy::too_many_lines)]
6339    fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
6340        use Opcode::*;
6341        match op {
6342            // -- constants and stack shuffling -----------------------------
6343            Nop => {}
6344            PushMinus1 => self.push(Value::Int(-1)),
6345            Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
6346                let value = match op {
6347                    Push0 => 0,
6348                    Push1 => 1,
6349                    Push2 => 2,
6350                    Push3 => 3,
6351                    Push4 => 4,
6352                    Push5 => 5,
6353                    Push6 => 6,
6354                    _ => 7,
6355                };
6356                self.push(Value::Int(value));
6357            }
6358            PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
6359            PushBigintI32 => {
6360                // The immediate form of a `BigInt` literal; the reference has the same
6361                // split between this and a constant-pool entry.
6362                let value = crate::bigint::BigInt::from_i64(a as i64);
6363                self.push(self.bigint(value));
6364            }
6365            PushTrue => self.push(Value::Bool(true)),
6366            PushFalse => self.push(Value::Bool(false)),
6367            PushEmptyString => self.push(self.string("")),
6368            Undefined => self.push(Value::Undefined),
6369            Null => self.push(Value::Null),
6370            Object => {
6371                let proto = self.realm.object_proto.clone();
6372                self.push(Value::Object(self.new_object(Some(proto))));
6373            }
6374            PushThis => {
6375                let this = self.frame().this.clone();
6376                self.push(this);
6377            }
6378            PushConst | PushConst8 => {
6379                let value = self.constant(a as usize)?;
6380                self.push(value);
6381            }
6382            PushAtomValue => {
6383                let text = self.atom_text(a as usize);
6384                self.push(self.string(text));
6385            }
6386            Dup => {
6387                let value = self.peek(0);
6388                self.push(value);
6389            }
6390            Dup2 => {
6391                // `a b -> a b a b`
6392                let b = self.peek(0);
6393                let a = self.peek(1);
6394                self.push(a);
6395                self.push(b);
6396            }
6397            Dup3 => {
6398                // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
6399                // prototype and key while reading the current value through them.
6400                let c = self.peek(0);
6401                let b = self.peek(1);
6402                let a = self.peek(2);
6403                self.push(a);
6404                self.push(b);
6405                self.push(c);
6406            }
6407            Swap => {
6408                // `a b -> b a`
6409                let bottom = self.pop();
6410                let top = self.pop();
6411                self.push(bottom);
6412                self.push(top);
6413            }
6414            Perm3 => {
6415                // `a b c -> b a c`, the reference's reordering for a spread method
6416                // call: `obj func array` becomes the `func this array` that `apply`
6417                // takes.
6418                let c = self.pop();
6419                let b = self.pop();
6420                let a = self.pop();
6421                self.push(b);
6422                self.push(a);
6423                self.push(c);
6424            }
6425            Dup1 => {
6426                let value = self.peek(1);
6427                self.push(value);
6428            }
6429            Drop => {
6430                self.pop();
6431            }
6432            Nip => {
6433                // `a b -> b`
6434                let top = self.pop();
6435                self.pop();
6436                self.push(top);
6437            }
6438            Perm4 => {
6439                // `obj prop a b -> a obj prop b`, the reference's reordering for a
6440                // postfix update of a computed element: it puts the *old* value
6441                // underneath the receiver and key so `put_array_el` can consume them
6442                // and leave the old value as the expression's result.
6443                let d = self.pop();
6444                let c = self.pop();
6445                let b = self.pop();
6446                let a = self.pop();
6447                self.push(c);
6448                self.push(a);
6449                self.push(b);
6450                self.push(d);
6451            }
6452            Insert2 => {
6453                // `obj a -> a obj a`
6454                let value = self.pop();
6455                let object = self.pop();
6456                self.push(value.clone());
6457                self.push(object);
6458                self.push(value);
6459            }
6460            Insert3 => {
6461                // `obj prop a -> a obj prop a`
6462                let value = self.pop();
6463                let key = self.pop();
6464                let object = self.pop();
6465                self.push(value.clone());
6466                self.push(object);
6467                self.push(key);
6468                self.push(value);
6469            }
6470            Insert4 => {
6471                // `this obj prop a -> a this obj prop a`
6472                //
6473                // `put_super_value` consumes all four and yields nothing, so the copy
6474                // underneath is what leaves the assignment an expression value.
6475                let value = self.pop();
6476                let key = self.pop();
6477                let object = self.pop();
6478                let receiver = self.pop();
6479                self.push(value.clone());
6480                self.push(receiver);
6481                self.push(object);
6482                self.push(key);
6483                self.push(value);
6484            }
6485            Swap2 => {
6486                // `a b c d -> c d a b`
6487                let d = self.pop();
6488                let c = self.pop();
6489                let b = self.pop();
6490                let a = self.pop();
6491                self.push(c);
6492                self.push(d);
6493                self.push(a);
6494                self.push(b);
6495            }
6496            Rot3l => {
6497                // `x a b -> a b x`
6498                let b = self.pop();
6499                let a = self.pop();
6500                let x = self.pop();
6501                self.push(a);
6502                self.push(b);
6503                self.push(x);
6504            }
6505            Rot3r => {
6506                // `a b c -> c a b`
6507                let c = self.pop();
6508                let b = self.pop();
6509                let a_value = self.pop();
6510                self.push(c);
6511                self.push(a_value);
6512                self.push(b);
6513            }
6514
6515            Rest => {
6516                // `...rest` in a parameter list: the arguments from index `a` on, as a
6517                // real array. It takes nothing off the stack — the arguments are in the
6518                // frame, not on it.
6519                let frame = self.frame();
6520                let from = a as usize;
6521                let collected: Vec<Value> = frame.passed.iter().skip(from).cloned().collect();
6522                let array = self.new_array(collected);
6523                self.push(Value::Object(array));
6524            }
6525
6526            // -- slots ------------------------------------------------------
6527            GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
6528                let slot = self.slot_operand(op, a);
6529                let value = self.get_loc(slot);
6530                self.push(value);
6531            }
6532            PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
6533                let slot = self.slot_operand(op, a);
6534                let value = self.pop();
6535                self.put_loc(slot, value);
6536            }
6537            SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
6538                let slot = self.slot_operand(op, a);
6539                let value = self.pop();
6540                self.put_loc(slot, value.clone());
6541                self.push(value);
6542            }
6543            // The `_check` forms are the temporal dead zone: they throw when the
6544            // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
6545            // *reads*, so only the two writes may pop — mishandling that quietly
6546            // consumes the value the caller pushed just before.
6547            GetLocCheck => {
6548                let slot = self.slot_operand(op, a);
6549                let value = self.get_loc(slot);
6550                if matches!(value, Value::Uninitialized) {
6551                    return Err(self.dead_zone(slot, VarSlot::Loc));
6552                }
6553                self.push(value);
6554            }
6555            PutLocCheck | SetLocCheck => {
6556                let slot = self.slot_operand(op, a);
6557                let value = self.pop();
6558                if matches!(value, Value::Uninitialized) {
6559                    return Err(self.dead_zone(slot, VarSlot::Loc));
6560                }
6561                // The initialiser goes through `put_loc`, not this, so any store that
6562                // reaches here is a later assignment — which a `const` refuses.
6563                if self.is_read_only(slot, VarSlot::Loc) {
6564                    return Err(self.read_only(slot, VarSlot::Loc));
6565                }
6566                if op == SetLocCheck {
6567                    self.put_loc(slot, value.clone());
6568                    self.push(value);
6569                } else {
6570                    self.put_loc(slot, value);
6571                }
6572            }
6573            PutLocCheckInit => {
6574                // The one store that *initialises* a lexical slot: `this` in a derived
6575                // constructor, which only exists after `super()` has run. A second
6576                // initialisation is the error the reference reports as
6577                // "'this' can be initialized only once".
6578                let slot = self.slot_operand(op, a);
6579                let value = self.pop();
6580                if !matches!(self.get_loc(slot), Value::Uninitialized) {
6581                    return Err(Signal::Throw(self.make_error(
6582                        "ReferenceError",
6583                        "'this' can be initialized only once",
6584                    )));
6585                }
6586                self.put_loc(slot, value);
6587            }
6588            CheckCtor => {
6589                // A class constructor may only run under `new`, which is what makes
6590                // `class A {}; A()` a TypeError.
6591                if matches!(self.frame().new_target, Value::Undefined) {
6592                    return Err(Signal::Throw(self.make_error(
6593                        "TypeError",
6594                        "class constructors must be invoked with 'new'",
6595                    )));
6596                }
6597            }
6598            InitCtor => {
6599                // The body a derived class gets when it declares no constructor:
6600                // forward every argument to the parent constructor, keeping `new.target`.
6601                if matches!(self.frame().new_target, Value::Undefined) {
6602                    return Err(Signal::Throw(self.make_error(
6603                        "TypeError",
6604                        "class constructors must be invoked with 'new'",
6605                    )));
6606                }
6607                let Some(callee) = self.current_callee() else {
6608                    return Err(Signal::Throw(
6609                        self.make_error("TypeError", "no constructor to inherit from"),
6610                    ));
6611                };
6612                let parent = callee.proto().map_or(Value::Null, Value::Object);
6613                let new_target = self.frame().new_target.clone();
6614                let args = self.frame().passed.clone();
6615                let result = self.construct(parent, new_target, args)?;
6616                self.push(result);
6617            }
6618            SetLocUninitialized => {
6619                let slot = self.slot_operand(op, a);
6620                self.put_loc(slot, Value::Uninitialized);
6621            }
6622            CloseLoc => {
6623                // "Close" a binding: give it a *fresh* cell holding the current
6624                // value. Closures created before this point keep the old cell and the
6625                // ones created after see the new one, which is what makes every
6626                // iteration of `for (let i ...)` capture its own `i`, and what freezes
6627                // a block-scoped binding when the block ends.
6628                //
6629                // Clearing the slot instead (which this used to do) broke both: a
6630                // closure over a captured block variable read `undefined`, and a loop
6631                // terminated after one iteration.
6632                let slot = self.slot_operand(op, a);
6633                let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
6634                if index >= 0 {
6635                    let current = self.frame().cells[index as usize].get();
6636                    let fresh = self.new_cell(current);
6637                    if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
6638                        *cell = fresh;
6639                    }
6640                }
6641            }
6642            GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
6643                let slot = self.slot_operand(op, a);
6644                let value = self.get_arg(slot);
6645                self.push(value);
6646            }
6647            PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
6648                let slot = self.slot_operand(op, a);
6649                let value = self.pop();
6650                self.put_arg(slot, value);
6651            }
6652            SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
6653                let slot = self.slot_operand(op, a);
6654                let value = self.pop();
6655                self.put_arg(slot, value.clone());
6656                self.push(value);
6657            }
6658
6659            // -- closure variables ------------------------------------------
6660            GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
6661                let slot = self.slot_operand(op, a);
6662                // A name a direct `eval` created shadows the binding the compiler chose.
6663                // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
6664                // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
6665                // and only a runtime lookup can know that.
6666                if let Some(cell) = self.eval_created_local(slot) {
6667                    self.push(cell.get());
6668                    return self.step();
6669                }
6670                let value = self.cell_value(slot)?;
6671                self.push(value);
6672            }
6673            GetVarRefCheck => {
6674                let slot = self.slot_operand(op, a);
6675                let value = self.cell_value(slot)?;
6676                if matches!(value, Value::Uninitialized) {
6677                    return Err(self.dead_zone(slot, VarSlot::Closure));
6678                }
6679                self.push(value);
6680            }
6681            PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
6682                let slot = self.slot_operand(op, a);
6683                let value = self.pop();
6684                if let Some(cell) = self.eval_created_local(slot) {
6685                    cell.set(value);
6686                    return self.step();
6687                }
6688                // Same rule as `PutLocCheck`: a checked store to a captured binding
6689                // refuses a `const` once its initialiser has run.
6690                if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
6691                    return Err(self.read_only(slot, VarSlot::Closure));
6692                }
6693                self.set_cell(slot, value)?;
6694            }
6695            SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
6696                let slot = self.slot_operand(op, a);
6697                let value = self.pop();
6698                if let Some(cell) = self.eval_created_local(slot) {
6699                    cell.set(value.clone());
6700                    self.push(value);
6701                    return self.step();
6702                }
6703                self.set_cell(slot, value.clone())?;
6704                self.push(value);
6705            }
6706
6707            // -- globals ----------------------------------------------------
6708            GetVar => {
6709                let value = self.get_global(a as usize)?;
6710                self.push(value);
6711            }
6712            GetVarUndef => {
6713                let value = self
6714                    .get_global(a as usize)
6715                    .or_else(|_| Ok(Value::Undefined))?;
6716                self.push(value);
6717            }
6718            DeleteVar => {
6719                // `delete name` for a name that is not a declared binding. A lexical
6720                // global lives in the reference table and cannot be deleted; anything
6721                // reachable only as a property of the global object is *implicit* —
6722                // `x = 1` with no declaration — and goes away if it is configurable,
6723                // which is what `delete` on an implicit global answers.
6724                let name = self.atom_text(a as usize);
6725                let global = self.realm.global.clone();
6726                let deleted = if self.realm.globals.contains_key(&name) {
6727                    false
6728                } else if global.own_property(&name).is_some() {
6729                    self.delete_property(&global, &name)?
6730                } else {
6731                    true
6732                };
6733                self.push(Value::Bool(deleted));
6734            }
6735            PutVar => {
6736                let value = self.pop();
6737                self.put_global(a as usize, value)?;
6738            }
6739            PutVarInit => {
6740                let slot = a as usize;
6741                let value = self.pop();
6742                self.init_global(slot, value)?;
6743            }
6744
6745            // -- arithmetic -------------------------------------------------
6746            Add => self.binary_add()?,
6747            Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
6748                let raw_right = self.pop();
6749                let raw_left = self.pop();
6750                // BigInt arithmetic is a separate path, and not only for the type of the
6751                // result: `ToNumber` of a bigint throws, so mixing the two must be an error
6752                // rather than a silent conversion.
6753                if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
6754                    let left = self.primitive_of(raw_left)?;
6755                    let right = self.primitive_of(raw_right)?;
6756                    let value = self.bigint_arithmetic(op, left, right)?;
6757                    self.push(value);
6758                } else {
6759                    let right = self.numeric(raw_right)?;
6760                    let left = self.numeric(raw_left)?;
6761                    self.push(arithmetic(op, left, right)?);
6762                }
6763            }
6764            Neg => {
6765                let raw = self.pop();
6766                match raw {
6767                    // A bigint negates exactly, however wide it is.
6768                    Value::BigInt(big) => {
6769                        let negated = big.negate();
6770                        self.push(self.bigint(negated));
6771                    }
6772                    other => {
6773                        let value = self.numeric(other)?;
6774                        self.push(negate(value));
6775                    }
6776                }
6777            }
6778            Plus => {
6779                let value = self.pop();
6780                // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
6781                // unary plus is defined to produce a *number*, which a bigint cannot
6782                // become without loss. It used to fall through to `NaN`.
6783                if matches!(value, Value::BigInt(_)) {
6784                    return Err(self.type_error("cannot convert bigint to number"));
6785                }
6786                let numeric = self.numeric_of(value)?;
6787                self.push(numeric);
6788            }
6789            Inc => {
6790                let raw = self.pop();
6791                let (_, updated) = self.advance_numeric(raw, true)?;
6792                self.push(updated);
6793            }
6794            Dec => {
6795                let raw = self.pop();
6796                let (_, updated) = self.advance_numeric(raw, false)?;
6797                self.push(updated);
6798            }
6799            PostInc | PostDec => {
6800                // `x -> x x+1`: the *new* value ends up on top, so the store the
6801                // compiler emits right after (`put_var`) writes the incremented
6802                // one, while the old value stays underneath for the expression's
6803                // own result. Getting this backwards makes `i++` a no-op, which
6804                // turns `while (i < 3)` into an infinite loop.
6805                let raw = self.pop();
6806                let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
6807                self.push(old);
6808                self.push(updated);
6809            }
6810            Not => {
6811                let raw = self.pop();
6812                match raw {
6813                    // `~x` on a bigint is `-x - 1`, exact at any width.
6814                    Value::BigInt(big) => {
6815                        let inverted = big.bitnot();
6816                        self.push(self.bigint(inverted));
6817                    }
6818                    other => {
6819                        let value = self.numeric(other)?;
6820                        self.push(Value::Int(!value.to_int32()));
6821                    }
6822                }
6823            }
6824            Lnot => {
6825                let value = self.pop();
6826                self.push(Value::Bool(!value.to_boolean()));
6827            }
6828
6829            // -- comparison -------------------------------------------------
6830            Lt | Lte | Gt | Gte => {
6831                let right = self.pop();
6832                let left = self.pop();
6833                let answer = self.relational(op, left, right);
6834                self.push(answer);
6835            }
6836            Eq | Neq => {
6837                let right = self.pop();
6838                let left = self.pop();
6839                let equal = self.abstract_equals(left, right)?;
6840                self.push(Value::Bool(if op == Eq { equal } else { !equal }));
6841            }
6842            StrictEq => {
6843                let right = self.pop();
6844                let left = self.pop();
6845                self.push(Value::Bool(left.strict_equals(&right)));
6846            }
6847            StrictNeq => {
6848                let right = self.pop();
6849                let left = self.pop();
6850                self.push(Value::Bool(!left.strict_equals(&right)));
6851            }
6852            IsUndefined => {
6853                // `=== undefined`, which is what a destructuring default tests. It is
6854                // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
6855                let value = self.pop();
6856                self.push(Value::Bool(matches!(value, Value::Undefined)));
6857            }
6858            IsUndefinedOrNull => {
6859                let value = self.pop();
6860                self.push(Value::Bool(value.is_nullish()));
6861            }
6862            Typeof => {
6863                let value = self.pop();
6864                self.push(self.string(value.type_of()));
6865            }
6866            ToObject => {
6867                // A destructuring *object* pattern starts here, which is why
6868                // `var {} = null` throws. Only `undefined` and `null` are refused; a
6869                // primitive is boxed.
6870                let value = self.pop();
6871                let object = self.object_from(&value)?;
6872                self.push(Value::Object(object));
6873            }
6874            Instanceof => {
6875                let constructor = self.pop();
6876                let object = self.pop();
6877                let answer = self.instance_of(&object, &constructor)?;
6878                self.push(Value::Bool(answer));
6879            }
6880            In => {
6881                let object = self.pop();
6882                let key = self.pop();
6883                let answer = self.has_property(&key, &object)?;
6884                self.push(Value::Bool(answer));
6885            }
6886
6887            // -- control flow -----------------------------------------------
6888            Goto | Goto8 | Goto16 => {
6889                self.frame_mut().pc = a as usize;
6890            }
6891            IfTrue | IfTrue8 => {
6892                let value = self.pop();
6893                if value.to_boolean() {
6894                    self.frame_mut().pc = a as usize;
6895                }
6896            }
6897            IfFalse | IfFalse8 => {
6898                let value = self.pop();
6899                if !value.to_boolean() {
6900                    self.frame_mut().pc = a as usize;
6901                }
6902            }
6903            Catch => {
6904                // Pushes the handler target onto the value stack; `unwind` finds it.
6905                self.push(Value::CatchOffset(a));
6906            }
6907            Gosub => {
6908                self.push(Value::ReturnAddress(next as u32));
6909                self.frame_mut().pc = a as usize;
6910            }
6911            Ret => {
6912                let value = self.pop();
6913                match value {
6914                    Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
6915                    _ => {
6916                        return Err(Signal::Throw(
6917                            self.make_error("InternalError", "invalid return address"),
6918                        ));
6919                    }
6920                }
6921            }
6922            NipCatch => {
6923                // `catch_offset ... ret_val -> ret_val`: drop everything down to and
6924                // including the marker, keeping the top value.
6925                let top = self.pop();
6926                loop {
6927                    match self.pop() {
6928                        Value::CatchOffset(_) | Value::Undefined => break,
6929                        _ => {}
6930                    }
6931                    if self.frame().stack.is_empty() {
6932                        break;
6933                    }
6934                }
6935                self.push(top);
6936            }
6937            Throw => {
6938                let value = self.pop();
6939                return Err(Signal::Throw(value));
6940            }
6941            ThrowError => {
6942                let name = self.atom_text(a as usize);
6943                let (class, message) = match b {
6944                    0 => ("TypeError", format!("'{name}' is read-only")),
6945                    1 => ("SyntaxError", format!("redeclaration of '{name}'")),
6946                    2 => ("ReferenceError", format!("'{name}' is not initialized")),
6947                    // `delete super.x` is a syntax-level mistake the reference reports
6948                    // with this wording, not a property-access failure.
6949                    3 => (
6950                        "ReferenceError",
6951                        "unsupported reference to 'super'".to_string(),
6952                    ),
6953                    4 => (
6954                        "TypeError",
6955                        "iterator does not have a throw method".to_string(),
6956                    ),
6957                    5 => (
6958                        "ReferenceError",
6959                        "invalid assignment left-hand side".to_string(),
6960                    ),
6961                    _ => ("TypeError", format!("invalid operation on '{name}'")),
6962                };
6963                return Err(Signal::Throw(self.make_error(class, &message)));
6964            }
6965            InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
6966            Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
6967            YieldStar | AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
6968            Await => return Ok(Step::Suspend(SuspendKind::Await)),
6969            ReturnAsync => {
6970                // The reference's `return_async` returns `undefined` and lets the resume
6971                // machinery pick the real value off `sp[-1]`, which is how it tells a
6972                // completion from a suspension. Carrying the value explicitly says the
6973                // same thing without the implicit stack slot.
6974                let value = self.pop();
6975                return Ok(Step::Return(value));
6976            }
6977            Return => {
6978                let value = self.pop();
6979                return Ok(Step::Return(value));
6980            }
6981            ReturnUndef => return Ok(Step::Return(Value::Undefined)),
6982
6983            // -- calls ------------------------------------------------------
6984            Call | Call0 | Call1 | Call2 | Call3 => {
6985                let argc = self.argc_operand(op, a);
6986                let args = self.pop_n(argc);
6987                let callee = self.pop();
6988                // A plain call has no receiver; the callee decides what to do with
6989                // `undefined` (a sloppy function substitutes the global object).
6990                if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
6991                    self.push(result);
6992                }
6993            }
6994            CallConstructor => {
6995                // `constructor this_obj args… -> object`. The duplicated
6996                // constructor is `new.target`; this milestone does not expose it,
6997                // so the extra copy is simply consumed here.
6998                let argc = a as usize;
6999                let args = self.pop_n(argc);
7000                let new_target = self.pop();
7001                let callee = self.pop();
7002                let result = self.construct(callee, new_target, args)?;
7003                self.push(result);
7004            }
7005            CallMethod => {
7006                let argc = a as usize;
7007                let args = self.pop_n(argc);
7008                let callee = self.pop();
7009                let this = self.pop();
7010                if let Some(result) = self.call_or_push(callee, this, args)? {
7011                    self.push(result);
7012                }
7013            }
7014            Apply => {
7015                // `func this array -> result`, the spread-call form: the compiler
7016                // builds one array of arguments, and all that is left here is to
7017                // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
7018                let array = self.pop();
7019                let this = self.pop();
7020                let callee = self.pop();
7021                let args = self.array_like_to_args(&array)?;
7022                if a & 1 != 0 {
7023                    let result = self.construct(callee, this, args)?;
7024                    self.push(result);
7025                } else if let Some(result) = self.call_or_push(callee, this, args)? {
7026                    self.push(result);
7027                }
7028            }
7029            TailCall | TailCallMethod => {
7030                // `tail_call` is `call` whose result is returned immediately — the
7031                // reference jumps straight to `done` instead of storing the value and
7032                // running on. The callee still gets its own frame, so deep tail
7033                // recursion hits the stack limit exactly like plain recursion does;
7034                // marking this frame lets the return path unwind without needing
7035                // instructions after the call.
7036                let argc = if op == TailCallMethod {
7037                    a as usize
7038                } else {
7039                    self.argc_operand(op, a)
7040                };
7041                let args = self.pop_n(argc);
7042                let callee = self.pop();
7043                let this = if op == TailCallMethod {
7044                    self.pop()
7045                } else {
7046                    Value::Undefined
7047                };
7048                if let Value::Object(function) = &callee
7049                    && let Some((code, env)) = bytecode_of(function)
7050                {
7051                    // A generator or async body is not run here at all: calling it only
7052                    // *creates* the generator/coroutine, so it must not inherit this
7053                    // frame. Doing so made `function f(){ return g() }` push `g`'s body
7054                    // onto `f`'s frame, and the first `yield`/`await` then reported
7055                    // "a generator body ran as an ordinary call".
7056                    if code.code.kind.is_generator() || code.code.kind.is_async() {
7057                        let value = self.call_value(callee, this, args)?;
7058                        return Ok(Step::Return(value));
7059                    }
7060                    self.frame_mut().tail = true;
7061                    self.push_frame(code, env, this, args, callee)?;
7062                    return Ok(Step::Continue);
7063                }
7064                // A native callee has no frame to reuse, so its value is simply
7065                // returned.
7066                let value = self.call_value(callee, this, args)?;
7067                return Ok(Step::Return(value));
7068            }
7069
7070            // -- objects ----------------------------------------------------
7071            SpecialObject => {
7072                let value = self.special_object(a)?;
7073                self.push(value);
7074            }
7075            GetLength => {
7076                // `get_length` is the `.length` read; an array and a string answer
7077                // from their own length, anything else from the property.
7078                let target = self.pop();
7079                let value = match &target {
7080                    Value::Object(object) => match object.array_length() {
7081                        Some(length) => crate::object::length_value(length),
7082                        None => self.read_field(&target, "length")?,
7083                    },
7084                    Value::String(text) => Value::Int(text.utf16_len() as i32),
7085                    _ => self.read_field(&target, "length")?,
7086                };
7087                self.push(value);
7088            }
7089            GetField | GetField2 => {
7090                let object = self.pop();
7091                let key = self.atom_text(a as usize);
7092                let value = self.read_field(&object, &key)?;
7093                if op == GetField2 {
7094                    self.push(object);
7095                }
7096                self.push(value);
7097            }
7098            GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
7099                let key = self.pop();
7100                let object = self.pop();
7101                let key = self.propkey(&key)?;
7102                let value = self.read_field_key(&object, &key)?;
7103                if matches!(op, GetArrayEl2 | GetArrayEl3) {
7104                    self.push(object);
7105                }
7106                if op == GetArrayEl3 {
7107                    // The key goes back in its *value* form, which the compiler stores
7108                    // into the target of a destructuring assignment.
7109                    self.push(match &key {
7110                        PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
7111                        PropertyKey::String(text) => self.string_wtf8(text.clone()),
7112                    });
7113                }
7114                self.push(value);
7115            }
7116            PutField => {
7117                let value = self.pop();
7118                let object = self.pop();
7119                let key = self.atom_text(a as usize);
7120                self.write_field(&object, &key, value)?;
7121            }
7122            PutArrayEl => {
7123                let value = self.pop();
7124                let key = self.pop();
7125                let object = self.pop();
7126                let key = self.propkey(&key)?;
7127                self.write_field_key(&object, &key, value)?;
7128            }
7129            DefineField => {
7130                let value = self.pop();
7131                let object = self.pop();
7132                let key = self.atom_text(a as usize);
7133                // `{m: function(){}}` names the function `m`, the same way assigning
7134                // it to a property does. Without this the frame is anonymous and a
7135                // stack trace reads `at  (file:1:2)`.
7136                self.set_function_name(&value, &key);
7137                if let Some(target) = object.as_object() {
7138                    // Only an *array* stores into the element vector. A numeric key
7139                    // on an ordinary object is an ordinary property, which is what
7140                    // makes `{1: 'a'}` iterate as a key rather than disappear.
7141                    let stored = target.is_array()
7142                        && array_index(&key)
7143                            .is_some_and(|index| target.array_set(index as usize, value.clone()));
7144                    if !stored {
7145                        target.define_data(&key, value);
7146                    }
7147                }
7148                self.push(object);
7149            }
7150            DefineArrayEl => {
7151                // `obj key value -> obj key`. The *value* form of the key is what goes
7152                // back on the stack — the compiler stores it into the pattern's binding —
7153                // so the symbol is not stringified on the way through.
7154                let value = self.pop();
7155                let key_value = self.pop();
7156                let object = self.peek(0);
7157                let key = self.propkey(&key_value)?;
7158                self.write_field_key(&object, &key, value)?;
7159                self.push(key_value);
7160            }
7161            SetHomeObject => {
7162                // `obj func -> obj func`: records the object a method was defined on so
7163                // `super` inside it resolves against that object's prototype.
7164                let function = self.peek(0);
7165                let home = self.peek(1);
7166                if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
7167                    function.set_home_object(Some(home.clone()));
7168                }
7169            }
7170            Regexp => {
7171                // `pattern flags -> regexp`. A literal compiles here rather than through the
7172                // constructor, which is both what the reference's dedicated opcode is for
7173                // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
7174                let flags = self.pop();
7175                let pattern = self.pop();
7176                let pattern = self.to_js_string(&pattern)?;
7177                let flags = self.to_js_string(&flags)?;
7178                let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
7179                self.push(Value::Object(object));
7180            }
7181            UsingDisposeInit => {
7182                // The error state a disposal accumulates into. Uninitialised means "no
7183                // failure yet"; anything else is the exception being propagated.
7184                self.push(Value::Uninitialized);
7185            }
7186            UsingCheck => {
7187                // `value -> value, method`: validate and snapshot the disposer now, so a
7188                // later change to `Symbol.dispose` cannot change what gets called, and so a
7189                // value that is not disposable fails before the body runs.
7190                let value = self.pop();
7191                let method = self.using_method_for(&value, a as u8 == 1)?;
7192                self.push(value);
7193                self.push(method);
7194            }
7195            UsingDispose => {
7196                // `error_state -> error_state'`: dispose the variable at `slot` — its value
7197                // is `slot`, its snapshotted method `slot + 1` — folding any failure into
7198                // the pending error.
7199                let slot = self.slot_operand(op, a);
7200                let error_state = self.pop();
7201                let merged = self.using_dispose_once(slot, error_state)?;
7202                self.push(merged);
7203            }
7204            UsingDisposeMerge => {
7205                let new_error = self.pop();
7206                let error_state = self.pop();
7207                let merged = self.merge_dispose_error(new_error, error_state);
7208                self.push(merged);
7209            }
7210            UsingDisposeEnd => {
7211                // A disposal that failed replaces the block's normal completion, so the
7212                // error state becomes a real throw here rather than at the call site.
7213                let error_state = self.pop();
7214                if !matches!(error_state, Value::Uninitialized) {
7215                    return Err(Signal::Throw(error_state));
7216                }
7217            }
7218            UsingDisposeAsync => {
7219                // `await using` needs a promise to await and this runtime has no
7220                // `Promise` builtin, so the disposer is called synchronously and its result
7221                // discarded. That is correct for a disposer that returns nothing and is
7222                // reported as a gap rather than silently skipped.
7223                let slot = self.slot_operand(op, a);
7224                let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
7225                self.push(error_state);
7226            }
7227            GetSuper => {
7228                // `obj -> obj's prototype`: the starting point of a `super` lookup.
7229                let object = self.pop();
7230                let proto = match &object {
7231                    Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
7232                    _ => Value::Null,
7233                };
7234                self.push(proto);
7235            }
7236            GetSuperValue => {
7237                // `receiver proto key -> value`, searching from `proto` but reporting to
7238                // `receiver`, which is what `super.g` must do for a getter to see `this`.
7239                //
7240                // Three values in, one out: the receiver is *consumed*, not left under the
7241                // result. Leaving it there was invisible for `super.x` in `return` or
7242                // statement position (the result is what gets popped) and corrupted the
7243                // frame everywhere else — `print(super.x)` left the class where the call
7244                // opcode looks for the receiver and called the class itself.
7245                let key = self.pop();
7246                let proto = self.pop();
7247                let receiver = self.pop();
7248                let value = self.super_read(&receiver, &proto, &key)?;
7249                self.push(value);
7250            }
7251            PutSuperValue => {
7252                // `receiver proto key value ->`: a store that starts at `proto` but
7253                // assigns to `receiver`.
7254                let value = self.pop();
7255                let key = self.pop();
7256                let proto = self.pop();
7257                let receiver = self.pop();
7258                self.super_write(&receiver, &proto, &key, value)?;
7259            }
7260            DefineClass => {
7261                // `parent ctor -> ctor proto`: the constructor becomes the class and a
7262                // fresh prototype object lands on top for the methods to go on.
7263                let name = self.atom_text(a as usize);
7264                let (ctor, proto) = self.define_class(&name, b)?;
7265                self.push(ctor);
7266                self.push(Value::Object(proto));
7267            }
7268            DefineClassComputed => {
7269                // `parent ctor key -> ctor proto key`: the computed name stays put so
7270                // `define_field`-style consumers can still read it.
7271                let key = self.pop();
7272                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
7273                let (ctor, proto) = self.define_class(&name, b)?;
7274                self.push(ctor);
7275                self.push(Value::Object(proto));
7276                self.push(key);
7277            }
7278            DefineMethod => {
7279                let function = self.pop();
7280                let object = self.pop();
7281                let key = self.atom_text(a as usize);
7282                // A method's `[[HomeObject]]` is the object it was defined on, which is
7283                // what `super` inside it resolves against.
7284                if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
7285                    function.set_home_object(Some(object.clone()));
7286                }
7287                self.set_function_name(&function, &key_with_accessor_prefix(&key, b));
7288                if let Some(array) = object.as_object() {
7289                    define_function_property(array, &PropertyKey::from(key.as_str()), function, b);
7290                }
7291                self.push(object);
7292            }
7293            DefineMethodComputed => {
7294                let function = self.pop();
7295                let key = self.pop();
7296                let object = self.pop();
7297                let key = self.propkey(&key)?;
7298                self.set_function_name(&function, &key_with_accessor_prefix(&key.to_string(), a));
7299                if let Some(array) = object.as_object() {
7300                    define_function_property(array, &key, function, a);
7301                }
7302                self.push(object);
7303            }
7304            SetProto => {
7305                let proto = self.pop();
7306                let object = self.pop();
7307                if let Some(target) = object.as_object() {
7308                    target.set_proto(proto.as_object().cloned());
7309                }
7310                self.push(object);
7311            }
7312            CopyDataProperties => {
7313                let exclusion = self.pop();
7314                let source = self.pop();
7315                let target = self.peek(0);
7316                self.copy_properties(&target, &source, &exclusion)?;
7317                self.push(source);
7318                self.push(exclusion);
7319            }
7320            ToPropkey => {
7321                // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
7322                // and stringifying here would turn `{[Symbol("b")]: 2}` into an
7323                // ordinary `"Symbol(b)"` property.
7324                let value = self.pop();
7325                let key = match self.propkey(&value)? {
7326                    PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
7327                    PropertyKey::String(text) => self.string_wtf8(text),
7328                };
7329                self.push(key);
7330            }
7331            SetName => {
7332                let function = self.peek(0);
7333                let name = self.atom_text(a as usize);
7334                self.set_function_name(&function, &name);
7335            }
7336            SetNameComputed => {
7337                let key = self.peek(1);
7338                let function = self.peek(0);
7339                let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
7340                self.set_function_name(&function, &name);
7341            }
7342
7343            // -- arrays -----------------------------------------------------
7344            ArrayFrom => {
7345                let count = a as usize;
7346                let elements = self.pop_n(count);
7347                let array = self.new_array(elements);
7348                self.push(Value::Object(array));
7349            }
7350            Append => {
7351                // `array index iterable -> array new_index`
7352                let iterable = self.pop();
7353                self.pop();
7354                let array = self.peek(0);
7355                let added = self.append_enumerate(&array, &iterable)?;
7356                self.push(Value::Int(added));
7357            }
7358
7359            // -- iteration --------------------------------------------------
7360            ForInStart => {
7361                let value = self.pop();
7362                let record = self.for_in_record(&value)?;
7363                self.push(Value::Object(record));
7364            }
7365            ForInNext => {
7366                // `record -> record key done`. The flag is *done*, not "found":
7367                // the compiler tests it with `if_false` to jump back into the body,
7368                // so reporting `true` while keys remain would end the loop at once.
7369                let record = self.peek(0);
7370                match self.for_in_advance(&record)? {
7371                    Some(key) => {
7372                        let text = self.string(key);
7373                        self.push(text);
7374                        self.push(Value::Bool(false));
7375                    }
7376                    None => {
7377                        self.push(Value::Undefined);
7378                        self.push(Value::Bool(true));
7379                    }
7380                }
7381            }
7382            ForOfStart => {
7383                let value = self.pop();
7384                let iterator = self.get_iterator(&value)?;
7385                self.push(iterator.object);
7386                self.push(iterator.next);
7387                self.push(Value::CatchOffset(0));
7388            }
7389            ForOfNext => {
7390                // `iter next catch_offset -> iter next catch_offset value done`.
7391                //
7392                // The operand is how many values sit *above* the iterator triple: a
7393                // destructuring rest element keeps its target array and running index
7394                // there while draining the iterator, so the triple is not at the top.
7395                let extra = a as usize;
7396                let iterator_slot = 2 + extra;
7397                // An exhausted iterator is replaced by `undefined` (see below), so a
7398                // second step must not call `next` again — `Array.from` and a
7399                // destructuring pattern both keep stepping past the end.
7400                let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
7401                    (Value::Undefined, true)
7402                } else {
7403                    let iterator = Iterator {
7404                        object: self.peek(iterator_slot),
7405                        next: self.peek(1 + extra),
7406                    };
7407                    self.iterator_step(&iterator)?
7408                };
7409                if done {
7410                    // The result's `value` is meaningless once the iterator is done:
7411                    // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
7412                    // rather than binding the generator's return value.
7413                    let top = self.frame().stack.len() - 1 - iterator_slot;
7414                    self.frame_mut().stack[top] = Value::Undefined;
7415                    self.push(Value::Undefined);
7416                    self.push(Value::Bool(true));
7417                } else {
7418                    self.push(value);
7419                    self.push(Value::Bool(false));
7420                }
7421            }
7422            IteratorNext => {
7423                // `iter next catch val -> iter next catch val'`: replace the argument with
7424                // the result of `next(val)`. The triple below stays put, which is why the
7425                // three instructions of the `yield*` loop all address the stack the same way.
7426                let value = self.pop();
7427                let object = self.peek(2);
7428                let next = self.peek(1);
7429                let result = self.call_value(next, object, vec![value])?;
7430                self.push(result);
7431            }
7432            IteratorCall => {
7433                // `iter next catch val -> iter next catch val' flag`.
7434                //
7435                // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
7436                // The flag is `true` when the method was missing, which is how the
7437                // caller learns that the inner iterator cannot take part in the
7438                // unwinding.
7439                let value = self.pop();
7440                let object = self.peek(2);
7441                let key = if a & 1 != 0 { "throw" } else { "return" };
7442                let method = self.read_field(&object, key)?;
7443                if matches!(method, Value::Undefined | Value::Null) {
7444                    self.push(value);
7445                    self.push(Value::Bool(true));
7446                } else {
7447                    let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
7448                    let result = self.call_value(method, object, argument)?;
7449                    self.push(result);
7450                    self.push(Value::Bool(false));
7451                }
7452            }
7453            IteratorCheckObject => {
7454                if !matches!(self.peek(0), Value::Object(_)) {
7455                    return Err(Signal::Throw(
7456                        self.make_error("TypeError", "iterator must return an object"),
7457                    ));
7458                }
7459            }
7460            IteratorClose => {
7461                // `iter next catch_offset ->`
7462                self.pop();
7463                self.pop();
7464                self.pop();
7465            }
7466            Import => {
7467                // `import(specifier)`: the options slot is on top and is not read yet.
7468                let _options = self.pop();
7469                let specifier = self.pop();
7470                let promise = self.dynamic_import(specifier)?;
7471                self.push(promise);
7472            }
7473            ForAwaitOfStart => {
7474                // Same triple as `for of`, but from `Symbol.asyncIterator` with a
7475                // `Symbol.iterator` fallback.
7476                let value = self.pop();
7477                let iterator = self.get_async_iterator(&value)?;
7478                self.push(iterator.object);
7479                self.push(iterator.next);
7480                self.push(Value::CatchOffset(0));
7481            }
7482            ForAwaitOfNext => {
7483                // `for await` steps the iterator and leaves the *result* wrapped in a
7484                // promise, so the `await` the compiler emits right after this can suspend
7485                // on it. Unwrapping happens in `iterator_get_value_done`.
7486                let extra = a as usize;
7487                let iterator_slot = 2 + extra;
7488                let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
7489                    Value::Undefined
7490                } else {
7491                    let iterator = Iterator {
7492                        object: self.peek(iterator_slot),
7493                        next: self.peek(1 + extra),
7494                    };
7495                    let next = iterator.next.clone();
7496                    self.call_value(next, iterator.object, Vec::new())?
7497                };
7498                let promise = self.promise_resolve_value(result)?;
7499                self.push(promise);
7500            }
7501            IteratorGetValueDone => {
7502                // `result -> value done`. A missing result object means the iterator was
7503                // already exhausted, which the loop treats as `done`.
7504                let result = self.pop();
7505                let Value::Object(object) = &result else {
7506                    self.push(Value::Undefined);
7507                    self.push(Value::Bool(true));
7508                    return Ok(Step::Continue);
7509                };
7510                let done = self
7511                    .get_property(object, "done")?
7512                    .is_some_and(|value| value.to_boolean());
7513                if done {
7514                    self.push(Value::Undefined);
7515                    self.push(Value::Bool(true));
7516                } else {
7517                    let value = self
7518                        .get_property(object, "value")?
7519                        .unwrap_or(Value::Undefined);
7520                    self.push(value);
7521                    self.push(Value::Bool(false));
7522                }
7523            }
7524
7525            Delete => {
7526                // `delete obj[key]`, where the key was just pushed. Deleting an array
7527                // index leaves a *hole* rather than closing the gap, and a
7528                // non-configurable property answers `false` and stays.
7529                let key = self.pop();
7530                let target = self.pop();
7531                let key = self.propkey(&key)?;
7532                let text_label = key.as_str().unwrap_or("").to_string();
7533                let deleted = match &target {
7534                    Value::Object(object) => {
7535                        let object = object.clone();
7536                        self.delete_property_key(&object, &key)?
7537                    }
7538                    // A string's `length` and its index properties are
7539                    // non-configurable, so deleting one answers `false`.
7540                    Value::String(text) => {
7541                        !(text_label == "length"
7542                            || array_index(&text_label)
7543                                .is_some_and(|index| (index as usize) < text.utf16_len()))
7544                    }
7545                    // "delete null.a" is a TypeError, not a no-op: the operator needs an
7546                    // object to delete from, and only a *boxable* primitive has one.
7547                    Value::Undefined | Value::Null => {
7548                        return Err(Signal::Throw(
7549                            self.make_error("TypeError", "cannot convert to object"),
7550                        ));
7551                    }
7552                    // Any other primitive has no own properties; deleting nothing
7553                    // succeeds.
7554                    _ => true,
7555                };
7556                self.push(Value::Bool(deleted));
7557            }
7558
7559            // -- exceptions and bookkeeping ---------------------------------
7560            Fclosure | Fclosure8 => {
7561                let value = self.closure(a as usize)?;
7562                self.push(value);
7563            }
7564
7565            other => {
7566                let name = other.info().name;
7567                return Err(Signal::Throw(self.make_error(
7568                    "InternalError",
7569                    &format!("{name} is not implemented yet"),
7570                )));
7571            }
7572        }
7573        Ok(Step::Continue)
7574    }
7575
7576    // -- operand helpers ----------------------------------------------------
7577
7578    /// The slot index an operand names, taking short forms into account.
7579    fn slot_operand(&self, op: Opcode, a: u32) -> usize {
7580        use Opcode::*;
7581        match op {
7582            GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
7583            | SetVarRef0 => 0,
7584            GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
7585            | SetVarRef1 => 1,
7586            GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
7587            | SetVarRef2 => 2,
7588            GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
7589            | SetVarRef3 => 3,
7590            _ => a as usize,
7591        }
7592    }
7593
7594    /// The argument count of a call, taking `call0`…`call3` into account.
7595    fn argc_operand(&self, op: Opcode, a: u32) -> usize {
7596        use Opcode::*;
7597        match op {
7598            Call0 => 0,
7599            Call1 => 1,
7600            Call2 => 2,
7601            Call3 => 3,
7602            _ => a as usize,
7603        }
7604    }
7605
7606    fn atom_text(&self, index: usize) -> String {
7607        self.frame()
7608            .code
7609            .code
7610            .atoms
7611            .get(index)
7612            .map(|atom| match atom {
7613                Atom::Str(text) => text.clone(),
7614                Atom::Index(value) => value.to_string(),
7615            })
7616            .unwrap_or_default()
7617    }
7618
7619    fn constant(&mut self, index: usize) -> JsResult<Value> {
7620        let constant = self.frame().code.code.cpool.get(index).cloned();
7621        Ok(match &constant {
7622            Some(Constant::Number(number)) => Value::Float(*number),
7623            Some(Constant::String(text)) => self.string(text.clone()),
7624            Some(Constant::BigInt { digits, radix }) => {
7625                match crate::bigint::BigInt::from_radix(digits, *radix) {
7626                    Some(big) => self.bigint(big),
7627                    // A literal the parser accepted is always parseable; a failure here
7628                    // would be a compiler bug, so it reads as an `InternalError`.
7629                    None => {
7630                        return Err(Signal::Throw(
7631                            self.make_error("InternalError", "unparseable bigint literal"),
7632                        ));
7633                    }
7634                }
7635            }
7636            Some(Constant::Function(_)) => {
7637                return Err(Signal::Throw(
7638                    self.make_error("InternalError", "a bare function constant"),
7639                ));
7640            }
7641            // A tagged template's call site: a frozen array of the cooked chunks with a
7642            // frozen `raw` array beside it, which is what `String.raw` reads back.
7643            Some(Constant::Template { cooked, raw }) => {
7644                let cooked_values: Vec<Value> = cooked
7645                    .iter()
7646                    .map(|chunk| match chunk {
7647                        Some(text) => self.string(text.clone()),
7648                        None => Value::Undefined,
7649                    })
7650                    .collect();
7651                let raw_values: Vec<Value> =
7652                    raw.iter().map(|text| self.string(text.clone())).collect();
7653                let raw_array = self.new_array(raw_values);
7654                raw_array.set_extensible(false);
7655                let template = self.new_array(cooked_values);
7656                template.define(
7657                    "raw",
7658                    Property::with_attributes(Value::Object(raw_array), false, false),
7659                );
7660                template.set_extensible(false);
7661                Value::Object(template)
7662            }
7663            _ => Value::Undefined,
7664        })
7665    }
7666
7667    /// The reference cell a closure-variable slot names.
7668    ///
7669    /// Two kinds of binding share this addressing: a genuine closure variable
7670    /// (captured from an enclosing function) lives in this frame's environment,
7671    /// while a *declared global* lives in the realm so that a script, a function
7672    /// declaration and their uses all see one binding. A plain `Global` — an
7673    /// undeclared name that may be satisfied by the global object — has no cell at
7674    /// all, which is how `typeof x` still works for a name that does not exist.
7675    /// The reference cell a closure-variable slot names.
7676    ///
7677    /// The environment is resolved once, when the closure is built, and this is
7678    /// just the lookup afterwards. A *declared global* is in there too, pointing at
7679    /// the realm's cell, so a script, a hoisted function declaration and their uses
7680    /// all share one binding. A plain `Global` — a name the script never declared —
7681    /// is read and written through `get_var`/`put_var` by name instead, which is
7682    /// what lets the global object satisfy it.
7683    fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
7684        self.frame().env.cells.get(slot).cloned()
7685    }
7686
7687    /// Whether `slot` refers to a global binding through the reference table.
7688    ///
7689    /// A global's cell in the closure environment only exists so the slot has
7690    /// something to point at; the binding itself lives on the global object (a `var`)
7691    /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
7692    /// be routed, not performed on the placeholder.
7693    fn is_global_slot(&self, slot: usize) -> bool {
7694        self.frame()
7695            .code
7696            .code
7697            .closure_vars
7698            .get(slot)
7699            .is_some_and(|c| {
7700                // A module's declarations and imports are *not* globals: their cells are
7701                // the module environment's, filled by the host, so the placeholder routing
7702                // must not apply to them.
7703                matches!(
7704                    c.closure_type,
7705                    ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
7706                )
7707            })
7708    }
7709
7710    fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
7711        if self.is_global_slot(slot) {
7712            return self.get_global(slot);
7713        }
7714        Ok(self
7715            .var_ref_cell(slot)
7716            .map(|cell| cell.get())
7717            .unwrap_or(Value::Undefined))
7718    }
7719
7720    fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
7721        // A function declaration is hoisted by storing into a global reference before
7722        // the body runs, so this path is also what puts it on the global object.
7723        if self.is_global_slot(slot) {
7724            return self.put_global(slot, value);
7725        }
7726        if let Some(cell) = self.var_ref_cell(slot) {
7727            cell.set(value);
7728        }
7729        Ok(())
7730    }
7731
7732    // -- closures -----------------------------------------------------------
7733
7734    /// Build the closure for the function constant `index`.
7735    ///
7736    /// Every entry in the child's closure table names where its binding lives in
7737    /// *this* frame: a local or argument slot that was marked captured, or a cell
7738    /// this frame is itself holding. That is how a variable three functions deep
7739    /// stays one binding.
7740    fn closure(&mut self, index: usize) -> JsResult<Value> {
7741        let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
7742        else {
7743            return Err(Signal::Throw(
7744                self.make_error("InternalError", "fclosure of a non-function"),
7745            ));
7746        };
7747        let mut cells = Vec::with_capacity(function.closure_vars.len());
7748        for closure_var in &function.closure_vars {
7749            let cell = match closure_var.closure_type {
7750                ClosureType::Arg => {
7751                    let slot = closure_var.var_idx as usize;
7752                    self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
7753                }
7754                ClosureType::Local => {
7755                    let slot = closure_var.var_idx as usize;
7756                    self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
7757                }
7758                ClosureType::Ref | ClosureType::GlobalRef => {
7759                    // A `Ref` names a cell in this frame's own closure table; a
7760                    // `GlobalRef` also starts there, then resolves by name below.
7761                    let slot = closure_var.var_idx as usize;
7762                    if let Some(cell) = self.frame().env.cells.get(slot) {
7763                        cells.push(cell.clone());
7764                        continue;
7765                    }
7766                    -1
7767                }
7768                _ => -1,
7769            };
7770            if cell >= 0 {
7771                let cell = self.frame().cells[cell as usize].clone();
7772                cells.push(cell);
7773                continue;
7774            }
7775            // A global: the cell is created on demand and shared through the realm,
7776            // so every function sees one binding.
7777            let name = closure_var.name.clone();
7778            let cell = match self.realm.globals.get(&name) {
7779                Some(cell) => cell.clone(),
7780                None => {
7781                    let cell = self.new_cell(Value::Undefined);
7782                    self.realm.globals.insert(name.clone(), cell.clone());
7783                    cell
7784                }
7785            };
7786            cells.push(cell);
7787        }
7788        let name = function.name.clone();
7789        // `.length` is the arity before any default or rest parameter, not the number
7790        // of slots a pattern parameter needs.
7791        let length = function.defined_args;
7792        // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
7793        // function and an arrow function do not. A *method* also does not, but that is not
7794        // known here — the method is marked when the `[[HomeObject]]` is attached (see
7795        // `set_home_object`), which is the moment it becomes a method.
7796        let function_kind = function.kind;
7797        let constructible =
7798            !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
7799        let code = Gc::new(self.heap, CompiledCode::new(*function));
7800        // A closure built inside an `eval` inherits the eval's view of the enclosing
7801        // bindings, so it can still read them once the eval has returned.
7802        let eval_scope = self
7803            .active_eval_scope
7804            .clone()
7805            .or_else(|| self.frame().env.eval_scope.clone());
7806        // A closure sees the variables a direct `eval` declared in the frame it was
7807        // created in — the ones declared before *and after* it, so the same object is
7808        // shared; only the phase bounds which of them are visible.
7809        let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
7810        let local_phase = if self.in_parameter_list() { 0 } else { 1 };
7811        let env = Gc::new(
7812            self.heap,
7813            ClosureEnv {
7814                cells,
7815                eval_scope,
7816                local_vars,
7817                local_phase,
7818            },
7819        );
7820        // A generator or async function inherits from `%GeneratorFunction.prototype%` or
7821        // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
7822        // the only thing that carries `Symbol.toStringTag`, so without it
7823        // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
7824        // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
7825        let proto = match function_kind {
7826            js_compile::bytecode::FunctionKind::AsyncGenerator => self
7827                .realm
7828                .async_generator_function_proto
7829                .clone()
7830                .or_else(|| self.realm.function_proto.clone().into()),
7831            js_compile::bytecode::FunctionKind::Generator => self
7832                .realm
7833                .generator_function_proto
7834                .clone()
7835                .or_else(|| self.realm.function_proto.clone().into()),
7836            js_compile::bytecode::FunctionKind::Async => self
7837                .realm
7838                .async_function_proto
7839                .clone()
7840                .or_else(|| self.realm.function_proto.clone().into()),
7841            js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
7842        };
7843        let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
7844        object.set_constructible(constructible);
7845        object.define(
7846            "length",
7847            Property::name_or_length(Value::Int(length as i32)),
7848        );
7849        // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
7850        // that checks the own-property descriptor fails if the property is missing.
7851        object.define("name", Property::name_or_length(self.string(name)));
7852        // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
7853        // when `[[Construct]]` is created, so a generator, an async function and an arrow
7854        // function have none of their own. Installing it unconditionally gave
7855        // `Array.fromAsync` (an async function) an own `prototype` property, which
7856        // `builtin.js` checks for absence.
7857        if constructible {
7858            self.install_function_prototype(&object);
7859        }
7860        Ok(Value::Object(object))
7861    }
7862
7863    // -- conversions used by the operators ----------------------------------
7864
7865    fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
7866        // `+x` is `ToNumber`, which for a string parses it and for an object runs
7867        // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
7868        // string, which then behaves differently in every later comparison.
7869        match value {
7870            Value::Int(_) | Value::Float(_) => Ok(value),
7871            other => Ok(Value::Float(self.to_js_number(&other)?)),
7872        }
7873    }
7874
7875    /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
7876    ///
7877    /// Returns the *converted* old value and the new one, because the two callers need
7878    /// different halves: `++x` yields the new value, while `x++` yields the old one and
7879    /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
7880    /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
7881    /// boolean.
7882    ///
7883    /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
7884    /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
7885    /// a bigint algorithm then ran exactly once.
7886    fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
7887        if let Value::BigInt(big) = &value {
7888            let one = crate::bigint::BigInt::from_i64(1);
7889            let next = if up { big.add(&one) } else { big.sub(&one) };
7890            return Ok((value, self.bigint(next)));
7891        }
7892        let old = self.numeric(value)?;
7893        let new = if up {
7894            increment(old.clone())
7895        } else {
7896            decrement(old.clone())
7897        };
7898        Ok((old, new))
7899    }
7900
7901    fn numeric(&mut self, value: Value) -> JsResult<Value> {
7902        // `ToNumber` on an object runs `ToPrimitive` first, which is how
7903        // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
7904        // heard at all. Reading the object's own tag instead (`other.to_number()`)
7905        // turned the whole operand into `NaN` and swallowed the exception.
7906        match value {
7907            Value::Int(_) | Value::Float(_) => Ok(value),
7908            other => Ok(Value::Float(self.to_js_number(&other)?)),
7909        }
7910    }
7911
7912    /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
7913    fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
7914        match value {
7915            Value::BigInt(big) => Ok((**big).clone()),
7916            // The reference words this the same way for every operator, so a failing
7917            // script reads identically; the operator itself adds nothing a caller can use.
7918            _ => Err(Signal::Throw(
7919                self.make_error("TypeError", "cannot convert bigint to number"),
7920            )),
7921        }
7922    }
7923
7924    /// Arithmetic where at least one operand is a `BigInt`.
7925    ///
7926    /// The two numeric types never mix, so a bigint paired with anything else is an error
7927    /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
7928    /// that the relational operators handle it separately.
7929    fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
7930        use Opcode::*;
7931        let a = self.bigint_operand(&left)?;
7932        let b = self.bigint_operand(&right)?;
7933        let result = match op {
7934            Add => a.add(&b),
7935            Sub => a.sub(&b),
7936            Mul => a.mul(&b),
7937            Div | Mod => {
7938                let Some((quotient, remainder)) = a.div_rem(&b) else {
7939                    return Err(Signal::Throw(
7940                        self.make_error("RangeError", "division by zero"),
7941                    ));
7942                };
7943                if op == Div { quotient } else { remainder }
7944            }
7945            Pow => {
7946                let Some(value) = a.pow(&b) else {
7947                    return Err(Signal::Throw(self.make_error(
7948                        "RangeError",
7949                        "BigInt exponent must be non-negative and not absurdly large",
7950                    )));
7951                };
7952                value
7953            }
7954            And => a.bitand(&b),
7955            Or => a.bitor(&b),
7956            Xor => a.bitxor(&b),
7957            Shl | Sar => {
7958                // A shift count is a `BigInt` here, and both directions are exact; a
7959                // negative count would be the other direction, which the spec forbids.
7960                let Some(count) = b.to_i64() else {
7961                    return Err(Signal::Throw(
7962                        self.make_error("RangeError", "BigInt shift count is too large"),
7963                    ));
7964                };
7965                if count < 0 {
7966                    return Err(Signal::Throw(self.make_error(
7967                        "RangeError",
7968                        "BigInt shift count must be non-negative",
7969                    )));
7970                }
7971                if op == Shl {
7972                    a.shl(count as u64)
7973                } else {
7974                    a.shr(count as u64)
7975                }
7976            }
7977            // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
7978            _ => {
7979                return Err(Signal::Throw(self.make_error(
7980                    "TypeError",
7981                    "BigInts have no unsigned right shift, use >> instead",
7982                )));
7983            }
7984        };
7985        Ok(self.bigint(result))
7986    }
7987
7988    /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
7989    ///
7990    /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
7991    /// is on the mathematical values, and nothing is rounded first.
7992    fn relational(&mut self, op: Opcode, left: Value, right: Value) -> Value {
7993        use Opcode::*;
7994        let ordering = match (&left, &right) {
7995            (Value::String(a), Value::String(b)) => {
7996                Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
7997            }
7998            (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
7999            // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
8000            // is true even though `2.5` has no bigint form.
8001            (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
8002                let b = other.to_number();
8003                if b.is_nan() {
8004                    None
8005                } else {
8006                    compare_bigint_and_f64(a, b)
8007                }
8008            }
8009            (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
8010                let a = other.to_number();
8011                if a.is_nan() {
8012                    None
8013                } else {
8014                    compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
8015                }
8016            }
8017            _ => left.to_number().partial_cmp(&right.to_number()),
8018        };
8019        let _ = self;
8020        let answer = match (op, ordering) {
8021            (_, None) => false,
8022            (Lt, Some(ordering)) => ordering.is_lt(),
8023            (Lte, Some(ordering)) => ordering.is_le(),
8024            (Gt, Some(ordering)) => ordering.is_gt(),
8025            (Gte, Some(ordering)) => ordering.is_ge(),
8026            _ => false,
8027        };
8028        Value::Bool(answer)
8029    }
8030
8031    fn binary_add(&mut self) -> JsResult<()> {
8032        let right = self.pop();
8033        let left = self.pop();
8034        let left = self.primitive_of(left)?;
8035        let right = self.primitive_of(right)?;
8036        // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
8037        // that check comes before the bigint one: `"" + 1n` is a string, not a
8038        // mixed-type error.
8039        if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
8040            // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
8041            // `TypeError`, the one place a symbol and a string do not mix.
8042            let left = self.checked_to_wtf8(&left)?;
8043            let right = self.checked_to_wtf8(&right)?;
8044            // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
8045            // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
8046            let text = left.concat(&right);
8047            self.push(self.string_wtf8(text));
8048            return Ok(());
8049        }
8050        // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
8051        // not a conversion.
8052        if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
8053            let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
8054            self.push(value);
8055            return Ok(());
8056        }
8057        let left = self.numeric(left)?;
8058        let right = self.numeric(right)?;
8059        self.push(add_numbers(left, right));
8060        Ok(())
8061    }
8062
8063    fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
8064        self.to_primitive(value, Hint::Default)
8065    }
8066
8067    /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
8068    ///
8069    /// The order depends on the hint: the "number" order tries `valueOf` first and
8070    /// `toString` second, the "string" order the other way round, and the default
8071    /// hint uses the number order. A result that is still an object is a `TypeError`,
8072    /// because no built-in `valueOf`/`toString` returns one.
8073    pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
8074        let Value::Object(object) = &value else {
8075            return Ok(value);
8076        };
8077        // A Date overrides the default hint to mean "string", which is what
8078        // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
8079        // this, `"" + new Date()` would print the milliseconds, not the date.
8080        let hint = if hint == Hint::Default && is_date_object(self, object) {
8081            Hint::String
8082        } else {
8083            hint
8084        };
8085        // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
8086        // handed the hint as a string. This is the hook a Date uses for its default hint
8087        // and a script uses to take over conversion entirely.
8088        let key = self.realm.well_known_key(WellKnown::ToPrimitive);
8089        if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
8090            if !function.is_callable() {
8091                return Err(self.type_error("Symbol.toPrimitive is not a function"));
8092            }
8093            let hint = match hint {
8094                Hint::String => "string",
8095                Hint::Number => "number",
8096                Hint::Default => "default",
8097            };
8098            let hint = self.string(hint);
8099            let result = self.call_value(
8100                Value::Object(function),
8101                Value::Object(object.clone()),
8102                vec![hint],
8103            )?;
8104            if matches!(result, Value::Object(_)) {
8105                return Err(self.type_error("cannot convert object to primitive value"));
8106            }
8107            return Ok(result);
8108        }
8109        let order: [&str; 2] = match hint {
8110            Hint::String => ["toString", "valueOf"],
8111            Hint::Number | Hint::Default => ["valueOf", "toString"],
8112        };
8113        let receiver = object.clone();
8114        for method in order {
8115            if let Some(function) = self.get_property(&receiver, method)?
8116                && matches!(&function, Value::Object(object) if object.is_callable())
8117            {
8118                let result =
8119                    self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
8120                if !matches!(result, Value::Object(_)) {
8121                    return Ok(result);
8122                }
8123            }
8124        }
8125        Err(self.type_error("cannot convert object to primitive value"))
8126    }
8127
8128    /// `ToString` with the object case going through `ToPrimitive`.
8129    pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
8130        if matches!(value, Value::Object(_)) {
8131            let primitive = self.to_primitive(value.clone(), Hint::String)?;
8132            return Ok(primitive.to_js_string());
8133        }
8134        Ok(value.to_js_string())
8135    }
8136
8137    /// `ToString` that keeps the string's code units instead of flattening them.
8138    ///
8139    /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
8140    /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
8141    pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
8142        if matches!(value, Value::Symbol(_)) {
8143            return Err(Signal::Throw(
8144                self.make_error("TypeError", "cannot convert symbol to string"),
8145            ));
8146        }
8147        // An object runs `ToPrimitive` first, which may itself produce a symbol.
8148        let value = self.to_primitive(value.clone(), Hint::String)?;
8149        match value {
8150            Value::Symbol(_) => Err(Signal::Throw(
8151                self.make_error("TypeError", "cannot convert symbol to string"),
8152            )),
8153            Value::String(text) => Ok(text.wtf8().clone()),
8154            other => Ok(crate::value::Wtf8::new(other.to_js_string())),
8155        }
8156    }
8157
8158    /// `ToNumber` with the object case going through `ToPrimitive`.
8159    pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
8160        let value = if matches!(value, Value::Object(_)) {
8161            self.to_primitive(value.clone(), Hint::Number)?
8162        } else {
8163            value.clone()
8164        };
8165        // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
8166        // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
8167        // `NaN` to stay total, and the operators check for the bigint themselves — but
8168        // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
8169        // refuse, and answering `NaN` made them silently wrong instead.
8170        // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
8171        // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
8172        match value {
8173            Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
8174            Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
8175            other => Ok(other.to_number()),
8176        }
8177    }
8178
8179    /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
8180    /// [`ElementType::write`].
8181    ///
8182    /// This is separated from the write because both conversions are observable script —
8183    /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
8184    /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
8185    /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
8186    /// setters, and a plain `a[i] = v`.
8187    pub(crate) fn element_value(
8188        &mut self,
8189        element: crate::builtins::typedarray::ElementType,
8190        value: Value,
8191    ) -> JsResult<Value> {
8192        // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
8193        // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
8194        let primitive = match &value {
8195            Value::Object(_) => self.to_primitive(value, Hint::Number)?,
8196            _ => value,
8197        };
8198        if element.is_bigint() {
8199            let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
8200            Ok(Value::BigInt(Gc::new(self.heap, big)))
8201        } else {
8202            // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
8203            Ok(Value::Float(self.to_js_number(&primitive)?))
8204        }
8205    }
8206
8207    /// `ToPropertyKey`: what a computed member access uses as its key.
8208    ///
8209    /// A symbol is returned as itself, never stringified — that is what keeps
8210    /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
8211    fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
8212        match value {
8213            Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
8214            // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
8215            // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
8216            // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
8217            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
8218                Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
8219                Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
8220                other => Ok(PropertyKey::String(crate::value::Wtf8::new(
8221                    other.to_js_string(),
8222                ))),
8223            },
8224            _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
8225        }
8226    }
8227
8228    /// `ToPropertyKey` for the callers that can only use a string key.
8229    ///
8230    /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
8231    /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
8232    /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
8233    /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
8234    /// program continues with a value nobody asked for.
8235    fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
8236        use crate::value::Wtf8;
8237        Ok(match value {
8238            // A string key keeps its code units. Going through a lossy `String` would make
8239            // `o["\uD800"]` and `o["\uFFFD"]` the same property.
8240            Value::String(text) => text.wtf8().clone(),
8241            Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
8242            // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
8243            // falling back to its `ToString` would print `[object Object]`.
8244            Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
8245                Value::String(text) => text.wtf8().clone(),
8246                other => Wtf8::new(other.to_js_string()),
8247            },
8248            other => Wtf8::new(other.to_js_string()),
8249        })
8250    }
8251
8252    // -- object operations used by instructions -----------------------------
8253
8254    /// Read `object[key]`, returning `undefined` when the property is missing.
8255    ///
8256    /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
8257    /// primitive (looking through its prototype) as well as an object — which is what
8258    /// `get_field`/`get_array_el` need and what a builtin reading a property off an
8259    /// argument needs too.
8260    pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
8261        self.read_field_key(object, &PropertyKey::from(key))
8262    }
8263
8264    /// [`Interp::read_field`] with a key that may be a symbol.
8265    ///
8266    /// A symbol key never reaches the string shortcuts: a string's `length` and its
8267    /// indices are string properties, and a symbol named `length` is a different
8268    /// property that a string primitive cannot have.
8269    pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
8270        let text = key.as_str().unwrap_or("");
8271        let Value::Object(object) = object else {
8272            // Reading a property of `undefined`/`null` is the classic TypeError.
8273            if object.is_nullish() {
8274                return Err(Signal::Throw(self.make_error(
8275                    "TypeError",
8276                    &format!("cannot read property '{key}' of {}", object.to_js_string()),
8277                )));
8278            }
8279            // A string has `length` and index access without being boxed.
8280            if let Value::String(value) = object {
8281                if text == "length" {
8282                    return Ok(Value::Int(value.utf16_len() as i32));
8283                }
8284                if let Some(index) = array_index(text) {
8285                    return Ok(match value.wtf8().unit_at(index as usize) {
8286                        Some(unit) => self.string_wtf8(unit),
8287                        None => Value::Undefined,
8288                    });
8289                }
8290            }
8291            // A property of a primitive is looked up on its prototype: this is what
8292            // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
8293            let prototype = match object {
8294                Value::String(_) => self.realm.string_proto.clone(),
8295                Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
8296                Value::Bool(_) => self.realm.boolean_proto.clone(),
8297                // A symbol's methods live on `Symbol.prototype`, reached the same way —
8298                // `sym.description` reads through the prototype, not off the symbol.
8299                Value::Symbol(_) => self.realm.symbol_proto.clone(),
8300                // …and a bigint's on `BigInt.prototype`, which is how
8301                // `(255n).toString(16)` reaches its method.
8302                Value::BigInt(_) => self.realm.bigint_proto.clone(),
8303                _ => None,
8304            };
8305            if let Some(prototype) = prototype
8306                && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
8307            {
8308                return Ok(value);
8309            }
8310            return Ok(Value::Undefined);
8311        };
8312        Ok(self
8313            .get_property_key(object, key)?
8314            .unwrap_or(Value::Undefined))
8315    }
8316
8317    fn write_field(&mut self, object: &Value, key: &str, value: Value) -> JsResult<()> {
8318        self.write_field_key(object, &PropertyKey::from(key), value)
8319    }
8320
8321    fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
8322        let Value::Object(object) = object else {
8323            return Err(Signal::Throw(self.make_error(
8324                "TypeError",
8325                &format!("cannot set property '{key}' of {}", object.to_js_string()),
8326            )));
8327        };
8328        // `put_field`/`put_array_el` are plain assignments, so the mode decides.
8329        let on_failure = if self.frame().code.code.strict {
8330            DeleteFailure::Throw
8331        } else {
8332            DeleteFailure::Ignore
8333        };
8334        self.set_property_with_key(object, key, value, on_failure)
8335    }
8336
8337    /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
8338    ///
8339    /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
8340    /// symbol. That is right for `String(sym)` and for error messages, and wrong for
8341    /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
8342    /// `Number.parseInt(sym)` — so those callers use this instead.
8343    pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
8344        if matches!(value, Value::Symbol(_)) {
8345            return Err(Signal::Throw(
8346                self.make_error("TypeError", "cannot convert symbol to string"),
8347            ));
8348        }
8349        // An object runs `ToPrimitive` first, which may itself produce a symbol —
8350        // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
8351        let value = self.to_primitive(value.clone(), Hint::String)?;
8352        if matches!(value, Value::Symbol(_)) {
8353            return Err(Signal::Throw(
8354                self.make_error("TypeError", "cannot convert symbol to string"),
8355            ));
8356        }
8357        Ok(value.to_js_string())
8358    }
8359
8360    /// `ToPropertyKey` for a builtin that takes a key argument.
8361    ///
8362    /// Fallible: a key whose `toString` throws has to propagate that error, both for
8363    /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
8364    /// for a template substitution. This used to answer `"[object Object]"` on a throw,
8365    /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
8366    pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
8367        self.propkey(value)
8368    }
8369
8370    /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
8371    ///
8372    /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
8373    /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
8374    /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
8375    /// `RangeError` — and why this cannot be a plain `ToNumber`.
8376    pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
8377        let number = match value {
8378            Value::Int(number) => *number as f64,
8379            Value::Float(number) => *number,
8380            // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
8381            // `null` is 0, `false` is 0, `true` is 1. Refusing them made
8382            // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
8383            // reference answers 0.
8384            Value::Null | Value::Bool(_) => value.to_number(),
8385            _ => {
8386                let primitive = self.to_primitive(value.clone(), Hint::Number)?;
8387                match primitive {
8388                    Value::Int(number) => number as f64,
8389                    Value::Float(number) => number,
8390                    other => {
8391                        // `ToString` then `ToNumber`, so a string length goes through the
8392                        // full numeric-literal grammar: `"0x00B"` is 11 and `"  5  "` is 5.
8393                        // `Value::to_number` on the string already implements exactly that.
8394                        let text = self.to_js_string(&other)?;
8395                        crate::value::string_to_number(&text)
8396                    }
8397                }
8398            }
8399        };
8400        // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
8401        // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
8402        // is a `RangeError`, not `0`.
8403        if !number.is_finite()
8404            || number.fract() != 0.0
8405            || !(0.0..=u32::MAX as f64).contains(&number)
8406        {
8407            return Err(self.range_error("invalid array length"));
8408        }
8409        Ok(number as u32)
8410    }
8411
8412    /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
8413    /// `Object.getOwnPropertySymbols` put in their result array.
8414    pub fn key_value(&self, key: &PropertyKey) -> Value {
8415        match key {
8416            PropertyKey::String(text) => self.string_wtf8(text.clone()),
8417            PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
8418        }
8419    }
8420
8421    /// Fill in a String exotic object: `_value`, `length` and the index properties.
8422    ///
8423    /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
8424    /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
8425    /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
8426    /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
8427    /// the two paths had drifted; this is the one both now use.
8428    ///
8429    /// The indices are *code units*, so an astral character occupies two of them — the
8430    /// same rule `s.length` and `s[i]` follow.
8431    /// Give an already-created object the internal slot that makes it a wrapper of
8432    /// `value`, so the primitive's prototype methods work on it.
8433    ///
8434    /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
8435    /// which are wrappers of their own type holding the empty value.
8436    pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
8437        self.internal_set(object, "_value", value);
8438    }
8439
8440    pub(crate) fn init_string_wrapper(
8441        &mut self,
8442        object: &Gc<JsObject>,
8443        text: &Gc<crate::value::JsString>,
8444    ) {
8445        object.define(
8446            "length",
8447            Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
8448        );
8449        for index in 0..text.utf16_len() {
8450            if let Some(unit) = text.wtf8().unit_at(index) {
8451                object.define(
8452                    &index.to_string(),
8453                    // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
8454                    Property::with_attributes(self.string_wtf8(unit), false, true),
8455                );
8456            }
8457        }
8458        object.define_key(
8459            &self.internal_slot("_value"),
8460            Property::with_attributes(Value::String(text.clone()), false, false),
8461        );
8462    }
8463
8464    /// `ToObject`: box a primitive, refuse `undefined` and `null`.
8465    ///
8466    /// A destructuring *object* pattern starts with this, which is why `var {} = null`
8467    /// throws. The wrapper carries its primitive in `_value` — the same slot
8468    /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
8469    /// on a boxed value no constructor ever built.
8470    pub(crate) fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
8471        let (prototype, primitive) = match value {
8472            Value::Object(object) => return Ok(object.clone()),
8473            Value::String(text) => {
8474                let object = self.new_object(self.realm.string_proto.clone());
8475                self.init_string_wrapper(&object, text);
8476                return Ok(object);
8477            }
8478            Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
8479            Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
8480            // A symbol and a bigint box into wrappers whose methods live on
8481            // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
8482            // `Object(1n).toString(2)` both go through the wrapper. Falling into the
8483            // branch below instead produced an object with *no* prototype, so those
8484            // methods were unreachable on a box.
8485            Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
8486            Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
8487            Value::Undefined | Value::Null => {
8488                return Err(Signal::Throw(self.make_error(
8489                    "TypeError",
8490                    &format!("cannot convert {} to object", value.to_js_string()),
8491                )));
8492            }
8493            _ => (None, value.clone()),
8494        };
8495        let object = self.new_object(prototype);
8496        self.internal_set(&object, "_value", primitive);
8497        Ok(object)
8498    }
8499
8500    /// `a == b`, the coercing comparison.
8501    ///
8502    /// An object operand is converted with `ToPrimitive` *through the interpreter*,
8503    /// which is what makes `[] == ""` true: `[]` becomes `""` via
8504    /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
8505    /// because the conversion is allowed to call script code, so the two primitive
8506    /// operands are handed back to it.
8507    fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
8508        if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
8509            return Ok(left.loose_equals(&right));
8510        }
8511        // `null == undefined` holds even though neither is an object.
8512        if matches!(left, Value::Undefined | Value::Null)
8513            && matches!(right, Value::Undefined | Value::Null)
8514        {
8515            return Ok(true);
8516        }
8517        if matches!(left, Value::Undefined | Value::Null)
8518            || matches!(right, Value::Undefined | Value::Null)
8519        {
8520            return Ok(false);
8521        }
8522        // Two objects compare by identity. Only an object *against a primitive* is
8523        // converted, which is why `{} == {}` is false while `[] == ""` is true.
8524        if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
8525            return Ok(a.ptr_eq(b));
8526        }
8527        let left = self.to_primitive(left, Hint::Default)?;
8528        let right = self.to_primitive(right, Hint::Default)?;
8529        Ok(left.loose_equals(&right))
8530    }
8531
8532    fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
8533        let Value::Object(object) = object else {
8534            return Err(Signal::Throw(
8535                self.make_error("TypeError", "cannot use 'in' on a non-object"),
8536            ));
8537        };
8538        let key = self.propkey(key)?;
8539        // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
8540        // trap. One implementation, so an array's derived `length` and its inherited holes
8541        // cannot be right in one caller and wrong in another.
8542        self.has_own_or_inherited(object, &key)
8543    }
8544
8545    fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
8546        let Value::Object(target) = object else {
8547            return Ok(false);
8548        };
8549        let Value::Object(function) = constructor else {
8550            return Err(Signal::Throw(self.make_error(
8551                "TypeError",
8552                "right-hand side of 'instanceof' is not callable",
8553            )));
8554        };
8555        let prototype = self.get_property(function, "prototype")?;
8556        let Some(Value::Object(prototype)) = prototype else {
8557            return Ok(false);
8558        };
8559        // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
8560        // which is also what makes `proxyOfInstance instanceof C` work.
8561        let mut current = Some(target.clone());
8562        while let Some(object) = current {
8563            if object.ptr_eq(&prototype) {
8564                return Ok(true);
8565            }
8566            current = self.object_prototype_of(&object)?;
8567        }
8568        Ok(false)
8569    }
8570
8571    /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
8572    pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
8573        if let Some(proto) = self.proxy_get_prototype_of(object)? {
8574            return Ok(proto);
8575        }
8576        Ok(object.proto())
8577    }
8578
8579    /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
8580    pub fn object_set_prototype_of(
8581        &mut self,
8582        object: &Gc<JsObject>,
8583        proto: Option<Gc<JsObject>>,
8584    ) -> JsResult<bool> {
8585        if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
8586            return Ok(answer);
8587        }
8588        object.set_proto(proto);
8589        Ok(true)
8590    }
8591
8592    /// `[[IsExtensible]]`, with the proxy trap when there is one.
8593    pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
8594        if let Some(answer) = self.proxy_is_extensible(object)? {
8595            return Ok(answer);
8596        }
8597        Ok(object.is_extensible())
8598    }
8599
8600    /// `[[PreventExtensions]]`, with the proxy trap when there is one.
8601    pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
8602        if let Some(answer) = self.proxy_prevent_extensions(object)? {
8603            return Ok(answer);
8604        }
8605        object.set_extensible(false);
8606        Ok(true)
8607    }
8608
8609    fn copy_properties(
8610        &mut self,
8611        target: &Value,
8612        source: &Value,
8613        exclusion: &Value,
8614    ) -> JsResult<()> {
8615        // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
8616        // does contribute: its index properties are own, enumerable and writable, which
8617        // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
8618        // with no own properties, so they copy nothing, and spreading `undefined`/`null`
8619        // is a no-op.
8620        let Some(target) = target.as_object() else {
8621            return Ok(());
8622        };
8623        let source_object = match source {
8624            Value::Object(object) => object.clone(),
8625            Value::String(text) => {
8626                // Untaken keys are the string's indices, which are code units.
8627                for index in 0..text.utf16_len() {
8628                    if let Some(unit) = text.wtf8().unit_at(index) {
8629                        target.define_data(&index.to_string(), self.string_wtf8(unit));
8630                    }
8631                }
8632                return Ok(());
8633            }
8634            _ => return Ok(()),
8635        };
8636        // An object *rest* element passes the keys already taken by the literal part as
8637        // an array of strings; a spread passes `null`, which excludes nothing. Only the
8638        // string keys of the exclusion array are meaningful, so an array is read by its
8639        // elements rather than by its own property names.
8640        let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
8641        if let Value::Object(list) = exclusion
8642            && let Some(length) = list.array_length()
8643        {
8644            for index in 0..length {
8645                if let Some(value) = list.array_get(index) {
8646                    excluded.push(self.propkey_of(&value)?);
8647                }
8648            }
8649        }
8650        let source = &source_object;
8651        // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
8652        // Reading the property table directly made every spread of a proxy empty.
8653        let keys = self.object_own_property_keys(source)?;
8654        for as_key in keys {
8655            if as_key.is_symbol() {
8656                // A spread copies string-keyed properties only.
8657                continue;
8658            }
8659            if excluded.contains(&crate::value::Wtf8::new(
8660                as_key.as_str().unwrap_or_default(),
8661            )) {
8662                continue;
8663            }
8664            let enumerable = self
8665                .object_get_own_property(source, &as_key)?
8666                .is_some_and(|property| property.enumerable);
8667            if !enumerable {
8668                continue;
8669            }
8670            let value = self
8671                .get_property_key(source, &as_key)?
8672                .unwrap_or(Value::Undefined);
8673            target.define_data_key(&as_key, value);
8674        }
8675        Ok(())
8676    }
8677
8678    // -- iteration ---------------------------------------------------------
8679
8680    /// One object's own keys in enumeration order: array indices ascending, then the
8681    /// rest in insertion order.
8682    ///
8683    /// An index is ASCII, so a key with no `&str` form is never one. The flag says
8684    /// whether the key is enumerable, which the caller resolves per key because an
8685    /// array's elements are not in the same store as its named properties.
8686    fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
8687        // An index can arrive twice, once from the array's element store and once from
8688        // its property map, so the numeric keys go through a map that keeps the
8689        // enumerable answer if either source gave one.
8690        let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
8691        for (key, enumerable) in &own {
8692            if let Some(index) = key.as_str().and_then(array_index) {
8693                let entry = numeric.entry(index).or_insert(false);
8694                *entry = *entry || *enumerable;
8695            }
8696        }
8697        let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
8698            .into_iter()
8699            .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
8700            .collect();
8701        ordered.extend(
8702            own.into_iter()
8703                .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
8704        );
8705        ordered
8706    }
8707
8708    /// Build the key list a `for-in` loop walks.
8709    ///
8710    /// The order is the specification's: own properties before inherited ones, and
8711    /// within one object the integer-like keys in ascending numeric order ahead of the
8712    /// string keys in insertion order. A shadowed key only appears once, and a key that
8713    /// is a non-enumerable own property anywhere nearer is skipped entirely.
8714    fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
8715        let record = self.new_object(None);
8716        let mut keys: Vec<crate::value::Wtf8> = Vec::new();
8717        // A proxy supplies its own key list, and — the reason this is not just another
8718        // branch of the ordinary walk — *re-decides* whether each key is enumerable as
8719        // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
8720        // descriptor there.
8721        if let Value::Object(object) = value
8722            && object.proxy_state().is_some()
8723        {
8724            let own = self
8725                .proxy_own_keys(object)?
8726                .unwrap_or_else(|| object.own_property_keys());
8727            let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
8728            let mut numeric: Vec<u32> = Vec::new();
8729            let mut rest: Vec<PropertyKey> = Vec::new();
8730            for key in own {
8731                match key.as_str().and_then(array_index) {
8732                    Some(index) => numeric.push(index),
8733                    None => rest.push(key),
8734                }
8735            }
8736            numeric.sort_unstable();
8737            ordered.extend(
8738                numeric
8739                    .into_iter()
8740                    .map(|index| PropertyKey::from(index.to_string())),
8741            );
8742            ordered.extend(rest);
8743            for (index, key) in ordered.into_iter().enumerate() {
8744                record.define_data(&index.to_string(), self.key_value(&key));
8745            }
8746            record.define_data("__index", Value::Int(0));
8747            // The mark that makes `for_in_advance` re-ask the proxy per key.
8748            record.define_data("__proxy", Value::Object(object.clone()));
8749            return Ok(record);
8750        }
8751        if let Value::Object(object) = value {
8752            let mut chain = vec![object.clone()];
8753            chain.extend(object.chain());
8754            // Every own string key the walk has seen, enumerable or not. A
8755            // non-enumerable own property still hides a same-named enumerable one
8756            // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
8757            // keeps `x` out of the loop even when the prototype has one.
8758            let mut visited: Vec<crate::value::Wtf8> = Vec::new();
8759            for object in chain {
8760                let mut own: Vec<(crate::value::Wtf8, bool)> = object
8761                    .own_property_keys()
8762                    .iter()
8763                    .filter_map(|key| key.as_wtf8().cloned())
8764                    .map(|key| {
8765                        let enumerable = object
8766                            .own_property(&key.to_string_lossy())
8767                            .map(|property| property.enumerable)
8768                            .unwrap_or(false);
8769                        (key, enumerable)
8770                    })
8771                    .collect();
8772                if let Some(length) = object.array_length() {
8773                    own.retain(|(key, _)| key.as_str() != Some("length"));
8774                    for index in 0..length {
8775                        if object.array_get(index).is_some() {
8776                            own.push((crate::value::Wtf8::new(index.to_string()), true));
8777                        }
8778                    }
8779                }
8780                // Integer-like keys come first in ascending order, then the rest in
8781                // insertion order — and the ordering is *per object*, not for the chain
8782                // as a whole: one pass over every collected key lifted a prototype's
8783                // `"4"` above the target's own `x`/`y`, which is not the order
8784                // `for…in` reports.
8785                for (key, enumerable) in Self::order_own_keys(own) {
8786                    if visited.contains(&key) {
8787                        continue;
8788                    }
8789                    visited.push(key.clone());
8790                    if enumerable {
8791                        keys.push(key);
8792                    }
8793                }
8794            }
8795        }
8796        for (index, key) in keys.into_iter().enumerate() {
8797            record.define_data(&index.to_string(), self.string_wtf8(key));
8798        }
8799        record.define_data("__index", Value::Int(0));
8800        Ok(record)
8801    }
8802
8803    /// The next key of a `for…in` record, `None` when the loop is done.
8804    ///
8805    /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
8806    /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
8807    /// the loop reaches it, so a handler that stops reporting a key partway through drops
8808    /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
8809    /// key the handler had already withdrawn.
8810    fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
8811        let Value::Object(record) = record else {
8812            return Ok(None);
8813        };
8814        let proxy = record
8815            .own_property("__proxy")
8816            .and_then(|property| property.value);
8817        loop {
8818            let index = record
8819                .own_property("__index")
8820                .and_then(|property| property.value)
8821                .map(|value| value.to_int32())
8822                .unwrap_or(0);
8823            let Some(candidate) = record
8824                .own_property(&index.to_string())
8825                .and_then(|property| property.value)
8826            else {
8827                return Ok(None);
8828            };
8829            record.define_data("__index", Value::Int(index + 1));
8830            let text = candidate.to_js_string();
8831            let Some(Value::Object(proxy)) = &proxy else {
8832                return Ok(Some(text));
8833            };
8834            // The candidate is already a key string here, so the lookup does not need a
8835            // second `ToPropertyKey` conversion.
8836            let key = PropertyKey::from(text.as_str());
8837            let live = match self.proxy_get_own_property(proxy, &key)? {
8838                Some(descriptor) => descriptor,
8839                // Not a proxy after all, or it lost its state: fall back to the target.
8840                None => proxy.own_property_key(&key),
8841            };
8842            if live.is_some_and(|property| property.enumerable) {
8843                return Ok(Some(text));
8844            }
8845            // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
8846            // next one.
8847        }
8848    }
8849
8850    /// The iterator for `for-of`: the object and its `next` method.
8851    ///
8852    /// An object that already carries a `next` method is used as it is — that is what
8853    /// `arr.values()` returns — and only arrays and strings get the built-in
8854    /// sequence iterator.
8855    /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
8856    ///
8857    /// Callers that must choose between the iterable and the array-like protocol — the
8858    /// typed-array constructor is the main one — need to ask *before* committing to one.
8859    pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
8860        let key = self.realm.well_known_key(WellKnown::Iterator);
8861        let method = self.read_field_key(value, &key)?;
8862        if matches!(method, Value::Undefined | Value::Null) {
8863            return Ok(false);
8864        }
8865        if !matches!(&method, Value::Object(object) if object.is_callable()) {
8866            return Err(Signal::Throw(
8867                self.make_error("TypeError", "Symbol.iterator is not callable"),
8868            ));
8869        }
8870        Ok(true)
8871    }
8872
8873    /// Collect everything an iterable yields, closing it if the walk is abandoned.
8874    ///
8875    /// The cap is a guard against a generator that never ends: an unbounded collect would
8876    /// be an out-of-memory abort rather than a catchable error.
8877    pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8878        const MAX_ITEMS: usize = 1 << 24;
8879        let iterator = self.get_iterator(value)?;
8880        let mut out = Vec::new();
8881        loop {
8882            let (element, done) = self.iterator_step(&iterator)?;
8883            if done {
8884                return Ok(out);
8885            }
8886            out.push(element);
8887            if out.len() > MAX_ITEMS {
8888                return Err(self.range_error("iterable is too long to collect"));
8889            }
8890        }
8891    }
8892
8893    /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
8894    ///
8895    /// A native constructor calls this once it has validated its arguments, which is the
8896    /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
8897    /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
8898    /// never reached. The prototype comes from `new.target` when it is an object, and from
8899    /// `default_proto` otherwise.
8900    pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
8901        let Some(target) = self.pending_new_target.clone() else {
8902            return Ok(self.new_object(Some(default_proto)));
8903        };
8904        let Some(target) = target.as_object().cloned() else {
8905            return Ok(self.new_object(Some(default_proto)));
8906        };
8907        let proto = match self.get_property(&target, "prototype")? {
8908            Some(Value::Object(proto)) => proto,
8909            _ => default_proto,
8910        };
8911        Ok(self.new_object(Some(proto)))
8912    }
8913
8914    /// Whether this call is a construction, i.e. `new.target` is defined.
8915    ///
8916    /// A native constructor receives `this = undefined` (it builds its own instance), so it
8917    /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
8918    /// The native function currently executing, if any.
8919    pub fn current_native(&self) -> Option<Gc<JsObject>> {
8920        self.current_native.clone()
8921    }
8922
8923    /// Whether this call is a construction, i.e. `new.target` is defined.
8924    pub fn is_constructing(&self) -> bool {
8925        self.pending_new_target.is_some()
8926    }
8927
8928    /// The `TypeError` a constructor too primitive to have a wrapper raises.
8929    ///
8930    /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
8931    /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
8932    /// happens inside the native function, which is why the trace carries an
8933    /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
8934    /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
8935    /// constructor`, and an unnamed one reports the leading space of `" is not a
8936    /// constructor"` because the reference formats the empty name as it is.
8937    ///
8938    /// It is also the answer for a `new.target` that cannot be named at all — not a
8939    /// function, or a throwing `name` getter — where the reference falls back to the bare
8940    /// `not a constructor`.
8941    pub fn not_a_constructor_error(&mut self) -> Signal {
8942        let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
8943        self.not_a_constructor_error_for(target)
8944    }
8945
8946    /// The same `TypeError` for an explicit target, for the callers that check
8947    /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
8948    pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
8949        let target = match target {
8950            Value::Object(target) if target.is_callable() => target,
8951            _ => return self.type_error("not a constructor"),
8952        };
8953        let name = match self.get_property(&target, "name") {
8954            Ok(Some(value)) => value.to_js_string(),
8955            _ => return self.type_error("not a constructor"),
8956        };
8957        self.type_error(format!("{name} is not a constructor"))
8958    }
8959
8960    /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
8961    ///
8962    /// True whenever `new.target` is not the callee itself, or when it has no usable
8963    /// `prototype` — the cases where reading the property is observable at all.
8964    pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
8965        match &self.pending_new_target {
8966            Some(Value::Object(target)) => !target.ptr_eq(callee),
8967            Some(_) => true,
8968            None => false,
8969        }
8970    }
8971
8972    /// The symbol key for one of the engine's own hidden slots.
8973    ///
8974    /// Cached on the realm, so every object of a kind shares one key and a slot can be
8975    /// read back by name.
8976    pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
8977        if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
8978            return PropertyKey::Symbol(symbol.clone());
8979        }
8980        let symbol = Gc::new(
8981            self.heap,
8982            crate::value::JsSymbol::new(Some(name.to_string())),
8983        );
8984        self.realm
8985            .internal_slots
8986            .borrow_mut()
8987            .insert(name, Value::Symbol(symbol.clone()));
8988        PropertyKey::Symbol(symbol)
8989    }
8990
8991    /// Read a hidden slot, or `None` when the object has none of that name.
8992    pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
8993        let slots = self.realm.internal_slots.borrow();
8994        let Value::Symbol(symbol) = slots.get(name)? else {
8995            return None;
8996        };
8997        object
8998            .own_property_key(&PropertyKey::Symbol(symbol.clone()))
8999            .and_then(|property| property.value)
9000    }
9001
9002    /// Define a hidden slot.
9003    pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
9004        let key = self.internal_slot(name);
9005        object.define_key(&key, Property::with_attributes(value, false, false));
9006    }
9007
9008    /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
9009    ///
9010    /// The method is looked up on the value (through its prototype), called with no
9011    /// arguments, and its result becomes the iterator. A generator gets here through
9012    /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
9013    /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
9014    ///
9015    /// This used to be a shortcut — "has a callable `next`, or is an array" — because
9016    /// there were no symbols to key the protocol on. Now that there are, the shortcut is
9017    /// gone: a `for…of` over `null`, over a plain object, or over an object whose
9018    /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
9019    /// does, and a user-defined iterable works without a special case.
9020    /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
9021    /// `Symbol.iterator`.
9022    ///
9023    /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
9024    /// iterable is legal there, and each value it produces is simply already settled by
9025    /// the time the `await` around it runs.
9026    fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
9027        let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
9028        let method = self.read_field_key(value, &async_key)?;
9029        let has_async = matches!(&method, Value::Object(object) if object.is_callable());
9030        if !has_async {
9031            return self.get_iterator(value);
9032        }
9033        let iterator = self.call_value(method, value.clone(), Vec::new())?;
9034        if !matches!(iterator, Value::Object(_)) {
9035            return Err(Signal::Throw(
9036                self.make_error("TypeError", "iterator is not an object"),
9037            ));
9038        }
9039        let next = self.read_field(&iterator, "next")?;
9040        Ok(Iterator {
9041            object: iterator,
9042            next,
9043        })
9044    }
9045
9046    pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
9047        let key = self.realm.well_known_key(WellKnown::Iterator);
9048        let method = self.read_field_key(value, &key)?;
9049        let Value::Object(function) = &method else {
9050            return Err(Signal::Throw(self.make_error(
9051                "TypeError",
9052                &format!("{} is not iterable", value.to_js_string()),
9053            )));
9054        };
9055        if !function.is_callable() {
9056            return Err(Signal::Throw(self.make_error(
9057                "TypeError",
9058                &format!("{} is not iterable", value.to_js_string()),
9059            )));
9060        }
9061        let iterator = self.call_value(method, value.clone(), Vec::new())?;
9062        // The spec requires an object here; a primitive iterator has no `next` to call
9063        // and would fail one step later with a confusing message.
9064        if !matches!(iterator, Value::Object(_)) {
9065            return Err(Signal::Throw(
9066                self.make_error("TypeError", "iterator is not an object"),
9067            ));
9068        }
9069        let next = self.read_field(&iterator, "next")?;
9070        Ok(Iterator {
9071            object: iterator,
9072            next,
9073        })
9074    }
9075
9076    /// Drain anything with a `Symbol.iterator` method, or answer `None` when the value is
9077    /// not iterable.
9078    ///
9079    /// Shared so that `Array.from`, the `Promise` combinators and `for…of` all agree on
9080    /// what "iterable" means. A `Map` and a `Set` have no `length`, so an array-like-only
9081    /// reader silently produced an empty array for both — `Array.from(new Set([1,2]))`
9082    /// was `[]`.
9083    pub fn iterable_values(&mut self, value: &Value) -> JsResult<Option<Vec<Value>>> {
9084        let key = self.realm.well_known_key(WellKnown::Iterator);
9085        let method = self.read_field_key(value, &key)?;
9086        if !matches!(&method, Value::Object(object) if object.is_callable()) {
9087            return Ok(None);
9088        }
9089        let iterator = self.get_iterator(value)?;
9090        let mut out = Vec::new();
9091        loop {
9092            let (element, done) = self.iterator_step(&iterator)?;
9093            if done {
9094                return Ok(Some(out));
9095            }
9096            out.push(element);
9097        }
9098    }
9099
9100    /// One step of an internal iterator: the value and whether it is exhausted.
9101    pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
9102        // A real iterator (`next` is a function) answers with a result object.
9103        if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
9104            let result =
9105                self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
9106            let Some(result) = result.as_object().cloned() else {
9107                return Err(self.type_error("iterator result is not an object"));
9108            };
9109            let done = self
9110                .get_property(&result, "done")?
9111                .is_some_and(|value| value.to_boolean());
9112            let value = self
9113                .get_property(&result, "value")?
9114                .unwrap_or(Value::Undefined);
9115            return Ok((value, done));
9116        }
9117        // An iterator whose `next` is not callable is treated as exhausted, which is
9118        // what `for (x of {})` relies on: `for_of_start` has already refused the ones
9119        // that are not iterable at all.
9120        Ok((Value::Undefined, true))
9121    }
9122
9123    /// `[...iterable]`: append everything the iterator yields, and answer the next
9124    /// index.
9125    ///
9126    /// This goes through the same iterator machinery `for-of` uses rather than copying
9127    /// an array's elements, because a spread source is any iterable: a string spreads
9128    /// into its characters and an array iterator spreads into its results. Handling
9129    /// only arrays made `[..."ab"]` come out empty with no error at all.
9130    fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
9131        let Some(target) = array.as_object().cloned() else {
9132            return Ok(0);
9133        };
9134        let start = target.array_length().unwrap_or(0);
9135        let mut added = 0;
9136        let iterator = self.get_iterator(iterable)?;
9137        loop {
9138            let (value, done) = self.iterator_step(&iterator)?;
9139            if done {
9140                break;
9141            }
9142            target.array_set(start + added, value);
9143            added += 1;
9144        }
9145        Ok((start + added) as i32)
9146    }
9147
9148    /// How an uncaught exception is reported.
9149    ///
9150    /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
9151    /// with `ToString` — `js_std_dump_error` is three lines that end in
9152    /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
9153    /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
9154    /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
9155    ///
9156    /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
9157    /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
9158    /// `toString`"; it does call it, but only for objects of a class it does not know how
9159    /// to walk, and never for errors, arrays or plain objects.
9160    ///
9161    /// A printer that fails must not take the reporter down with it, so that case falls
9162    /// back to the `ToString` rendering.
9163    pub fn describe_exception(&mut self, value: &Value) -> String {
9164        match crate::print::sprint(self, value) {
9165            Ok(text) => text,
9166            Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
9167        }
9168    }
9169
9170    /// The current call stack, formatted the way `qjs` prints `error.stack`.
9171    ///
9172    /// One `    at name (file:line:col)` line per active frame, innermost first. The
9173    /// position is the one recorded for the instruction each frame is stopped on, which
9174    /// is why the compiler builds a pc-to-position table per function: without it a
9175    /// trace could only name the function, not the line inside it.
9176    ///
9177    /// A frame whose code has no positions prints just `(file)`, matching the
9178    /// reference's output for stripped bytecode.
9179    pub fn stack_trace(&self) -> String {
9180        self.stack_trace_skipping(0)
9181    }
9182
9183    /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
9184    fn stack_trace_skipping(&self, skip: usize) -> String {
9185        // One ordered list, innermost first, so `skip` counts the same thing whether the
9186        // frames it leaves out are native or bytecode. Indices rather than references: a
9187        // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
9188        let depth = self.frames.len();
9189        let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
9190        // A native entered while `at` bytecode frames were live was called *from* the
9191        // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
9192        // entered at the current depth are therefore innermost of all.
9193        let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
9194            for (index, (_, _, at)) in self.native_frames.iter().enumerate().rev() {
9195                if *at == wanted {
9196                    order.push((true, index));
9197                }
9198            }
9199        };
9200        push_natives(&mut order, depth);
9201        for index in (0..depth).rev() {
9202            order.push((false, index));
9203            push_natives(&mut order, index);
9204        }
9205        // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
9206        // barrier. Natives entered at exactly the barrier depth are the eval entry point
9207        // itself (`evalScript (native)`), and the reference leaves those out too.
9208        if let Some(barrier) = self.trace_barriers.last().copied() {
9209            order.retain(|(is_native, index)| match is_native {
9210                true => *index == usize::MAX || self.native_frames[*index].2 > barrier,
9211                false => *index >= barrier,
9212            });
9213        }
9214
9215        let mut out = String::new();
9216        for (is_native, index) in order.into_iter().skip(skip) {
9217            match is_native {
9218                true => {
9219                    out.push_str("    at ");
9220                    out.push_str(&self.native_frames[index].0);
9221                    out.push_str(" (native)\n");
9222                }
9223                false => {
9224                    let frame = &self.frames[index];
9225                    let code = &frame.code.code;
9226                    let file = code.filename.as_deref().unwrap_or("<input>");
9227                    // The name comes from the function *object*, not from the compiled code:
9228                    // an anonymous function expression is named by the property it is stored
9229                    // in (`{valueOf: function(){}}`), which only the object knows.
9230                    let bound_name = match &frame.callee {
9231                        Value::Object(object) => {
9232                            object
9233                                .own_property("name")
9234                                .and_then(|property| match property.value {
9235                                    Some(Value::String(text)) if !text.wtf8().is_empty() => {
9236                                        Some(text.to_string_lossy().into_owned())
9237                                    }
9238                                    _ => None,
9239                                })
9240                        }
9241                        _ => None,
9242                    };
9243                    // No callee object means the body was entered by the host, so the
9244                    // name has to come from the compiled code. Two cases differ:
9245                    //
9246                    // * an *unnamed* function of any kind — the reference reads the
9247                    //   `name` property, finds it empty, and prints `<anonymous>`;
9248                    // * a *module* body, which has no `name` property at all: the
9249                    //   reference builds that function object with `js_closure2` and
9250                    //   never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
9251                    //   so a trace reaching it also prints `<anonymous>` — while a
9252                    //   *script* body prints `<eval>`, its `name`.
9253                    let unnamed = code.name.is_empty() || code.module.is_some();
9254                    out.push_str("    at ");
9255                    match bound_name.as_deref() {
9256                        Some(name) => out.push_str(name),
9257                        None if unnamed => out.push_str("<anonymous>"),
9258                        None => out.push_str(&code.name),
9259                    }
9260                    match code.position_at(frame.at as u32) {
9261                        Some((line, column)) => {
9262                            out.push_str(&format!(" ({file}:{line}:{column})\n"));
9263                        }
9264                        None => out.push_str(&format!(" ({file})\n")),
9265                    }
9266                }
9267            }
9268        }
9269        out
9270    }
9271
9272    /// Give an anonymous function the name of the property it is stored in.
9273    ///
9274    /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
9275    /// enumerable and not configurable, and a function that already has a real name
9276    /// keeps it.
9277    ///
9278    /// "Already named" means a *non-empty* name: every function object is created with
9279    /// a `name` of `""` so the property exists on all of them, and treating that empty
9280    /// string as a name left every anonymous function nameless — which is how a stack
9281    /// trace came out as `at  (file:1:2)` instead of `at valueOf (file:1:2)`.
9282    fn set_function_name(&mut self, function: &Value, name: &str) {
9283        let Value::Object(object) = function else {
9284            return;
9285        };
9286        // `SetFunctionName` applies to *functions* and classes only, and only when they are
9287        // anonymous. Without the callability guard, `{value: someObject}` renamed
9288        // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
9289        // on the right-hand side of a property. That is how a `zipKeyed` result object
9290        // acquired a `name` property, and it applied to `Object.defineProperty` too, which
9291        // has no `NamedEvaluation` at all.
9292        if !object.is_callable() {
9293            return;
9294        }
9295        if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
9296            && !existing.wtf8().is_empty()
9297        {
9298            return;
9299        }
9300        let text = self.string(name);
9301        object.define("name", Property::name_or_length(text));
9302    }
9303
9304    // -- global declarations -----------------------------------------------
9305
9306    /// Declare a global binding, creating its reference cell.
9307    /// Declare a `var` or function global, whose home is the global object.
9308    ///
9309    /// Writable and enumerable but not configurable: `globalThis.v` reads it,
9310    /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
9311    /// such as `print`, or a redeclaration — is left alone.
9312    pub fn declare_var_global(&mut self, name: &str) {
9313        // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
9314        // global object is exactly the leak `typeof my_var === "undefined"` after
9315        // `eval("var my_var=2")` rules out.
9316        if let Some(scope) = self.eval_scope.as_mut() {
9317            scope.entry(name.to_string()).or_insert(Value::Undefined);
9318            return;
9319        }
9320        // A sloppy direct eval declares into its *caller's* variable environment. Doing
9321        // this on the global object instead made `eval("var c = 1")` inside a parameter
9322        // list overwrite a global `c`, and made two calls to the same function share one
9323        // binding.
9324        if let Some(cell) = self.declare_eval_local(name) {
9325            cell.set(Value::Undefined);
9326            return;
9327        }
9328        let global = self.realm.global.clone();
9329        if global.own_property(name).is_some() {
9330            return;
9331        }
9332        // A `var` in a *direct* declaration is non-configurable, but one introduced by an
9333        // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
9334        // whole point of that trick and what lets `Object.defineProperty` reshape it
9335        // afterwards. `eval_scope` is `Some` while an eval is running.
9336        let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
9337        global.define(
9338            name,
9339            Property {
9340                value: Some(Value::Undefined),
9341                writable: true,
9342                enumerable: true,
9343                configurable: from_eval,
9344                ..Property::default()
9345            },
9346        );
9347    }
9348
9349    /// Declare a *lexical* global binding, which starts in its dead zone.
9350    ///
9351    /// Only `let`/`const`/`class` need this: a `var` global is a property of the
9352    /// global object and is created when its initialiser runs.
9353    pub fn declare_global(&mut self, name: &str, is_const: bool) {
9354        if is_const {
9355            self.realm.lexical_consts.insert(name.to_string());
9356        }
9357        if !self.realm.globals.contains_key(name) {
9358            // `Uninitialized` rather than `Undefined`: the binding exists but is not
9359            // readable until its initialiser runs, and that is what `let x` before
9360            // `x = 1` has to observe.
9361            let cell = self.new_cell(Value::Uninitialized);
9362            self.realm.globals.insert(name.to_string(), cell);
9363            self.realm.declared.push(name.to_string());
9364        }
9365    }
9366}
9367
9368/// The bytecode and environment of a function object, if it is a bytecode function.
9369///
9370/// Extracted before a call so no borrow of the object is held across it.
9371fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
9372    function.with(|data| match &data.kind {
9373        ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
9374        _ => None,
9375    })
9376}
9377
9378/// A native call target, extracted before the call so no borrow is held.
9379enum NativeCall {
9380    Native(NativeFn),
9381    /// A host closure. The `Rc` was cloned out of the function object, so calling it does
9382    /// not hold that object's `RefCell` borrow.
9383    Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
9384    Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
9385    Bound {
9386        target: Value,
9387        this: Value,
9388        leading: Vec<Value>,
9389    },
9390    /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
9391    Revoker(crate::object::ProxyRef),
9392    /// A promise's `resolve`.
9393    PromiseResolve(Gc<JsObject>),
9394    /// A promise's `reject`.
9395    PromiseReject(Gc<JsObject>),
9396    /// One continuation of an `await`.
9397    AwaitResume {
9398        coroutine: Gc<JsObject>,
9399        promise: Gc<JsObject>,
9400        kind: ResumeKind,
9401    },
9402    /// One element of a `Promise` combinator settling.
9403    CombinatorSettle {
9404        state: Gc<JsObject>,
9405        index: usize,
9406        fulfilled: bool,
9407    },
9408    /// One of `Promise.prototype.finally`'s two shims.
9409    FinallyShim {
9410        callback: Option<Value>,
9411        fulfilled: bool,
9412    },
9413    /// Settle a promise with a fixed outcome.
9414    SettlePromise {
9415        promise: Gc<JsObject>,
9416        value: Value,
9417        rejected: bool,
9418    },
9419    /// Continue an async generator after its `await` settled.
9420    GeneratorResume {
9421        generator: Gc<JsObject>,
9422        promise: Gc<JsObject>,
9423        kind: ResumeKind,
9424    },
9425    /// Read a module namespace's binding out of its cell.
9426    ModuleBinding(Gc<Cell>),
9427    /// Answer a pending async-generator method with `{value, done}`.
9428    YieldResult {
9429        promise: Gc<JsObject>,
9430        done: bool,
9431    },
9432    /// One step of `AsyncDisposableStack.disposeAsync`.
9433    DisposeStep {
9434        remaining: Gc<JsObject>,
9435        promise: Gc<JsObject>,
9436        error: Value,
9437        rejected: bool,
9438    },
9439}
9440
9441/// What a store does when the object refuses the write.
9442#[derive(Clone, Copy, PartialEq, Eq)]
9443pub enum DeleteFailure {
9444    /// Raise a `TypeError`, which is what strict mode and every built-in does.
9445    Throw,
9446    /// Ignore the write, which is what a sloppy-mode assignment does.
9447    Ignore,
9448}
9449
9450/// Whether `object` is a `Date` instance, by the class tag it carries.
9451///
9452/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
9453/// builtins module depending on the interpreter's conversion order.
9454fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
9455    interp
9456        .internal_get(object, "_class")
9457        .is_some_and(|value| value.to_js_string() == "Date")
9458}
9459
9460/// Which type `ToPrimitive` prefers when it converts an object.
9461#[derive(Clone, Copy, PartialEq, Eq)]
9462pub enum Hint {
9463    /// The default hint, which behaves like [`Hint::Number`].
9464    Default,
9465    /// `Number(obj)` and the arithmetic operators.
9466    Number,
9467    /// `String(obj)` and `ToPropertyKey`.
9468    String,
9469}
9470
9471/// Which table a binding slot indexes, for the messages that name it.
9472#[derive(Clone, Copy)]
9473enum VarSlot {
9474    Loc,
9475    Closure,
9476}
9477
9478/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
9479fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
9480    Ok(this)
9481}
9482
9483/// An internal iterator: the sequence plus a cursor.
9484pub(crate) struct Iterator {
9485    pub(crate) object: Value,
9486    pub(crate) next: Value,
9487}
9488
9489/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
9490/// and plain `a` for a method.
9491///
9492/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
9493/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
9494/// reads `at get a (file:1:2)`.
9495fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
9496    match flags & 3 {
9497        1 => format!("get {key}"),
9498        2 => format!("set {key}"),
9499        _ => key.to_string(),
9500    }
9501}
9502
9503/// Define a method or accessor property, per the `define_method` flag byte.
9504///
9505/// The low two bits pick value/getter/setter and bit 2 marks the property
9506/// enumerable.
9507///
9508/// A getter and a setter arrive as two separate `define_method` instructions, and the
9509/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
9510/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
9511/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
9512/// `JS_DefineProperty`, which leaves the other half alone.
9513fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
9514    let enumerable = flags & 4 != 0;
9515    let kind = flags & 3;
9516    let existing = object.own_property_key(key);
9517    let property = match kind {
9518        1 => Property {
9519            getter: Some(function),
9520            // The setter half, if this literal already defined one.
9521            setter: existing
9522                .filter(Property::is_accessor)
9523                .and_then(|p| p.setter),
9524            enumerable,
9525            configurable: true,
9526            ..Property::default()
9527        },
9528        2 => Property {
9529            getter: existing
9530                .filter(Property::is_accessor)
9531                .and_then(|p| p.getter),
9532            setter: Some(function),
9533            enumerable,
9534            configurable: true,
9535            ..Property::default()
9536        },
9537        _ => Property {
9538            value: Some(function),
9539            writable: true,
9540            enumerable,
9541            configurable: true,
9542            ..Property::default()
9543        },
9544    };
9545    object.define_key(key, property);
9546}
9547
9548// ---------------------------------------------------------------------------
9549// Operand decoding
9550// ---------------------------------------------------------------------------
9551
9552/// Decode the instruction at `pc` into `(opcode, operand a, operand b, next pc)`.
9553///
9554/// Jump operands are resolved to absolute byte offsets here, because the encoding
9555/// stores them relative to the byte after the opcode and every use site would
9556/// otherwise repeat that arithmetic.
9557fn decode(code: &[u8], pc: usize) -> Option<(Opcode, u32, u32, usize)> {
9558    let op = Opcode::from_u8(*code.get(pc)?)?;
9559    let info = op.info();
9560    let base = pc + 1;
9561    let read_u8 = |offset: usize| -> u32 { code.get(base + offset).copied().unwrap_or(0) as u32 };
9562    let read_u16 = |offset: usize| -> u32 {
9563        let mut value = 0u32;
9564        for index in 0..2 {
9565            value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
9566        }
9567        value
9568    };
9569    let read_u32 = |offset: usize| -> u32 {
9570        let mut value = 0u32;
9571        for index in 0..4 {
9572            value = (value << 8) | code.get(base + offset + index).copied().unwrap_or(0) as u32;
9573        }
9574        value
9575    };
9576    let jump = |offset: usize, width: usize| -> u32 {
9577        let raw = match width {
9578            1 => read_u8(offset) as u8 as i8 as i64,
9579            2 => read_u16(offset) as u16 as i16 as i64,
9580            _ => read_u32(offset) as i32 as i64,
9581        };
9582        (base as i64 + raw) as u32
9583    };
9584    let (a, b) = match info.format {
9585        OpFormat::None
9586        | OpFormat::NoneInt
9587        | OpFormat::NoneLoc
9588        | OpFormat::NoneArg
9589        | OpFormat::NoneVarRef
9590        | OpFormat::Npopx => (0, 0),
9591        OpFormat::U8 | OpFormat::Loc8 | OpFormat::Const8 => (read_u8(0), 0),
9592        OpFormat::I8 => (read_u8(0) as u8 as i8 as i32 as u32, 0),
9593        OpFormat::Label8 => (jump(0, 1), 0),
9594        OpFormat::U16 | OpFormat::Npop | OpFormat::Loc | OpFormat::Arg | OpFormat::VarRef => {
9595            (read_u16(0), 0)
9596        }
9597        OpFormat::I16 => (read_u16(0) as u16 as i16 as i32 as u32, 0),
9598        OpFormat::Label16 => (jump(0, 2), 0),
9599        OpFormat::NpopU16 => (read_u16(0), read_u16(2)),
9600        OpFormat::U32 | OpFormat::Const | OpFormat::Atom => (read_u32(0), 0),
9601        OpFormat::I32 | OpFormat::Label => (
9602            if info.format == OpFormat::Label {
9603                jump(0, 4)
9604            } else {
9605                read_u32(0) as i32 as u32
9606            },
9607            0,
9608        ),
9609        OpFormat::AtomU8 | OpFormat::AtomLabelU8 => (read_u32(0), read_u8(4)),
9610        OpFormat::AtomU16 | OpFormat::AtomLabelU16 | OpFormat::LabelU16 => {
9611            (read_u32(0), read_u16(4))
9612        }
9613    };
9614    Some((op, a, b, pc + info.size as usize))
9615}
9616
9617/// How `print` renders a value: the reference's `JS_PrintValue`.
9618///
9619/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
9620/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
9621/// The format is reproduced closely because the test suite compares output text:
9622///
9623/// * an empty container has two spaces inside its brackets — `[  ]`, `{  }`;
9624/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
9625/// * a cycle prints `[circular N]` with `N` the stack index of the object;
9626/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
9627///   end print as `<N empty item(s)>`;
9628/// * a string is quoted inside a container but raw at the top level, which is why
9629///   `print("x")` and `print(["x"])` differ.
9630pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
9631    // A string argument is printed raw: `js_print` converts it with `ToString`
9632    // instead of dumping it, and the quoting only appears inside a container.
9633    if let Value::String(text) = value {
9634        return text.to_string_lossy().into_owned();
9635    }
9636    let mut printer = Printer {
9637        interp,
9638        out: String::new(),
9639        stack: Vec::new(),
9640    };
9641    printer.value(value, 0);
9642    printer.out
9643}
9644
9645/// The internal class name an object carries, when it has one.
9646fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
9647    interp
9648        .internal_get(object, "_class")
9649        .map(|value| value.to_js_string())
9650}
9651
9652/// A string property, looked up the way `GetProperty` does: own first, then the
9653/// prototype chain. Needed because the print formatter holds the interpreter
9654/// immutably and so cannot run getters.
9655fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
9656    let mut current = Some(object.clone());
9657    // Bounded, because a prototype cycle would otherwise loop forever.
9658    for _ in 0..100 {
9659        let node = current?;
9660        if let Some(property) = node.own_property(name)
9661            && let Some(value) = property.value
9662        {
9663            return Some(value.to_js_string());
9664        }
9665        current = node.with(|data| data.proto.clone());
9666    }
9667    None
9668}
9669
9670/// The `JS_PrintValue` state: output, and the objects currently being printed.
9671struct Printer<'a, 'rt> {
9672    /// Kept for the class-name lookups that typed arrays and `Date` will need.
9673    #[allow(dead_code)]
9674    interp: &'a Interp<'rt>,
9675    out: String,
9676    stack: Vec<Gc<JsObject>>,
9677}
9678
9679impl Printer<'_, '_> {
9680    /// Depth past which a container is summarised by its class name.
9681    const MAX_DEPTH: usize = 2;
9682
9683    fn value(&mut self, value: &Value, level: usize) {
9684        match value {
9685            Value::Undefined
9686            | Value::Uninitialized
9687            | Value::Hole
9688            | Value::CatchOffset(_)
9689            | Value::ReturnAddress(_) => self.out.push_str("undefined"),
9690            Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
9691            // The printer writes a bigint the way the language spells one, so a dump is
9692            // unambiguous about which kind of number it is showing.
9693            Value::BigInt(big) => {
9694                self.out.push_str(&big.to_decimal_string());
9695                self.out.push('n');
9696            }
9697            Value::Null => self.out.push_str("null"),
9698            Value::Bool(true) => self.out.push_str("true"),
9699            Value::Bool(false) => self.out.push_str("false"),
9700            Value::Int(number) => self.out.push_str(&number.to_string()),
9701            Value::Float(number) => {
9702                self.out
9703                    .push_str(&crate::value::number_to_string_for_print(*number));
9704            }
9705            Value::String(text) => self.print_string(&text.to_string_lossy()),
9706            Value::Object(object) => self.object(object, level),
9707        }
9708    }
9709
9710    fn object(&mut self, object: &Gc<JsObject>, level: usize) {
9711        // A cycle is reported rather than followed; the index is where the object
9712        // already sits in the print stack, which is what the reference shows.
9713        if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
9714            self.out.push_str(&format!("[circular {index}]"));
9715            return;
9716        }
9717        if object.is_callable() {
9718            let name = object
9719                .own_property("name")
9720                .and_then(|property| property.value)
9721                .map(|value| value.to_js_string())
9722                .unwrap_or_default();
9723            if name.is_empty() {
9724                self.out.push_str("[Function (anonymous)]");
9725            } else {
9726                self.out.push_str(&format!("[Function {name}]"));
9727            }
9728            return;
9729        }
9730        if level >= Self::MAX_DEPTH {
9731            let class = if object.is_array() { "Array" } else { "Object" };
9732            self.out.push_str(&format!("[{class}]"));
9733            return;
9734        }
9735        // `Date` and `Error` print as themselves rather than as bags of properties:
9736        // the ISO string, and `Name: message` followed by the trace.
9737        if let Some(class) = class_of(self.interp, object) {
9738            if class == "Date" {
9739                self.date(object);
9740                return;
9741            }
9742            if class == "Error" {
9743                self.error(object);
9744                return;
9745            }
9746        }
9747        self.stack.push(object.clone());
9748        if object.is_array() {
9749            self.array(object, level);
9750        } else {
9751            self.plain_object(object, level);
9752        }
9753        self.stack.pop();
9754    }
9755
9756    /// A Date prints as its ISO string; an invalid one falls through to the plain
9757    /// object form, the way the reference falls back when `toISOString` throws.
9758    fn date(&mut self, object: &Gc<JsObject>) {
9759        let value = self
9760            .interp
9761            .internal_get(object, "_date_value")
9762            .map(|value| value.to_number());
9763        match value.and_then(crate::builtins::date::iso_string) {
9764            Some(text) => self.out.push_str(&text),
9765            None => self.plain_object(object, 0),
9766        }
9767    }
9768
9769    /// `Name: message`, then the trace with its trailing newline removed.
9770    fn error(&mut self, object: &Gc<JsObject>) {
9771        let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
9772        self.out.push_str(&name);
9773        if let Some(message) = inherited(object, "message")
9774            && !message.is_empty()
9775        {
9776            self.out.push_str(": ");
9777            self.out.push_str(&message);
9778        }
9779        if let Some(stack) = inherited(object, "stack") {
9780            self.out.push('\n');
9781            self.out.push_str(stack.trim_end_matches('\n'));
9782        }
9783    }
9784
9785    fn array(&mut self, object: &Gc<JsObject>, level: usize) {
9786        let elements = object.array_elements().unwrap_or_default();
9787        self.out.push_str("[ ");
9788        // An interior hole means the array is "sparse": the reference prints those
9789        // as `index: value` pairs and says nothing about the holes themselves, while
9790        // a hole run at the end becomes a single `<N empty items>` note.
9791        let last_present = elements
9792            .iter()
9793            .rposition(|value| !matches!(value, Value::Hole));
9794        let has_interior_hole = match last_present {
9795            Some(last) => elements[..last]
9796                .iter()
9797                .any(|value| matches!(value, Value::Hole)),
9798            None => false,
9799        };
9800        let mut first = true;
9801        if has_interior_hole {
9802            let mut index = 0;
9803            while index < elements.len() {
9804                let value = &elements[index];
9805                if matches!(value, Value::Hole) {
9806                    index += 1;
9807                    continue;
9808                }
9809                if !first {
9810                    self.out.push_str(", ");
9811                }
9812                first = false;
9813                self.out.push_str(&format!("{index}: "));
9814                self.value(value, level + 1);
9815                index += 1;
9816            }
9817        } else {
9818            for (index, value) in elements.iter().enumerate() {
9819                if matches!(value, Value::Hole) {
9820                    continue;
9821                }
9822                if !first {
9823                    self.out.push_str(", ");
9824                }
9825                first = false;
9826                let _ = index;
9827                self.value(value, level + 1);
9828            }
9829            if let Some(last) = last_present {
9830                let trailing = elements.len() - last - 1;
9831                if trailing > 0 {
9832                    if !first {
9833                        self.out.push_str(", ");
9834                    }
9835                    self.out.push_str(&format!(
9836                        "<{trailing} empty item{}>",
9837                        if trailing > 1 { "s" } else { "" }
9838                    ));
9839                }
9840            } else if !elements.is_empty() {
9841                let count = elements.len();
9842                self.out.push_str(&format!(
9843                    "<{count} empty item{}>",
9844                    if count > 1 { "s" } else { "" }
9845                ));
9846            }
9847        }
9848        self.out.push_str(" ]");
9849    }
9850
9851    fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
9852        self.out.push_str("{ ");
9853        let mut first = true;
9854        for key in object.own_keys() {
9855            let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
9856                continue;
9857            };
9858            if !property.enumerable {
9859                continue;
9860            }
9861            if !first {
9862                self.out.push_str(", ");
9863            }
9864            first = false;
9865            self.out
9866                .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
9867                    &key.to_string_lossy(),
9868                )));
9869            self.out.push_str(": ");
9870            // An accessor has no value to dump; the reference names the half that
9871            // exists instead of calling it.
9872            if property.is_accessor() {
9873                let text = match (property.getter.is_some(), property.setter.is_some()) {
9874                    (true, true) => "[Getter/Setter]",
9875                    (false, true) => "[Setter]",
9876                    _ => "[Getter]",
9877                };
9878                self.out.push_str(text);
9879            } else {
9880                self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
9881            }
9882        }
9883        self.out.push_str(" }");
9884    }
9885
9886    /// A string inside a container, quoted with the escapes `js_print_string1` uses.
9887    fn print_string(&mut self, text: &str) {
9888        self.out.push('"');
9889        for character in text.chars() {
9890            match character {
9891                '"' => self.out.push_str("\\\""),
9892                '\\' => self.out.push_str("\\\\"),
9893                '\n' => self.out.push_str("\\n"),
9894                '\r' => self.out.push_str("\\r"),
9895                '\t' => self.out.push_str("\\t"),
9896                c if (c as u32) < 0x20 => {
9897                    self.out.push_str(&format!("\\u{:04x}", c as u32));
9898                }
9899                c => self.out.push(c),
9900            }
9901        }
9902        self.out.push('"');
9903    }
9904}
9905
9906/// How `print` renders a value.
9907///
9908/// `ToString`, except that negative zero keeps its sign — the reference's host
9909/// printer does that while `String(-0)` is `"0"`.
9910pub fn display(value: &Value) -> String {
9911    match value {
9912        Value::Float(number) => crate::value::number_to_string_for_print(*number),
9913        Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
9914            "undefined".to_string()
9915        }
9916        other => other.to_js_string(),
9917    }
9918}
9919
9920// ---------------------------------------------------------------------------
9921// Numeric operators
9922// ---------------------------------------------------------------------------
9923
9924/// `a + b` keeping the `Int` representation when it fits.
9925fn add_numbers(left: Value, right: Value) -> Value {
9926    match (&left, &right) {
9927        (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
9928            Some(sum) => Value::Int(sum),
9929            None => Value::Float(*a as f64 + *b as f64),
9930        },
9931        _ => Value::Float(left.to_number() + right.to_number()),
9932    }
9933}
9934
9935/// The arithmetic operators other than `+`, which needs string concatenation.
9936fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
9937    use Opcode::*;
9938    let (a, b) = (left.to_number(), right.to_number());
9939    Ok(match op {
9940        Sub => match (&left, &right) {
9941            (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
9942                Some(value) => Value::Int(value),
9943                None => Value::Float(a - b),
9944            },
9945            _ => Value::Float(a - b),
9946        },
9947        Mul => Value::Float(a * b),
9948        Div => Value::Float(a / b),
9949        Mod => Value::Float(js_mod(a, b)),
9950        Pow => Value::Float(a.powf(b)),
9951        And => Value::Int(left.to_int32() & right.to_int32()),
9952        Or => Value::Int(left.to_int32() | right.to_int32()),
9953        Xor => Value::Int(left.to_int32() ^ right.to_int32()),
9954        Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
9955        Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
9956        // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
9957        // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
9958        // fits the small-integer representation stays an `Int`; the rest become a
9959        // float, which is how the reference keeps `n >>> 0` non-negative.
9960        Shr => {
9961            let shifted = left.to_uint32() >> (right.to_uint32() & 31);
9962            match i32::try_from(shifted) {
9963                Ok(value) => Value::Int(value),
9964                Err(_) => Value::Float(shifted as f64),
9965            }
9966        }
9967        _ => Value::Float(a),
9968    })
9969}
9970
9971/// `%`, which follows the sign of the dividend rather than Rust's.
9972fn js_mod(left: f64, right: f64) -> f64 {
9973    if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
9974        return f64::NAN;
9975    }
9976    if right.is_infinite() {
9977        return left;
9978    }
9979    let remainder = left % right;
9980    // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
9981    // the spec makes the sign match the dividend.
9982    if remainder == 0.0 {
9983        0.0f64.copysign(left)
9984    } else {
9985        remainder
9986    }
9987}
9988
9989fn negate(value: Value) -> Value {
9990    match value {
9991        Value::Int(0) => Value::Float(-0.0),
9992        Value::Int(i) => Value::Int(-i),
9993        other => Value::Float(-other.to_number()),
9994    }
9995}
9996
9997fn increment(value: Value) -> Value {
9998    match value {
9999        Value::Int(i) => match i.checked_add(1) {
10000            Some(next) => Value::Int(next),
10001            None => Value::Float(i as f64 + 1.0),
10002        },
10003        other => Value::Float(other.to_number() + 1.0),
10004    }
10005}
10006
10007fn decrement(value: Value) -> Value {
10008    match value {
10009        Value::Int(i) => match i.checked_sub(1) {
10010            Some(next) => Value::Int(next),
10011            None => Value::Float(i as f64 - 1.0),
10012        },
10013        other => Value::Float(other.to_number() - 1.0),
10014    }
10015}
10016
10017/// Compare a `BigInt` with an `f64` on their mathematical values.
10018///
10019/// Neither side is rounded to the other's precision: the number is split into its integer
10020/// part (compared as an exact bigint) and its fraction, which is what decides the answer
10021/// when the integer parts are equal. An infinite value is larger than every bigint.
10022fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
10023    use std::cmp::Ordering;
10024    if number.is_nan() {
10025        return None;
10026    }
10027    if number.is_infinite() {
10028        return Some(if number > 0.0 {
10029            Ordering::Less
10030        } else {
10031            Ordering::Greater
10032        });
10033    }
10034    let truncated = number.trunc();
10035    // A number wider than `i128` still has an exact integer part, but no bigint form we can
10036    // build cheaply; the sign of the difference is all that is needed, so compare against
10037    // the bigint's own magnitude instead.
10038    if truncated.abs() >= 1.7e38 {
10039        let big_as_f64 = big.to_f64();
10040        return big_as_f64.partial_cmp(&number);
10041    }
10042    let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
10043    match big.cmp(&integer) {
10044        Ordering::Equal => {
10045            // Same integer part: the fraction decides, and a negative number's fraction is
10046            // below the integer (`-1.5` truncates to `-1`).
10047            if number > truncated {
10048                Some(Ordering::Less)
10049            } else if number < truncated {
10050                Some(Ordering::Greater)
10051            } else {
10052                Some(Ordering::Equal)
10053            }
10054        }
10055        other => Some(other),
10056    }
10057}