quickjs/interp.rs
1//! The bytecode interpreter.
2//!
3//! The machine is the same shape as the reference's: a value stack per frame, a
4//! program counter into `js_compile`'s resolved bytecode, and a frame chain. Two
5//! properties of that design are worth stating up front because they are visible
6//! everywhere below.
7//!
8//! **Frames are explicit, not recursive.** A JavaScript call pushes a frame onto
9//! [`Interp::frames`] and the loop continues; it never recurses in Rust. Deep
10//! JavaScript recursion therefore costs heap, not C stack, and the depth limit is
11//! ours to enforce rather than the host's to crash.
12//!
13//! **Exceptions live on the value stack.** `catch` pushes a [`Value::CatchOffset`]
14//! marker and an exception is found by walking the frame's stack downwards looking
15//! for the innermost one. There is no side table, which is why a `try` inside a
16//! loop costs nothing until it throws.
17
18use std::collections::{BTreeMap, BTreeSet};
19
20use js_compile::bytecode::{Atom, ClosureType, Constant, Function as CompiledFunction};
21use js_compile::opcode::Opcode;
22use js_gc::{Gc, Heap, WeakGc};
23
24use crate::object::{
25 Callable, 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` in a *sync* generator: like `Yield`, but the value is already an
66 /// `{value, done}` object from the inner iterator and is handed straight back.
67 YieldStar,
68 /// `yield* expr` in an *async* generator: the compiled shape extracts `.value` first, so
69 /// what was yielded is the plain value and still has to be awaited and wrapped —
70 /// `AsyncGeneratorYield` does `Await(value)` before handing it out. Sharing `YieldStar`
71 /// made it pass a bare value through as if it were an iterator result, so
72 /// `async function* g(){ yield* [1] }` answered `{value: {value: 1, done: false}}`.
73 AsyncYieldStar,
74 /// `await expr`: the value is a promise the async machinery has to settle first.
75 Await,
76}
77
78/// Everything one JavaScript realm owns.
79///
80/// A realm is the set of objects a script can reach without naming them: the global
81/// object, the prototype chain roots, and the global binding cells.
82pub struct Realm {
83 /// The global object.
84 pub global: Gc<JsObject>,
85 /// `Object.prototype`.
86 pub object_proto: Gc<JsObject>,
87 /// `Function.prototype`, which is itself callable.
88 pub function_proto: Gc<JsObject>,
89 /// `Array.prototype`.
90 pub array_proto: Gc<JsObject>,
91 /// Reference cells for globals declared by the script.
92 ///
93 /// A declared global is read with `get_var` (by name) but written with
94 /// `put_var_ref` (through the cell), so the cell is what makes a function
95 /// declaration and its uses agree on one binding.
96 pub globals: BTreeMap<String, Gc<Cell>>,
97 /// Names of the globals that came from a *declaration*, which are
98 /// non-configurable properties of the global object.
99 pub declared: Vec<String>,
100 /// Names among the lexical globals that are `const`.
101 ///
102 /// `const`-ness cannot be read back off the bytecode in every case: a closure that
103 /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
104 /// path does not carry, so a store through it would look like a plain `let`. The
105 /// realm records it once, at declaration, and answers for every reader.
106 pub lexical_consts: BTreeSet<String>,
107 /// The error constructors by class name, so a runtime error can throw a real
108 /// `TypeError` instance rather than a look-alike object.
109 pub errors: BTreeMap<&'static str, Gc<JsObject>>,
110 /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
111 pub string_proto: Option<Gc<JsObject>>,
112 /// `Number.prototype`.
113 pub number_proto: Option<Gc<JsObject>>,
114 /// `Boolean.prototype`.
115 pub boolean_proto: Option<Gc<JsObject>>,
116 /// `BigInt.prototype`.
117 pub bigint_proto: Option<Gc<JsObject>>,
118 /// `Error.prototype`, the prototype of every error instance.
119 pub error_proto: Gc<JsObject>,
120 /// `Date.prototype`, so the constructor can build an instance in the
121 /// function-call form (`Date()` returns a string) without going through `new`.
122 pub date_proto: Gc<JsObject>,
123 /// `%GeneratorPrototype%`, the prototype of every generator object.
124 pub generator_proto: Gc<JsObject>,
125 /// `Promise.prototype`, the prototype of every promise.
126 pub promise_proto: Option<Gc<JsObject>>,
127 /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
128 pub async_generator_proto: Option<Gc<JsObject>>,
129 /// `Symbol.prototype`.
130 pub symbol_proto: Option<Gc<JsObject>>,
131 /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
132 /// `_date_value`.
133 ///
134 /// These are *symbol* keys on purpose. A `"_value"` property is visible to
135 /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
136 /// language does not have and `new Error()` listed `_class` beside `message` and
137 /// `stack` — and a caller that copies every own property (which
138 /// `Object.create(null, props)` effectively does) tried to write an internal name and
139 /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
140 /// and `JSON.stringify`, while remaining an ordinary traced property.
141 ///
142 /// `RefCell` because interning is memoisation rather than observable state: filling the
143 /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
144 /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
145 /// built while reporting a failure must not require an exclusive borrow.
146 pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
147
148 /// The `Symbol.for` registry: `key -> symbol`.
149 ///
150 /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
151 /// symbol every time within one script while a fresh realm starts empty.
152 pub symbol_registry: BTreeMap<String, Value>,
153 /// `RegExp.prototype`, filled in by the `RegExp` builtin.
154 pub regexp_proto: Option<Gc<JsObject>>,
155 /// The `RegExp` constructor.
156 pub regexp_ctor: Option<Gc<JsObject>>,
157 /// `SuppressedError.prototype`, which `using` builds its aggregates from.
158 ///
159 /// The prototype rather than the constructor on purpose: a script that replaces
160 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
161 /// error wrapping, which the `using` test suite checks explicitly.
162 pub suppressed_error_proto: Option<Gc<JsObject>>,
163 /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
164 pub disposable_stack_proto: Option<Gc<JsObject>>,
165 /// `Map.prototype`.
166 pub map_proto: Option<Gc<JsObject>>,
167 /// `Set.prototype`.
168 pub set_proto: Option<Gc<JsObject>>,
169 /// Every live `FinalizationRegistry`, held weakly.
170 ///
171 /// The cleanup callback has to run from a *safe point* — a place where script is not
172 /// already executing and no engine borrow is held — and the collector cannot enumerate
173 /// heap objects by type. Registering each registry here gives the drain a list to walk.
174 ///
175 /// The handles are weak on purpose: a registry the script dropped must be collectable,
176 /// and it must not be resurrected merely because the drain knew about it. Entries whose
177 /// target has expired are swept out as the drain walks, so the vector does not grow
178 /// without bound in a program that creates many short-lived registries.
179 pub finalization_registries: Vec<WeakGc<JsObject>>,
180 /// `ArrayBuffer.prototype`.
181 pub array_buffer_proto: Option<Gc<JsObject>>,
182 /// `%TypedArray%.prototype`, the prototype every view type inherits from.
183 pub typed_array_proto: Option<Gc<JsObject>>,
184 /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
185 ///
186 /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
187 /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
188 /// `"Object"` and `r instanceof Int32Array` is false.
189 pub typed_array_protos: Vec<Gc<JsObject>>,
190 /// `DataView.prototype`.
191 pub data_view_proto: Option<Gc<JsObject>>,
192 /// The `AsyncDisposableStack` prototype.
193 pub async_disposable_stack_proto: Option<Gc<JsObject>>,
194 /// `Iterator.prototype`.
195 pub iterator_proto: Option<Gc<JsObject>>,
196 /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
197 ///
198 /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
199 /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
200 /// `[object Iterator Helper]`).
201 pub iterator_helper_proto: Option<Gc<JsObject>>,
202 /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
203 /// that was not already an `Iterator`.
204 ///
205 /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
206 /// untouched and does *not* override `@@toStringTag`, so
207 /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
208 pub iterator_wrap_proto: Option<Gc<JsObject>>,
209 /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
210 pub generator_function_proto: Option<Gc<JsObject>>,
211 /// `%AsyncFunction.prototype%`.
212 pub async_function_proto: Option<Gc<JsObject>>,
213 /// `%AsyncGeneratorFunction.prototype%`.
214 pub async_generator_function_proto: Option<Gc<JsObject>>,
215 /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
216 ///
217 /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
218 /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
219 /// prototype per iterator made every array iterator's prototype distinct.
220 pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
221 /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
222 ///
223 /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
224 /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
225 /// both faster and impossible to break from a script.
226 well_known_symbols: WellKnownSymbols,
227}
228
229/// One binding of the frame that called `eval`, so the eval'd code can read and
230/// write it by name.
231struct EvalBinding {
232 /// The name it was declared with.
233 name: String,
234 /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
235 /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
236 /// a function that declares `a` must find that `a`.
237 frame: usize,
238 /// Which table of that frame it lives in.
239 slot: EvalSlot,
240 /// The slot index within that table.
241 index: usize,
242}
243
244/// Which table of a frame an [`EvalBinding`] indexes.
245#[derive(Clone, Copy)]
246enum EvalSlot {
247 Arg,
248 Local,
249}
250
251/// One activation record.
252struct Frame {
253 /// The bytecode being run.
254 code: Gc<CompiledCode>,
255 /// The cells this closure captured.
256 env: Gc<ClosureEnv>,
257 /// The `this` binding.
258 this: Value,
259 /// Argument slots, sized to the declared parameter count.
260 args: Vec<Value>,
261 /// How many values the caller actually passed, which is what `arguments.length`
262 /// reports and what `...rest` slices from.
263 passed_count: usize,
264 /// The passed values, **only when they do not fit in [`Self::args`]**.
265 ///
266 /// `args` is sized to the declared parameters, so a call that passes no more than
267 /// that already holds every passed value in its first `passed_count` slots — copying
268 /// them here as well was two writes and a buffer per call, on the hottest path in
269 /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
270 /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
271 /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
272 /// its own copy.
273 passed_overflow: Option<Vec<Value>>,
274 /// Local slots.
275 locals: Vec<Value>,
276 /// Reference cells for this frame's own captured bindings.
277 cells: Vec<Gc<Cell>>,
278 /// The operand stack.
279 stack: Vec<Value>,
280 /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
281 local_vars: Option<Gc<LocalVars>>,
282
283 /// Byte offset of the next instruction.
284 pc: usize,
285 /// Byte offset of the instruction being executed, which is what a stack trace
286 /// reports. `pc` has already moved past it by the time an instruction runs.
287 at: usize,
288 /// The callee, so a native builtin can tell which constructor it is.
289 callee: Value,
290 /// `new.target`: the constructor under `new`, `undefined` for a plain call.
291 new_target: Value,
292 /// What this frame costs against [`Interp::stack_limit`], in bytes.
293 ///
294 /// Cached rather than recomputed because it is charged on every call and a call is the
295 /// hottest thing in the interpreter.
296 cost: usize,
297 /// [`Interp::stack_used`] before this frame was pushed.
298 ///
299 /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
300 /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
301 /// leave the counter wrong. There are eight places that drop frames; one subtraction
302 /// forgotten in any of them would leak budget until the depth limit moved.
303 stack_base: usize,
304 /// Whether this frame's body ended in a `tail_call`.
305 ///
306 /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
307 /// with its own frame just like `call` does and only skips storing the result
308 /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
309 /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
310 /// pushed as usual, and this marker makes its return value the *caller's* return
311 /// value without running the instructions after the call.
312 tail: bool,
313}
314
315impl Frame {
316 /// The values the caller actually passed, which is what `arguments` exposes.
317 ///
318 /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
319 fn passed(&self) -> &[Value] {
320 match &self.passed_overflow {
321 Some(values) => values,
322 None => &self.args[..self.passed_count],
323 }
324 }
325
326 /// The decoded instructions of the function this frame runs.
327 ///
328 /// A method rather than `frame.code.insns` at the call site so that the borrow is
329 /// obviously of the frame — the dispatch loop holds one across a `get`.
330 fn insns(&self) -> &[crate::insn::Insn] {
331 &self.code.insns
332 }
333}
334
335impl js_gc::Trace for Frame {
336 fn trace(&self, tracer: &mut js_gc::Tracer) {
337 self.code.trace(tracer);
338 self.env.trace(tracer);
339 self.this.trace(tracer);
340 for value in &self.args {
341 value.trace(tracer);
342 }
343 for value in self.passed() {
344 value.trace(tracer);
345 }
346 for value in &self.locals {
347 value.trace(tracer);
348 }
349 for cell in &self.cells {
350 cell.trace(tracer);
351 }
352 if let Some(local_vars) = &self.local_vars {
353 tracer.visit(local_vars);
354 }
355 for value in &self.stack {
356 value.trace(tracer);
357 }
358 self.callee.trace(tracer);
359 self.new_target.trace(tracer);
360 }
361}
362
363/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
364/// emitted `if_false` treats as "keep going".
365/// How many finished frames' value buffers are kept for reuse.
366const RECYCLE_SLOTS: usize = 8;
367
368/// The largest buffer worth keeping. See [`Interp::free_values`].
369const RECYCLE_MAX_CAPACITY: usize = 4096;
370
371const RESUME_NEXT: i32 = 0;
372/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
373/// generator fall into its `return_async`.
374const RESUME_RETURN: i32 = 1;
375/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
376/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
377/// must forward the exception into the inner iterator rather than finish.
378const RESUME_THROW: i32 = 2;
379
380/// One microtask.
381///
382/// The queue holds *data* rather than closures because its contents are GC values: a
383/// closure would be invisible to the collector, and a pending reaction is exactly the
384/// kind of thing that must keep its handlers and its promise alive.
385pub enum Job {
386 /// A `then` reaction about to run.
387 Reaction {
388 /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
389 handler: Option<Value>,
390 /// The value or reason to call it with.
391 argument: Value,
392 /// Whether the source promise rejected, which decides the pass-through kind.
393 rejected: bool,
394 /// The promise the answer settles.
395 promise: Gc<JsObject>,
396 },
397 /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
398 Thenable {
399 /// The `then` that was found on the value.
400 then: Value,
401 /// The thenable itself, which becomes `then`'s `this`.
402 value: Value,
403 /// The promise being resolved.
404 promise: Gc<JsObject>,
405 },
406 /// A pending `import(specifier)`.
407 Import {
408 /// The specifier, already converted to a string.
409 specifier: String,
410 /// The module that asked, which the specifier resolves against.
411 referrer: String,
412 /// The promise `import()` handed back.
413 promise: Gc<JsObject>,
414 },
415 /// An async generator resuming after the value it awaited settled.
416 GeneratorResume {
417 /// The async generator to continue.
418 generator: Gc<JsObject>,
419 /// The promise the pending method returned.
420 promise: Gc<JsObject>,
421 /// Whether this delivers the value or raises the reason.
422 kind: ResumeKind,
423 /// The settled value, or the rejection reason.
424 value: Value,
425 },
426 /// An async function resuming after the value it awaited settled.
427 Resume {
428 /// The body, parked in a coroutine.
429 coroutine: Gc<JsObject>,
430 /// The promise the async function handed its caller.
431 promise: Gc<JsObject>,
432 /// Whether this resumption delivers a value or raises one.
433 kind: ResumeKind,
434 /// The settled value, or the rejection reason.
435 value: Value,
436 },
437}
438
439/// One macro-task: work the event loop owes the script but has not run yet.
440///
441/// The microtask queue ([`Job`]) is different: those run before the host regains control.
442/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
443/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
444/// logic: the engine decides *what* is due, the host decides *how to wait*.
445///
446/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
447/// reference counting even though nothing else references it — the same rule the `HostFn`
448/// documentation states from the other side (a host closure must not hold a `Gc`, so the
449/// `Gc` lives here instead).
450pub enum Task {
451 /// A `setTimeout` that is due at `due_at`.
452 ///
453 /// There is no `setInterval` variant because the reference has no `os.setInterval` at
454 /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
455 /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
456 /// would give this engine a timer the reference cannot produce, with nothing to
457 /// compare it against.
458 Timer {
459 /// The id `setTimeout` returned, for `clearTimeout`.
460 id: i32,
461 /// What to call when it fires.
462 callback: Value,
463 /// When it becomes runnable, as a monotonic instant.
464 due_at: std::time::Instant,
465 },
466}
467
468/// A descriptor the host has to poll, and which directions have a handler.
469///
470/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
471/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
472/// blocks on it, and the host reports back through [`Interp::fire_fd`].
473#[derive(Debug, Clone, Copy, PartialEq, Eq)]
474pub struct FdInterest {
475 /// The descriptor to watch.
476 pub fd: i32,
477 /// Whether `os.setReadHandler` registered a callback.
478 pub read: bool,
479 /// Whether `os.setWriteHandler` registered a callback.
480 pub write: bool,
481}
482
483/// The callbacks registered for one descriptor, per direction.
484#[derive(Default)]
485pub(crate) struct FdHandlers {
486 /// `os.setReadHandler`'s callback.
487 pub read: Option<Value>,
488 /// `os.setWriteHandler`'s callback.
489 pub write: Option<Value>,
490}
491
492/// The file name `eval` reports, which the reference does not inherit from the caller.
493///
494/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
495/// reference and the names show up in stack traces.
496/// The description of the private symbol a class brand is made from.
497///
498/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
499/// place no script can reach, since no expression can name a private symbol.
500const BRAND_DESCRIPTION: &str = "brand";
501
502/// One validated property lookup.
503///
504/// Covers both own-property hits and prototype hits. The second kind was deliberately left
505/// uncached at first ("a prototype hit depends on more than the object and the name"), and
506/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
507/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
508/// names on every iteration (measured: 100 ns per call over an empty loop).
509pub struct FieldCache {
510 /// The name, so two different properties of one object do not collide.
511 key: PropertyKey,
512 /// Where the value was found, relative to the chain below.
513 index: usize,
514 /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
515 level: u8,
516 /// The receiver and every prototype down to (and including) the level that answered,
517 /// each with the length of its property table at the time.
518 ///
519 /// That length is the whole guard, and it is sufficient for the ways the answer can
520 /// change without a lookup: adding or deleting any property moves it, and a
521 /// same-length rewrite is caught by `cached_data_property` re-checking the key and
522 /// refusing an accessor. Storing the *whole* chain — not just the object that answered
523 /// — is what catches a property appearing on an *intermediate* prototype and shadowing
524 /// the one that was cached.
525 ///
526 /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
527 /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
528 chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
529}
530
531/// How many links of a prototype chain a [`FieldCache`] remembers.
532///
533/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
534/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
535/// at three.
536const MAX_CACHED_CHAIN: usize = 3;
537
538/// A remembered global-variable lookup.
539///
540/// A `var` global is an ordinary property of the global object, so reading one walks the
541/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
542/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
543/// fixed by the bytecode, and the slot in the object's table only changes if the global
544/// object is mutated, which the index-and-name check below catches.
545pub struct GlobalCache {
546 /// The global object the lookup was resolved on, weakly.
547 object: js_gc::WeakGc<JsObject>,
548 /// Index of the data property in the global object's table.
549 index: usize,
550}
551
552/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
553const GLOBAL_CACHE_SLOTS: usize = 1024;
554
555/// How many property lookups are remembered.
556///
557/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
558/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
559/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
560/// lookup itself. Making it bigger stops helping: the working set of a real program's
561/// property sites is bounded by its code size.
562const FIELD_CACHE_SLOTS: usize = 4096;
563
564/// How much the heap may grow past the last `out of memory` before saying it again.
565///
566/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
567/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
568/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
569/// because it looks like it works. The reference gets this for free: it fails inside
570/// `js_malloc`, and its printing path happens not to allocate.
571///
572/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
573/// allocating is stopped within a rounding error of the limit) and far above what a
574/// handler needs.
575const OOM_HYSTERESIS: usize = 64 * 1024;
576
577/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
578pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
579
580/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
581///
582/// Chosen so that the byte budget is what actually decides for every ordinary
583/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
584/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
585/// millions of frames.
586pub const MAX_FRAMES: usize = 200_000;
587
588const EVAL_FILE: &str = "<input>";
589
590/// The file name `std.evalScript` reports.
591const EVAL_SCRIPT_FILE: &str = "<evalScript>";
592
593/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
594///
595/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
596/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
597fn clamp_delay(delay_ms: f64) -> std::time::Duration {
598 // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
599 // on a float, which reads as a typo even when it is deliberate. Both NaN and a
600 // non-positive delay mean "due now".
601 if delay_ms.is_nan() || delay_ms <= 0.0 {
602 return std::time::Duration::ZERO;
603 }
604 std::time::Duration::from_secs_f64(delay_ms / 1000.0)
605}
606
607impl js_gc::Trace for Task {
608 fn trace(&self, tracer: &mut js_gc::Tracer) {
609 let Task::Timer { callback, .. } = self;
610 callback.trace(tracer);
611 }
612}
613
614/// What one turn of the event loop did, so the caller cannot spin by accident.
615///
616/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
617/// core until the timer is due. Naming the three cases makes the wait explicit.
618#[derive(Debug, Clone, Copy, PartialEq, Eq)]
619pub enum Turn {
620 /// Something ran. Call again immediately — there may be more ready work.
621 Ran,
622 /// Nothing is runnable, but descriptors are registered: the host must poll
623 /// [`Interp::pending_fds`] for at most this long, then report readiness with
624 /// [`Interp::fire_fd`].
625 ///
626 /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
627 /// the failure this project treats as worst — a handler that silently never fires —
628 /// so the two cannot be confused by accident.
629 Poll(std::time::Duration),
630 /// Nothing is runnable yet, but something is pending. Block at most this long, then
631 /// call again.
632 Wait(std::time::Duration),
633 /// Nothing is pending at all: the loop is done.
634 Done,
635}
636
637impl js_gc::Trace for Job {
638 fn trace(&self, tracer: &mut js_gc::Tracer) {
639 match self {
640 Job::Reaction {
641 handler,
642 argument,
643 promise,
644 ..
645 } => {
646 if let Some(handler) = handler {
647 handler.trace(tracer);
648 }
649 argument.trace(tracer);
650 tracer.visit(promise);
651 }
652 Job::Thenable {
653 then,
654 value,
655 promise,
656 } => {
657 then.trace(tracer);
658 value.trace(tracer);
659 tracer.visit(promise);
660 }
661 Job::Resume {
662 coroutine,
663 promise,
664 value,
665 ..
666 } => {
667 tracer.visit(coroutine);
668 tracer.visit(promise);
669 value.trace(tracer);
670 }
671 Job::Import { promise, .. } => tracer.visit(promise),
672 Job::GeneratorResume {
673 generator,
674 promise,
675 value,
676 ..
677 } => {
678 tracer.visit(generator);
679 tracer.visit(promise);
680 value.trace(tracer);
681 }
682 }
683 }
684}
685
686/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
687#[derive(Debug, Clone, Copy, PartialEq, Eq)]
688pub enum ResumeKind {
689 /// The generator was just created and is being run to its first suspension.
690 Start,
691 /// `next(v)`.
692 Next,
693 /// `return(v)`.
694 Return,
695 /// `throw(e)`.
696 Throw,
697}
698
699/// A generator object's saved execution.
700///
701/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
702/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
703/// separately allocated buffers.
704pub struct GeneratorState {
705 /// The detached frame, or `None` once the generator has finished or while it runs.
706 frame: Option<Frame>,
707 /// How far it got.
708 phase: GeneratorPhase,
709 /// Whether the last suspension was an `await` rather than a `yield`.
710 ///
711 /// The two resume with *different stack shapes*: a `yield` is re-entered with the
712 /// value and a magic number, because the emitted code branches on which method
713 /// resumed it, while an `await` simply continues with its value. Getting this wrong
714 /// leaves an extra value on the operand stack that the next instruction then
715 /// consumes — a wrong answer rather than a crash.
716 parked_on_await: bool,
717 /// Whether the last suspension was a `yield*` rather than a plain `yield`.
718 ///
719 /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
720 /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
721 /// has to be forwarded into the inner iterator's `throw` method instead — which is the
722 /// `rethrow` branch the compiled delegation emits — because that is the whole point of
723 /// delegating. Tracking it as part of the phase, the way the reference splits
724 /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
725 /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
726 /// exception and never reached `xs.throw`.
727 parked_on_yield_star: bool,
728 /// Pending `next`/`return`/`throw` calls, oldest first.
729 ///
730 /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
731 /// called back to back must answer in that order, with the second call's value
732 /// arriving at the *second* `yield`. Running each call straight into the body — which
733 /// is what this engine did before — delivered the last queued value to whichever
734 /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
735 /// `a === b ===` the final argument.
736 ///
737 /// The front entry is the one being served; it stays there (with `async_busy` set)
738 /// until its promise settles, because an `await` inside the body is a suspension of
739 /// the *driver*, not the end of the request.
740 requests: std::collections::VecDeque<AsyncRequest>,
741 /// Whether the front request is in flight.
742 async_busy: bool,
743}
744
745/// How one async-generator request ended.
746enum AsyncOutcome {
747 /// The method answered this `{value, done}`.
748 Value(Value),
749 /// The body threw.
750 Error(Value),
751}
752
753/// One queued `next`/`return`/`throw` on an async generator: the reference's
754/// `JSAsyncGeneratorRequest`.
755pub struct AsyncRequest {
756 /// Which method was called.
757 kind: ResumeKind,
758 /// Its argument.
759 value: Value,
760 /// The promise the method answered.
761 promise: Gc<JsObject>,
762}
763
764/// Which of §27.5.3.3's states a generator is in.
765#[derive(Debug, Clone, Copy, PartialEq, Eq)]
766enum GeneratorPhase {
767 /// Created, `initial_yield` reached, body not entered.
768 SuspendedStart,
769 /// Parked at a `yield`.
770 SuspendedYield,
771 /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
772 Executing,
773 /// Finished; the frame is gone.
774 Completed,
775}
776
777impl js_gc::Trace for GeneratorState {
778 fn trace(&self, tracer: &mut js_gc::Tracer) {
779 if let Some(frame) = &self.frame {
780 frame.trace(tracer);
781 }
782 for request in &self.requests {
783 request.value.trace(tracer);
784 tracer.visit(&request.promise);
785 }
786 }
787}
788
789/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
790/// them in.
791///
792/// Each is a field rather than a map entry because the runtime reads them on hot paths
793/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
794/// failure — reaching a default here means the builtin did not install, and every
795/// accessor panics rather than silently answering `undefined`.
796///
797/// [`builtins::symbol`]: crate::builtins::symbol
798#[derive(Default)]
799pub struct WellKnownSymbols {
800 /// The symbol values, positionally. Empty until `Symbol` installs.
801 symbols: Vec<Value>,
802}
803
804/// Which well-known symbol a caller wants.
805///
806/// A typed accessor beats passing a name around: a typo is a compile error rather than
807/// an `undefined` key that quietly matches nothing.
808#[derive(Debug, Clone, Copy, PartialEq, Eq)]
809pub enum WellKnown {
810 /// `Symbol.toPrimitive`.
811 ToPrimitive,
812 /// `Symbol.iterator`.
813 Iterator,
814 /// `Symbol.match`.
815 Match,
816 /// `Symbol.matchAll`.
817 MatchAll,
818 /// `Symbol.replace`.
819 Replace,
820 /// `Symbol.search`.
821 Search,
822 /// `Symbol.split`.
823 Split,
824 /// `Symbol.toStringTag`.
825 ToStringTag,
826 /// `Symbol.isConcatSpreadable`.
827 IsConcatSpreadable,
828 /// `Symbol.hasInstance`.
829 HasInstance,
830 /// `Symbol.species`.
831 Species,
832 /// `Symbol.unscopables`.
833 Unscopables,
834 /// `Symbol.asyncIterator`.
835 AsyncIterator,
836 /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
837 Disposable,
838 /// `Symbol.asyncDispose` — the awaited form.
839 AsyncDisposable,
840}
841
842impl WellKnown {
843 /// The index `Symbol`'s installer creates this symbol at.
844 fn index(self) -> usize {
845 match self {
846 WellKnown::ToPrimitive => 0,
847 WellKnown::Iterator => 1,
848 WellKnown::Match => 2,
849 WellKnown::MatchAll => 3,
850 WellKnown::Replace => 4,
851 WellKnown::Search => 5,
852 WellKnown::Split => 6,
853 WellKnown::ToStringTag => 7,
854 WellKnown::IsConcatSpreadable => 8,
855 WellKnown::HasInstance => 9,
856 WellKnown::Species => 10,
857 WellKnown::Unscopables => 11,
858 WellKnown::AsyncIterator => 12,
859 WellKnown::Disposable => 13,
860 WellKnown::AsyncDisposable => 14,
861 }
862 }
863}
864
865impl Realm {
866 /// Record the well-known symbols, in the order `Symbol`'s installer made them.
867 pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
868 self.well_known_symbols.symbols = symbols;
869 }
870
871 /// A well-known symbol.
872 pub fn well_known(&self, which: WellKnown) -> Value {
873 self.well_known_symbols
874 .symbols
875 .get(which.index())
876 .cloned()
877 .unwrap_or(Value::Undefined)
878 }
879
880 /// The well-known symbol as a property key.
881 pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
882 match self.well_known(which) {
883 Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
884 // Unreachable once `Symbol` has installed; an empty string key matches
885 // nothing, which degrades to "the object has no such method".
886 _ => PropertyKey::from(String::new()),
887 }
888 }
889}
890
891/// The interpreter: a realm plus a frame stack.
892pub struct Interp<'a> {
893 /// The heap everything is allocated on.
894 pub heap: &'a Heap,
895 /// The realm.
896 pub realm: Realm,
897 /// Active frames, outermost first.
898 frames: Vec<Frame>,
899 /// Value buffers from frames that have finished, reused by the next call.
900 ///
901 /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
902 /// the locals and the operand stack — and free all four on return. `call:recursion`
903 /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
904 /// keep 27 frames alive. Recycling makes it proportional to *depth*.
905 ///
906 /// Bounded in both directions: a few buffers per kind, and none larger than
907 /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
908 /// and keeping its buffer would pin that memory for the rest of the run.
909 free_values: Vec<Vec<Value>>,
910 /// A strict-mode `eval`'s own variable scope, while its script runs.
911 ///
912 /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
913 /// become a global. Name lookups still fall through to the realm, which is why
914 /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
915 eval_scope: Option<BTreeMap<String, Value>>,
916 /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
917 /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
918 eval_depth: usize,
919 /// The calling frame's own bindings, which the running `eval` can read and write.
920 ///
921 /// Held separately from [`Interp::eval_scope`] because these already exist: reads
922 /// come from the frame, and a write is applied back to the frame (or to the cell
923 /// the frame captured) when the eval finishes. That is what makes
924 /// `f("a = 3")` visible to the caller as `a === 3`.
925 eval_bindings: Vec<EvalBinding>,
926 /// The calling frame's `arguments`, while an `eval` runs.
927 ///
928 /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
929 /// own yet still has to see the caller's `arguments`.
930 eval_arguments: Option<Value>,
931 /// The `with` objects live at the moment the running `eval` started, innermost first.
932 ///
933 /// `None` outside an eval, which is what keeps a finished block's object from
934 /// shadowing ordinary bytecode reads.
935 eval_with: Option<Vec<Gc<JsObject>>>,
936 /// The bindings the running direct `eval` makes visible, as name → cell.
937 ///
938 /// Set for the duration of an eval and then restored, but every closure created
939 /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
940 /// `eval("f = () => i")` work after the eval has returned.
941 active_eval_scope: Option<Gc<EvalScope>>,
942 /// The frame that called the direct `eval` currently running, if any.
943 ///
944 /// A sloppy eval declares its `var`s in that frame's variable environment rather than
945 /// on the global object, which is what keeps
946 /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
947 /// gives each call its own `x`.
948 eval_caller: Option<Option<usize>>,
949 /// The caller's `new.target`, while an `eval` runs.
950 ///
951 /// The eval'd code is a script with no constructor of its own, so it inherits the
952 /// one the enclosing function was called with.
953 eval_new_target: Option<Value>,
954 /// `new.target` for the frame about to be pushed.
955 ///
956 /// `construct` parks the constructor here and `push_frame` takes it, which is how the
957 /// value reaches the frame without threading a parameter through every call site.
958 pending_new_target: Option<Value>,
959 /// Names of the native functions currently executing, outermost first.
960 ///
961 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
962 /// trace still names it with `(native)` instead of a position, so the names are
963 /// tracked separately and stitched into [`Interp::stack_trace`].
964 ///
965 /// The third field is how many bytecode frames were live when the native was entered,
966 /// which is what places it *among* them rather than before all of them. Native
967 /// functions used to be emitted up front on the grounds that they never re-enter
968 /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
969 /// The natives currently running, innermost last: the function object and the
970 /// depth it was entered at.
971 ///
972 /// The *name* is deliberately not stored. It used to be, read with
973 /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
974 /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
975 /// benchmark. A stack trace is built rarely; it can read the name then.
976 native_frames: Vec<(Gc<JsObject>, usize)>,
977 /// The native function currently executing, for the ones that have to know *which*
978 /// function they are — a typed-array constructor reads its element type off itself.
979 ///
980 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
981 /// reports whatever the enclosing bytecode frame was called with.
982 current_native: Option<Gc<JsObject>>,
983 /// Text written by `print` and friends, in order.
984 ///
985 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
986 /// once at the end, which is also when upstream's line buffering becomes
987 /// visible for the cases compared here.
988 pub output: String,
989 /// Where `print` also writes, as it goes. `output` keeps the full log for
990 /// [`crate::Context::output`]; this is the live copy, flushed per line.
991 ///
992 /// Both exist on purpose. A host that gives a script a sink sees output *when it
993 /// happens* — which is what a timer callback's `console.log` has to do, and what the
994 /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
995 /// this repository keep reading the accumulated `String`. Buffering only (no sink)
996 /// would show a script's output all at once when it finished.
997 pub output_sink: Option<Box<dyn std::io::Write>>,
998 /// Where recent property reads found their value.
999 ///
1000 /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1001 /// table remembering *which object* and *which entry of its property table* answered a
1002 /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1003 /// can move; the property can become an accessor), which is what makes a stale entry a
1004 /// miss rather than a wrong answer.
1005 ///
1006 /// The object is held weakly: a cache that held it strongly would keep up to
1007 /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1008 /// program cannot see and cannot work around.
1009 pub field_cache: Vec<Option<FieldCache>>,
1010 /// Global lookups, by binding slot. See [`GlobalCache`].
1011 global_cache: Vec<Option<GlobalCache>>,
1012 /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1013 /// under its limit. See [`Interp::check_memory`].
1014 pub oom_reported_at: usize,
1015 /// The most stack a JavaScript call chain may use, in bytes of frame state.
1016 ///
1017 /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1018 /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1019 /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1020 /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1021 /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1022 /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1023 ///
1024 /// The numbers come out close for the same reason a C frame and a heap frame of this
1025 /// shape cost about the same (both are a few hundred bytes, dominated by the value
1026 /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1027 /// and this engine lands in the same neighbourhood — measured, not fudged, by
1028 /// `crates/quickjs-cli/tests/limits.rs`.
1029 pub stack_limit: usize,
1030 /// The most frames that may be live at once, whatever the byte budget says.
1031 ///
1032 /// A second bound for a reason the reference does not have: our frames cost less than
1033 /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1034 /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1035 /// `--stack-size 1G` from being a memory bomb.
1036 pub max_frames: usize,
1037 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1038 ///
1039 /// Script execution does not return until this has drained, which is what makes
1040 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1041 /// than never. Reactions append to it while it drains, so the loop is a `while` and
1042 /// not a `for`.
1043 pub(crate) jobs: std::collections::VecDeque<Job>,
1044 /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1045 ///
1046 /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1047 /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1048 pub(crate) tasks: Vec<Task>,
1049 /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1050 /// barrier'd evaluation started.
1051 ///
1052 /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1053 /// lets a REPL report an error from the line it just evaluated without also reporting
1054 /// its own readline loop.
1055 trace_barriers: Vec<usize>,
1056 /// `os.signal` handlers, keyed by signal number.
1057 ///
1058 /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1059 /// a handler cannot be freed while it is still registered.
1060 pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1061 /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1062 ///
1063 /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1064 /// that is only reachable from a host closure could be freed while still registered.
1065 pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1066 /// The next timer id.
1067 ///
1068 /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1069 /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1070 next_timer_id: i32,
1071 /// Errors thrown by timer callbacks, already rendered.
1072 ///
1073 /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1074 /// that throws has no promise behind it. Both are reported by the host at the end of
1075 /// the loop, but only one is fixed up by a later `.catch`.
1076 timer_errors: Vec<String>,
1077 /// The module registry, keyed by canonical name.
1078 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1079 /// How the host turns a specifier into bytes.
1080 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1081 /// The module the host was asked to run, for `import.meta.main`.
1082 pub main_module_name: Option<String>,
1083 /// Module bodies currently running, innermost last.
1084 ///
1085 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1086 /// this is the only place that knows which module that is.
1087 pub module_stack: Vec<String>,
1088 /// Rejections that no handler has claimed, with the promise they belong to.
1089 ///
1090 /// A `then` registered later prunes its entry, which is why the promise is kept: the
1091 /// reason alone cannot say whether somebody eventually listened.
1092 unhandled: Vec<(Gc<JsObject>, Value)>,
1093}
1094
1095impl<'a> Interp<'a> {
1096 /// Build an interpreter over `heap`, with a fresh realm.
1097 pub fn new(heap: &'a Heap) -> Interp<'a> {
1098 let object_proto = JsObject::ordinary(heap, None);
1099 let function_proto = JsObject::function(
1100 heap,
1101 Some(object_proto.clone()),
1102 Callable::Native {
1103 func: |_, _, _| Ok(Value::Undefined),
1104 own_instance: false,
1105 },
1106 );
1107 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1108 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1109 let mut interp = Interp {
1110 heap,
1111 realm: Realm {
1112 global,
1113 object_proto,
1114 function_proto,
1115 array_proto,
1116 globals: BTreeMap::new(),
1117 declared: Vec::new(),
1118 lexical_consts: BTreeSet::new(),
1119 errors: BTreeMap::new(),
1120 string_proto: None,
1121 number_proto: None,
1122 boolean_proto: None,
1123 bigint_proto: None,
1124 error_proto: JsObject::ordinary(heap, None),
1125 date_proto: JsObject::ordinary(heap, None),
1126 generator_proto: JsObject::ordinary(heap, None),
1127 promise_proto: None,
1128 async_generator_proto: None,
1129 symbol_proto: None,
1130 symbol_registry: BTreeMap::new(),
1131 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1132 regexp_proto: None,
1133 regexp_ctor: None,
1134 suppressed_error_proto: None,
1135 disposable_stack_proto: None,
1136 map_proto: None,
1137 set_proto: None,
1138 finalization_registries: Vec::new(),
1139 array_buffer_proto: None,
1140 typed_array_proto: None,
1141 typed_array_protos: Vec::new(),
1142 data_view_proto: None,
1143 async_disposable_stack_proto: None,
1144 iterator_proto: None,
1145 iterator_helper_proto: None,
1146 iterator_wrap_proto: None,
1147 generator_function_proto: None,
1148 async_function_proto: None,
1149 async_generator_function_proto: None,
1150 iterator_protos: std::collections::BTreeMap::new(),
1151 well_known_symbols: WellKnownSymbols::default(),
1152 },
1153 frames: Vec::new(),
1154 free_values: Vec::new(),
1155 global_cache: {
1156 let mut cache = Vec::new();
1157 cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1158 cache
1159 },
1160 eval_scope: None,
1161 eval_depth: 0,
1162 eval_bindings: Vec::new(),
1163 eval_arguments: None,
1164 eval_with: None,
1165 active_eval_scope: None,
1166 eval_caller: None,
1167 pending_new_target: None,
1168 eval_new_target: None,
1169 native_frames: Vec::new(),
1170 current_native: None,
1171 output: String::new(),
1172 output_sink: None,
1173 field_cache: {
1174 let mut cache = Vec::new();
1175 cache.resize_with(FIELD_CACHE_SLOTS, || None);
1176 cache
1177 },
1178 oom_reported_at: 0,
1179 // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1180 // absent.
1181 stack_limit: DEFAULT_STACK_SIZE,
1182 max_frames: MAX_FRAMES,
1183 jobs: std::collections::VecDeque::new(),
1184 tasks: Vec::new(),
1185 trace_barriers: Vec::new(),
1186 signal_handlers: std::collections::BTreeMap::new(),
1187 fd_handlers: std::collections::BTreeMap::new(),
1188 next_timer_id: 1,
1189 timer_errors: Vec::new(),
1190 modules: std::collections::BTreeMap::new(),
1191 module_loader: None,
1192 main_module_name: None,
1193 module_stack: Vec::new(),
1194 unhandled: Vec::new(),
1195 };
1196 crate::builtins::install(&mut interp);
1197 interp
1198 }
1199
1200 // -- allocation helpers -------------------------------------------------
1201
1202 /// A new string value.
1203 /// A `BigInt` value from a computed big integer.
1204 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1205 Value::BigInt(Gc::new(self.heap, value))
1206 }
1207
1208 /// A string value from bytes that are already WTF-8, which is how a string with an
1209 /// unpaired surrogate reaches a `Value`.
1210 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1211 Value::string_wtf8(self.heap, text)
1212 }
1213
1214 /// A new string value, from text that is valid UTF-8.
1215 pub fn string(&self, text: impl Into<String>) -> Value {
1216 Value::string(self.heap, text)
1217 }
1218
1219 /// A new ordinary object with the given prototype.
1220 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1221 JsObject::ordinary(self.heap, proto)
1222 }
1223
1224 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1225 ///
1226 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1227 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1228 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1229 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1230 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1231 /// said `[object Object]` instead of `[object Array Iterator]`.
1232 ///
1233 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1234 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1235 /// its own.
1236 pub fn new_iterator_prototype(
1237 &mut self,
1238 tag: &str,
1239 next: crate::object::NativeFn,
1240 ) -> Gc<JsObject> {
1241 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1242 return existing.clone();
1243 }
1244 let parent = self.realm.iterator_proto.clone();
1245 let proto = self.new_object(parent);
1246 let next = self.new_native("next", 0, next);
1247 proto.define(
1248 "next",
1249 Property::with_attributes(Value::Object(next), true, false),
1250 );
1251 let key = self.realm.well_known_key(WellKnown::Iterator);
1252 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1253 proto.define_key(
1254 &key,
1255 Property::with_attributes(Value::Object(identity), true, false),
1256 );
1257 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1258 let tag_value = self.string(tag);
1259 proto.define_key(&tag_key, Property::with_attributes(tag_value, false, false));
1260 self.realm
1261 .iterator_protos
1262 .insert(tag.to_string(), proto.clone());
1263 proto
1264 }
1265
1266 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1267 ///
1268 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1269 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1270 /// produced. That is why the two branches are not merged.
1271 pub fn object_own_property_keys(
1272 &mut self,
1273 object: &Gc<JsObject>,
1274 ) -> JsResult<Vec<PropertyKey>> {
1275 if let Some(keys) = self.proxy_own_keys(object)? {
1276 return Ok(keys);
1277 }
1278 // Integer-like keys ascending, then the string keys in insertion order, then the
1279 // symbols — the order every schema that walks an object expects.
1280 let entries = object.property_entries();
1281 let mut numeric: Vec<u32> = Vec::new();
1282 let mut strings: Vec<PropertyKey> = Vec::new();
1283 let mut symbols: Vec<PropertyKey> = Vec::new();
1284 for (key, _) in entries {
1285 match &key {
1286 // A class-private name is never reported by any enumeration: that is the
1287 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1288 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1289 // symbol skip, `Object.assign`) therefore cannot see it.
1290 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1291 PropertyKey::Symbol(_) => symbols.push(key),
1292 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1293 Some(index) => {
1294 if !numeric.contains(&index) {
1295 numeric.push(index);
1296 }
1297 }
1298 None => strings.push(key),
1299 },
1300 }
1301 }
1302 numeric.sort_unstable();
1303 let mut keys: Vec<PropertyKey> = numeric
1304 .into_iter()
1305 .map(|index| PropertyKey::from(index.to_string()))
1306 .collect();
1307 keys.extend(strings);
1308 keys.extend(symbols);
1309 Ok(keys)
1310 }
1311
1312 /// The state behind a promise object, or `None` when `object` is not one.
1313 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1314 object.with(|data| match &data.kind {
1315 ObjectKind::Promise(state) => Some(state.clone()),
1316 _ => None,
1317 })
1318 }
1319
1320 /// A new pending promise.
1321 pub fn new_promise(&mut self) -> Gc<JsObject> {
1322 let proto = self.realm.promise_proto.clone();
1323 let promise = JsObject::ordinary(self.heap, proto);
1324 promise.with_mut(|data| {
1325 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1326 crate::object::PromiseState::default(),
1327 )));
1328 });
1329 promise
1330 }
1331
1332 /// Fulfil `promise`, unless it has already settled.
1333 ///
1334 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1335 /// after `reject`, changes nothing.
1336 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1337 let Some(state) = self.promise_state(promise) else {
1338 return;
1339 };
1340 let reactions = {
1341 let mut state = state.borrow_mut();
1342 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1343 return;
1344 }
1345 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1346 std::mem::take(&mut state.reactions)
1347 };
1348 self.queue_reactions(reactions, value, false);
1349 }
1350
1351 /// Reject `promise`, unless it has already settled.
1352 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1353 let Some(state) = self.promise_state(promise) else {
1354 return;
1355 };
1356 let reactions = {
1357 let mut state = state.borrow_mut();
1358 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1359 return;
1360 }
1361 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1362 std::mem::take(&mut state.reactions)
1363 };
1364 // Remember it only when nothing is listening *now*; a `then` registered later
1365 // prunes the entry in `perform_then`.
1366 if reactions.is_empty() {
1367 self.unhandled.push((promise.clone(), reason.clone()));
1368 }
1369 self.queue_reactions(reactions, reason, true);
1370 }
1371
1372 /// Queue one job per reaction.
1373 ///
1374 /// This is what makes `then` asynchronous even on an already-settled promise:
1375 /// `p.then(f); g()` calls `g` first.
1376 fn queue_reactions(
1377 &mut self,
1378 reactions: Vec<crate::object::PromiseReaction>,
1379 argument: Value,
1380 rejected: bool,
1381 ) {
1382 for reaction in reactions {
1383 let handler = if rejected {
1384 reaction.on_rejected.clone()
1385 } else {
1386 reaction.on_fulfilled.clone()
1387 };
1388 self.jobs.push_back(Job::Reaction {
1389 handler,
1390 argument: argument.clone(),
1391 rejected,
1392 promise: reaction.promise,
1393 });
1394 }
1395 }
1396
1397 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1398 /// resolve/reject pair.
1399 ///
1400 /// The pair are callable objects rather than Rust closures, because the script gets
1401 /// them and may stash them for later.
1402 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1403 let promise = self.new_promise();
1404 let resolve = JsObject::function(
1405 self.heap,
1406 Some(self.realm.function_proto.clone()),
1407 Callable::PromiseResolve(promise.clone()),
1408 );
1409 let reject = JsObject::function(
1410 self.heap,
1411 Some(self.realm.function_proto.clone()),
1412 Callable::PromiseReject(promise.clone()),
1413 );
1414 (promise, Value::Object(resolve), Value::Object(reject))
1415 }
1416
1417 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1418 /// promise, as `{ value: completion }`.
1419 ///
1420 /// The three cases are the reference's, and they differ on purpose:
1421 ///
1422 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1423 /// exception before any promise exists;
1424 /// * a **runtime** error rejects the returned promise;
1425 /// * success resolves it with `{ value }`, where the value is the script's completion
1426 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1427 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1428 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1429 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1430 ///
1431 /// # What this does not do
1432 ///
1433 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1434 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1435 /// the parser and the suspension machinery to accept a suspended top-level script, and
1436 /// is not implemented — such source is a syntax error here. Everything else about the
1437 /// flag is reproduced.
1438 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1439 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1440 // too, and the reference truncates that one at the same place as a runtime failure.
1441 if barrier {
1442 let depth = self.frames.len();
1443 self.trace_barriers.push(depth);
1444 }
1445 // Compiled before the promise exists, so a parse failure propagates as a throw
1446 // instead of being folded into a rejection.
1447 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1448 Ok(compiled) => compiled,
1449 Err(error) => {
1450 if barrier {
1451 self.trace_barriers.pop();
1452 }
1453 return Err(error);
1454 }
1455 };
1456 // An async body answers its own promise, and that promise is what the reference
1457 // hands back — the same object, not a wrapper around it. Its resolution value is
1458 // the `{value}` object the compiled epilogue built.
1459 if compiled.kind.is_async() {
1460 let strict = compiled.strict;
1461 let promise = self.run_eval_script(compiled, strict)?;
1462 if barrier {
1463 self.trace_barriers.pop();
1464 }
1465 return Ok(promise);
1466 }
1467 let (promise, resolve, reject) = self.new_promise_capability();
1468 let strict = compiled.strict;
1469 match self.run_eval_script(compiled, strict) {
1470 Ok(value) => {
1471 // `{ value }` is a plain object, so resolving with it adopts nothing even
1472 // when the completion value is itself a promise.
1473 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1474 self.set_property(&wrapped, "value", value)?;
1475 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1476 }
1477 Err(Signal::Throw(error)) => {
1478 self.call_value(reject, Value::Undefined, vec![error])?;
1479 }
1480 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1481 }
1482 if barrier {
1483 self.trace_barriers.pop();
1484 }
1485 Ok(Value::Object(promise))
1486 }
1487
1488 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1489 ///
1490 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1491 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1492 /// timer table, where the collector already scans it.
1493 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1494 let (promise, resolve, _reject) = self.new_promise_capability();
1495 let resolve = self.new_host_function(
1496 "resolve",
1497 1,
1498 Box::new(
1499 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1500 let value = args.first().cloned().unwrap_or(Value::Undefined);
1501 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1502 },
1503 ),
1504 );
1505 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1506 // timer table is part of what the collector walks.
1507 self.schedule_timer(Value::Object(resolve), delay_ms);
1508 Ok(Value::Object(promise))
1509 }
1510
1511 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1512 /// new promise resolved with it.
1513 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1514 if let Value::Object(object) = &value
1515 && self.promise_state(object).is_some()
1516 {
1517 return Ok(value);
1518 }
1519 let promise = self.new_promise();
1520 self.resolve_promise_with(&promise, value)?;
1521 Ok(Value::Object(promise))
1522 }
1523
1524 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1525 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1526 // Resolving a promise with itself is a `TypeError`. The check exists because the
1527 // alternative is a chain of self-reactions that never settles.
1528 if let Value::Object(object) = &value
1529 && object.ptr_eq(promise)
1530 {
1531 // The spec rejects *and* throws, so both the promise and the caller see it.
1532 let thrown = self.type_error("cannot resolve a promise with itself");
1533 let Signal::Throw(error) = thrown.clone() else {
1534 unreachable!("type_error always throws")
1535 };
1536 self.reject_promise(promise, error);
1537 return Err(thrown);
1538 }
1539 let then = match &value {
1540 Value::Object(object) => self.get_property(object, "then")?,
1541 _ => None,
1542 };
1543 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1544 if !callable_then {
1545 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1546 self.fulfill_promise(promise, value);
1547 return Ok(());
1548 }
1549 // Adopting a thenable is asynchronous — `then` is called from a job, never from
1550 // inside `resolve`, so a script cannot make a promise settle synchronously.
1551 self.jobs.push_back(Job::Thenable {
1552 then: then.expect("checked callable"),
1553 value,
1554 promise: promise.clone(),
1555 });
1556 Ok(())
1557 }
1558
1559 /// `Promise.prototype.then`: register a reaction and answer the derived promise.
1560 pub fn perform_then(
1561 &mut self,
1562 promise: &Gc<JsObject>,
1563 on_fulfilled: Option<Value>,
1564 on_rejected: Option<Value>,
1565 ) -> JsResult<Value> {
1566 let Some(state) = self.promise_state(promise) else {
1567 return Err(self.type_error("not a promise"));
1568 };
1569 // Whether a rejection handler is being attached decides whether a recorded
1570 // rejection stops being unhandled, so it is read before the values are moved.
1571 let has_rejection_handler = on_rejected.is_some();
1572 let derived = self.new_promise();
1573 let reaction = crate::object::PromiseReaction {
1574 on_fulfilled,
1575 on_rejected,
1576 promise: derived.clone(),
1577 };
1578 let settled = {
1579 let mut state = state.borrow_mut();
1580 // A rejection somebody reacts to is no longer unhandled.
1581 state.handled = true;
1582 match &state.status {
1583 crate::object::PromiseStatus::Pending => {
1584 state.reactions.push(reaction.clone());
1585 None
1586 }
1587 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
1588 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
1589 }
1590 };
1591 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
1592 // later, means somebody is listening after all.
1593 if has_rejection_handler {
1594 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
1595 }
1596 if let Some((argument, rejected)) = settled {
1597 let handler = if rejected {
1598 reaction.on_rejected
1599 } else {
1600 reaction.on_fulfilled
1601 };
1602 self.jobs.push_back(Job::Reaction {
1603 handler,
1604 argument,
1605 rejected,
1606 promise: reaction.promise,
1607 });
1608 }
1609 Ok(Value::Object(derived))
1610 }
1611
1612 /// The rejections nobody listened to, formatted the way the reference reports them.
1613 ///
1614 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
1615 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
1616 /// unhandled at the point the queue drains, because a `then` may still be attached
1617 /// before the host acts on it.
1618 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
1619 let entries = std::mem::take(&mut self.unhandled);
1620 // Somebody may have attached a handler after the rejection was recorded, so the
1621 // promise is the authority rather than the list.
1622 let still_unhandled: Vec<Value> = entries
1623 .into_iter()
1624 .filter_map(|(promise, reason)| {
1625 let handled = self
1626 .promise_state(&promise)
1627 .map(|state| state.borrow().handled)
1628 .unwrap_or(true);
1629 (!handled).then_some(reason)
1630 })
1631 .collect();
1632 still_unhandled
1633 .into_iter()
1634 .map(|reason| {
1635 let text = self.describe_exception(&reason);
1636 let stack = match &reason {
1637 Value::Object(object) => self
1638 .get_property(object, "stack")
1639 .ok()
1640 .flatten()
1641 .map(|value| value.to_js_string())
1642 // `stack` carries a trailing newline of its own, which would leave
1643 // a blank line between two reported rejections.
1644 .map(|text| text.trim_end().to_string())
1645 .unwrap_or_default(),
1646 _ => String::new(),
1647 };
1648 if stack.is_empty() {
1649 format!("Possibly unhandled promise rejection: {text}")
1650 } else {
1651 format!("Possibly unhandled promise rejection: {text}\n{stack}")
1652 }
1653 })
1654 .collect()
1655 }
1656
1657 /// Run the microtask queue to exhaustion.
1658 ///
1659 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
1660 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
1661 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
1662 ///
1663 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
1664 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
1665 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
1666 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
1667 crate::builtins::json::parse_text(self, text, true)
1668 }
1669
1670 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
1671 ///
1672 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
1673 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
1674 /// immediately, and `setTimeout(f, -1)` is ordinary code.
1675 ///
1676 /// The callback is called with **no arguments**. The reference stores only the function
1677 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
1678 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
1679 /// extra arguments arrive as `undefined`.
1680 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
1681 let id = self.next_timer_id;
1682 // Wrap rather than grow: the id reaches the script as an `Int32`.
1683 self.next_timer_id = if self.next_timer_id == i32::MAX {
1684 1
1685 } else {
1686 self.next_timer_id + 1
1687 };
1688 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
1689 self.tasks.push(Task::Timer {
1690 id,
1691 callback,
1692 due_at,
1693 });
1694 id
1695 }
1696
1697 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
1698 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
1699 pub fn cancel_timer(&mut self, id: i32) -> bool {
1700 let before = self.tasks.len();
1701 self.tasks.retain(|task| match task {
1702 Task::Timer { id: task_id, .. } => *task_id != id,
1703 });
1704 self.tasks.len() != before
1705 }
1706
1707 /// How long until the earliest pending timer, or `None` when none is pending.
1708 pub fn next_timeout(&self) -> Option<std::time::Duration> {
1709 let now = std::time::Instant::now();
1710 self.tasks
1711 .iter()
1712 .map(|task| match task {
1713 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
1714 })
1715 .min()
1716 }
1717
1718 /// Run one turn of the event loop.
1719 ///
1720 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
1721 /// run at most one due timer, then drain again. The blocking belongs to the caller
1722 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
1723 /// is how it asks.
1724 ///
1725 /// One timer per turn rather than all of them: a timer callback may schedule another
1726 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
1727 /// starve the microtask queue.
1728 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
1729 self.drain_jobs()?;
1730 let now = std::time::Instant::now();
1731 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
1732 // followed by `setTimeout(g, 1)` must run `g` first.
1733 let due = self
1734 .tasks
1735 .iter()
1736 .enumerate()
1737 .filter(|(_, task)| match task {
1738 Task::Timer { due_at, .. } => *due_at <= now,
1739 })
1740 .min_by_key(|(_, task)| match task {
1741 Task::Timer { due_at, .. } => *due_at,
1742 })
1743 .map(|(index, _)| index);
1744 let Some(index) = due else {
1745 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
1746 // descriptor is registered but no timer is closer, so a script that never
1747 // touches the descriptor still gets control back. Without a cap a handler on a
1748 // descriptor that is never ready would block for as long as the host allows.
1749 let timeout = self
1750 .next_timeout()
1751 .unwrap_or(std::time::Duration::from_secs(10))
1752 .min(std::time::Duration::from_secs(10));
1753 if !self.fd_handlers.is_empty() {
1754 // Blocking on a timer while descriptors are registered would starve them,
1755 // and blocking on the descriptors while a timer is due would delay it; the
1756 // host polls with the earlier of the two deadlines, which this timeout is.
1757 return Ok(Turn::Poll(timeout));
1758 }
1759 return Ok(match self.next_timeout() {
1760 Some(wait) => Turn::Wait(wait),
1761 None => Turn::Done,
1762 });
1763 };
1764 let Task::Timer { callback, .. } = self.tasks.remove(index);
1765 let this = Value::Undefined;
1766 // A throwing timer callback must not stop the loop: the reference reports it and
1767 // keeps going, because the alternative is that one bad timer silently stops every
1768 // later one.
1769 // No arguments: see `schedule_timer` — the reference calls the callback bare.
1770 match self.call_value(callback, this, Vec::new()) {
1771 Ok(_) => {}
1772 Err(Signal::Throw(value)) => {
1773 let text = self.describe_exception(&value);
1774 self.timer_errors.push(text);
1775 }
1776 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1777 }
1778 self.drain_jobs()?;
1779 Ok(Turn::Ran)
1780 }
1781
1782 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
1783 ///
1784 /// `callback` of `None` unregisters that direction, and an entry with neither direction
1785 /// left is removed — the reference does the same, so a script can rely on
1786 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
1787 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
1788 let entry = self.fd_handlers.entry(fd).or_default();
1789 if readable {
1790 entry.read = callback;
1791 } else {
1792 entry.write = callback;
1793 }
1794 if entry.read.is_none() && entry.write.is_none() {
1795 self.fd_handlers.remove(&fd);
1796 }
1797 }
1798
1799 /// Register or clear an `os.signal` handler.
1800 ///
1801 /// `None` removes it; the host separately restores the default disposition or sets
1802 /// ignore, because which of those happened is the script's choice (`null` versus
1803 /// `undefined`) and not something this table can express.
1804 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
1805 match handler {
1806 Some(handler) => {
1807 self.signal_handlers.insert(signal, handler);
1808 }
1809 None => {
1810 self.signal_handlers.remove(&signal);
1811 }
1812 }
1813 }
1814
1815 /// Run the handler for `signal`, reporting whether one ran.
1816 ///
1817 /// A throwing handler is reported and the loop continues, like a timer's.
1818 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
1819 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
1820 return Ok(false);
1821 };
1822 match self.call_value(handler, Value::Undefined, Vec::new()) {
1823 Ok(_) => {}
1824 Err(Signal::Throw(value)) => {
1825 let text = self.describe_exception(&value);
1826 self.timer_errors.push(text);
1827 }
1828 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1829 }
1830 self.drain_jobs()?;
1831 Ok(true)
1832 }
1833
1834 /// The descriptors the host has to poll, and in which direction.
1835 ///
1836 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
1837 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
1838 /// `os_poll` asks for.
1839 pub fn pending_fds(&self) -> Vec<FdInterest> {
1840 self.fd_handlers
1841 .iter()
1842 .map(|(fd, entry)| FdInterest {
1843 fd: *fd,
1844 read: entry.read.is_some(),
1845 write: entry.write.is_some(),
1846 })
1847 .collect()
1848 }
1849
1850 /// Call the handler registered for `fd`, reporting whether one ran.
1851 ///
1852 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
1853 /// poll iteration and then restarts the loop, because the handler may have changed the
1854 /// registration list underneath it; doing the same here keeps a handler that
1855 /// unregisters itself from being called with stale state.
1856 ///
1857 /// A throwing handler is reported and the loop continues — a bad handler must not stop
1858 /// every later one, exactly as with timers.
1859 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
1860 let Some(entry) = self.fd_handlers.get(&fd) else {
1861 return Ok(false);
1862 };
1863 let callback = if readable {
1864 entry.read.clone()
1865 } else if writable {
1866 entry.write.clone()
1867 } else {
1868 None
1869 };
1870 let Some(callback) = callback else {
1871 return Ok(false);
1872 };
1873 self.drain_jobs()?;
1874 match self.call_value(callback, Value::Undefined, Vec::new()) {
1875 Ok(_) => {}
1876 Err(Signal::Throw(value)) => {
1877 let text = self.describe_exception(&value);
1878 self.timer_errors.push(text);
1879 }
1880 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1881 }
1882 self.drain_jobs()?;
1883 Ok(true)
1884 }
1885
1886 /// Take the errors timer callbacks threw, leaving the list empty.
1887 pub fn take_timer_errors(&mut self) -> Vec<String> {
1888 std::mem::take(&mut self.timer_errors)
1889 }
1890
1891 /// Whether anything is still pending: a microtask or a timer.
1892 pub fn has_pending_work(&self) -> bool {
1893 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
1894 }
1895
1896 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
1897 pub fn has_pending_timers_or_jobs(&self) -> bool {
1898 !self.jobs.is_empty() || !self.tasks.is_empty()
1899 }
1900
1901 /// Run every queued microtask, including ones queued while draining.
1902 pub fn drain_jobs(&mut self) -> JsResult<()> {
1903 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
1904 // would spin forever, so the drain is bounded the way the call stack is.
1905 let mut budget = 1_000_000usize;
1906 while let Some(job) = self.jobs.pop_front() {
1907 if budget == 0 {
1908 return Err(Signal::Throw(
1909 self.make_error("InternalError", "promise job queue did not drain"),
1910 ));
1911 }
1912 budget -= 1;
1913 self.run_job(job)?;
1914 // `FinalizationRegistry` at the job boundary: this is the safe point where the
1915 // engine may run script that the script itself did not ask for. Doing it here
1916 // rather than from a drop hook is what keeps the callback out of arbitrary
1917 // engine bookkeeping — see `builtins::weak`'s header.
1918 crate::builtins::weak::drain_finalizers(self)?;
1919 }
1920 // A script that queued no jobs may still have dropped targets, so the checkpoint
1921 // runs once more after the queue empties.
1922 crate::builtins::weak::drain_finalizers(self)?;
1923 Ok(())
1924 }
1925
1926 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
1927 ///
1928 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
1929 /// `None` and is swept out here. This is also where the realm learns that a registry
1930 /// died, which is why it is a mutation rather than a read.
1931 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
1932 let handles = std::mem::take(&mut self.realm.finalization_registries);
1933 let mut live = Vec::with_capacity(handles.len());
1934 for handle in handles {
1935 let Some(object) = handle.upgrade() else {
1936 continue;
1937 };
1938 let Some(state) = object.finalization_state() else {
1939 continue;
1940 };
1941 live.push((object.clone(), *state));
1942 self.realm.finalization_registries.push(object.downgrade());
1943 }
1944 live
1945 }
1946
1947 /// Run one microtask.
1948 fn run_job(&mut self, job: Job) -> JsResult<()> {
1949 match job {
1950 Job::Reaction {
1951 handler: None,
1952 argument,
1953 rejected,
1954 promise,
1955 } => {
1956 // No handler: the settlement passes straight through to the derived
1957 // promise, which is why `p.catch(f)` ignores fulfilments.
1958 if rejected {
1959 self.reject_promise(&promise, argument);
1960 } else {
1961 self.fulfill_promise(&promise, argument);
1962 }
1963 Ok(())
1964 }
1965 Job::Reaction {
1966 handler: Some(handler),
1967 argument,
1968 promise,
1969 ..
1970 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
1971 Ok(answer) => {
1972 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
1973 self.reject_promise(&promise, error);
1974 }
1975 Ok(())
1976 }
1977 Err(Signal::Throw(reason)) => {
1978 self.reject_promise(&promise, reason);
1979 Ok(())
1980 }
1981 Err(other) => Err(other),
1982 },
1983 Job::Thenable {
1984 then,
1985 value,
1986 promise,
1987 } => {
1988 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
1989 // the value it produces settles `promise`.
1990 // The thenable's `then` gets this promise's own pair, so whatever it
1991 // produces settles `promise`.
1992 let resolve = JsObject::function(
1993 self.heap,
1994 Some(self.realm.function_proto.clone()),
1995 Callable::PromiseResolve(promise.clone()),
1996 );
1997 let reject = JsObject::function(
1998 self.heap,
1999 Some(self.realm.function_proto.clone()),
2000 Callable::PromiseReject(promise.clone()),
2001 );
2002 match self.call_value(
2003 then,
2004 value,
2005 vec![Value::Object(resolve), Value::Object(reject)],
2006 ) {
2007 Ok(_) => Ok(()),
2008 Err(Signal::Throw(reason)) => {
2009 self.reject_promise(&promise, reason);
2010 Ok(())
2011 }
2012 Err(other) => Err(other),
2013 }
2014 }
2015 Job::Resume {
2016 coroutine,
2017 promise,
2018 kind,
2019 value,
2020 } => self.drive_async(&coroutine, &promise, kind, value),
2021 Job::GeneratorResume {
2022 generator,
2023 promise,
2024 kind,
2025 value,
2026 } => self.step_async_generator(&generator, &promise, kind, value),
2027 Job::Import {
2028 specifier,
2029 referrer,
2030 promise,
2031 } => {
2032 self.run_dynamic_import(&specifier, &referrer, &promise);
2033 Ok(())
2034 }
2035 }
2036 }
2037
2038 /// One element of a `Promise` combinator settled.
2039 ///
2040 /// The shared state object holds the results array, the number still outstanding, and
2041 /// the combinator's own resolve/reject pair. `all` fills by index so the answer keeps
2042 /// the input order; `race` settles on the first element and ignores the rest, which a
2043 /// one-shot settle gives for free.
2044 fn settle_combinator(
2045 &mut self,
2046 state: &Gc<JsObject>,
2047 index: usize,
2048 fulfilled: bool,
2049 value: Value,
2050 ) -> JsResult<()> {
2051 let kind = state
2052 .own_property("kind")
2053 .and_then(|property| property.value)
2054 .map(|value| value.to_int32())
2055 .unwrap_or(0);
2056 let outcome = state
2057 .own_property("outcome")
2058 .and_then(|property| property.value);
2059 let Some(Value::Object(outcome)) = outcome else {
2060 return Ok(());
2061 };
2062 if kind == 3 {
2063 // `race`: the first settlement wins; the rest are ignored by the one-shot rule.
2064 if fulfilled {
2065 self.resolve_promise_with(&outcome, value)?;
2066 } else {
2067 self.reject_promise(&outcome, value);
2068 }
2069 return Ok(());
2070 }
2071 let results = state
2072 .own_property("results")
2073 .and_then(|property| property.value)
2074 .and_then(|value| value.as_object().cloned());
2075 let remaining = state
2076 .own_property("remaining")
2077 .and_then(|property| property.value)
2078 .map(|value| value.to_int32())
2079 .unwrap_or(0);
2080 match kind {
2081 0 => {
2082 // `all`: the first rejection wins outright.
2083 if !fulfilled {
2084 self.reject_promise(&outcome, value);
2085 return Ok(());
2086 }
2087 let Some(results) = &results else {
2088 return Ok(());
2089 };
2090 results.array_set(self.heap, index, value);
2091 }
2092 1 => {
2093 // `allSettled`: never rejects; each slot records what happened.
2094 let Some(results) = &results else {
2095 return Ok(());
2096 };
2097 let record = self.new_object(Some(self.realm.object_proto.clone()));
2098 if fulfilled {
2099 record.define_data("status", self.string("fulfilled"));
2100 record.define_data("value", value);
2101 } else {
2102 record.define_data("status", self.string("rejected"));
2103 record.define_data("reason", value);
2104 }
2105 results.array_set(self.heap, index, Value::Object(record));
2106 }
2107 // `any`: the first fulfilment wins; a full sweep of rejections does not settle
2108 // here — it is handled by the count below.
2109 2 if fulfilled => {
2110 self.resolve_promise_with(&outcome, value)?;
2111 return Ok(());
2112 }
2113 _ => {}
2114 }
2115 let left = remaining - 1;
2116 state.define_data("remaining", Value::Int(left));
2117 if left != 0 {
2118 return Ok(());
2119 }
2120 match kind {
2121 0 | 1 => {
2122 let Some(results) = results else {
2123 return Ok(());
2124 };
2125 self.resolve_promise_with(&outcome, Value::Object(results))?;
2126 }
2127 2 => {
2128 let error = self.make_error("AggregateError", "all promises were rejected");
2129 self.reject_promise(&outcome, error);
2130 }
2131 _ => {}
2132 }
2133 Ok(())
2134 }
2135
2136 /// Build an async function's result: a promise whose body runs as a coroutine.
2137 pub fn new_async_function(
2138 &mut self,
2139 function: Value,
2140 this: Value,
2141 args: Vec<Value>,
2142 ) -> JsResult<Value> {
2143 let promise = self.new_promise();
2144 let coroutine = self.new_coroutine(function, this, args)?;
2145 if let Err(Signal::Throw(reason)) =
2146 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2147 {
2148 self.reject_promise(&promise, reason);
2149 }
2150 Ok(Value::Object(promise))
2151 }
2152
2153 /// The coroutine an async body runs in.
2154 ///
2155 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2156 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2157 /// than growing a second state machine. The difference is only in the ending — a
2158 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2159 /// Run `code` as an async function body, answering the promise it settles.
2160 ///
2161 /// Used for a module with top-level `await`: its body is an async function whose
2162 /// caller is the host, so there is no function object to pass through
2163 /// [`Interp::new_async_function`].
2164 pub fn run_async_body(
2165 &mut self,
2166 code: Gc<CompiledCode>,
2167 env: Gc<ClosureEnv>,
2168 this: Value,
2169 ) -> JsResult<Value> {
2170 let promise = self.new_promise();
2171 let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2172 if let Err(Signal::Throw(reason)) =
2173 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2174 {
2175 self.reject_promise(&promise, reason);
2176 }
2177 Ok(Value::Object(promise))
2178 }
2179
2180 fn new_coroutine(
2181 &mut self,
2182 function: Value,
2183 this: Value,
2184 args: Vec<Value>,
2185 ) -> JsResult<Gc<JsObject>> {
2186 let Some(object) = function.as_object().cloned() else {
2187 return Err(self.type_error("not a function"));
2188 };
2189 let Some((code, env)) = bytecode_of(&object) else {
2190 return Err(self.type_error("not a function"));
2191 };
2192 self.new_coroutine_from(code, env, this, args)
2193 }
2194
2195 /// Build a coroutine over an already-resolved body.
2196 fn new_coroutine_from(
2197 &mut self,
2198 code: Gc<CompiledCode>,
2199 env: Gc<ClosureEnv>,
2200 this: Value,
2201 args: Vec<Value>,
2202 ) -> JsResult<Gc<JsObject>> {
2203 let function = Value::Undefined;
2204 self.push_frame(code, env, this, args, function)?;
2205 let frame = self.frames.pop().expect("push_frame just pushed it");
2206 let state = GeneratorState {
2207 frame: Some(frame),
2208 phase: GeneratorPhase::SuspendedStart,
2209 parked_on_await: false,
2210 parked_on_yield_star: false,
2211 requests: std::collections::VecDeque::new(),
2212 async_busy: false,
2213 };
2214 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2215 coroutine.with_mut(|data| {
2216 data.kind = ObjectKind::Generator(Box::new(state));
2217 });
2218 Ok(coroutine)
2219 }
2220
2221 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2222 /// `await` and `value` is what it awaited.
2223 fn resume_coroutine(
2224 &mut self,
2225 coroutine: &Gc<JsObject>,
2226 kind: ResumeKind,
2227 value: Value,
2228 ) -> JsResult<(Value, bool)> {
2229 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2230 ObjectKind::Generator(state) => Some(std::mem::replace(
2231 state.as_mut(),
2232 GeneratorState {
2233 frame: None,
2234 phase: GeneratorPhase::Executing,
2235 parked_on_await: false,
2236 parked_on_yield_star: false,
2237 requests: std::collections::VecDeque::new(),
2238 async_busy: false,
2239 },
2240 )),
2241 _ => None,
2242 }) else {
2243 return Err(self.type_error("not a coroutine"));
2244 };
2245 let result = self.step_generator(&mut state, kind, value);
2246 coroutine.with_mut(|data| {
2247 data.kind = ObjectKind::Generator(Box::new(state));
2248 });
2249 let (value, done, _ready, _reason) = result?;
2250 Ok((value, done))
2251 }
2252
2253 /// Advance an async body and settle its promise with the outcome.
2254 fn drive_async(
2255 &mut self,
2256 coroutine: &Gc<JsObject>,
2257 promise: &Gc<JsObject>,
2258 kind: ResumeKind,
2259 value: Value,
2260 ) -> JsResult<()> {
2261 match self.resume_coroutine(coroutine, kind, value) {
2262 Ok((value, true)) => {
2263 // `Ok` with `done` means the body finished *normally*, even when it was
2264 // resumed by a `throw` — `try { await p } catch {}` completes by
2265 // returning. Only the `Err` arm below is a rejection.
2266 //
2267 // Resolving rather than fulfilling matters: `return promise` in an async
2268 // body adopts the inner promise, so `async function f(){ return
2269 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2270 // promise.
2271 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2272 self.reject_promise(promise, reason);
2273 }
2274 Ok(())
2275 }
2276 Ok((value, false)) => {
2277 // Parked on `await`: follow what it awaited and resume with the outcome.
2278 let awaited = match self.promise_resolve_value(value) {
2279 Ok(awaited) => awaited,
2280 Err(Signal::Throw(error)) => {
2281 self.reject_promise(promise, error);
2282 return Ok(());
2283 }
2284 Err(other) => return Err(other),
2285 };
2286 self.hook_await(awaited, coroutine, promise)
2287 }
2288 Err(Signal::Throw(reason)) => {
2289 self.reject_promise(promise, reason);
2290 Ok(())
2291 }
2292 Err(other) => Err(other),
2293 }
2294 }
2295
2296 /// Arrange for `coroutine` to resume when `awaited` settles.
2297 fn hook_await(
2298 &mut self,
2299 awaited: Value,
2300 coroutine: &Gc<JsObject>,
2301 promise: &Gc<JsObject>,
2302 ) -> JsResult<()> {
2303 let resumed = JsObject::function(
2304 self.heap,
2305 Some(self.realm.function_proto.clone()),
2306 Callable::AwaitResume {
2307 coroutine: coroutine.clone(),
2308 promise: promise.clone(),
2309 kind: ResumeKind::Next,
2310 },
2311 );
2312 let raised = JsObject::function(
2313 self.heap,
2314 Some(self.realm.function_proto.clone()),
2315 Callable::AwaitResume {
2316 coroutine: coroutine.clone(),
2317 promise: promise.clone(),
2318 kind: ResumeKind::Throw,
2319 },
2320 );
2321 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2322 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2323 let Value::Object(awaited) = &awaited else {
2324 self.jobs.push_back(Job::Resume {
2325 coroutine: coroutine.clone(),
2326 promise: promise.clone(),
2327 kind: ResumeKind::Next,
2328 value: awaited,
2329 });
2330 return Ok(());
2331 };
2332 self.perform_then(
2333 awaited,
2334 Some(Value::Object(resumed)),
2335 Some(Value::Object(raised)),
2336 )?;
2337 Ok(())
2338 }
2339
2340 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2341 /// things an engine keeps outside it — array elements and an array's `length`.
2342 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2343 if let Some(property) = object.own_property_key(key) {
2344 return Some(property);
2345 }
2346 // An array's elements live in their own vector rather than the property table, so
2347 // a descriptor for one has to be synthesized — with the attributes an element has.
2348 if let Some(index) = key.as_str().and_then(array_index)
2349 && let Some(value) = object.array_get(index as usize)
2350 && !matches!(value, Value::Hole)
2351 {
2352 return Some(Property::data(value));
2353 }
2354 // `length` is an own property of an array that is not in its property table
2355 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2356 // and non-enumerable.
2357 if key.as_str() == Some("length")
2358 && let Some(length) = object.array_length()
2359 {
2360 return Some(Property {
2361 value: Some(crate::object::length_value(length)),
2362 writable: object.length_writable(),
2363 enumerable: false,
2364 configurable: false,
2365 getter: None,
2366 setter: None,
2367 });
2368 }
2369 None
2370 }
2371
2372 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2373 pub fn object_get_own_property(
2374 &mut self,
2375 object: &Gc<JsObject>,
2376 key: &PropertyKey,
2377 ) -> JsResult<Option<Property>> {
2378 if let Some(answer) = self.proxy_get_own_property(object, key)? {
2379 return Ok(answer);
2380 }
2381 Ok(Self::ordinary_own_property(object, key))
2382 }
2383
2384 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
2385 pub fn object_define_own_property(
2386 &mut self,
2387 object: &Gc<JsObject>,
2388 key: &PropertyKey,
2389 property: Property,
2390 ) -> JsResult<bool> {
2391 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
2392 return Ok(accepted);
2393 }
2394 // An array index is stored in the element vector, which can hold a plain value and
2395 // nothing else. An accessor — or a data property with non-default attributes —
2396 // therefore has to live in the property table, and the element slot is blanked so
2397 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
2398 // {get})` stored the accessor where no read ever looked, and the array kept
2399 // answering its old value.
2400 // An array's `length` is not stored in the property table, so defining it has to
2401 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
2402 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
2403 // {value: 1})` reported success and changed nothing.
2404 if key.as_str() == Some("length") && object.is_array() {
2405 // `{writable: false}` on `length` does not change the length, but it does make
2406 // it read-only — after which neither a later `{writable: true}` nor a store
2407 // past the end may succeed.
2408 if property.value.is_none() {
2409 if !object.length_writable() && property.writable {
2410 return Ok(false);
2411 }
2412 object.set_length_writable(property.writable);
2413 return Ok(true);
2414 }
2415 if !object.length_writable() {
2416 return Ok(false);
2417 }
2418 }
2419 if key.as_str() == Some("length")
2420 && object.is_array()
2421 && let Some(value) = property.value.clone()
2422 {
2423 let requested = value.to_number();
2424 let valid = requested.is_finite()
2425 && requested >= 0.0
2426 && requested.fract() == 0.0
2427 && requested <= u32::MAX as f64;
2428 if !valid {
2429 return Err(self.range_error("invalid array length"));
2430 }
2431 // Truncating deletes the elements above the new length, and a non-configurable
2432 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
2433 // makes `a.length = 2` fail rather than quietly drop it.
2434 let current = object.array_length().unwrap_or(0);
2435 let requested = requested as usize;
2436 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
2437 return Ok(false);
2438 }
2439 object.array_set_length(self.heap, requested);
2440 return Ok(true);
2441 }
2442 let plain = property.writable
2443 && property.enumerable
2444 && property.configurable
2445 && !property.is_accessor();
2446 if let Some(index) = key.as_str().and_then(array_index)
2447 && object.is_array()
2448 {
2449 // Growing the array needs a writable `length`: after
2450 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
2451 // be added.
2452 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
2453 return Ok(false);
2454 }
2455 if plain && property.value.is_some() {
2456 // An ordinary element: the vector is where a read looks first, so it has
2457 // to be the vector that changes — unless the index is too far out to be
2458 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
2459 // one property, because past its own limit it stores the index as an
2460 // ordinary key. Falling through to `define_key` below is the same choice,
2461 // and the alternative was worse: the store used to be *dropped* and the
2462 // length left at 0, which is a silent wrong answer.
2463 let value = property.value.clone().unwrap_or(Value::Undefined);
2464 object.delete_key(key);
2465 if object.array_set(self.heap, index as usize, value) {
2466 return Ok(true);
2467 }
2468 object.define_key(key, property);
2469 // A sparse store past the dense limit still extends `length`, which is what
2470 // `a[a.length] = v` relies on — but only extends: shortening would delete
2471 // the sparse properties above the index, including this one.
2472 if index as usize + 1 > object.array_length().unwrap_or(0) {
2473 object.array_set_length(self.heap, index as usize + 1);
2474 }
2475 return Ok(true);
2476 }
2477 object.define_key(key, property);
2478 // The slot stays, so `length` does not shrink; a hole is not an element, so
2479 // the table entry is now what a read finds.
2480 object.array_set(self.heap, index as usize, Value::Hole);
2481 return Ok(true);
2482 }
2483 object.define_key(key, property);
2484 Ok(true)
2485 }
2486
2487 /// Build a proxy object over `target`, with its traps read from `handler`.
2488 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
2489 JsObject::proxy(self.heap, target, handler)
2490 }
2491
2492 /// The `revoke` function for a proxy's slots.
2493 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
2494 JsObject::function(
2495 self.heap,
2496 Some(self.realm.function_proto.clone()),
2497 Callable::Revoker(slots),
2498 )
2499 }
2500
2501 /// A new array.
2502 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
2503 let array = JsObject::array(
2504 self.heap,
2505 Some(self.realm.array_proto.clone()),
2506 elements.len(),
2507 );
2508 for (index, element) in elements.into_iter().enumerate() {
2509 array.array_set(self.heap, index, element);
2510 }
2511 array
2512 }
2513
2514 /// A new native function object.
2515 ///
2516 /// The observable `name` and `length` are installed as properties here, which is
2517 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
2518 /// so `f.name = "x"` behaves like the writable property it is.
2519 /// A native constructor that builds its own instance after validating its arguments.
2520 ///
2521 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
2522 /// check runs before `new.target.prototype` is read.
2523 pub fn new_native_ctor(
2524 &self,
2525 name: impl Into<String>,
2526 length: u32,
2527 func: NativeFn,
2528 ) -> Gc<JsObject> {
2529 let function = JsObject::function(
2530 self.heap,
2531 Some(self.realm.function_proto.clone()),
2532 Callable::Native {
2533 func,
2534 own_instance: true,
2535 },
2536 );
2537 function.set_constructible(true);
2538 function.define(
2539 "length",
2540 Property::name_or_length(Value::Int(length as i32)),
2541 );
2542 function.define("name", Property::name_or_length(self.string(name)));
2543 function
2544 }
2545
2546 /// A native constructor that lets `new` build the instance first.
2547 ///
2548 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
2549 /// validation that must precede reading `new.target.prototype`, so the object can be
2550 /// created before the implementation runs. Distinct from [`Interp::new_native`],
2551 /// which makes a *method* and therefore not a constructor at all.
2552 pub fn new_native_constructor(
2553 &self,
2554 name: impl Into<String>,
2555 length: u32,
2556 func: NativeFn,
2557 ) -> Gc<JsObject> {
2558 let function = self.new_native(name, length, func);
2559 function.set_constructible(true);
2560 function
2561 }
2562
2563 /// A new host function object: a native closure that carries its own state.
2564 ///
2565 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
2566 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
2567 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
2568 /// this safe: the closure must not capture a `Gc`.
2569 pub fn new_host_function(
2570 &self,
2571 name: impl Into<String>,
2572 length: u32,
2573 func: crate::object::HostFn,
2574 ) -> Gc<JsObject> {
2575 self.new_host_inner(name.into(), length, func, false)
2576 }
2577
2578 /// A host constructor: `new` hands it `this = undefined`, so it validates its
2579 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
2580 pub fn new_host_ctor(
2581 &self,
2582 name: impl Into<String>,
2583 length: u32,
2584 func: crate::object::HostFn,
2585 ) -> Gc<JsObject> {
2586 let function = self.new_host_inner(name.into(), length, func, true);
2587 function.set_constructible(true);
2588 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
2589 // installs its own methods on it, so it starts as a plain object.
2590 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
2591 function.define(
2592 "prototype",
2593 Property {
2594 value: Some(Value::Object(proto)),
2595 writable: true,
2596 enumerable: false,
2597 configurable: false,
2598 ..Property::default()
2599 },
2600 );
2601 function
2602 }
2603
2604 fn new_host_inner(
2605 &self,
2606 name: String,
2607 length: u32,
2608 func: crate::object::HostFn,
2609 own_instance: bool,
2610 ) -> Gc<JsObject> {
2611 let function = JsObject::function(
2612 self.heap,
2613 Some(self.realm.function_proto.clone()),
2614 Callable::Host {
2615 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
2616 own_instance,
2617 },
2618 );
2619 function.define(
2620 "length",
2621 Property::name_or_length(Value::Int(length as i32)),
2622 );
2623 function.define("name", Property::name_or_length(self.string(name)));
2624 function
2625 }
2626
2627 /// A new native function object.
2628 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
2629 let function = JsObject::function(
2630 self.heap,
2631 Some(self.realm.function_proto.clone()),
2632 Callable::Native {
2633 func,
2634 own_instance: false,
2635 },
2636 );
2637 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
2638 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
2639 // `length,name` and this listed `name,length`. A bytecode function already gets it
2640 // the right way round; only native ones were built backwards.
2641 function.define(
2642 "length",
2643 Property::name_or_length(Value::Int(length as i32)),
2644 );
2645 function.define("name", Property::name_or_length(self.string(name)));
2646 function
2647 }
2648
2649 /// A new bound function.
2650 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
2651 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
2652 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
2653 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
2654 let constructible = target
2655 .as_object()
2656 .is_some_and(|target| target.is_constructor());
2657 let bound = JsObject::function(
2658 self.heap,
2659 Some(self.realm.function_proto.clone()),
2660 Callable::Bound { target, this, args },
2661 );
2662 bound.set_constructible(constructible);
2663 bound
2664 }
2665
2666 /// A new reference cell.
2667 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
2668 Gc::new(self.heap, Cell::new(value))
2669 }
2670
2671 // -- running ------------------------------------------------------------
2672
2673 /// Evaluate `code` as a script body and return its completion value.
2674 /// Compile and run `source` for the engine's own use, returning its completion value.
2675 ///
2676 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
2677 /// needs to be a real async function, and the engine already runs those as coroutines,
2678 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
2679 ///
2680 /// Differences from [`Self::eval_in_global`], both deliberate:
2681 ///
2682 /// * It does **not** drain the microtask queue. Install runs while the realm is still
2683 /// being built, and the source is an IIFE that only constructs a closure, so there
2684 /// is nothing to drain — and draining here would run script-queued jobs in the
2685 /// middle of `install`.
2686 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
2687 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
2688 /// and it should not look like the user wrote something wrong.
2689 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
2690 let program = match js_parse::parse_script(source) {
2691 Ok(program) => program,
2692 Err(error) => {
2693 let message = format!("builtin source does not parse: {error}");
2694 return Err(Signal::Throw(self.make_error("InternalError", &message)));
2695 }
2696 };
2697 let mut code = match js_compile::compile_script(&program) {
2698 Ok(code) => code,
2699 Err(error) => {
2700 let message = format!("builtin source does not compile: {}", error.message);
2701 return Err(Signal::Throw(self.make_error("InternalError", &message)));
2702 }
2703 };
2704 // The frame has to name something, and `<builtin>` is what a stack trace through
2705 // this code should say.
2706 code.set_filename("<builtin>");
2707 let compiled = Gc::new(self.heap, CompiledCode::new(code));
2708 let closure_vars = compiled.code.closure_vars.clone();
2709 let env = self.global_env(&closure_vars);
2710 let this = Value::Object(self.realm.global.clone());
2711 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
2712 }
2713
2714 /// Run an already-parsed script and drain the microtasks it queued.
2715 ///
2716 /// The drain is what lets an `async` function's body advance past its first `await`
2717 /// before the host sees the result: nothing else pumps the job queue.
2718 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
2719 let compiled = Gc::new(self.heap, CompiledCode::new(code));
2720 let closure_vars = compiled.code.closure_vars.clone();
2721 let env = self.global_env(&closure_vars);
2722 let this = Value::Object(self.realm.global.clone());
2723 let callee = Value::Undefined;
2724 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
2725 // The script is done, so the microtasks it queued run before the host sees the
2726 // result. Without this an `async` function's body would never advance past its
2727 // first `await`, because nothing else drains the queue.
2728 self.drain_jobs()?;
2729 Ok(result)
2730 }
2731
2732 /// Compile and run `source` in global scope, returning its completion value.
2733 ///
2734 /// This is what `eval` and `new Function` use. Running it as a script means it
2735 /// sees the global object and nothing else, which is right for `eval("1+1")` and
2736 /// for a `Function` body; a *direct* eval that reads a local variable would need
2737 /// the compiler to hand its variable environment over, which is not implemented.
2738 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
2739 self.eval_in_global_named(source, EVAL_FILE, false)
2740 }
2741
2742 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
2743 ///
2744 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
2745 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
2746 /// through the code, so they cannot share one constant.
2747 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
2748 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
2749 }
2750
2751 fn eval_in_global_named(&mut self, source: &str, file: &str, barrier: bool) -> JsResult<Value> {
2752 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
2753 // eval-created global binding — configurable, unlike a script's own `var`.
2754 self.eval_depth += 1;
2755 if barrier {
2756 let depth = self.frames.len();
2757 self.trace_barriers.push(depth);
2758 }
2759 let result = self.eval_in_global_inner(source, file);
2760 if barrier {
2761 self.trace_barriers.pop();
2762 }
2763 self.eval_depth -= 1;
2764 result
2765 }
2766
2767 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
2768 let compiled = self.compile_global_script(source, file, false)?;
2769 let strict = compiled.strict;
2770 self.run_eval_script(compiled, strict)
2771 }
2772
2773 /// Parse and compile `source` as a global script, without running it.
2774 ///
2775 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
2776 /// before a promise exists to reject — while still evaluating in the same eval context
2777 /// (direct-eval strictness, `new.target`, `super`).
2778 fn compile_global_script(
2779 &mut self,
2780 source: &str,
2781 file: &str,
2782 async_body: bool,
2783 ) -> JsResult<CompiledFunction> {
2784 // A *direct* eval inherits the strictness of the code that called it, which is
2785 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
2786 // implicit global. The caller's frame is the innermost one here, because a
2787 // native function does not push a frame of its own.
2788 let strict = self.current_strict();
2789 // `eval` runs in the caller's function context, so `new.target` is legal here
2790 // even though the source is a bare script — and so is `super.x` when the caller
2791 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
2792 // caller's, which is what `special_object 4` already does.
2793 let context = js_parse::EvalContext {
2794 in_method: self.enclosing_home_object().is_some(),
2795 // `super()` belongs to a derived constructor, and an eval'd body is not a
2796 // constructor at all: the caller frame's `this` is already built.
2797 in_derived_constructor: false,
2798 };
2799 // A *global* eval is not a function body: `new.target` and `super` are out of
2800 // reach there. Its `{async: true}` form differs in the other direction — the body
2801 // may `await` — so the two flags are independent and the reference sets both from
2802 // the eval type rather than from the caller.
2803 let parsed = if async_body {
2804 js_parse::parse_suspensible_global_eval(source, strict)
2805 } else {
2806 js_parse::parse_eval_script_in(source, strict, context)
2807 };
2808 let program = match parsed {
2809 Ok(program) => program,
2810 Err(error) => {
2811 // The message is bare: the position lives in `fileName`,
2812 // `lineNumber`, `columnNumber` and the stack frame above, which is where
2813 // the reference puts it. An `invalid source: L:C: ` prefix made
2814 // `e.message` differ from the reference while the stack already agreed.
2815 return Err(Signal::Throw(self.syntax_error_at(
2816 file,
2817 error.span.start.line,
2818 error.span.start.column,
2819 &error.message,
2820 )));
2821 }
2822 };
2823 let mut compiled = match if async_body {
2824 js_compile::compile_script_suspensible(&program)
2825 } else {
2826 js_compile::compile_script(&program)
2827 } {
2828 Ok(compiled) => compiled,
2829 // A construct the compiler does not handle yet is reported the same way a
2830 // parse error is: it happens before anything runs, so the trace is the
2831 // position in the source followed by the caller.
2832 Err(error) => {
2833 return Err(Signal::Throw(self.syntax_error_at(
2834 file,
2835 error.span.start.line,
2836 error.span.start.column,
2837 &error.message,
2838 )));
2839 }
2840 };
2841 compiled.set_filename(file);
2842 Ok(compiled)
2843 }
2844
2845 /// Run an `eval`'d script in the caller's scope.
2846 ///
2847 /// Three things have to come from the calling frame, because the eval'd code is a
2848 /// script and would otherwise see only the global object:
2849 ///
2850 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
2851 /// * `arguments`, exposed as a binding of the eval's own scope, so
2852 /// `f("arguments.length", 1)` sees the caller's arguments;
2853 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
2854 /// `eval("var v = 1")` into the global object.
2855 ///
2856 /// Locals of the calling function are *not* reachable: that needs the compiler to
2857 /// hand its variable environment over, which this milestone does not do.
2858 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
2859 // `this` and `arguments` come from the innermost frame only — those are not
2860 // lexical — while the name bindings come from the whole chain of frames, part
2861 // of it being ordinary scope resolution.
2862 // An arrow has no `this` of its own, so an `eval` inside one inherits the
2863 // enclosing function's receiver — the lexical `this` the arrow was compiled to
2864 // read from its closure.
2865 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
2866 // variable environment is the innermost frame of all: an arrow's own body is where
2867 // `var`s declared by an `eval` inside it belong.
2868 let caller_index = self
2869 .frames
2870 .iter()
2871 .rposition(|frame| !frame.code.code.is_arrow)
2872 .or_else(|| self.frames.len().checked_sub(1));
2873 let env_index = self.frames.len().checked_sub(1);
2874 let caller = caller_index.and_then(|index| self.frames.get(index));
2875 let (this, passed) = match caller {
2876 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
2877 // No frame at all: the eval is running at the top level, so there is
2878 // nothing to inherit and the global receiver is right.
2879 None => (Value::Object(self.realm.global.clone()), Vec::new()),
2880 };
2881 // Innermost frame first, so the first binding found for a name is the one that
2882 // shadows the rest. A script frame (`<eval>`) contributes nothing.
2883 let mut bindings: Vec<EvalBinding> = Vec::new();
2884 // The calling function's own bindings, resolved by the compiler at the call
2885 // site. That table is the only reliable answer when a name is declared twice in
2886 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
2887 // body means, and guessing by declaration order picks the wrong one as soon as
2888 // two loops in a row use the same name.
2889 // Only a *direct* eval sees the caller's scope. The compiler records a site for
2890 // every direct call — a bare `eval(...)` callee — so finding one at the current
2891 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
2892 // callee to a value first and leave no site behind.
2893 let mut direct = false;
2894 let mut resolved_here = false;
2895 if let Some(frame) = self.frames.last() {
2896 let (line, column) = frame
2897 .code
2898 .code
2899 .position_at(frame.at as u32)
2900 .unwrap_or_default();
2901 // The nearest site at or before the current position, not an exact match:
2902 // the recorded position of the `call` instruction is the callee's, which
2903 // sits a few columns inside the call expression the compiler recorded. A
2904 // site is unique per call, so "the closest one behind us" identifies it.
2905 if let Some(site) = frame
2906 .code
2907 .code
2908 .eval_sites
2909 .iter()
2910 .filter(|site| (site.line, site.column) <= (line, column))
2911 .max_by_key(|site| (site.line, site.column))
2912 {
2913 direct = true;
2914 resolved_here = true;
2915 for binding in &site.bindings {
2916 // An enclosing function's frame sits `owner` levels below the one
2917 // running the call.
2918 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
2919 else {
2920 continue;
2921 };
2922 bindings.push(EvalBinding {
2923 name: binding.name.clone(),
2924 frame,
2925 slot: if binding.is_arg {
2926 EvalSlot::Arg
2927 } else {
2928 EvalSlot::Local
2929 },
2930 index: binding.index as usize,
2931 });
2932 }
2933 }
2934 }
2935 for frame_index in (0..self.frames.len()).rev() {
2936 // Skip the innermost frame's flat scan when the compiler already answered
2937 // for it; an enclosing frame still needs one, because the eval resolves
2938 // those names dynamically.
2939 if resolved_here && frame_index == self.frames.len() - 1 {
2940 continue;
2941 }
2942 let frame = &self.frames[frame_index];
2943 for (index, arg) in frame.code.code.args.iter().enumerate() {
2944 bindings.push(EvalBinding {
2945 name: arg.name.clone(),
2946 frame: frame_index,
2947 slot: EvalSlot::Arg,
2948 index,
2949 });
2950 }
2951 for (index, local) in frame.code.code.vars.iter().enumerate() {
2952 bindings.push(EvalBinding {
2953 name: local.name.clone(),
2954 frame: frame_index,
2955 slot: EvalSlot::Local,
2956 index,
2957 });
2958 }
2959 }
2960 let mut seen = BTreeSet::new();
2961 bindings.retain(|binding| seen.insert(binding.name.clone()));
2962
2963 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
2964 // elements is all the spec's ordinary uses need.
2965 //
2966 // Known divergence: this is bound for a *global* eval too, where there is no
2967 // caller and the reference throws `'arguments' is not defined`. Deciding properly
2968 // needs "does the calling frame have an `arguments` of its own", which is not
2969 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
2970 // script or eval body does not, and `eval(b)` passes the callee as a value so even
2971 // the call-site detection does not answer it. Modelled as a binding in the caller's
2972 // variable environment, this would fall out; that is a larger change than the one
2973 // this comment is attached to.
2974 let arguments = Value::Object(self.new_array(passed));
2975
2976 // Only a *strict* eval gets a variable environment of its own. A sloppy one
2977 // declares its `var`s in the caller's — which for a top-level eval is the global
2978 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
2979 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
2980 // vanish into a scope nobody reads back from.
2981 let previous_scope = if code_strict {
2982 self.eval_scope.replace(BTreeMap::new())
2983 } else {
2984 None
2985 };
2986 let previous_arguments = self.eval_arguments.replace(arguments);
2987 let previous_with = self.eval_with.replace(self.with_objects());
2988 let inherited_new_target = self
2989 .frames
2990 .iter()
2991 .rev()
2992 .find(|frame| !frame.code.code.is_arrow)
2993 .map(|frame| frame.new_target.clone());
2994 let previous_new_target = self
2995 .eval_new_target
2996 .replace(inherited_new_target.unwrap_or(Value::Undefined));
2997 let eval_cells = self.eval_cells_for(&bindings);
2998 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
2999 // A sloppy direct eval declares its `var`s in the caller's variable environment;
3000 // `declare_eval_local` needs to know which frame that is.
3001 // An indirect eval gets the global environment, so nothing of the caller's is
3002 // recorded as the place its `var`s belong.
3003 let previous_caller = self
3004 .eval_caller
3005 .replace(if direct { env_index } else { None });
3006 // The cell-based view of the same bindings, which is what a closure created
3007 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3008 // whose compiler did not put a binding in a cell simply does not appear here —
3009 // reads and writes still work through `eval_bindings`, they just cannot outlive
3010 // the eval.
3011 let previous_eval_scope = self
3012 .active_eval_scope
3013 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3014 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3015 let closure_vars = compiled.code.closure_vars.clone();
3016 let env = self.global_env(&closure_vars);
3017 let callee = Value::Undefined;
3018 // An async body does not run here: it becomes a coroutine and answers a promise,
3019 // which is what makes `await` legal in it. `this` still has to be the caller's
3020 // (for a global eval, the global object), because `this` is not part of `await`.
3021 let result = if compiled.code.kind.is_async() {
3022 self.run_async_body(compiled, env, this)
3023 } else {
3024 self.execute(compiled, env, this, Vec::new(), callee)
3025 };
3026 self.eval_scope = previous_scope;
3027 self.eval_arguments = previous_arguments;
3028 self.eval_with = previous_with;
3029 self.eval_new_target = previous_new_target;
3030 self.eval_bindings = previous_bindings;
3031 self.eval_caller = previous_caller;
3032 self.active_eval_scope = previous_eval_scope;
3033 result
3034 }
3035
3036 /// The cell-backed subset of `bindings`, in the same priority order.
3037 ///
3038 /// Both lookup routes have to agree — the eval's own reads go through
3039 /// [`Interp::eval_binding_value`] and the closures it builds go through
3040 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
3041 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
3042 /// is not in a cell simply does not appear: reads and writes still work, they just
3043 /// cannot be handed to a closure that outlives the eval.
3044 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
3045 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
3046 for binding in bindings {
3047 let Some(frame) = self.frames.get(binding.frame) else {
3048 continue;
3049 };
3050 let cell = match binding.slot {
3051 EvalSlot::Arg => frame
3052 .code
3053 .arg_cell
3054 .get(binding.index)
3055 .copied()
3056 .unwrap_or(-1),
3057 EvalSlot::Local => frame
3058 .code
3059 .loc_cell
3060 .get(binding.index)
3061 .copied()
3062 .unwrap_or(-1),
3063 };
3064 if cell < 0 {
3065 continue;
3066 }
3067 if let Some(cell) = frame.cells.get(cell as usize) {
3068 names.push((binding.name.clone(), cell.clone()));
3069 }
3070 }
3071 names
3072 }
3073
3074 /// A `SyntaxError` that reports where in the source it happened.
3075 ///
3076 /// Compile-time failures never run, so they have no frame of their own; the
3077 /// reference still puts the position first in the trace, with no function name and
3078 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
3079 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
3080 /// reference borrows), which is how a script reads the position without parsing
3081 /// the trace.
3082 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
3083 ///
3084 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
3085 /// `columnNumber`, which is how the reference prints one. A positionless error
3086 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
3087 /// the reference raises it from `js_resolve_module`, where there is no position.
3088 pub(crate) fn syntax_error_plain(
3089 &mut self,
3090 error: &js_parse::SyntaxError,
3091 file: &str,
3092 ) -> Value {
3093 if error.positionless {
3094 return self.make_error("SyntaxError", &error.message);
3095 }
3096 self.syntax_error_at(
3097 file,
3098 error.span.start.line,
3099 error.span.start.column,
3100 &error.message,
3101 )
3102 }
3103
3104 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
3105 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
3106 let value = self.make_error("SyntaxError", message);
3107 if let Value::Object(object) = &value {
3108 let text = self.string(blamed);
3109 object.define("stack", Property::with_attributes(text, true, true));
3110 let name = self.string(file);
3111 object.define("fileName", Property::with_attributes(name, true, true));
3112 object.define(
3113 "lineNumber",
3114 Property::with_attributes(Value::Int(line as i32), true, true),
3115 );
3116 object.define(
3117 "columnNumber",
3118 Property::with_attributes(Value::Int(column as i32), true, true),
3119 );
3120 }
3121 value
3122 }
3123
3124 /// Run a compiled script whose completion value is a function, returning it.
3125 ///
3126 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
3127 /// get the closure out, which keeps the constant-pool plumbing in one place.
3128 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
3129 self.run_script(code)
3130 }
3131
3132 /// The environment of a script or of any function compiled at global scope:
3133 /// every entry is a global binding, so each one resolves to the realm's cell.
3134 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
3135 let mut cells = Vec::with_capacity(closure_vars.len());
3136 for closure_var in closure_vars {
3137 let cell = match closure_var.closure_type {
3138 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
3139 if closure_var.is_lexical =>
3140 {
3141 // A lexical declaration: the cell is created here holding the
3142 // dead-zone marker, which is what makes the binding exist and
3143 // unreadable before its initialiser runs.
3144 self.declare_global(&closure_var.name, closure_var.is_const);
3145 self.realm.globals[&closure_var.name].clone()
3146 }
3147 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
3148 // A `var` or function declaration becomes a property of the global
3149 // object, and it exists from here on — which is why
3150 // `print(v); var v = 1` prints `undefined` instead of raising.
3151 // Declaring it at instantiation time (rather than at the
3152 // initialiser) is also what makes it non-configurable: the store
3153 // then lands on an existing property instead of creating one.
3154 self.declare_var_global(&closure_var.name);
3155 // The cell is a placeholder that nothing indexes; it cannot be
3156 // omitted because the slot has to hold something.
3157 self.new_cell(Value::Undefined)
3158 }
3159 _ => {
3160 // An undeclared global is read by name; the cell is a
3161 // placeholder that nothing indexes.
3162 self.new_cell(Value::Undefined)
3163 }
3164 };
3165 cells.push(cell);
3166 }
3167 Gc::new(
3168 self.heap,
3169 ClosureEnv {
3170 cells,
3171 eval_scope: None,
3172 local_vars: None,
3173 local_phase: 1,
3174 },
3175 )
3176 }
3177
3178 /// Push a frame and run until it returns.
3179 pub(crate) fn execute(
3180 &mut self,
3181 code: Gc<CompiledCode>,
3182 env: Gc<ClosureEnv>,
3183 this: Value,
3184 args: Vec<Value>,
3185 callee: Value,
3186 ) -> JsResult<Value> {
3187 let depth = self.frames.len();
3188 self.push_frame(code, env, this, args, callee)?;
3189 loop {
3190 // The fast loop first: it runs whole runs of records with `pc` in a register.
3191 //
3192 // `step`'s `pc` lives in the frame, so every instruction writes it back and
3193 // reads it again — a store, a load and two bounds checks that a loop body does
3194 // not need, because nothing outside the loop can run in between. This is the
3195 // classic split: advance a register, and only spill it when leaving.
3196 //
3197 // `Some(value)` means the function ended by running off the end of its
3198 // instruction array, which is a normal return.
3199 let step = match self.run_fast() {
3200 Some(value) => Ok(Step::Return(value)),
3201 None => self.step(),
3202 };
3203 match step {
3204 Ok(Step::Continue) => {}
3205 Ok(Step::Return(value)) => {
3206 self.pop_frame();
3207 // A frame that ended in a `tail_call` hands its value straight to
3208 // its caller: nothing after the call can run, so every frame above
3209 // the callee unwinds with the same value. See [`Frame::tail`] —
3210 // the reference does not reuse frames either, so recursion depth
3211 // and the stack-overflow limit behave the same way.
3212 while self.frames.len() > depth && self.frame().tail {
3213 self.pop_frame();
3214 }
3215 if self.frames.len() == depth {
3216 return Ok(value);
3217 }
3218 // The caller resumes with the value on its stack.
3219 self.frames
3220 .last_mut()
3221 .expect("a caller is live")
3222 .stack
3223 .push(value);
3224 }
3225 Err(Signal::Throw(value)) => {
3226 // A handler lives on the stack of the frame that is throwing —
3227 // `catch` pushed it there — so this frame gets the first chance
3228 // to catch before it is popped.
3229 let value = value;
3230 loop {
3231 if self.frames.len() <= depth {
3232 return Err(Signal::Throw(value));
3233 }
3234 if self.catch_here(value.clone()).is_some() {
3235 break;
3236 }
3237 self.frames.pop();
3238 }
3239 }
3240 // A `yield` in a frame that `execute` is running directly means a
3241 // generator body was entered as an ordinary call, which only happens if
3242 // the generator check in `call_or_push` was bypassed.
3243 Ok(Step::Suspend(_)) => {
3244 return Err(Signal::Throw(self.make_error(
3245 "InternalError",
3246 "a generator body ran as an ordinary call",
3247 )));
3248 }
3249 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
3250 }
3251 }
3252 }
3253
3254 /// Install a handler for `value` if this frame has one, resuming at it.
3255 ///
3256 /// The scan is the reference's: walk the frame's stack downwards looking for the
3257 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
3258 /// `0` is an enumerator marker rather than a handler — it exists so that a
3259 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
3260 /// here and the unwinding continues.
3261 fn catch_here(&mut self, value: Value) -> Option<()> {
3262 let frame = self.frames.last_mut()?;
3263 while let Some(top) = frame.stack.pop() {
3264 if let Value::CatchOffset(offset) = top {
3265 if offset == 0 {
3266 continue;
3267 }
3268 frame.stack.push(value);
3269 frame.pc = offset as usize;
3270 return Some(());
3271 }
3272 }
3273 None
3274 }
3275
3276 fn push_frame(
3277 &mut self,
3278 code: Gc<CompiledCode>,
3279 env: Gc<ClosureEnv>,
3280 this: Value,
3281 mut args: Vec<Value>,
3282 callee: Value,
3283 ) -> JsResult<()> {
3284 // Two bounds, and the byte budget is the one that decides in practice. The
3285 // reference's message is `stack overflow` on an `InternalError`, not V8's
3286 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
3287 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
3288 let frame_cost = Self::frame_cost(&code);
3289 let stack_base = self.stack_used();
3290 if self.frames.len() >= self.max_frames
3291 || stack_base.saturating_add(frame_cost) > self.stack_limit
3292 {
3293 return Err(Signal::Throw(
3294 self.make_error("InternalError", "stack overflow"),
3295 ));
3296 }
3297 let arg_count = code.code.args.len();
3298 // How many were actually passed, which `arguments.length` reports and
3299 // `assert(x)` depends on: a call with one argument must not look like a call
3300 // with one argument and an explicit `undefined`.
3301 let passed = args.len();
3302 // Missing arguments are `undefined` in their slots; extra ones are dropped
3303 // from the slots but still reachable through `arguments`.
3304 //
3305 // A call that passes no more than the declared parameters needs **no** copy:
3306 // after the resize below, `args[..passed]` *is* the passed values. Only the
3307 // extra ones — which `truncate` is about to drop — have to be kept, and they are
3308 // the rare case. This used to copy every call: one `Value` clone per argument
3309 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
3310 let passed_overflow = (passed > arg_count).then(|| {
3311 let mut values = self.take_values(passed, Value::Undefined);
3312 values[..passed].clone_from_slice(&args[..passed]);
3313 values
3314 });
3315 // Only when the counts differ, which for the overwhelmingly common call — as many
3316 // arguments as parameters — is never. `resize` followed by `truncate` on equal
3317 // lengths is two length compares and nothing else, but this is the hottest few
3318 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
3319 if passed != arg_count {
3320 args.resize(arg_count, Value::Undefined);
3321 args.truncate(arg_count);
3322 }
3323 let cell_count = code.code.var_ref_count as usize;
3324 let mut cells = Vec::with_capacity(cell_count);
3325 for _ in 0..cell_count {
3326 cells.push(self.new_cell(Value::Undefined));
3327 }
3328 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
3329 // A captured argument lives in its cell, not in the argument slot, so the
3330 // incoming value has to be moved there before the body runs.
3331 for (slot, cell) in code.arg_cell.iter().enumerate() {
3332 if *cell >= 0
3333 && let Some(value) = args.get(slot).cloned()
3334 {
3335 cells[*cell as usize].set(value);
3336 }
3337 }
3338 // Sloppy mode substitutes the global object for a missing receiver and boxes a
3339 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
3340 // reports `object`. Strict mode passes the value through untouched.
3341 let this = if code.code.strict {
3342 this
3343 } else if this.is_nullish() {
3344 Value::Object(self.realm.global.clone())
3345 } else if matches!(this, Value::Object(_)) {
3346 this
3347 } else {
3348 match crate::builtins::this_object(self, &this) {
3349 Ok(boxed) => Value::Object(boxed),
3350 Err(_) => this,
3351 }
3352 };
3353 let stack_depth = code.code.stack_size as usize + 1;
3354 // Taken before the `push` borrows `self.frames`, because the operand stack comes
3355 // out of the same recycle pool the locals did.
3356 let stack = self.take_values(stack_depth, Value::Undefined);
3357 self.frames.push(Frame {
3358 code,
3359 env,
3360 this,
3361 args,
3362 passed_count: passed,
3363 passed_overflow,
3364 locals,
3365 cells,
3366 local_vars: None,
3367 // Exactly the depth the compiler computed, so the operand stack never
3368 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
3369 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
3370 // the buffer between calls, so "exactly" costs nothing after the first one.
3371 stack,
3372 pc: 0,
3373 at: 0,
3374 callee,
3375 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
3376 cost: frame_cost,
3377 stack_base,
3378 tail: false,
3379 });
3380 Ok(())
3381 }
3382
3383 /// A value buffer of `len` slots, from the recycle pool when there is one.
3384 ///
3385 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
3386 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
3387 // A frame with no locals asks for nothing, and that is most frames: taking a
3388 // buffer out of the pool, clearing it and resizing it to zero is four operations
3389 // and a pool pop for an empty `Vec`, which is free to construct.
3390 if len == 0 {
3391 return Vec::new();
3392 }
3393 let mut buffer = self.free_values.pop().unwrap_or_default();
3394 buffer.clear();
3395 buffer.resize(len, fill);
3396 buffer
3397 }
3398
3399 /// Return a finished frame's value buffers for the next call to reuse.
3400 fn recycle(&mut self, frame: &mut Frame) {
3401 for mut buffer in [
3402 std::mem::take(&mut frame.locals),
3403 frame.passed_overflow.take().unwrap_or_default(),
3404 std::mem::take(&mut frame.stack),
3405 ] {
3406 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
3407 // GC root: it kept every value the frame held reachable, which is invisible
3408 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
3409 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
3410 // exactly that within one run — the target `{}` of a finished IIFE was still
3411 // in its operand stack, in the pool.
3412 buffer.clear();
3413 // A buffer with no capacity is what `Vec::new` is; putting it back would just
3414 // fill the pool with nothing to offer.
3415 if self.free_values.len() < RECYCLE_SLOTS
3416 && buffer.capacity() > 0
3417 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
3418 {
3419 self.free_values.push(buffer);
3420 }
3421 }
3422 }
3423
3424 /// Pop a finished frame and keep its buffers.
3425 ///
3426 /// Every place that drops a frame goes through here: a recycled buffer is also where
3427 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
3428 /// nothing but the reuse.
3429 fn pop_frame(&mut self) -> Option<Frame> {
3430 let mut frame = self.frames.pop()?;
3431 self.recycle(&mut frame);
3432 Some(frame)
3433 }
3434
3435 /// A memory checkpoint: does the heap still fit under its limit?
3436 ///
3437 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
3438 /// a `Cell` read and a predictable branch, and the point of asking that often is that
3439 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
3440 /// only at calls would let it run until the machine died, which is the exact failure
3441 /// `--memory-limit` exists to prevent.
3442 ///
3443 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
3444 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
3445 /// script that catches it, drops the reference and carries on is legitimate: measured
3446 /// on `qjs --memory-limit 1M`, the engine recovers.
3447 fn check_memory(&mut self) -> JsResult<()> {
3448 // One `Cell` read and a predictable branch when no limit is set, and an integer
3449 // compare when one is. Containers report their own growth as it happens
3450 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
3451 // walking it here was the first version and it was O(live) per 256 instructions,
3452 // which turned a 100k-element push loop into a five-minute one.
3453 let Some(limit) = self.heap.memory_limit() else {
3454 return Ok(());
3455 };
3456 let used = self.heap.used_bytes();
3457 if used <= limit {
3458 // Back under the limit — a collection or a dropped reference did it. The next
3459 // time it goes over is a new failure, not a repeat of this one.
3460 self.oom_reported_at = 0;
3461 return Ok(());
3462 }
3463 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
3464 // block runs normally after `out of memory` — it allocates nothing, so nothing
3465 // fails. A check that re-fired on every instruction made the handler itself throw,
3466 // which is a dead end: the error became unobservable from script.
3467 //
3468 // Comparing against the total at the last report gives the same behaviour: the
3469 // handler runs while the total is unchanged, and the very next allocation over the
3470 // limit fails.
3471 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
3472 {
3473 return Ok(());
3474 }
3475 self.oom_reported_at = used;
3476 Err(Signal::Throw(
3477 self.make_error("InternalError", "out of memory"),
3478 ))
3479 }
3480
3481 /// Fail before allocating `payload` bytes, if they would not fit.
3482 ///
3483 /// For the allocations whose size comes from script data — `new Array(n)`,
3484 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
3485 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
3486 /// answering NULL for the one big request.
3487 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
3488 if self.heap.fits(payload) {
3489 return Ok(());
3490 }
3491 Err(Signal::Throw(
3492 self.make_error("InternalError", "out of memory"),
3493 ))
3494 }
3495
3496 /// Bytes of frame state the live call chain accounts for.
3497 pub fn stack_used(&self) -> usize {
3498 match self.frames.last() {
3499 Some(frame) => frame.stack_base + frame.cost,
3500 None => 0,
3501 }
3502 }
3503
3504 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
3505 ///
3506 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
3507 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
3508 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
3509 /// instead. That is the whole difference between the two models: it rations C stack, we
3510 /// ration frame state, and both quantities are dominated by the value slots — which is
3511 /// why the two depths come out comparable rather than merely proportional.
3512 fn frame_cost(code: &CompiledCode) -> usize {
3513 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
3514 std::mem::size_of::<Frame>()
3515 + std::mem::size_of::<Value>() * slots
3516 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
3517 }
3518
3519 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
3520 ///
3521 /// Only names the eval created are here: a name the frame already declared statically
3522 /// is written through to its own slot instead, so this cannot shadow a real local.
3523 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
3524 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
3525 let (local_vars, phase) = self.visible_local_vars()?;
3526 if !local_vars.contains(name) {
3527 return None;
3528 }
3529 local_vars.get(name, phase)
3530 }
3531
3532 /// The variables a direct `eval` declared, as the code currently running sees them.
3533 ///
3534 /// Inside an eval that is the *caller's* set — the eval's own variable environment
3535 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
3536 /// else it is the current frame's, falling back to the frame the closure was created
3537 /// in.
3538 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
3539 ///
3540 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
3541 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
3542 /// refcount operations (the clone out of the frame, the drop at the end of the match)
3543 /// just to be asked `is_none`.
3544 fn has_visible_local_vars(&self) -> bool {
3545 let index = match self.eval_caller.flatten() {
3546 Some(caller) => caller,
3547 None => match self.frames.len().checked_sub(1) {
3548 Some(top) => top,
3549 None => return false,
3550 },
3551 };
3552 match self.frames.get(index) {
3553 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
3554 None => false,
3555 }
3556 }
3557
3558 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
3559 // While an `eval` runs, its own frame is on top but its variable environment is
3560 // the *caller's* — so the caller is what the lookup has to start from.
3561 let (index, phase) = match self.eval_caller.flatten() {
3562 Some(caller) => (
3563 caller,
3564 if self.in_parameter_list_at(caller) {
3565 0
3566 } else {
3567 1
3568 },
3569 ),
3570 None => (
3571 self.frames.len().checked_sub(1)?,
3572 if self.in_parameter_list() { 0 } else { 1 },
3573 ),
3574 };
3575 let frame = self.frames.get(index)?;
3576 // The frame's own variables, or — for an arrow, which has no variable environment
3577 // of its own — the one it was created in, which `ClosureEnv` carries.
3578 if let Some(local_vars) = frame.local_vars.clone() {
3579 return Some((local_vars, phase));
3580 }
3581 frame
3582 .env
3583 .local_vars
3584 .clone()
3585 .map(|local_vars| (local_vars, frame.env.local_phase))
3586 }
3587
3588 /// Whether the innermost frame is still evaluating its parameter list.
3589 ///
3590 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
3591 /// and a closure created there may only see that much of [`LocalVars`].
3592 fn in_parameter_list(&self) -> bool {
3593 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
3594 }
3595
3596 /// [`Interp::in_parameter_list`] for a specific frame.
3597 fn in_parameter_list_at(&self, frame: usize) -> bool {
3598 let Some(frame) = self.frames.get(frame) else {
3599 return false;
3600 };
3601 let code = &frame.code.code;
3602 if !code.has_parameter_expressions {
3603 return false;
3604 }
3605 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
3606 // function as its body and let a direct `eval` act accordingly.
3607 if code.body_start == (0, 0) {
3608 return false;
3609 }
3610 match code.position_at(frame.at as u32) {
3611 Some(position) => position < code.body_start,
3612 None => false,
3613 }
3614 }
3615
3616 fn frame(&self) -> &Frame {
3617 self.frames.last().expect("a frame is live")
3618 }
3619
3620 fn frame_mut(&mut self) -> &mut Frame {
3621 self.frames.last_mut().expect("a frame is live")
3622 }
3623
3624 // -- slot access --------------------------------------------------------
3625
3626 /// Move a local's value out, leaving `undefined` in the slot.
3627 ///
3628 /// `None` for a captured slot: its value lives in a cell shared with every closure
3629 /// that closed over it, so it can never be exclusively ours and must not be taken.
3630 ///
3631 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
3632 /// for every read and fatal for this one — a clone is exactly the second handle that
3633 /// rules out growing the string in place.
3634 fn take_loc(&mut self, slot: usize) -> Option<Value> {
3635 let frame = self.frames.last_mut()?;
3636 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
3637 return None;
3638 }
3639 frame
3640 .locals
3641 .get_mut(slot)
3642 .map(|value| std::mem::replace(value, Value::Undefined))
3643 }
3644
3645 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
3646 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
3647 ///
3648 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
3649 /// it** — the value is put back before the general path runs — so a `valueOf` that
3650 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
3651 /// error as it would have without the fusion. This is why the in-place attempt is a
3652 /// `take` and not a `get`: an optimisation that changes what an exception observes is
3653 /// a wrong answer with a good excuse.
3654 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
3655 // The take is `matches!`-guarded on the *right* operand only, and the taken value
3656 // is put back on every path that does not append. An earlier version wrote the two
3657 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
3658 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
3659 // through with its value already taken and dropped: the general path below then
3660 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
3661 // A wrong answer, from an optimisation, with every test green.
3662 if matches!(right, Value::String(_))
3663 && let Some(taken) = self.take_loc(slot)
3664 {
3665 if let Value::String(mut left) = taken {
3666 let appended = match left.get_mut() {
3667 Some(string) => string.append_in_place(
3668 // The pattern is the one `matches!` just checked.
3669 match &right {
3670 Value::String(text) => text,
3671 _ => unreachable!("guarded above"),
3672 },
3673 ),
3674 None => None,
3675 };
3676 self.put_loc(slot, Value::String(left));
3677 if let Some(added) = appended {
3678 // The buffer grew where it stood, so the heap's running total has to
3679 // be told: `measure_used` would report the new length, and the two must
3680 // agree or the subtraction at free time leaves the counter wrong.
3681 self.heap.adjust_payload(added as isize);
3682 return Ok(());
3683 }
3684 } else {
3685 self.put_loc(slot, taken);
3686 }
3687 }
3688 // The two-number case, without an operand stack round trip. Everything below
3689 // this point is the *general* path: push both, call `binary_add`, pop the answer,
3690 // store it — five operations and two `Value` clones for what is one integer add.
3691 // `AddImmLoc` already answers this shape that way; the fusion above it was written
3692 // for string append and never got the numeric half, so `t += i` — a counting loop
3693 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
3694 let left = self.get_loc(slot);
3695 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
3696 self.put_loc(
3697 slot,
3698 match a.checked_add(*b) {
3699 Some(sum) => Value::Int(sum),
3700 None => Value::Float(*a as f64 + *b as f64),
3701 },
3702 );
3703 return Ok(());
3704 }
3705 self.push(left);
3706 self.push(right);
3707 self.binary_add()?;
3708 let value = self.pop();
3709 self.put_loc(slot, value);
3710 Ok(())
3711 }
3712
3713 fn get_arg(&self, slot: usize) -> Value {
3714 let frame = self.frame();
3715 let cell = frame.code.arg_cell.get(slot).copied().unwrap_or(-1);
3716 if cell == -1 {
3717 return frame.args.get(slot).cloned().unwrap_or(Value::Undefined);
3718 }
3719 match frame.cells.get(cell as usize) {
3720 Some(cell) => cell.get(),
3721 None => Value::Undefined,
3722 }
3723 }
3724
3725 fn put_arg(&mut self, slot: usize, value: Value) {
3726 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
3727 if cell == -1 {
3728 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
3729 *slot = value;
3730 }
3731 } else {
3732 self.frame().cells[cell as usize].set(value);
3733 }
3734 }
3735
3736 fn get_loc(&self, slot: usize) -> Value {
3737 let frame = self.frame();
3738 // The cell mapping is `-1` for every slot that was not captured — which is all of
3739 // them in a function that creates no closure. Testing that first means the common
3740 // case is one array read and a clone: 20% of every loop iteration used to go
3741 // through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a sample of
3742 // `dispatch:arith`), and inlining took `dispatch:arith` from 629 to 445 ms.
3743 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
3744 if cell == -1 {
3745 return frame.locals.get(slot).cloned().unwrap_or(Value::Undefined);
3746 }
3747 // A captured slot reads through its cell and ignores the slot entirely — the rule
3748 // the helper this replaced applied, kept identical.
3749 match frame.cells.get(cell as usize) {
3750 Some(cell) => cell.get(),
3751 None => Value::Undefined,
3752 }
3753 }
3754
3755 fn put_loc(&mut self, slot: usize, value: Value) {
3756 // One borrow instead of three, and the cell check on the frame we already hold.
3757 let frame = self.frames.last_mut().expect("a frame is live");
3758 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
3759 if cell < 0 {
3760 if let Some(slot) = frame.locals.get_mut(slot) {
3761 *slot = value;
3762 }
3763 } else if let Some(cell) = frame.cells.get(cell as usize) {
3764 cell.set(value);
3765 }
3766 }
3767
3768 // -- globals ------------------------------------------------------------
3769
3770 /// The name a global-slot operand refers to.
3771 fn global_name(&self, slot: usize) -> String {
3772 self.frame()
3773 .code
3774 .code
3775 .closure_vars
3776 .get(slot)
3777 .map(|c| c.name.clone())
3778 .unwrap_or_default()
3779 }
3780
3781 /// The facts about a global binding that decide where it lives.
3782 ///
3783 /// A script's globals split in two, and the split is observable: `var` and
3784 /// function declarations become properties of the global object (`globalThis.v`
3785 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
3786 /// declarations live in the global *lexical* environment and are invisible there
3787 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
3788 /// `is_lexical` flag means the answer is already in the bytecode.
3789 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
3790 let name = self.global_name(slot);
3791 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
3792 // while forwarding a reference through a nested function is built with the
3793 // flags cleared, so `const c` would look like an ordinary `var` from inside a
3794 // closure. Presence in the realm's lexical table is the same fact, recorded
3795 // once, and every slot sees it.
3796 let lexical = self.realm.globals.contains_key(&name);
3797 let is_const = self.realm.lexical_consts.contains(&name);
3798 (name, lexical, is_const)
3799 }
3800
3801 /// The value of `name` in the innermost active `with` object, if any.
3802 ///
3803 /// The active objects are the [`VarKind::With`] locals of every frame still running,
3804 /// innermost frame first and innermost block first within one. Walking frames rather
3805 /// than keeping a separate stack is what makes a closure called from inside a `with`
3806 /// see it, and what keeps the object alive only as long as the block is.
3807 /// The innermost active `with` object that has `name`, if any.
3808 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
3809 let objects = self.eval_with.clone().unwrap_or_default();
3810 for object in objects {
3811 let key = self.string(name.to_string());
3812 if self
3813 .has_property(&key, &Value::Object(object.clone()))
3814 .ok()?
3815 {
3816 return Some(object);
3817 }
3818 }
3819 None
3820 }
3821
3822 /// Every active `with` object, innermost first.
3823 fn with_objects(&self) -> Vec<Gc<JsObject>> {
3824 let mut objects = Vec::new();
3825 for frame in self.frames.iter().rev() {
3826 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
3827 if var.kind != js_compile::VarKind::With {
3828 continue;
3829 }
3830 // A captured binding lives in its cell and not in the slot list, so the
3831 // cell is consulted first — a closure created inside the block is exactly
3832 // what makes the object captured. Before the store runs the slot still
3833 // holds `undefined`, and a `with` object is always boxed, so a non-object
3834 // entry is simply not in scope yet.
3835 let value = frame
3836 .code
3837 .loc_cell
3838 .get(index)
3839 .copied()
3840 .filter(|cell| *cell >= 0)
3841 .and_then(|cell| frame.cells.get(cell as usize))
3842 .map(|cell| cell.get())
3843 .or_else(|| frame.locals.get(index).cloned());
3844 if let Some(Value::Object(object)) = value {
3845 objects.push(object);
3846 }
3847 }
3848 }
3849 objects
3850 }
3851
3852 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
3853 for object in self.eval_with.clone().unwrap_or_default() {
3854 let key = self.string(name.to_string());
3855 if self.has_property(&key, &Value::Object(object.clone()))? {
3856 return Ok(Some(self.read_field(&Value::Object(object), name)?));
3857 }
3858 }
3859 Ok(None)
3860 }
3861
3862 /// Whether every scope between here and the global object is an ordinary one.
3863 ///
3864 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
3865 /// bytecode resolved; when any is live the general path has to run in full order. When
3866 /// none is — every ordinary program — a global read is a property read and nothing
3867 /// else, and that is worth caching.
3868 fn scopes_are_plain(&self) -> bool {
3869 self.eval_caller.is_none()
3870 && self.eval_with.is_none()
3871 && self.eval_arguments.is_none()
3872 && self.eval_bindings.is_empty()
3873 && self.eval_scope.is_none()
3874 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
3875 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
3876 // its `ClosureEnv`, so the test has to be the same one the general path makes.
3877 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
3878 // upstream corpus caught and no unit test did.
3879 && !self.has_visible_local_vars()
3880 && self.frame().env.eval_scope.is_none()
3881 }
3882
3883 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
3884 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
3885 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
3886 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
3887 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
3888 // borrow outlive the `&mut self` the lookup needs.
3889 //
3890 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
3891 // forwarded through a nested function has its flags cleared, so the flag cannot
3892 // be believed.
3893 let code = self.frame().code.clone();
3894 let name = code
3895 .code
3896 .closure_vars
3897 .get(slot)
3898 .map(|c| c.name.as_str())
3899 .unwrap_or_default();
3900 let lexical = self.realm.globals.contains_key(name);
3901 // The common case, first: an ordinary global `var`, with a cache in front of the
3902 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
3903 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
3904 // cache hit and return without touching any of it.
3905 if !lexical && self.scopes_are_plain() {
3906 return self.get_plain_global(name, slot);
3907 }
3908 if name == "arguments"
3909 && let Some(arguments) = &self.eval_arguments
3910 {
3911 return Ok(arguments.clone());
3912 }
3913 // A `with` block around the *call site* is part of the scope an `eval` sees, so
3914 // the objects live when the eval started are consulted before anything else. The
3915 // snapshot is taken at entry rather than scanning the frames on every read: a
3916 // block that has already finished still leaves its object in the slot, and a
3917 // bytecode read outside the block must not see it.
3918 if let Some(value) = self.with_lookup(name)? {
3919 return Ok(value);
3920 }
3921 // A variable a direct `eval` declared shadows everything the compiler resolved,
3922 // including an enclosing function's binding: the eval put it in the caller's own
3923 // variable environment, which is nearer than any captured scope.
3924 if let Some((local_vars, phase)) = self.visible_local_vars()
3925 && let Some(cell) = local_vars.get(name, phase)
3926 {
3927 return Ok(cell.get());
3928 }
3929 // The frame that called `eval` is the innermost scope the eval'd code sees, so
3930 // its local `a` wins over a global `a`.
3931 if let Some(value) = self.eval_binding_value(name) {
3932 return Ok(value);
3933 }
3934 // A closure created by an `eval` resolves its free names against the bindings
3935 // that eval saw, even after the eval (and its frames) are gone.
3936 if let Some(cell) = self
3937 .frame()
3938 .env
3939 .eval_scope
3940 .as_ref()
3941 .and_then(|scope| scope.get(name))
3942 {
3943 let value = cell.get();
3944 if matches!(value, Value::Uninitialized) {
3945 return Err(self.throw_reference(name));
3946 }
3947 return Ok(value);
3948 }
3949 // A binding declared by the strict `eval` currently running shadows anything
3950 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
3951 if let Some(scope) = &self.eval_scope
3952 && let Some(value) = scope.get(name)
3953 {
3954 return Ok(value.clone());
3955 }
3956 if lexical {
3957 // A lexical global is a binding in a side table, so the dead zone is
3958 // visible and it is nowhere on the global object.
3959 if let Some(cell) = self.realm.globals.get(name) {
3960 let value = cell.get();
3961 if matches!(value, Value::Uninitialized) {
3962 return Err(self.throw_reference(name));
3963 }
3964 return Ok(value);
3965 }
3966 return Err(self.throw_reference(name));
3967 }
3968 // A `var` global is an ordinary property, so the prototype chain and the
3969 // global object's own builtins are all reachable through it.
3970 match self.get_property(&self.realm.global.clone(), name)? {
3971 Some(value) => Ok(value),
3972 None => Err(self.throw_reference(name)),
3973 }
3974 }
3975
3976 /// Read a plain global `var`: a cached own data property, or the full lookup.
3977 ///
3978 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
3979 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
3980 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
3981 let object = self.realm.global.clone();
3982 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
3983 if let Some(cached) = &self.global_cache[site]
3984 && object.upgrades_to(&cached.object)
3985 && let Some(value) = object.data_property_at(cached.index, name)
3986 {
3987 return Ok(value);
3988 }
3989 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
3990 // chain exactly as before, then remember the answer if it is worth remembering.
3991 let Some(value) = self.get_property(&object, name)? else {
3992 return Err(self.throw_reference(name));
3993 };
3994 if let Some(index) = object.own_data_index(name) {
3995 self.global_cache[site] = Some(GlobalCache {
3996 object: object.downgrade(),
3997 index,
3998 });
3999 }
4000 Ok(value)
4001 }
4002
4003 /// Store to a global binding.
4004 ///
4005 /// Returns a signal when the store is refused: a `const` global may only be
4006 /// written by its initialiser, and a non-configurable `var` global may not be
4007 /// deleted but is always writable.
4008 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4009 let (name, lexical, is_const) = self.global_binding(slot);
4010
4011 // An assignment inside a `with` writes through to the object that supplies the
4012 // name, which for an `eval` means consulting the same chain `get_global` does.
4013 if let Some(owner) = self.with_owner(&name) {
4014 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
4015 return Ok(());
4016 }
4017 // A variable the running eval *declared* takes the write before any caller
4018 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
4019 // environment even when an enclosing function has a `var c` of its own.
4020 if self.eval_caller.flatten().is_some()
4021 && let Some((local_vars, phase)) = self.visible_local_vars()
4022 && local_vars.contains(&name)
4023 && let Some(cell) = local_vars.get(&name, phase)
4024 {
4025 cell.set(value);
4026 return Ok(());
4027 }
4028 // A binding of the frame that called `eval` takes the write, which is what
4029 // makes `f("a = 3")` change the caller's `a`.
4030 if self.set_eval_binding(&name, &value)? {
4031 return Ok(());
4032 }
4033 // A closure that outlived its `eval` writes through to the same cell it reads.
4034 if let Some(cell) = self
4035 .frame()
4036 .env
4037 .eval_scope
4038 .as_ref()
4039 .and_then(|scope| scope.get(&name))
4040 .cloned()
4041 {
4042 cell.set(value);
4043 return Ok(());
4044 }
4045 // Inside a strict `eval`, a name it declared itself is stored there. An
4046 // *assignment* to a name nobody declared is not a declaration, so it falls
4047 // through: strict mode raises `ReferenceError` for it, which is what
4048 // `eval("1 + (@not_def = 1)")` has to do.
4049 if let Some(scope) = self.eval_scope.as_mut()
4050 && scope.contains_key(&name)
4051 {
4052 scope.insert(name, value);
4053 return Ok(());
4054 }
4055 if lexical {
4056 if let Some(cell) = self.realm.globals.get(&name).cloned() {
4057 if is_const && !matches!(cell.get(), Value::Uninitialized) {
4058 return Err(self.read_only_global(&name));
4059 }
4060 cell.set(value);
4061 return Ok(());
4062 }
4063 // Writing an undeclared lexical global is a `ReferenceError` in strict
4064 // mode and a silent global creation otherwise; creating the cell here
4065 // keeps both paths from losing the value.
4066 let cell = self.new_cell(value);
4067 self.realm.globals.insert(name, cell);
4068 return Ok(());
4069 }
4070 // A variable a direct `eval` declared in this call shadows the global object, even
4071 // when the global already has a property of that name — `var c = "global"` at the
4072 // top level must not capture `eval("var c = 1")` inside a function.
4073 if let Some((local_vars, phase)) = self.visible_local_vars()
4074 && local_vars.contains(&name)
4075 && let Some(cell) = local_vars.get(&name, phase)
4076 {
4077 cell.set(value);
4078 return Ok(());
4079 }
4080 let global = self.realm.global.clone();
4081 match global.own_property(&name) {
4082 // A `var` global is writable, so the store goes straight through — but
4083 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
4084 // store (a non-writable or accessor-without-setter global) is a silent
4085 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
4086 // split every other assignment has.
4087 Some(_) => {
4088 let on_failure = if self.current_strict() {
4089 DeleteFailure::Throw
4090 } else {
4091 DeleteFailure::Ignore
4092 };
4093 self.set_property_with(&global, &name, value, on_failure)
4094 }
4095 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
4096 // declaration creates a *configurable* property, which is what makes it
4097 // deletable and is the one way a global differs from a declared `var`.
4098 // In strict mode the same store is a `ReferenceError` instead: that is the
4099 // whole point of strict mode, and creating the global silently meant
4100 // `"use strict"; x = 1` looked like it worked.
4101 None => {
4102 if self.current_strict() {
4103 return Err(self.throw_reference(&name));
4104 }
4105 // A direct eval declares here rather than on the global object: its
4106 // `var`s belong to the caller's variable environment. `declare_eval_local`
4107 // also covers a plain assignment to a variable an earlier eval made.
4108 if let Some(cell) = self.declare_eval_local(&name) {
4109 cell.set(value);
4110 return Ok(());
4111 }
4112 global.define_data(&name, value);
4113 Ok(())
4114 }
4115 }
4116 }
4117
4118 /// The value of a binding of the frame that called `eval`, if there is one.
4119 fn eval_binding_value(&self, name: &str) -> Option<Value> {
4120 let binding = self
4121 .eval_bindings
4122 .iter()
4123 .find(|binding| binding.name == name)?;
4124 let owner = self.frames.get(binding.frame)?;
4125 let (slot, index) = (binding.slot, binding.index);
4126 Some(match slot {
4127 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4128 cell if cell >= 0 => owner
4129 .cells
4130 .get(cell as usize)
4131 .map(|cell| cell.get())
4132 .unwrap_or(Value::Undefined),
4133 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
4134 },
4135 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4136 cell if cell >= 0 => owner
4137 .cells
4138 .get(cell as usize)
4139 .map(|cell| cell.get())
4140 .unwrap_or(Value::Undefined),
4141 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
4142 },
4143 })
4144 }
4145
4146 /// Write to a binding of the frame that called `eval`.
4147 ///
4148 /// `Ok(false)` means no binding matched and the caller should keep looking. A
4149 /// matched binding can still refuse the store, which is why this is fallible: a
4150 /// `const` is read-only everywhere, and a named function expression's own name is
4151 /// read-only in strict mode.
4152 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
4153 let Some(binding) = self
4154 .eval_bindings
4155 .iter()
4156 .find(|binding| binding.name == name)
4157 else {
4158 return Ok(false);
4159 };
4160 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
4161 let strict = self.current_strict();
4162 let Some(owner) = self.frames.get_mut(frame) else {
4163 return Ok(false);
4164 };
4165 match slot {
4166 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4167 cell if cell >= 0 => {
4168 if let Some(cell) = owner.cells.get(cell as usize) {
4169 cell.set(value.clone());
4170 }
4171 }
4172 _ => {
4173 if let Some(slot) = owner.args.get_mut(index) {
4174 *slot = value.clone();
4175 }
4176 }
4177 },
4178 EvalSlot::Local => {
4179 let declared = owner.code.code.vars.get(index);
4180 // A `const` is read-only even through `eval`. The realm records this for
4181 // globals (see `lexical_consts`), but a local's `const`-ness is only in
4182 // the bytecode, so this is where it has to be enforced.
4183 if declared.is_some_and(|var| var.is_const) {
4184 return Err(self.read_only_local(name));
4185 }
4186 // The name of a named function expression is read-only too, but only
4187 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
4188 // such a name is ignored, the same as a direct store would be.
4189 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
4190 return if strict {
4191 Err(self.read_only_local(name))
4192 } else {
4193 Ok(true)
4194 };
4195 }
4196 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4197 cell if cell >= 0 => {
4198 if let Some(cell) = owner.cells.get(cell as usize) {
4199 cell.set(value.clone());
4200 }
4201 }
4202 _ => {
4203 if let Some(slot) = owner.locals.get_mut(index) {
4204 *slot = value.clone();
4205 }
4206 }
4207 }
4208 }
4209 }
4210 Ok(true)
4211 }
4212
4213 /// The `TypeError` an assignment to a read-only binding raises.
4214 fn read_only_local(&self, name: &str) -> Signal {
4215 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4216 }
4217
4218 /// Declare `name` as a variable of the frame that called the running `eval`.
4219 ///
4220 /// `None` when there is no direct eval in progress, or it was called from the top
4221 /// level — then the caller's variable environment *is* the global one and the
4222 /// existing path is right.
4223 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
4224 let caller = self.eval_caller.flatten()?;
4225 // The bottom frame is the top-level script, whose variable environment *is* the
4226 // global one — so `eval("var x = 1")` at the top level still creates a global.
4227 if caller == 0 {
4228 return None;
4229 }
4230 // A name the eval's *own* variable environment already binds is not a new
4231 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
4232 // `arguments`, and creating a second binding would leave the first — the one
4233 // closures read — untouched. A binding of an *outer* frame does not count: a
4234 // declaration shadows it rather than writing through.
4235 if self
4236 .eval_bindings
4237 .iter()
4238 .any(|binding| binding.name == name && binding.frame == caller)
4239 {
4240 return None;
4241 }
4242 let phase = if self.in_parameter_list_at(caller) {
4243 0
4244 } else {
4245 1
4246 };
4247 self.frame_local_vars(caller)?;
4248 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
4249 if let Some(cell) = local_vars.get(name, 1) {
4250 return Some(cell);
4251 }
4252 let cell = self.new_cell(Value::Undefined);
4253 Some(local_vars.declare(name, phase, cell))
4254 }
4255
4256 /// Make sure `frame` has a `LocalVars`, creating it on demand.
4257 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
4258 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
4259 return Some(local_vars.clone());
4260 }
4261 let local_vars = Gc::new(self.heap, LocalVars::new());
4262 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
4263 Some(local_vars)
4264 }
4265
4266 /// Whether the realm already has a binding for `name`, lexically or as an *own*
4267 /// property of the global object. Used to decide whether a store inside an
4268 /// `eval` writes through to the realm or declares a binding of its own.
4269 ///
4270 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
4271 /// write to `Object.prototype.toString`, and must not shadow it either.
4272 fn global_knows(&mut self, name: &str) -> bool {
4273 if self.realm.globals.contains_key(name) {
4274 return true;
4275 }
4276 self.realm.global.own_property(name).is_some()
4277 }
4278
4279 /// Whether the code currently running is strict.
4280 ///
4281 /// Read off the frame's function, which is where the parser's answer ended up; a
4282 /// native function never runs strict-only checks, and there is no frame at all
4283 /// before the first script.
4284 pub fn current_strict(&self) -> bool {
4285 self.frames
4286 .last()
4287 .is_some_and(|frame| frame.code.code.strict)
4288 }
4289
4290 /// Initialise a declared global, which is what ends its dead zone.
4291 ///
4292 /// A `var` global becomes a property of the global object: writable, so a later
4293 /// assignment goes through, and non-configurable, so `delete` refuses.
4294 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4295 let (name, lexical, _) = self.global_binding(slot);
4296 // A `var` declared by the strict `eval` currently running belongs to the
4297 // eval's scope, not to the global object: `eval("var v = 1")` must not make
4298 // `typeof v` answer `"number"` afterwards. A name the realm already has is
4299 // initialised in place, which is what a re-declaration inside eval does.
4300 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
4301 self.eval_scope
4302 .as_mut()
4303 .expect("checked above")
4304 .insert(name, value);
4305 return Ok(());
4306 }
4307 if let Some(scope) = self.eval_scope.as_mut()
4308 && scope.contains_key(&name)
4309 {
4310 scope.insert(name, value);
4311 return Ok(());
4312 }
4313 if lexical {
4314 // The cell exists (created at declaration time) holding the dead-zone
4315 // marker; storing the value is what makes the binding readable.
4316 if let Some(cell) = self.realm.globals.get(&name).cloned() {
4317 cell.set(value);
4318 return Ok(());
4319 }
4320 let cell = self.new_cell(value);
4321 self.realm.globals.insert(name, cell);
4322 return Ok(());
4323 }
4324 let global = self.realm.global.clone();
4325 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
4326 // to answer `false` and leave the binding in place. `with_attributes` ties
4327 // `configurable` to `writable`, so the property is built field by field.
4328 global.define(
4329 &name,
4330 Property {
4331 value: Some(value),
4332 writable: true,
4333 enumerable: true,
4334 configurable: false,
4335 ..Property::default()
4336 },
4337 );
4338 Ok(())
4339 }
4340
4341 /// The `TypeError` a store to a `const` global raises.
4342 fn read_only_global(&self, name: &str) -> Signal {
4343 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4344 }
4345
4346 // -- properties ---------------------------------------------------------
4347
4348 /// Read `object[key]`, following the prototype chain.
4349 ///
4350 /// An inherited accessor runs with the *receiver* as `this`, which is why the
4351 /// lookup returns the owner rather than just the value.
4352 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
4353 self.get_property_key(object, &PropertyKey::from(key))
4354 }
4355
4356 /// [`Interp::get_property`] with a key that may be a symbol.
4357 pub fn get_property_key(
4358 &mut self,
4359 object: &Gc<JsObject>,
4360 key: &PropertyKey,
4361 ) -> JsResult<Option<Value>> {
4362 self.get_property_key_for(object, None, key)
4363 }
4364
4365 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
4366 ///
4367 /// The receiver matters when the property is found on a *prototype*: a getter has to
4368 /// see the object the read started from. For a primitive that is the primitive
4369 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
4370 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
4371 /// the owner.
4372 pub fn get_property_key_for(
4373 &mut self,
4374 object: &Gc<JsObject>,
4375 receiver: Option<&Value>,
4376 key: &PropertyKey,
4377 ) -> JsResult<Option<Value>> {
4378 // A proxy answers for itself, before any of the shortcuts below: `new
4379 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
4380 // have.
4381 if object.proxy_state().is_some() {
4382 let receiver = receiver
4383 .cloned()
4384 .unwrap_or_else(|| Value::Object(object.clone()));
4385 return self.proxy_get(object, &receiver, key);
4386 }
4387 // The element-vector and `length` shortcuts are string-only: an array index
4388 // has no symbol spelling.
4389 if let Some(text) = key.as_str() {
4390 if let Some(value) = self.own_element(object, text) {
4391 return Ok(Some(value));
4392 }
4393 // `length` is not stored as a property: an array's length is its element
4394 // count, and keeping one copy of it is what makes `push`/`pop` and
4395 // `a.length = n` agree.
4396 if let Some(length) = object.array_length()
4397 && text == "length"
4398 {
4399 // Not `Value::Int(length as i32)`: see [`length_value`].
4400 return Ok(Some(crate::object::length_value(length)));
4401 }
4402 }
4403 match lookup_key(object, key) {
4404 Some((_, property)) => {
4405 if property.is_accessor() {
4406 match &property.getter {
4407 Some(getter) if !matches!(getter, Value::Undefined) => {
4408 let receiver = receiver
4409 .cloned()
4410 .unwrap_or_else(|| Value::Object(object.clone()));
4411 self.call_value(getter.clone(), receiver, Vec::new())
4412 .map(Some)
4413 }
4414 // An accessor with no getter reads as `undefined`.
4415 _ => Ok(Some(Value::Undefined)),
4416 }
4417 } else {
4418 Ok(property.value)
4419 }
4420 }
4421 None => Ok(None),
4422 }
4423 }
4424
4425 /// `super.key` — start the search at `proto`, but report to `receiver`.
4426 ///
4427 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
4428 /// found on the prototype of a class has to see the *instance* as `this`, and a
4429 /// plain property read off `proto` would lose that.
4430 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
4431 let start = self.require_object(proto)?;
4432 let key = self.propkey(key)?;
4433 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
4434 if matches!(proto, Value::Null) {
4435 return Ok(Value::Undefined);
4436 }
4437 match lookup_key(&start, &key) {
4438 Some((_, property)) if property.is_accessor() => match &property.getter {
4439 Some(getter) if !matches!(getter, Value::Undefined) => {
4440 self.call_value(getter.clone(), receiver.clone(), Vec::new())
4441 }
4442 _ => Ok(Value::Undefined),
4443 },
4444 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
4445 None => Ok(Value::Undefined),
4446 }
4447 }
4448
4449 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
4450 ///
4451 /// A setter found on the prototype runs with `receiver` as `this`; a data property
4452 /// is shadowed by a new own property on the receiver, the same rule an ordinary
4453 /// assignment follows.
4454 fn super_write(
4455 &mut self,
4456 receiver: &Value,
4457 proto: &Value,
4458 key: &Value,
4459 value: Value,
4460 ) -> JsResult<()> {
4461 let target = self.require_object(receiver)?;
4462 let key = self.propkey(key)?;
4463 if !matches!(proto, Value::Null)
4464 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
4465 {
4466 if property.is_accessor() {
4467 if let Some(setter) = &property.setter
4468 && !matches!(setter, Value::Undefined)
4469 {
4470 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
4471 }
4472 return Ok(());
4473 }
4474 // A data property on the prototype is writable or not; reading `owner` at
4475 // all is only for the attribute check.
4476 if !property.writable {
4477 return Err(self.type_error(format!("'{key}' is read-only")));
4478 }
4479 let _ = owner;
4480 }
4481 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
4482 }
4483
4484 /// The object a `super` operation needs, or the `TypeError` the spec raises.
4485 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
4486 match value.as_object() {
4487 Some(object) => Ok(object.clone()),
4488 None => Err(Signal::Throw(
4489 self.make_error("TypeError", "value is not an object"),
4490 )),
4491 }
4492 }
4493
4494 /// Build the class object `define_class` produces.
4495 ///
4496 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
4497 /// whose prototype property is a fresh object inheriting from the parent's
4498 /// prototype, and whose own prototype is the parent constructor — which is what makes
4499 /// a static method inherited too.
4500 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
4501 let ctor = self.pop();
4502 let parent = self.pop();
4503 let Value::Object(function) = &ctor else {
4504 return Err(Signal::Throw(
4505 self.make_error("TypeError", "class constructor must be a function"),
4506 ));
4507 };
4508 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
4509 // but gives the instances no prototype at all.
4510 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
4511 match &parent {
4512 Value::Null => (Some(self.realm.function_proto.clone()), None),
4513 Value::Object(parent_class) => {
4514 if !parent_class.is_callable() {
4515 return Err(Signal::Throw(
4516 self.make_error("TypeError", "parent class must be constructor"),
4517 ));
4518 }
4519 let proto = self.get_property(parent_class, "prototype")?;
4520 match proto {
4521 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
4522 Some(Value::Null) => (Some(parent_class.clone()), None),
4523 _ => {
4524 return Err(Signal::Throw(self.make_error(
4525 "TypeError",
4526 "parent prototype must be an object or null",
4527 )));
4528 }
4529 }
4530 }
4531 _ => {
4532 return Err(Signal::Throw(
4533 self.make_error("TypeError", "parent class must be constructor"),
4534 ));
4535 }
4536 }
4537 } else {
4538 (
4539 Some(self.realm.function_proto.clone()),
4540 Some(self.realm.object_proto.clone()),
4541 )
4542 };
4543 let proto = self.new_object(parent_proto);
4544 function.set_proto(parent_ctor);
4545 // A class is not callable without `new`, and its `prototype` is not writable —
4546 // both follow from being a class and are what `class A {}; A()` throws on.
4547 function.set_class_constructor(true);
4548 function.set_home_object(None);
4549 self.set_function_name(&ctor, name);
4550 self.define_class_properties(function, &ctor, &proto)?;
4551 Ok((ctor, proto))
4552 }
4553
4554 /// Give the constructor its `prototype` and `length`, and the prototype its
4555 /// `constructor` back-pointer.
4556 fn define_class_properties(
4557 &mut self,
4558 function: &Gc<JsObject>,
4559 ctor: &Value,
4560 proto: &Gc<JsObject>,
4561 ) -> JsResult<()> {
4562 proto.define(
4563 "constructor",
4564 Property::with_attributes(ctor.clone(), true, false),
4565 );
4566 function.define(
4567 "prototype",
4568 Property::prototype_of(Value::Object(proto.clone()), false),
4569 );
4570 if let Some((code, _)) = bytecode_of(function) {
4571 let length = code.code.defined_args;
4572 function.define(
4573 "length",
4574 Property::name_or_length(Value::Int(length as i32)),
4575 );
4576 }
4577 Ok(())
4578 }
4579
4580 /// The own array element `key` names, if this object has one.
4581 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
4582 let index = array_index(key)?;
4583 // A typed array's elements live in its buffer, not in a property list: reading one
4584 // goes through the view's element type so a bounds check and a detached buffer are
4585 // both handled there.
4586 if object.typed_array_parts().is_some() {
4587 return object.typed_array_element(index as usize);
4588 }
4589 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
4590 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
4591 // search early, which is why `Array.prototype[1] = 9` could not be seen through
4592 // `[1,,3][1]`.
4593 match object.array_get(index as usize) {
4594 Some(Value::Hole) | None => None,
4595 other => other,
4596 }
4597 }
4598
4599 /// Store `object[key] = value`, honouring setters and inherited properties.
4600 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
4601 self.set_property_with(object, key, value, DeleteFailure::Throw)
4602 }
4603
4604 /// Store a property, choosing what to do when the object refuses.
4605 ///
4606 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
4607 /// mode, which is the one place assignment differs by mode. Native code (the array
4608 /// methods, `JSON`) always asks for the throw.
4609 pub fn set_property_with(
4610 &mut self,
4611 object: &Gc<JsObject>,
4612 key: &str,
4613 value: Value,
4614 on_failure: DeleteFailure,
4615 ) -> JsResult<()> {
4616 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
4617 }
4618
4619 /// [`Interp::set_property_with`] with a key that may be a symbol.
4620 pub fn set_property_with_key(
4621 &mut self,
4622 object: &Gc<JsObject>,
4623 key: &PropertyKey,
4624 value: Value,
4625 on_failure: DeleteFailure,
4626 ) -> JsResult<()> {
4627 // A proxy's `set` trap decides, and its `false` means the same thing an
4628 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
4629 if object.proxy_state().is_some() {
4630 let receiver = Value::Object(object.clone());
4631 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
4632 return match (accepted, on_failure) {
4633 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
4634 (false, DeleteFailure::Throw) => {
4635 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
4636 }
4637 };
4638 }
4639 }
4640 // The element and `length` shortcuts only exist for string keys: an array
4641 // index has no symbol spelling, and a symbol named `length` is an ordinary
4642 // property.
4643 let text = key.as_str();
4644 // A typed array's elements are a window onto its buffer: the store has to go
4645 // through the view's element type so the value is wrapped (or clamped) and so an
4646 // out-of-range or detached write is a silent no-op, as the spec says.
4647 if let Some(text) = text
4648 && let Some(index) = array_index(text)
4649 && let Some(element) = object.typed_array_element_type()
4650 {
4651 // §10.4.5.5: an out-of-bounds index answers `true` *before* `V` is converted,
4652 // so a `valueOf` with a side effect must not run. Checking the length first is
4653 // what keeps `valueOfCalled` at 0 in `key-is-out-of-bounds-receiver-is-…`.
4654 let length = object.typed_array_length().unwrap_or(0);
4655 if index as usize >= length {
4656 return Ok(());
4657 }
4658 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
4659 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
4660 // in `Interp`, because it is script-observable and the storage borrow inside
4661 // `typed_array_set` must not be held across it.
4662 let stored = self.element_value(element, value)?;
4663 if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
4664 return Err(self.type_error(reason));
4665 }
4666 return Ok(());
4667 }
4668 if let Some(text) = text
4669 && let Some(index) = array_index(text)
4670 && object.is_array()
4671 {
4672 // An accessor defined on an index lives in the property table while the
4673 // element slot is a hole, so the store has to go through the property first.
4674 // Writing the vector directly skipped the setter entirely.
4675 if let Some(existing) = object.own_property_key(key) {
4676 if existing.is_accessor() {
4677 return match existing.setter.clone() {
4678 Some(setter) if !matches!(setter, Value::Undefined) => {
4679 let receiver = Value::Object(object.clone());
4680 self.call_value(setter, receiver, vec![value]).map(|_| ())
4681 }
4682 _ => match on_failure {
4683 DeleteFailure::Throw => Err(self.type_error(format!(
4684 "cannot set property '{text}', it has only a getter"
4685 ))),
4686 DeleteFailure::Ignore => Ok(()),
4687 },
4688 };
4689 }
4690 if !existing.writable {
4691 return match on_failure {
4692 DeleteFailure::Throw => {
4693 Err(self.type_error(format!("'{text}' is read-only")))
4694 }
4695 DeleteFailure::Ignore => Ok(()),
4696 };
4697 }
4698 }
4699 {
4700 // Growing the array needs a writable `length`.
4701 if (index as usize) >= object.array_length().unwrap_or(0)
4702 && !object.length_writable()
4703 {
4704 return match on_failure {
4705 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
4706 DeleteFailure::Ignore => Ok(()),
4707 };
4708 }
4709 // Adding an index past the end makes the array longer, which a
4710 // non-extensible array refuses.
4711 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
4712 return match on_failure {
4713 DeleteFailure::Throw => Err(self.type_error(format!(
4714 "cannot add property '{key}', object is not extensible"
4715 ))),
4716 DeleteFailure::Ignore => Ok(()),
4717 };
4718 }
4719 if object.element_is_locked(index) {
4720 return match on_failure {
4721 DeleteFailure::Throw => {
4722 Err(self.type_error(format!("'{key}' is read-only")))
4723 }
4724 DeleteFailure::Ignore => Ok(()),
4725 };
4726 }
4727 // The element vector is only half of `[[Set]]` for an index: the
4728 // prototype chain is consulted first, and a setter there answers instead
4729 // of the element store. This branch used to write the element directly, so
4730 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
4731 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
4732 // the reference calls the setter and the array keeps no own index.
4733 if let Some((owner, property)) = lookup_key(object, key)
4734 && !owner.ptr_eq(object)
4735 {
4736 match &property {
4737 property if property.is_accessor() => {
4738 match &property.setter {
4739 Some(setter) if !matches!(setter, Value::Undefined) => {
4740 let receiver = Value::Object(object.clone());
4741 self.call_value(setter.clone(), receiver, vec![value])?;
4742 }
4743 _ => {
4744 return match on_failure {
4745 DeleteFailure::Throw => Err(self.type_error(format!(
4746 "cannot set property '{text}', it has only a getter"
4747 ))),
4748 DeleteFailure::Ignore => Ok(()),
4749 };
4750 }
4751 }
4752 return Ok(());
4753 }
4754 property if !property.writable => {
4755 return match on_failure {
4756 DeleteFailure::Throw => {
4757 Err(self.type_error(format!("'{text}' is read-only")))
4758 }
4759 DeleteFailure::Ignore => Ok(()),
4760 };
4761 }
4762 _ => {}
4763 }
4764 }
4765 if object.array_set(self.heap, index as usize, value.clone()) {
4766 return Ok(());
4767 }
4768 // Past the dense limit the slot is too far out to be worth one `Value`
4769 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
4770 // constant time by keeping the index as an ordinary property. The store
4771 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
4772 // to a legal program.
4773 object.define_key(key, Property::with_attributes(value, true, true));
4774 // Extend, never shorten: the index may be *inside* the current length (a
4775 // huge `length` with a sparse store), and shortening would delete the
4776 // sparse properties above it — including the one just stored.
4777 if index as usize + 1 > object.array_length().unwrap_or(0) {
4778 object.array_set_length(self.heap, index as usize + 1);
4779 }
4780 return Ok(());
4781 }
4782 }
4783 if text == Some("length") && object.is_array() {
4784 if !object.length_writable() {
4785 return match on_failure {
4786 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
4787 DeleteFailure::Ignore => Ok(()),
4788 };
4789 }
4790 let length = value.to_number();
4791 if length.is_finite() && length >= 0.0 {
4792 let length = length as usize;
4793 // `a.length = n` with `n` below a non-configurable element cannot
4794 // drop that element, so the whole assignment fails. The spec makes
4795 // this a `TypeError` rather than a silent no-op, in any mode.
4796 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
4797 // Sloppy mode stops the truncation at the blocking element
4798 // instead of failing; strict mode raises.
4799 // Both modes stop at the blocking element; they differ in
4800 // whether that is reported. The reference truncates *then*
4801 // throws, so the array is left in the shortened state.
4802 object.array_truncate(self.heap, blocked + 1);
4803 return match on_failure {
4804 DeleteFailure::Throw => {
4805 Err(self.type_error(format!("cannot delete property '{blocked}'")))
4806 }
4807 DeleteFailure::Ignore => Ok(()),
4808 };
4809 }
4810 object.array_set_length(self.heap, length);
4811 return Ok(());
4812 }
4813 }
4814 if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
4815 {
4816 return match on_failure {
4817 DeleteFailure::Throw => Err(self.type_error(format!(
4818 "cannot add property {}, object is not extensible",
4819 key
4820 ))),
4821 DeleteFailure::Ignore => Ok(()),
4822 };
4823 }
4824 if let Some((owner, property)) = lookup_key(object, key) {
4825 if property.is_accessor() {
4826 match &property.setter {
4827 Some(setter) if !matches!(setter, Value::Undefined) => {
4828 let receiver = Value::Object(object.clone());
4829 self.call_value(setter.clone(), receiver, vec![value])?;
4830 }
4831 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
4832 // Sloppy code swallows that refusal, strict code raises — the same
4833 // rule the read-only *data* property below follows, and skipping it
4834 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
4835 // return silently. The reference answers `TypeError: 'x' is
4836 // read-only`.
4837 _ => {
4838 return match on_failure {
4839 DeleteFailure::Throw => {
4840 Err(self.type_error(format!("'{key}' is read-only")))
4841 }
4842 DeleteFailure::Ignore => Ok(()),
4843 };
4844 }
4845 }
4846 return Ok(());
4847 }
4848 // A non-writable data property refuses the write, own **or inherited**: an
4849 // own one stops here because nothing may change it, and an inherited one
4850 // because §10.1.9.2 step 4 refuses to create the shadowing own property.
4851 //
4852 // The `ptr_eq` this used to carry meant an inherited read-only property fell
4853 // through to `define_data_key` and *did* create the shadow — `var o =
4854 // Object.create(Object.freeze({x: 1})); o.x = 9` answered `9` and
4855 // `o.hasOwnProperty('x')` answered `true`, where the reference answers `1`
4856 // and `false`.
4857 if !property.writable {
4858 return match on_failure {
4859 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
4860 DeleteFailure::Ignore => Ok(()),
4861 };
4862 }
4863 // An existing writable own property keeps its attributes: only the value
4864 // moves. Redefining instead would reset them, which is how a
4865 // non-configurable global `var` used to become deletable.
4866 if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
4867 return Ok(());
4868 }
4869 }
4870 // No own data property: create one, shadowing whatever the prototype holds.
4871 object.define_data_key(key, value);
4872 Ok(())
4873 }
4874
4875 /// Delete `object[key]`.
4876 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
4877 self.delete_property_key(object, &PropertyKey::from(key))
4878 }
4879
4880 /// [`Interp::delete_property`] with a key that may be a symbol.
4881 pub fn delete_property_key(
4882 &mut self,
4883 object: &Gc<JsObject>,
4884 key: &PropertyKey,
4885 ) -> JsResult<bool> {
4886 // A proxy decides for itself, and may even throw; the invariant checks live in
4887 // `proxy_delete`.
4888 if let Some(answer) = self.proxy_delete(object, key)? {
4889 return Ok(answer);
4890 }
4891 if let Some(index) = key.as_str().and_then(array_index)
4892 && let Some(length) = object.array_length()
4893 && (index as usize) < length
4894 {
4895 // An accessor defined on an index lives in the property table rather than the
4896 // element vector, so both have to be cleared: `delete` after
4897 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
4898 object.delete_key(key);
4899 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
4900 // index stops answering `in`.
4901 if object.element_is_undeletable(index) {
4902 return Ok(false);
4903 }
4904 object.array_set(self.heap, index as usize, Value::Hole);
4905 return Ok(true);
4906 }
4907 Ok(object.delete_key(key))
4908 }
4909
4910 // -- proxy traps --------------------------------------------------------
4911 //
4912 // A proxy's internal methods all look the same: ask the handler for the trap, call it
4913 // with the target and the operation's own arguments, then check the answer against
4914 // the target. The checks are not decoration — they are what stops a proxy from
4915 // reporting a `non-configurable` property as missing, which would let a frozen object
4916 // be rewritten by standing in front of it.
4917
4918 /// The target and handler of `object`, or `None` when it is not a proxy.
4919 ///
4920 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
4921 /// one has to fail: the slots the traps would have been read from are gone.
4922 fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
4923 let Some(state) = object.proxy_state() else {
4924 return Ok(None);
4925 };
4926 let state = state.borrow();
4927 match (&state.target, &state.handler) {
4928 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
4929 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
4930 }
4931 }
4932
4933 /// Call `handler[name]`, or answer `None` when the trap is absent.
4934 ///
4935 /// A trap that is present but not callable is a `TypeError` rather than "no trap":
4936 /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
4937 /// back to the target.
4938 fn proxy_trap(
4939 &mut self,
4940 handler: &Value,
4941 name: &str,
4942 args: Vec<Value>,
4943 ) -> JsResult<Option<Value>> {
4944 let Value::Object(table) = handler else {
4945 return Err(self.type_error("proxy handler is not an object"));
4946 };
4947 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
4948 match trap {
4949 Value::Undefined => Ok(None),
4950 Value::Object(function) if function.is_callable() => {
4951 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
4952 Ok(Some(answer))
4953 }
4954 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
4955 }
4956 }
4957
4958 /// Whether `object`'s own property `key` is one the target refuses to lose.
4959 ///
4960 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
4961 /// its value behind the target's back. This goes through
4962 /// [`Self::ordinary_own_property`] rather than the property table so that an array's
4963 /// elements and its `length` — both fixed, both outside the table — are covered.
4964 fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
4965 Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
4966 }
4967
4968 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
4969 fn proxy_get(
4970 &mut self,
4971 object: &Gc<JsObject>,
4972 receiver: &Value,
4973 key: &PropertyKey,
4974 ) -> JsResult<Option<Value>> {
4975 let Some((target, handler)) = self.proxy_parts(object)? else {
4976 return Ok(None);
4977 };
4978 let key_value = self.key_value(key);
4979 let Some(result) = self.proxy_trap(
4980 &handler,
4981 "get",
4982 vec![Value::Object(target.clone()), key_value, receiver.clone()],
4983 )?
4984 else {
4985 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
4986 // inherited getter still sees the proxy.
4987 return Ok(Some(
4988 self.get_property_key_for(&target, Some(receiver), key)?
4989 .unwrap_or(Value::Undefined),
4990 ));
4991 };
4992 if let Some(fixed) = Self::is_fixed_property(&target, key) {
4993 if fixed.is_accessor() {
4994 // A fixed accessor with no getter must read as `undefined`.
4995 let has_getter = fixed
4996 .getter
4997 .as_ref()
4998 .is_some_and(|getter| !matches!(getter, Value::Undefined));
4999 if !has_getter && !matches!(result, Value::Undefined) {
5000 return Err(self.type_error(format!(
5001 "proxy 'get' must report undefined for the non-configurable property '{key}'"
5002 )));
5003 }
5004 } else if !fixed.writable {
5005 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5006 if !fixed_value.same_value(&result) {
5007 return Err(self.type_error(format!(
5008 "proxy 'get' disagrees with the non-configurable property '{key}'"
5009 )));
5010 }
5011 }
5012 }
5013 Ok(Some(result))
5014 }
5015
5016 /// `[[Set]]` on a proxy.
5017 ///
5018 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
5019 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
5020 /// read-only store has.
5021 fn proxy_set(
5022 &mut self,
5023 object: &Gc<JsObject>,
5024 key: &PropertyKey,
5025 value: Value,
5026 receiver: &Value,
5027 ) -> JsResult<Option<bool>> {
5028 let Some((target, handler)) = self.proxy_parts(object)? else {
5029 return Ok(None);
5030 };
5031 let key_value = self.key_value(key);
5032 let Some(result) = self.proxy_trap(
5033 &handler,
5034 "set",
5035 vec![
5036 Value::Object(target.clone()),
5037 key_value,
5038 value.clone(),
5039 receiver.clone(),
5040 ],
5041 )?
5042 else {
5043 // No trap: store on the target, which is where an ordinary proxy write lands.
5044 self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
5045 return Ok(Some(true));
5046 };
5047 if !result.to_boolean() {
5048 return Ok(Some(false));
5049 }
5050 if let Some(fixed) = Self::is_fixed_property(&target, key) {
5051 if fixed.is_accessor() {
5052 let has_setter = fixed
5053 .setter
5054 .as_ref()
5055 .is_some_and(|setter| !matches!(setter, Value::Undefined));
5056 if !has_setter {
5057 return Err(self.type_error(format!(
5058 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
5059 )));
5060 }
5061 } else if !fixed.writable {
5062 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5063 if !fixed_value.same_value(&value) {
5064 return Err(self.type_error(format!(
5065 "proxy 'set' changed the non-configurable property '{key}'"
5066 )));
5067 }
5068 }
5069 }
5070 // A new property cannot appear on a target that refuses new properties.
5071 if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
5072 return Err(self.type_error(format!(
5073 "proxy 'set' added '{key}' to a non-extensible target"
5074 )));
5075 }
5076 Ok(Some(true))
5077 }
5078
5079 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
5080 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5081 let Some((target, handler)) = self.proxy_parts(object)? else {
5082 return Ok(None);
5083 };
5084 let key_value = self.key_value(key);
5085 let Some(result) = self.proxy_trap(
5086 &handler,
5087 "has",
5088 vec![Value::Object(target.clone()), key_value],
5089 )?
5090 else {
5091 return Ok(Some(self.has_own_or_inherited(&target, key)?));
5092 };
5093 if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5094 return Err(self.type_error(format!(
5095 "proxy 'has' denied the non-configurable property '{key}'"
5096 )));
5097 }
5098 // A non-extensible target cannot grow, so every own property it *has* is fixed.
5099 if !result.to_boolean()
5100 && !target.is_extensible()
5101 && Self::ordinary_own_property(&target, key).is_some()
5102 {
5103 return Err(self.type_error(format!(
5104 "proxy 'has' denied the own property '{key}' of a non-extensible target"
5105 )));
5106 }
5107 Ok(Some(result.to_boolean()))
5108 }
5109
5110 /// `[[Delete]]` on a proxy.
5111 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5112 let Some((target, handler)) = self.proxy_parts(object)? else {
5113 return Ok(None);
5114 };
5115 let key_value = self.key_value(key);
5116 let Some(result) = self.proxy_trap(
5117 &handler,
5118 "deleteProperty",
5119 vec![Value::Object(target.clone()), key_value],
5120 )?
5121 else {
5122 return Ok(Some(self.delete_property_key(&target, key)?));
5123 };
5124 if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5125 return Err(self.type_error(format!(
5126 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
5127 )));
5128 }
5129 if result.to_boolean()
5130 && !target.is_extensible()
5131 && Self::ordinary_own_property(&target, key).is_some()
5132 {
5133 return Err(self.type_error(format!(
5134 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
5135 )));
5136 }
5137 Ok(Some(result.to_boolean()))
5138 }
5139
5140 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
5141 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
5142 let Some((target, handler)) = self.proxy_parts(object)? else {
5143 return Ok(None);
5144 };
5145 let Some(result) =
5146 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
5147 else {
5148 // No trap: the target's own keys, already in the order an object reports.
5149 return Ok(Some(self.object_own_property_keys(&target)?));
5150 };
5151 // `CreateListFromArrayLike` with the string-or-symbol restriction.
5152 let list = self.list_from_array_like(&result, true)?;
5153 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
5154 for value in list {
5155 let key = self.propkey(&value)?;
5156 if keys.contains(&key) {
5157 return Err(self.type_error(format!(
5158 "proxy 'ownKeys' returned the duplicate key '{key}'"
5159 )));
5160 }
5161 keys.push(key);
5162 }
5163 for (key, property) in target.property_entries() {
5164 if !property.configurable && !keys.contains(&key) {
5165 return Err(self.type_error(format!(
5166 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
5167 )));
5168 }
5169 if !target.is_extensible() && !keys.contains(&key) {
5170 return Err(self.type_error(format!(
5171 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
5172 )));
5173 }
5174 }
5175 if !target.is_extensible() {
5176 let own = target.property_entries().len();
5177 if keys.len() != own {
5178 return Err(
5179 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
5180 );
5181 }
5182 }
5183 Ok(Some(keys))
5184 }
5185
5186 /// `[[GetOwnProperty]]` on a proxy.
5187 fn proxy_get_own_property(
5188 &mut self,
5189 object: &Gc<JsObject>,
5190 key: &PropertyKey,
5191 ) -> JsResult<Option<Option<Property>>> {
5192 let Some((target, handler)) = self.proxy_parts(object)? else {
5193 return Ok(None);
5194 };
5195 let key_value = self.key_value(key);
5196 let Some(result) = self.proxy_trap(
5197 &handler,
5198 "getOwnPropertyDescriptor",
5199 vec![Value::Object(target.clone()), key_value],
5200 )?
5201 else {
5202 // No trap: the target's own descriptor is the answer. This has to go through
5203 // the same synthesis an ordinary object gets, because a proxy's own property
5204 // table is empty by design — reading it directly reported `undefined` for
5205 // every key, including an array's indices and `length`.
5206 return Ok(Some(Self::ordinary_own_property(&target, key)));
5207 };
5208 let answer = if matches!(result, Value::Undefined) {
5209 None
5210 } else {
5211 Some(self.property_from_descriptor(&result)?)
5212 };
5213 let fixed = Self::is_fixed_property(&target, key);
5214 match (&answer, &fixed) {
5215 // A non-configurable property cannot be reported as absent.
5216 (None, Some(_)) => {
5217 return Err(self.type_error(format!(
5218 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
5219 )));
5220 }
5221 (Some(descriptor), Some(fixed)) => {
5222 if descriptor.configurable {
5223 return Err(self.type_error(format!(
5224 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
5225 )));
5226 }
5227 if fixed.is_accessor() != descriptor.is_accessor() {
5228 return Err(self.type_error(format!(
5229 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
5230 )));
5231 }
5232 if !fixed.is_accessor() && !fixed.writable {
5233 let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
5234 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
5235 if !fixed_value.same_value(&reported) {
5236 return Err(self.type_error(format!(
5237 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
5238 )));
5239 }
5240 }
5241 }
5242 _ => {}
5243 }
5244 Ok(Some(answer))
5245 }
5246
5247 /// `[[DefineOwnProperty]]` on a proxy.
5248 fn proxy_define_property(
5249 &mut self,
5250 object: &Gc<JsObject>,
5251 key: &PropertyKey,
5252 property: Property,
5253 ) -> JsResult<Option<bool>> {
5254 let Some((target, handler)) = self.proxy_parts(object)? else {
5255 return Ok(None);
5256 };
5257 let key_value = self.key_value(key);
5258 let descriptor = self.descriptor_from_property(&property);
5259 let Some(result) = self.proxy_trap(
5260 &handler,
5261 "defineProperty",
5262 vec![Value::Object(target.clone()), key_value, descriptor],
5263 )?
5264 else {
5265 return Ok(None);
5266 };
5267 if !result.to_boolean() {
5268 return Ok(Some(false));
5269 }
5270 let fixed = Self::is_fixed_property(&target, key);
5271 let creating = Self::ordinary_own_property(&target, key).is_none();
5272 if creating && !target.is_extensible() {
5273 return Err(self.type_error(format!(
5274 "proxy 'defineProperty' added '{key}' to a non-extensible target"
5275 )));
5276 }
5277 if let Some(fixed) = fixed {
5278 if property.configurable {
5279 return Err(self.type_error(format!(
5280 "proxy 'defineProperty' made the non-configurable '{key}' configurable"
5281 )));
5282 }
5283 if !fixed.writable && property.writable && !fixed.is_accessor() {
5284 return Err(self.type_error(format!(
5285 "proxy 'defineProperty' made the read-only '{key}' writable"
5286 )));
5287 }
5288 }
5289 Ok(Some(true))
5290 }
5291
5292 /// `[[GetPrototypeOf]]` on a proxy.
5293 fn proxy_get_prototype_of(
5294 &mut self,
5295 object: &Gc<JsObject>,
5296 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
5297 let Some((target, handler)) = self.proxy_parts(object)? else {
5298 return Ok(None);
5299 };
5300 let Some(result) = self.proxy_trap(
5301 &handler,
5302 "getPrototypeOf",
5303 vec![Value::Object(target.clone())],
5304 )?
5305 else {
5306 return Ok(Some(target.proto()));
5307 };
5308 let proto = match &result {
5309 Value::Null => None,
5310 Value::Object(proto) => Some(proto.clone()),
5311 _ => {
5312 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
5313 }
5314 };
5315 if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
5316 return Err(self.type_error(
5317 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
5318 ));
5319 }
5320 Ok(Some(proto))
5321 }
5322
5323 /// `[[SetPrototypeOf]]` on a proxy.
5324 fn proxy_set_prototype_of(
5325 &mut self,
5326 object: &Gc<JsObject>,
5327 proto: Option<Gc<JsObject>>,
5328 ) -> JsResult<Option<bool>> {
5329 let Some((target, handler)) = self.proxy_parts(object)? else {
5330 return Ok(None);
5331 };
5332 let proto_value = match &proto {
5333 Some(proto) => Value::Object(proto.clone()),
5334 None => Value::Null,
5335 };
5336 let Some(result) = self.proxy_trap(
5337 &handler,
5338 "setPrototypeOf",
5339 vec![Value::Object(target.clone()), proto_value],
5340 )?
5341 else {
5342 target.set_proto(proto);
5343 return Ok(Some(true));
5344 };
5345 if result.to_boolean()
5346 && !target.is_extensible()
5347 && !same_proto(proto.as_ref(), target.proto().as_ref())
5348 {
5349 return Err(self.type_error(
5350 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
5351 ));
5352 }
5353 Ok(Some(result.to_boolean()))
5354 }
5355
5356 /// `[[IsExtensible]]` on a proxy.
5357 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
5358 let Some((target, handler)) = self.proxy_parts(object)? else {
5359 return Ok(None);
5360 };
5361 let Some(result) = self.proxy_trap(
5362 &handler,
5363 "isExtensible",
5364 vec![Value::Object(target.clone())],
5365 )?
5366 else {
5367 return Ok(Some(target.is_extensible()));
5368 };
5369 // The answer is not the proxy's to invent: it must agree with the target, or a
5370 // script could learn `false` while the target keeps accepting new properties.
5371 if result.to_boolean() != target.is_extensible() {
5372 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
5373 }
5374 Ok(Some(result.to_boolean()))
5375 }
5376
5377 /// `[[PreventExtensions]]` on a proxy.
5378 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
5379 let Some((target, handler)) = self.proxy_parts(object)? else {
5380 return Ok(None);
5381 };
5382 let Some(result) = self.proxy_trap(
5383 &handler,
5384 "preventExtensions",
5385 vec![Value::Object(target.clone())],
5386 )?
5387 else {
5388 target.set_extensible(false);
5389 return Ok(Some(true));
5390 };
5391 if result.to_boolean() && target.is_extensible() {
5392 return Err(self.type_error(
5393 "proxy 'preventExtensions' reported success but the target is still extensible",
5394 ));
5395 }
5396 Ok(Some(result.to_boolean()))
5397 }
5398
5399 /// `[[Call]]` on a proxy, through the `apply` trap.
5400 fn proxy_apply(
5401 &mut self,
5402 object: &Gc<JsObject>,
5403 this: Value,
5404 args: Vec<Value>,
5405 ) -> JsResult<Option<Value>> {
5406 let Some((target, handler)) = self.proxy_parts(object)? else {
5407 return Ok(None);
5408 };
5409 // The trap gets the arguments as one array, which is the shape the spec passes
5410 // and the shape `apply` traps are written against (`args[0]` is the first one).
5411 let arguments = self.new_array(args.clone());
5412 let this_for_trap = this.clone();
5413 let Some(result) = self.proxy_trap(
5414 &handler,
5415 "apply",
5416 vec![
5417 Value::Object(target.clone()),
5418 this_for_trap,
5419 Value::Object(arguments),
5420 ],
5421 )?
5422 else {
5423 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
5424 };
5425 Ok(Some(result))
5426 }
5427
5428 /// `[[Construct]]` on a proxy, through the `construct` trap.
5429 fn proxy_construct(
5430 &mut self,
5431 object: &Gc<JsObject>,
5432 args: Vec<Value>,
5433 new_target: &Value,
5434 ) -> JsResult<Option<Value>> {
5435 let Some((target, handler)) = self.proxy_parts(object)? else {
5436 return Ok(None);
5437 };
5438 if !target.is_callable() {
5439 return Err(self.type_error("proxy target is not a constructor"));
5440 }
5441 let arguments = self.new_array(args.clone());
5442 let Some(result) = self.proxy_trap(
5443 &handler,
5444 "construct",
5445 vec![
5446 Value::Object(target.clone()),
5447 Value::Object(arguments),
5448 new_target.clone(),
5449 ],
5450 )?
5451 else {
5452 return Ok(Some(self.construct(
5453 Value::Object(target),
5454 new_target.clone(),
5455 args,
5456 )?));
5457 };
5458 if !matches!(result, Value::Object(_)) {
5459 return Err(self.type_error("proxy 'construct' must return an object"));
5460 }
5461 Ok(Some(result))
5462 }
5463
5464 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
5465 pub(crate) fn has_own_or_inherited(
5466 &mut self,
5467 object: &Gc<JsObject>,
5468 key: &PropertyKey,
5469 ) -> JsResult<bool> {
5470 // The object itself first: it may be a proxy, and then the answer is its trap's.
5471 if let Some(answer) = self.proxy_has(object, key)? {
5472 return Ok(answer);
5473 }
5474 // `has_own` rather than `own_property_key`: an array's elements and its derived
5475 // `length` are invisible to the property table, and `Array.prototype` is an array.
5476 if has_own(object, key) {
5477 return Ok(true);
5478 }
5479 // A hole is *not* the end of the search: the chain may still have the key, which
5480 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
5481 for ancestor in object.chain() {
5482 // A proxy further up the chain answers for itself.
5483 if let Some(answer) = self.proxy_has(&ancestor, key)? {
5484 return Ok(answer);
5485 }
5486 if has_own(&ancestor, key) {
5487 return Ok(true);
5488 }
5489 }
5490 Ok(false)
5491 }
5492
5493 /// `CreateListFromArrayLike`, optionally restricted to property keys.
5494 ///
5495 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
5496 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
5497 /// `TypeError` instead of a property named `"1.5"`.
5498 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
5499 let object = self.object_from(value)?;
5500 let length = self
5501 .get_property(&object, "length")?
5502 .map(|value| value.to_number())
5503 .unwrap_or(0.0);
5504 if !length.is_finite() || length < 0.0 {
5505 return Err(self.type_error("invalid array-like length"));
5506 }
5507 let length = length as usize;
5508 let mut items = Vec::with_capacity(length.min(1024));
5509 for index in 0..length {
5510 let item = self
5511 .get_property(&object, &index.to_string())?
5512 .unwrap_or(Value::Undefined);
5513 if keys_only && matches!(&item, Value::Symbol(_)) {
5514 items.push(item);
5515 continue;
5516 }
5517 if keys_only && !matches!(&item, Value::String(_)) {
5518 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
5519 }
5520 items.push(item);
5521 }
5522 Ok(items)
5523 }
5524
5525 /// A `Property` from the descriptor object a trap returned.
5526 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
5527 let object = self.object_from(value)?;
5528 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
5529 interp.get_property(&object, name)
5530 };
5531 let getter = field(self, "get")?;
5532 let setter = field(self, "set")?;
5533 let accessor = getter.is_some() || setter.is_some();
5534 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
5535 Ok(interp
5536 .get_property(&object, name)?
5537 .is_some_and(|value| value.to_boolean()))
5538 };
5539 let enumerable = boolean(self, "enumerable")?;
5540 let configurable = boolean(self, "configurable")?;
5541 if accessor {
5542 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
5543 return Err(
5544 self.type_error("a descriptor cannot be both a data property and an accessor")
5545 );
5546 }
5547 Ok(Property {
5548 getter: getter.or(Some(Value::Undefined)),
5549 setter: setter.or(Some(Value::Undefined)),
5550 enumerable,
5551 configurable,
5552 writable: false,
5553 value: None,
5554 })
5555 } else {
5556 Ok(Property {
5557 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
5558 writable: boolean(self, "writable")?,
5559 enumerable,
5560 configurable,
5561 getter: None,
5562 setter: None,
5563 })
5564 }
5565 }
5566
5567 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
5568 fn descriptor_from_property(&mut self, property: &Property) -> Value {
5569 let object = self.new_object(None);
5570 if property.is_accessor() {
5571 let getter = property.getter.clone().unwrap_or(Value::Undefined);
5572 let setter = property.setter.clone().unwrap_or(Value::Undefined);
5573 object.define_data("get", getter);
5574 object.define_data("set", setter);
5575 } else {
5576 let value = property.value.clone().unwrap_or(Value::Undefined);
5577 object.define_data("value", value);
5578 object.define_data("writable", Value::Bool(property.writable));
5579 }
5580 object.define_data("enumerable", Value::Bool(property.enumerable));
5581 object.define_data("configurable", Value::Bool(property.configurable));
5582 Value::Object(object)
5583 }
5584
5585 // -- calling ------------------------------------------------------------
5586
5587 /// Call `callee` with `this` and `args`.
5588 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
5589 let Value::Object(function) = &callee else {
5590 // `typeof x === "function"` is not enough to make `x()` legal: only a
5591 // callable object is. `null` and `undefined` need no special wording
5592 // here — their `ToString` already reads the way the reference's does.
5593 let what = format!("{} is not a function", callee.to_js_string());
5594 return Err(Signal::Throw(self.make_error("TypeError", &what)));
5595 };
5596 // A proxy of a function is called through its `apply` trap. It has no
5597 // `ObjectKind::Function` of its own, so this has to come before the dispatch
5598 // below, and a proxy of a non-function has nothing to forward to.
5599 if function.proxy_state().is_some() {
5600 return match self.proxy_apply(function, this, args)? {
5601 Some(result) => Ok(result),
5602 None => Err(Signal::Throw(
5603 self.make_error("TypeError", "proxy target is not callable"),
5604 )),
5605 };
5606 }
5607 let callable = function.with(|data| match &data.kind {
5608 ObjectKind::Function(callable) => match callable {
5609 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
5610 // The `Rc` is cloned out so the borrow of this object's data is released
5611 // before the closure runs: the closure may touch the same object.
5612 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
5613 Callable::Bound {
5614 target,
5615 this,
5616 args: leading,
5617 } => Some(NativeCall::Bound {
5618 target: target.clone(),
5619 this: this.clone(),
5620 leading: leading.clone(),
5621 }),
5622 Callable::Bytecode { code, env } => {
5623 Some(NativeCall::Bytecode(code.clone(), env.clone()))
5624 }
5625 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
5626 Callable::PromiseResolve(promise) => {
5627 Some(NativeCall::PromiseResolve(promise.clone()))
5628 }
5629 Callable::PromiseReject(promise) => {
5630 Some(NativeCall::PromiseReject(promise.clone()))
5631 }
5632 Callable::AwaitResume {
5633 coroutine,
5634 promise,
5635 kind,
5636 } => Some(NativeCall::AwaitResume {
5637 coroutine: coroutine.clone(),
5638 promise: promise.clone(),
5639 kind: *kind,
5640 }),
5641 Callable::CombinatorSettle {
5642 state,
5643 index,
5644 fulfilled,
5645 } => Some(NativeCall::CombinatorSettle {
5646 state: state.clone(),
5647 index: *index,
5648 fulfilled: *fulfilled,
5649 }),
5650 Callable::FinallyShim {
5651 callback,
5652 fulfilled,
5653 } => Some(NativeCall::FinallyShim {
5654 callback: callback.clone(),
5655 fulfilled: *fulfilled,
5656 }),
5657 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
5658 Callable::CompletedReturn {
5659 generator,
5660 promise,
5661 rejected,
5662 } => Some(NativeCall::CompletedReturn {
5663 generator: generator.clone(),
5664 promise: promise.clone(),
5665 rejected: *rejected,
5666 }),
5667 Callable::YieldResult {
5668 generator,
5669 promise,
5670 done,
5671 } => Some(NativeCall::YieldResult {
5672 generator: generator.clone(),
5673 promise: promise.clone(),
5674 done: *done,
5675 }),
5676 Callable::DisposeStep {
5677 remaining,
5678 promise,
5679 error,
5680 rejected,
5681 } => Some(NativeCall::DisposeStep {
5682 remaining: remaining.clone(),
5683 promise: promise.clone(),
5684 error: error.clone(),
5685 rejected: *rejected,
5686 }),
5687 Callable::GeneratorResume {
5688 generator,
5689 promise,
5690 kind,
5691 } => Some(NativeCall::GeneratorResume {
5692 generator: generator.clone(),
5693 promise: promise.clone(),
5694 kind: *kind,
5695 }),
5696 Callable::SettlePromise {
5697 promise,
5698 value,
5699 rejected,
5700 } => Some(NativeCall::SettlePromise {
5701 promise: promise.clone(),
5702 value: value.clone(),
5703 rejected: *rejected,
5704 }),
5705 },
5706 _ => None,
5707 });
5708 match callable {
5709 Some(NativeCall::Host(func)) => {
5710 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
5711 // function by name rather than stopping at the caller.
5712 let frame_less = function
5713 .own_property("_frame_less")
5714 .and_then(|property| property.value)
5715 .is_some_and(|value| value.to_boolean());
5716 let outer = if frame_less {
5717 None
5718 } else {
5719 self.native_frames
5720 .push((function.clone(), self.frames.len()));
5721 Some(self.current_native.replace(function.clone()))
5722 };
5723 let result = {
5724 let mut body = func.borrow_mut();
5725 body(self, this, &args)
5726 };
5727 if !frame_less {
5728 self.native_frames.pop();
5729 self.current_native = outer.flatten();
5730 }
5731 result
5732 }
5733 Some(NativeCall::Native(func)) => {
5734 // A function marked `_frame_less` is one the reference implements
5735 // without a call frame — `eval` is the only one so far.
5736 let frame_less = function
5737 .own_property("_frame_less")
5738 .and_then(|property| property.value)
5739 .is_some_and(|value| value.to_boolean());
5740 let outer = if frame_less {
5741 None
5742 } else {
5743 self.native_frames
5744 .push((function.clone(), self.frames.len()));
5745 Some(self.current_native.replace(function.clone()))
5746 };
5747 let result = func(self, this, &args);
5748 if !frame_less {
5749 self.native_frames.pop();
5750 self.current_native = outer.flatten();
5751 }
5752 result
5753 }
5754 Some(NativeCall::Revoker(slots)) => {
5755 // Idempotent: revoking twice answers `undefined` again rather than
5756 // complaining, which is what the spec says and what a `finally` block
5757 // relies on.
5758 let mut state = slots.borrow_mut();
5759 state.target = None;
5760 state.handler = None;
5761 Ok(Value::Undefined)
5762 }
5763 Some(NativeCall::PromiseResolve(promise)) => {
5764 // One-shot: a second call is silently ignored, which
5765 // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
5766 let value = args.first().cloned().unwrap_or(Value::Undefined);
5767 self.resolve_promise_with(&promise, value)?;
5768 Ok(Value::Undefined)
5769 }
5770 Some(NativeCall::PromiseReject(promise)) => {
5771 let reason = args.first().cloned().unwrap_or(Value::Undefined);
5772 self.reject_promise(&promise, reason);
5773 Ok(Value::Undefined)
5774 }
5775 Some(NativeCall::CombinatorSettle {
5776 state,
5777 index,
5778 fulfilled,
5779 }) => {
5780 let value = args.first().cloned().unwrap_or(Value::Undefined);
5781 self.settle_combinator(&state, index, fulfilled, value)?;
5782 Ok(Value::Undefined)
5783 }
5784 Some(NativeCall::AwaitResume {
5785 coroutine,
5786 promise,
5787 kind,
5788 }) => {
5789 // Resume *inline*, in the reaction that delivered the value. Deferring it
5790 // by another job inserts a tick between every `await` and its
5791 // continuation, which reorders `await` against unrelated `then` chains —
5792 // `f().then(g)` then runs before `f`'s own next statement.
5793 self.drive_async(
5794 &coroutine,
5795 &promise,
5796 kind,
5797 args.first().cloned().unwrap_or(Value::Undefined),
5798 )
5799 .map(|()| Value::Undefined)
5800 }
5801 Some(NativeCall::FinallyShim {
5802 callback,
5803 fulfilled,
5804 }) => {
5805 // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
5806 // that settles with the *original* outcome once the callback's result has
5807 // settled. The callback's own value is discarded — that is the whole
5808 // difference between `finally` and `then`.
5809 let original = args.first().cloned().unwrap_or(Value::Undefined);
5810 let result = match &callback {
5811 Some(callback) => {
5812 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
5813 }
5814 None => Value::Undefined,
5815 };
5816 let resolved = self.promise_resolve_value(result)?;
5817 let Value::Object(resolved) = resolved else {
5818 return Ok(original);
5819 };
5820 // The wait is a chained promise rather than a bare return, so a callback
5821 // that returns a slow promise really does delay the continuation.
5822 let waiting = self.new_promise();
5823 let pass = JsObject::function(
5824 self.heap,
5825 Some(self.realm.function_proto.clone()),
5826 Callable::SettlePromise {
5827 promise: waiting.clone(),
5828 value: original,
5829 rejected: !fulfilled,
5830 },
5831 );
5832 let pass = Value::Object(pass);
5833 // Whichever way the callback's promise settles, the original outcome wins.
5834 self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
5835 Ok(Value::Object(waiting))
5836 }
5837 Some(NativeCall::DisposeStep {
5838 remaining,
5839 promise,
5840 error,
5841 rejected,
5842 }) => {
5843 let error = if rejected {
5844 let reason = args.first().cloned().unwrap_or(Value::Undefined);
5845 self.merge_dispose_error(reason, error)
5846 } else {
5847 error
5848 };
5849 self.dispose_step(&remaining, &promise, error)?;
5850 Ok(Value::Undefined)
5851 }
5852 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
5853 Some(NativeCall::CompletedReturn {
5854 generator,
5855 promise,
5856 rejected,
5857 }) => {
5858 let value = args.first().cloned().unwrap_or(Value::Undefined);
5859 let outcome = if rejected {
5860 AsyncOutcome::Error(value)
5861 } else {
5862 AsyncOutcome::Value(self.iterator_result(value, true)?)
5863 };
5864 self.settle_async_request(&generator, &promise, outcome)?;
5865 Ok(Value::Undefined)
5866 }
5867 Some(NativeCall::YieldResult {
5868 generator,
5869 promise,
5870 done,
5871 }) => {
5872 let value = args.first().cloned().unwrap_or(Value::Undefined);
5873 let result = self.iterator_result(value, done)?;
5874 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
5875 Ok(Value::Undefined)
5876 }
5877 Some(NativeCall::GeneratorResume {
5878 generator,
5879 promise,
5880 kind,
5881 }) => {
5882 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
5883 // tick and reorders the generator against other chains.
5884 self.step_async_generator(
5885 &generator,
5886 &promise,
5887 kind,
5888 args.first().cloned().unwrap_or(Value::Undefined),
5889 )
5890 .map(|()| Value::Undefined)
5891 }
5892 Some(NativeCall::SettlePromise {
5893 promise,
5894 value,
5895 rejected,
5896 }) => {
5897 if rejected {
5898 self.reject_promise(&promise, value);
5899 } else {
5900 self.fulfill_promise(&promise, value);
5901 }
5902 Ok(Value::Undefined)
5903 }
5904 Some(NativeCall::Bound {
5905 target,
5906 this: bound_this,
5907 leading,
5908 }) => {
5909 let mut all = leading;
5910 all.extend(args);
5911 self.call_value(target, bound_this, all)
5912 }
5913 Some(NativeCall::Bytecode(code, env)) => {
5914 if code.code.kind.is_generator() {
5915 return self.new_generator(callee, this, args);
5916 }
5917 if code.code.kind.is_async() {
5918 // Same coroutine machinery as a generator; the difference is only in
5919 // what the completion does — see `new_async_function`.
5920 return self.new_async_function(callee, this, args);
5921 }
5922 self.execute(code, env, this, args, callee)
5923 }
5924 None => Err(Signal::Throw(
5925 self.make_error("TypeError", "not a function"),
5926 )),
5927 }
5928 }
5929
5930 /// Give a freshly built function its own `prototype` object.
5931 ///
5932 /// Every function that can be used with `new` carries one, and its
5933 /// `constructor` points back at the function — a reference cycle, which is
5934 /// exactly what the collector's cycle pass exists to reclaim.
5935 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
5936 let prototype = self.new_object(Some(self.realm.object_proto.clone()));
5937 let constructor = Value::Object(function.clone());
5938 prototype.define(
5939 "constructor",
5940 Property::with_attributes(constructor, true, false),
5941 );
5942 let value = Value::Object(prototype);
5943 function.define("prototype", Property::prototype_of(value, true));
5944 }
5945
5946 /// The object `special_object` builds.
5947 ///
5948 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
5949 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
5950 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
5951 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
5952 /// write through `arguments` does not reach the parameter.
5953 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
5954 match magic {
5955 0 | 1 => {
5956 let args = self.frame().passed().to_vec();
5957 let proto = self.realm.object_proto.clone();
5958 let object = self.new_object(Some(proto));
5959 // The marker `Object.prototype.toString` needs: an arguments object is an
5960 // ordinary object apart from reporting `[object Arguments]`, and that has
5961 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
5962 // show up ahead of them in a key listing anyway — it is non-enumerable.
5963 self.internal_set(&object, "_class", self.string("Arguments"));
5964 // `length` is writable and configurable but neither enumerable nor a
5965 // plain data property: `Object.keys(arguments)` lists the indices only,
5966 // which is how `{...arguments}` copies them without the length.
5967 object.define(
5968 "length",
5969 Property::with_attributes(Value::Int(args.len() as i32), true, false),
5970 );
5971 for (index, value) in args.into_iter().enumerate() {
5972 object.define_data(&index.to_string(), value);
5973 }
5974 // An arguments object is iterable: `[...arguments]` and
5975 // `for (const a of arguments)` both work, through the *array* iterator
5976 // because the object is array-like. Without this the whole spread form
5977 // reported "not iterable".
5978 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
5979 let values = self
5980 .realm
5981 .array_proto
5982 .own_property("values")
5983 .and_then(|property| property.value);
5984 if let Some(values) = values {
5985 object.define_key(
5986 &iterator_key,
5987 Property::with_attributes(values, true, false),
5988 );
5989 }
5990 Ok(Value::Object(object))
5991 }
5992 // `this.active_func`: the constructor `super()` resolves against.
5993 //
5994 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
5995 // own, so it inherits this from the function it was written in along with `this`
5996 // — and that is a lexical relationship, not a stack one: an arrow that escaped
5997 // the constructor and is called back later (`iter.return = () => super()`) has
5998 // the constructor nowhere on the stack. The compiler therefore reads it out of
5999 // a closure variable of the enclosing function, exactly as the reference does
6000 // with its `this_active_func` local.
6001 2 => Ok(self
6002 .current_callee()
6003 .map_or(Value::Undefined, Value::Object)),
6004 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
6005 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
6006 // its own either, so the lookup walks out to the nearest non-arrow frame for
6007 // the same reason as `this.active_func` above — without that, `super()` inside
6008 // an arrow passed `undefined` as the new target and the parent constructor was
6009 // then rejected for being invoked without `new`.
6010 3 => Ok(self
6011 .eval_new_target
6012 .clone()
6013 .unwrap_or_else(|| self.frame().new_target.clone())),
6014 // `[[HomeObject]]` of the function being run: what `super` is relative to.
6015 // An arrow has none of its own, so the lookup walks out to the enclosing
6016 // method — which is why `super` works inside an arrow inside a method.
6017 4 => Ok(self
6018 .frames
6019 .iter()
6020 .rev()
6021 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6022 .map_or(Value::Undefined, Value::Object)),
6023 // `import.meta`: the innermost module body's meta object. Outside a module
6024 // the compiler never emits this, so an empty fallback is unreachable rather
6025 // than permissive.
6026 6 => {
6027 let name = self.module_stack.last().cloned();
6028 let meta = name
6029 .and_then(|name| self.modules.get(&name).cloned())
6030 .and_then(|module| module.with(|r| r.import_meta.clone()));
6031 Ok(meta.map_or(Value::Undefined, Value::Object))
6032 }
6033 other => Err(Signal::Throw(self.make_error(
6034 "InternalError",
6035 &format!("special_object {other} is not implemented yet"),
6036 ))),
6037 }
6038 }
6039
6040 /// `[[HomeObject]]` of the innermost function that has one, if any.
6041 ///
6042 /// An arrow has none, so the search walks out to the enclosing method — the same
6043 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
6044 /// inside a method.
6045 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
6046 self.frames
6047 .iter()
6048 .rev()
6049 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6050 }
6051
6052 /// The dispose method a `using` declaration should snapshot, or an error.
6053 ///
6054 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
6055 /// is what makes a resource that only knows the synchronous protocol usable in both
6056 /// forms.
6057 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
6058 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
6059 if value.is_nullish() {
6060 return Ok(Value::Undefined);
6061 }
6062 let Some(object) = value.as_object() else {
6063 return Err(self.type_error("not an object"));
6064 };
6065 let mut method = if await_form {
6066 let found = self.get_property_key(
6067 object,
6068 &self.realm.well_known_key(WellKnown::AsyncDisposable),
6069 )?;
6070 match found {
6071 Some(found) if !found.is_nullish() => Some(found),
6072 _ => self
6073 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
6074 }
6075 } else {
6076 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
6077 };
6078 let Some(found) = method.take() else {
6079 return Err(self.type_error("value is not disposable"));
6080 };
6081 if found.is_nullish() {
6082 return Err(self.type_error("value is not disposable"));
6083 }
6084 let callable = found.as_object().is_some_and(|object| object.is_callable());
6085 if !callable {
6086 return Err(self.type_error("dispose method is not a function"));
6087 }
6088 Ok(found)
6089 }
6090
6091 /// Call one resource's disposer, folding a failure into `error_state`.
6092 ///
6093 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
6094 /// because a captured `using` binding lives in its reference cell and the local slot is
6095 /// stale — a closure over the resource is legal and must not change what is disposed.
6096 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
6097 let value = self.get_loc(slot);
6098 let method = self.get_loc(slot + 1);
6099 // A resource that was never initialised — its declaration threw — or that is
6100 // `null`/`undefined` has nothing to dispose.
6101 if value.is_nullish() || matches!(value, Value::Uninitialized) {
6102 return Ok(error_state);
6103 }
6104 if matches!(method, Value::Undefined | Value::Uninitialized) {
6105 return Ok(error_state);
6106 }
6107 match self.call_value(method, value, Vec::new()) {
6108 Ok(_) => Ok(error_state),
6109 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
6110 Err(other) => Err(other),
6111 }
6112 }
6113
6114 /// Combine a disposal failure with whatever was already going wrong.
6115 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
6116 if matches!(error_state, Value::Uninitialized) {
6117 return new_error;
6118 }
6119 self.new_suppressed_error(new_error, error_state)
6120 }
6121
6122 /// A `SuppressedError` instance built straight from its prototype.
6123 ///
6124 /// Not through the constructor: a script that rewrites
6125 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
6126 /// error wrapping.
6127 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
6128 let proto = self
6129 .realm
6130 .suppressed_error_proto
6131 .clone()
6132 .unwrap_or_else(|| self.realm.error_proto.clone());
6133 let object = self.new_object(Some(proto));
6134 object.define("error", Property::with_attributes(error, true, true));
6135 object.define(
6136 "suppressed",
6137 Property::with_attributes(suppressed, true, true),
6138 );
6139 object.define(
6140 "message",
6141 Property::with_attributes(self.string("SuppressedError"), true, true),
6142 );
6143 self.internal_set(&object, "_class", self.string("Error"));
6144 self.add_stack(&object);
6145 Value::Object(object)
6146 }
6147
6148 /// Call `callee`, or push its frame and let the main loop run it.
6149 ///
6150 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
6151 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
6152 /// continues, so `function f(){ return f() }` costs heap and stops at
6153 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
6154 /// is entered directly, and natives do not re-enter JavaScript in this
6155 /// milestone.
6156 ///
6157 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
6158 /// because the returning frame will.
6159 /// The elements of an array-like value, as a call argument list.
6160 ///
6161 /// `apply` accepts any array-like, not only a real array: the reference reads
6162 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
6163 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
6164 let Some(object) = value.as_object().cloned() else {
6165 if value.is_nullish() {
6166 // `f.apply(this, null)` passes no arguments at all.
6167 return Ok(Vec::new());
6168 }
6169 return Err(self.type_error("createListFromArrayLike called on non-object"));
6170 };
6171 let length = match self.get_property(&object, "length")? {
6172 Some(length) => length.to_number(),
6173 None => 0.0,
6174 };
6175 if !length.is_finite() || length <= 0.0 {
6176 return Ok(Vec::new());
6177 }
6178 let length = (length as usize).min(1_000_000);
6179 let mut args = Vec::with_capacity(length);
6180 for index in 0..length {
6181 let element = self.get_property(&object, &index.to_string())?;
6182 args.push(element.unwrap_or(Value::Undefined));
6183 }
6184 Ok(args)
6185 }
6186
6187 /// Turn a call to a generator function into a generator object.
6188 ///
6189 /// The frame is built exactly as an ordinary call would build it, then detached and
6190 /// stored in the generator before any body instruction runs — which is what makes
6191 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
6192 /// is `initial_yield`, the first instruction of every suspending body.
6193 pub fn new_generator(
6194 &mut self,
6195 function: Value,
6196 this: Value,
6197 args: Vec<Value>,
6198 ) -> JsResult<Value> {
6199 let Some(object) = function.as_object().cloned() else {
6200 return Err(self.type_error("not a generator function"));
6201 };
6202 let Some((code, env)) = bytecode_of(&object) else {
6203 return Err(self.type_error("not a generator function"));
6204 };
6205 let is_async = code.code.kind.is_async();
6206 self.push_frame(code, env, this, args, function)?;
6207 let frame = self.frames.pop().expect("push_frame just pushed it");
6208 // A fresh generator is *suspended at start*: the body has not run, so a
6209 // `return`/`throw` on it finishes without executing anything.
6210 let mut state = GeneratorState {
6211 frame: Some(frame),
6212 phase: GeneratorPhase::SuspendedStart,
6213 parked_on_await: false,
6214 parked_on_yield_star: false,
6215 requests: std::collections::VecDeque::new(),
6216 async_busy: false,
6217 };
6218 // Run to the first suspension. For a generator that is `initial_yield`, so no
6219 // body code runs; for a malformed body it would be the first `yield`.
6220 // An `async function*` answers an async generator: same coroutine, but its
6221 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
6222 let proto = if is_async {
6223 self.realm
6224 .async_generator_proto
6225 .clone()
6226 .unwrap_or_else(|| self.realm.generator_proto.clone())
6227 } else {
6228 self.realm.generator_proto.clone()
6229 };
6230 let generator = self.new_object(Some(proto));
6231 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
6232 Ok(_) => {}
6233 Err(error) => return Err(error),
6234 }
6235 generator.with_mut(|data| {
6236 data.kind = ObjectKind::Generator(Box::new(state));
6237 });
6238 Ok(Value::Object(generator))
6239 }
6240
6241 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
6242 ///
6243 /// Returns the `{value, done}` object itself rather than the pair, because a
6244 /// `yield*` suspension already has one — the inner iterator's own result — and the
6245 /// protocol says to hand that straight through rather than nest it.
6246 /// Advance a generator and report *why* it parked.
6247 ///
6248 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
6249 /// "hand this value to the caller" — but an async generator does: an `await` has to
6250 /// settle before it can answer, while a `yield` is the answer.
6251 fn resume_generator_detailed(
6252 &mut self,
6253 generator: &Gc<JsObject>,
6254 kind: ResumeKind,
6255 value: Value,
6256 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
6257 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
6258 ObjectKind::Generator(state) => Some(std::mem::replace(
6259 state.as_mut(),
6260 GeneratorState {
6261 frame: None,
6262 phase: GeneratorPhase::Executing,
6263 parked_on_await: false,
6264 parked_on_yield_star: false,
6265 requests: std::collections::VecDeque::new(),
6266 async_busy: false,
6267 },
6268 )),
6269 _ => None,
6270 }) else {
6271 return Err(self.type_error("not a generator"));
6272 };
6273 let result = self.step_generator(&mut state, kind, value);
6274 generator.with_mut(|data| {
6275 data.kind = ObjectKind::Generator(Box::new(state));
6276 });
6277 result
6278 }
6279
6280 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
6281 ///
6282 /// Returns the `{value, done}` object itself rather than the pair, because a
6283 /// `yield*` suspension already has one — the inner iterator's own result — and the
6284 /// protocol says to hand that straight through rather than nest it.
6285 pub fn resume_generator(
6286 &mut self,
6287 generator: &Gc<JsObject>,
6288 kind: ResumeKind,
6289 value: Value,
6290 ) -> JsResult<Value> {
6291 let (value, done, ready, _reason) =
6292 self.resume_generator_detailed(generator, kind, value)?;
6293 if ready {
6294 return Ok(value);
6295 }
6296 self.iterator_result(value, done)
6297 }
6298
6299 /// `next`/`return`/`throw` on an async generator, which answer a promise.
6300 ///
6301 /// The body is the same coroutine a sync generator runs; what changes is that an
6302 /// `await` inside it has to settle before the method can answer, so the step is
6303 /// driven off the job queue rather than returning inline.
6304 pub fn resume_async_generator(
6305 &mut self,
6306 generator: &Gc<JsObject>,
6307 kind: ResumeKind,
6308 value: Value,
6309 ) -> JsResult<Value> {
6310 let promise = self.new_promise();
6311 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
6312 // that order, and the second value must reach the *second* `yield`.
6313 let idle = generator.with_mut(|data| match &mut data.kind {
6314 ObjectKind::Generator(state) => {
6315 state.requests.push_back(AsyncRequest {
6316 kind,
6317 value,
6318 promise: promise.clone(),
6319 });
6320 !state.async_busy
6321 }
6322 _ => false,
6323 });
6324 if idle {
6325 self.next_async_request(generator)?;
6326 }
6327 Ok(Value::Object(promise))
6328 }
6329
6330 /// Serve the front queued request, if the generator is free to run one.
6331 ///
6332 /// A finished generator answers from the queue without running anything:
6333 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
6334 /// first, and `throw(e)` rejects.
6335 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
6336 enum Front {
6337 Idle,
6338 Run(ResumeKind, Value, Gc<JsObject>),
6339 Finished(ResumeKind, Value, Gc<JsObject>),
6340 }
6341 let front = generator.with_mut(|data| match &mut data.kind {
6342 ObjectKind::Generator(state) => {
6343 let Some(request) = state.requests.front() else {
6344 return Front::Idle;
6345 };
6346 // Busy means a request is still in flight — awaiting inside the body, not
6347 // finished. Serving another now would interleave two requests.
6348 if state.async_busy && state.phase != GeneratorPhase::Completed {
6349 return Front::Idle;
6350 }
6351 let kind = request.kind;
6352 let value = request.value.clone();
6353 let promise = request.promise.clone();
6354 state.async_busy = true;
6355 if state.phase == GeneratorPhase::Completed {
6356 Front::Finished(kind, value, promise)
6357 } else {
6358 Front::Run(kind, value, promise)
6359 }
6360 }
6361 _ => Front::Idle,
6362 });
6363 match front {
6364 Front::Idle => Ok(()),
6365 Front::Run(kind, value, promise) => {
6366 self.step_async_generator(generator, &promise, kind, value)
6367 }
6368 Front::Finished(kind, value, promise) => match kind {
6369 ResumeKind::Throw => {
6370 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
6371 }
6372 ResumeKind::Next | ResumeKind::Start => {
6373 let result = self.iterator_result(Value::Undefined, true)?;
6374 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
6375 }
6376 ResumeKind::Return => {
6377 // `js_async_generator_completed_return`: the value is awaited before it
6378 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
6379 // finished generator answers `1`, not a promise.
6380 let resolved = match self.promise_resolve_value(value) {
6381 Ok(resolved) => resolved,
6382 Err(Signal::Throw(reason)) => {
6383 return self.settle_async_request(
6384 generator,
6385 &promise,
6386 AsyncOutcome::Error(reason),
6387 );
6388 }
6389 Err(other) => return Err(other),
6390 };
6391 let done = JsObject::function(
6392 self.heap,
6393 Some(self.realm.function_proto.clone()),
6394 Callable::CompletedReturn {
6395 generator: generator.clone(),
6396 promise: promise.clone(),
6397 rejected: false,
6398 },
6399 );
6400 let failed = JsObject::function(
6401 self.heap,
6402 Some(self.realm.function_proto.clone()),
6403 Callable::CompletedReturn {
6404 generator: generator.clone(),
6405 promise: promise.clone(),
6406 rejected: true,
6407 },
6408 );
6409 let Value::Object(resolved) = resolved else {
6410 return self.settle_async_request(
6411 generator,
6412 &promise,
6413 AsyncOutcome::Error(Value::Undefined),
6414 );
6415 };
6416 self.perform_then(
6417 &resolved,
6418 Some(Value::Object(done)),
6419 Some(Value::Object(failed)),
6420 )?;
6421 Ok(())
6422 }
6423 },
6424 }
6425 }
6426
6427 /// Settle the front request and start the next one.
6428 ///
6429 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
6430 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
6431 /// generator would strand every later request.
6432 fn settle_async_request(
6433 &mut self,
6434 generator: &Gc<JsObject>,
6435 promise: &Gc<JsObject>,
6436 outcome: AsyncOutcome,
6437 ) -> JsResult<()> {
6438 let settled = generator.with_mut(|data| match &mut data.kind {
6439 ObjectKind::Generator(state) => {
6440 let front = state.requests.front();
6441 debug_assert!(
6442 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
6443 "a request settled outside its turn"
6444 );
6445 state.requests.pop_front();
6446 state.async_busy = false;
6447 true
6448 }
6449 _ => false,
6450 });
6451 if settled {
6452 match outcome {
6453 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
6454 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
6455 }
6456 }
6457 self.next_async_request(generator)
6458 }
6459
6460 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
6461 ///
6462 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
6463 /// disposer runs **synchronously** — the reference starts it before returning, which
6464 /// a test can observe by logging after the call — and the rest follow once their
6465 /// predecessor settles.
6466 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
6467 let promise = self.new_promise();
6468 let mut pairs = Vec::with_capacity(resources.len());
6469 for (value, method) in resources {
6470 let pair = self.new_array(vec![value, method]);
6471 pairs.push(Value::Object(pair));
6472 }
6473 let remaining = self.new_array(pairs);
6474 self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
6475 Ok(Value::Object(promise))
6476 }
6477
6478 /// One link of the `disposeAsync` chain.
6479 ///
6480 /// Loops while the disposers finish synchronously, and parks on the first thenable it
6481 /// meets — pushing itself back in as the continuation, with the accumulated error
6482 /// carried along so a later failure can still be folded into the `SuppressedError`.
6483 fn dispose_step(
6484 &mut self,
6485 remaining: &Gc<JsObject>,
6486 promise: &Gc<JsObject>,
6487 mut error: Value,
6488 ) -> JsResult<()> {
6489 loop {
6490 let length = remaining.array_length().unwrap_or(0);
6491 if length == 0 {
6492 if matches!(error, Value::Uninitialized) {
6493 self.fulfill_promise(promise, Value::Undefined);
6494 } else {
6495 self.reject_promise(promise, error);
6496 }
6497 return Ok(());
6498 }
6499 let Some(Value::Object(pair)) = remaining
6500 .array_get(length - 1)
6501 .filter(|v| !matches!(v, Value::Hole))
6502 else {
6503 remaining.array_truncate(self.heap, length - 1);
6504 continue;
6505 };
6506 remaining.array_truncate(self.heap, length - 1);
6507 let value = pair.array_get(0).unwrap_or(Value::Undefined);
6508 let Some(Value::Object(method)) = pair.array_get(1) else {
6509 continue;
6510 };
6511 if !method.is_callable() {
6512 continue;
6513 }
6514 match self.call_value(Value::Object(method), value, Vec::new()) {
6515 Ok(result) => {
6516 if !self.is_thenable(&result)? {
6517 // Finished synchronously; the next disposer is the next iteration.
6518 continue;
6519 }
6520 let awaited = match self.promise_resolve_value(result) {
6521 Ok(awaited) => awaited,
6522 Err(Signal::Throw(reason)) => {
6523 self.reject_promise(promise, reason);
6524 return Ok(());
6525 }
6526 Err(other) => return Err(other),
6527 };
6528 let Value::Object(awaited) = awaited else {
6529 continue;
6530 };
6531 let ok = JsObject::function(
6532 self.heap,
6533 Some(self.realm.function_proto.clone()),
6534 Callable::DisposeStep {
6535 remaining: remaining.clone(),
6536 promise: promise.clone(),
6537 error: error.clone(),
6538 rejected: false,
6539 },
6540 );
6541 let failed = JsObject::function(
6542 self.heap,
6543 Some(self.realm.function_proto.clone()),
6544 Callable::DisposeStep {
6545 remaining: remaining.clone(),
6546 promise: promise.clone(),
6547 error,
6548 rejected: true,
6549 },
6550 );
6551 self.perform_then(
6552 &awaited,
6553 Some(Value::Object(ok)),
6554 Some(Value::Object(failed)),
6555 )?;
6556 return Ok(());
6557 }
6558 Err(Signal::Throw(thrown)) => {
6559 error = self.merge_dispose_error(thrown, error);
6560 }
6561 Err(other) => return Err(other),
6562 }
6563 }
6564 }
6565
6566 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
6567 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
6568 let Value::Object(object) = value else {
6569 return Ok(false);
6570 };
6571 Ok(matches!(
6572 self.get_property(object, "then")?,
6573 Some(Value::Object(then)) if then.is_callable()
6574 ))
6575 }
6576
6577 /// One step of an async generator, settling `promise` with an `{value, done}` result.
6578 fn step_async_generator(
6579 &mut self,
6580 generator: &Gc<JsObject>,
6581 promise: &Gc<JsObject>,
6582 kind: ResumeKind,
6583 value: Value,
6584 ) -> JsResult<()> {
6585 let stepped = self.resume_generator_detailed(generator, kind, value);
6586 let (value, done, ready, reason) = match stepped {
6587 Ok(stepped) => stepped,
6588 Err(Signal::Throw(reason)) => {
6589 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
6590 }
6591 Err(other) => return Err(other),
6592 };
6593 // Only an `await` has to wait before the method can answer.
6594 if !done && reason == Some(SuspendKind::Await) {
6595 let awaited = match self.promise_resolve_value(value) {
6596 Ok(awaited) => awaited,
6597 Err(Signal::Throw(reason)) => {
6598 return self.settle_async_request(
6599 generator,
6600 promise,
6601 AsyncOutcome::Error(reason),
6602 );
6603 }
6604 Err(other) => return Err(other),
6605 };
6606 let Value::Object(awaited) = awaited else {
6607 return Ok(());
6608 };
6609 let resumed = JsObject::function(
6610 self.heap,
6611 Some(self.realm.function_proto.clone()),
6612 Callable::GeneratorResume {
6613 generator: generator.clone(),
6614 promise: promise.clone(),
6615 kind: ResumeKind::Next,
6616 },
6617 );
6618 let raised = JsObject::function(
6619 self.heap,
6620 Some(self.realm.function_proto.clone()),
6621 Callable::GeneratorResume {
6622 generator: generator.clone(),
6623 promise: promise.clone(),
6624 kind: ResumeKind::Throw,
6625 },
6626 );
6627 self.perform_then(
6628 &awaited,
6629 Some(Value::Object(resumed)),
6630 Some(Value::Object(raised)),
6631 )?;
6632 return Ok(());
6633 }
6634 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
6635 // completes it — both arrive as the settled value rather than as the promise
6636 // object. A plain value skips the round trip, which is also what keeps `yield 1`
6637 // from costing an extra tick.
6638 let awaits_value = self.is_thenable(&value)?;
6639 if awaits_value {
6640 let awaited = match self.promise_resolve_value(value) {
6641 Ok(awaited) => awaited,
6642 Err(Signal::Throw(reason)) => {
6643 return self.settle_async_request(
6644 generator,
6645 promise,
6646 AsyncOutcome::Error(reason),
6647 );
6648 }
6649 Err(other) => return Err(other),
6650 };
6651 let Value::Object(awaited) = awaited else {
6652 return Ok(());
6653 };
6654 // A rejected yield throws *at the yield* inside the body, so the rejection
6655 // resumes the generator rather than the method's promise.
6656 let answer = JsObject::function(
6657 self.heap,
6658 Some(self.realm.function_proto.clone()),
6659 Callable::YieldResult {
6660 generator: generator.clone(),
6661 promise: promise.clone(),
6662 done,
6663 },
6664 );
6665 let raise = JsObject::function(
6666 self.heap,
6667 Some(self.realm.function_proto.clone()),
6668 Callable::GeneratorResume {
6669 generator: generator.clone(),
6670 promise: promise.clone(),
6671 kind: ResumeKind::Throw,
6672 },
6673 );
6674 self.perform_then(
6675 &awaited,
6676 Some(Value::Object(answer)),
6677 Some(Value::Object(raise)),
6678 )?;
6679 return Ok(());
6680 }
6681 let result = if ready {
6682 // `yield*` handed back the inner iterator's own result object.
6683 value
6684 } else {
6685 self.iterator_result(value, done)?
6686 };
6687 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
6688 }
6689
6690 /// The `{value, done}` object an iterator method answers with.
6691 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
6692 let result = self.new_object(Some(self.realm.object_proto.clone()));
6693 result.define_data("value", value);
6694 result.define_data("done", Value::Bool(done));
6695 Ok(Value::Object(result))
6696 }
6697
6698 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
6699 fn step_generator(
6700 &mut self,
6701 state: &mut GeneratorState,
6702 kind: ResumeKind,
6703 value: Value,
6704 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
6705 match state.phase {
6706 GeneratorPhase::Executing => {
6707 return Err(self.type_error("cannot invoke a running generator"));
6708 }
6709 GeneratorPhase::Completed => {
6710 // A finished generator answers every resumption without running.
6711 return Ok(match kind {
6712 ResumeKind::Throw => return Err(Signal::Throw(value)),
6713 ResumeKind::Return => (value, true, false, None),
6714 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
6715 });
6716 }
6717 GeneratorPhase::SuspendedStart => {
6718 if kind != ResumeKind::Next && kind != ResumeKind::Start {
6719 // The body never started, so there is nothing to unwind or return
6720 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
6721 state.frame = None;
6722 state.phase = GeneratorPhase::Completed;
6723 return Ok(match kind {
6724 ResumeKind::Throw => return Err(Signal::Throw(value)),
6725 _ => (value, true, false, None),
6726 });
6727 }
6728 }
6729 GeneratorPhase::SuspendedYield => {}
6730 }
6731
6732 let Some(mut frame) = state.frame.take() else {
6733 return Ok((Value::Undefined, true, false, None));
6734 };
6735 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
6736 // number that says which method resumed it; the emitted `if_false` branches on
6737 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
6738 let mut raised = None;
6739 match kind {
6740 ResumeKind::Next | ResumeKind::Start => {
6741 if state.phase == GeneratorPhase::SuspendedYield {
6742 frame.stack.push(value);
6743 // An `await` resumes with its value alone; only a `yield` gets the
6744 // magic number that says which of `next`/`return` resumed it.
6745 if !state.parked_on_await {
6746 frame.stack.push(Value::Int(RESUME_NEXT));
6747 }
6748 }
6749 }
6750 ResumeKind::Return => {
6751 // A `return` on a not-yet-started generator is handled above, so this is
6752 // always a real resumption.
6753 frame.stack.push(value);
6754 frame.stack.push(Value::Int(RESUME_RETURN));
6755 }
6756 ResumeKind::Throw => {
6757 // At a `yield*` the exception is *data* for the delegation: the compiled
6758 // code resumes with the value and magic `2` and calls the inner iterator's
6759 // `throw`. Everywhere else it is raised at the suspension point, so the
6760 // body's own handler sees it.
6761 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
6762 frame.stack.push(value);
6763 frame.stack.push(Value::Int(RESUME_THROW));
6764 } else {
6765 raised = Some(value);
6766 }
6767 }
6768 }
6769 state.phase = GeneratorPhase::Executing;
6770
6771 let depth = self.frames.len();
6772 self.frames.push(frame);
6773 // A `throw` unwinds from where the frame parked, exactly as if the exception had
6774 // happened at the `yield`.
6775 if let Some(exception) = raised {
6776 if self.catch_here(exception.clone()).is_none() {
6777 self.pop_frame();
6778 state.phase = GeneratorPhase::Completed;
6779 return Err(Signal::Throw(exception));
6780 }
6781 }
6782
6783 // Only the generator's *own* frame ends the generator. The body may call ordinary
6784 // functions, and those push frames of their own: a `Step::Return` from one of them
6785 // is a nested call finishing, not the generator completing. Miscounting that is
6786 // silent — the generator reports the callee's value as its own result and marks
6787 // itself done — so the depth comparison is load-bearing, not defensive.
6788 let own_frame = depth + 1;
6789 loop {
6790 match self.step() {
6791 Ok(Step::Continue) => {}
6792 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
6793 let mut frame = self.frames.pop().expect("a frame is live");
6794 // `yield` left the value on the stack; `initial_yield` left nothing.
6795 let yielded = if reason == SuspendKind::Initial {
6796 Value::Undefined
6797 } else {
6798 frame.stack.pop().unwrap_or(Value::Undefined)
6799 };
6800 state.frame = Some(frame);
6801 state.parked_on_await = reason == SuspendKind::Await;
6802 state.parked_on_yield_star =
6803 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
6804 state.phase = if reason == SuspendKind::Initial {
6805 GeneratorPhase::SuspendedStart
6806 } else {
6807 GeneratorPhase::SuspendedYield
6808 };
6809 // `yield*` hands the inner iterator's own result object straight
6810 // back, so the caller sees one `{value, done}` rather than a nested
6811 // one — which is why the third field says "already a result".
6812 return Ok((
6813 yielded,
6814 false,
6815 reason == SuspendKind::YieldStar,
6816 Some(reason),
6817 ));
6818 }
6819 Ok(Step::Suspend(_)) => {
6820 // A `yield` in a frame other than the generator's would mean a
6821 // generator body entered as an ordinary call, which
6822 // `call_or_push` prevents.
6823 self.unwind_to(depth);
6824 state.phase = GeneratorPhase::Completed;
6825 return Err(Signal::Throw(self.make_error(
6826 "InternalError",
6827 "a generator body ran as an ordinary call",
6828 )));
6829 }
6830 Ok(Step::Return(value)) => {
6831 self.pop_frame();
6832 if self.frames.len() > depth {
6833 // A nested call finished: hand the value back to its caller and
6834 // keep running the generator body.
6835 self.frames
6836 .last_mut()
6837 .expect("a caller is live")
6838 .stack
6839 .push(value);
6840 continue;
6841 }
6842 state.phase = GeneratorPhase::Completed;
6843 // The reference closes the generator's closure variables here; ours
6844 // live in cells the frame owned, which the drop below releases.
6845 return Ok((value, true, false, None));
6846 }
6847 Err(Signal::Throw(exception)) => {
6848 // The frame that threw gets the first chance to catch, exactly as in
6849 // the ordinary call loop; a frame above the generator's is popped and
6850 // the exception carries on down.
6851 let exception = exception;
6852 loop {
6853 if self.frames.len() <= depth {
6854 // The generator's own frame is gone, so nothing here caught it.
6855 state.phase = GeneratorPhase::Completed;
6856 return Err(Signal::Throw(exception));
6857 }
6858 if self.catch_here(exception.clone()).is_some() {
6859 break;
6860 }
6861 self.pop_frame();
6862 }
6863 }
6864 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
6865 }
6866 }
6867 }
6868
6869 /// Pop frames until `depth` are left, keeping their buffers.
6870 fn unwind_to(&mut self, depth: usize) {
6871 while self.frames.len() > depth {
6872 self.pop_frame();
6873 }
6874 }
6875 fn call_or_push(
6876 &mut self,
6877 callee: Value,
6878 this: Value,
6879 args: Vec<Value>,
6880 ) -> JsResult<Option<Value>> {
6881 if let Value::Object(function) = &callee
6882 && let Some((code, env)) = bytecode_of(function)
6883 {
6884 // Calling a generator function does not run anything: it captures the
6885 // arguments in a frame and hands back the generator object.
6886 if code.code.kind.is_generator() {
6887 return self.new_generator(callee, this, args).map(Some);
6888 }
6889 // An async function answers a promise and runs its body as a coroutine, so it
6890 // takes the same path as a plain call into it.
6891 if code.code.kind.is_async() {
6892 return self.new_async_function(callee, this, args).map(Some);
6893 }
6894 self.push_frame(code, env, this, args, callee)?;
6895 return Ok(None);
6896 }
6897 self.call_value(callee, this, args).map(Some)
6898 }
6899
6900 /// `new callee(args)`.
6901 ///
6902 /// A constructor differs from a plain call in three ways: it gets a fresh object
6903 /// as `this` whose prototype is the constructor's `prototype` property, its
6904 /// return value is *replaced* by that object unless it returns an object itself,
6905 /// and a native constructor is expected to initialise the object it is given
6906 /// rather than build one.
6907 pub fn construct(
6908 &mut self,
6909 callee: Value,
6910 new_target: Value,
6911 args: Vec<Value>,
6912 ) -> JsResult<Value> {
6913 // `new` on a bound function constructs its *target*, prepending the arguments
6914 // the bind fixed and ignoring the bound `this` — a bound function is a
6915 // constructor only when its target is one, and `new` always makes a fresh
6916 // object of the target's prototype rather than reusing the bound receiver.
6917 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
6918 // ran the body with `this === null` and threw on `this.x = a`.
6919 let mut callee = callee;
6920 let mut new_target = new_target;
6921 let mut args = args;
6922 loop {
6923 let Some(object) = callee.as_object().cloned() else {
6924 return Err(Signal::Throw(
6925 self.make_error("TypeError", "not a constructor"),
6926 ));
6927 };
6928 // A proxy of a function constructs through its `construct` trap, and the
6929 // trap's answer is the result directly — no fresh object is made here.
6930 if object.proxy_state().is_some() {
6931 return match self.proxy_construct(&object, args, &new_target)? {
6932 Some(result) => Ok(result),
6933 None => Err(Signal::Throw(
6934 self.make_error("TypeError", "proxy target is not a constructor"),
6935 )),
6936 };
6937 }
6938 // A generator function has no `[[Construct]]`, and the reference names it in
6939 // the message: `new (function* G(){})()` reports "G is not a constructor".
6940 if object.with(|data| match &data.kind {
6941 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
6942 code.code.kind.is_generator()
6943 }
6944 _ => false,
6945 }) {
6946 let name = object
6947 .own_property("name")
6948 .and_then(|property| property.value)
6949 .map(|value| value.to_js_string())
6950 .unwrap_or_default();
6951 return Err(Signal::Throw(
6952 self.make_error("TypeError", &format!("{name} is not a constructor")),
6953 ));
6954 }
6955 let bound = object.with(|data| match &data.kind {
6956 ObjectKind::Function(Callable::Bound {
6957 target,
6958 args: leading,
6959 ..
6960 }) => Some((target.clone(), leading.clone())),
6961 _ => None,
6962 });
6963 let Some((target, leading)) = bound else {
6964 // Not a bound function, so this object is the callee. §7.2.4
6965 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
6966 // refusals above cover only the built-ins the reference also refuses by
6967 // name. Everything else — a method, an arrow, an async function — has no
6968 // `[[Construct]]` either, and answering "yes" here made
6969 // `new (Array.prototype.map)` build an object instead of throwing.
6970 if !object.is_constructor() {
6971 let name = object
6972 .own_property("name")
6973 .and_then(|property| property.value)
6974 .map(|value| value.to_js_string())
6975 .unwrap_or_default();
6976 return Err(Signal::Throw(
6977 self.make_error("TypeError", &format!("{name} is not a constructor")),
6978 ));
6979 }
6980 break;
6981 };
6982 let mut all = leading;
6983 all.extend(args);
6984 args = all;
6985 // A bound function that is its own `new.target` stands in for its target:
6986 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
6987 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
6988 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
6989 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
6990 _ => false,
6991 };
6992 if same_wrapper {
6993 new_target = target.clone();
6994 }
6995 callee = target;
6996 }
6997 let Value::Object(function) = &callee else {
6998 unreachable!("the loop above only breaks on an object");
6999 };
7000 // The fresh object's prototype comes from `new.target`, not from the callee: a
7001 // derived constructor reaches here through `super()`, and the instance must be a
7002 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
7003 // an object inheriting `D.prototype` rather than `C.prototype`.
7004 let prototype_source = match new_target.as_object() {
7005 Some(target) => target.clone(),
7006 None => function.clone(),
7007 };
7008 // A native constructor builds its own instance, through `new_ctor_instance`, once it
7009 // has validated its arguments. Pre-building one here would read
7010 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
7011 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
7012 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
7013 let is_native = function.native_creates_own_instance();
7014 let this = if is_native {
7015 Value::Undefined
7016 } else {
7017 let prototype = self.get_property(&prototype_source, "prototype")?;
7018 let prototype = match prototype {
7019 Some(Value::Object(proto)) => Some(proto),
7020 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
7021 // object, the answer is the realm's *intrinsic* prototype for this
7022 // constructor, not `%Object.prototype%`.
7023 _ => {
7024 let fallback = self.get_property(function, "prototype")?;
7025 match fallback {
7026 Some(Value::Object(proto)) => Some(proto),
7027 _ => Some(self.realm.object_proto.clone()),
7028 }
7029 }
7030 };
7031 Value::Object(self.new_object(prototype))
7032 };
7033 // `new.target` inside the body is the constructor that was written, so a bound
7034 // function's target sees itself rather than the bound wrapper.
7035 //
7036 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
7037 // `?`, so assigning `None` after the call would be skipped and the failed
7038 // `new.target` would stay visible to every later native call. The symptom was a
7039 // native constructor refusing a plain call — `var s = Symbol(); new
7040 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
7041 // "FinalizationRegistry is not a constructor".
7042 let outer_new_target = self.pending_new_target.replace(new_target);
7043 let result = self.call_value(callee, this.clone(), args);
7044 self.pending_new_target = outer_new_target;
7045 let result = result?;
7046 // A constructor that returns an object overrides `this`; any other return
7047 // value (including `undefined`) is ignored.
7048 Ok(match result {
7049 Value::Object(_) => result,
7050 _ => this,
7051 })
7052 }
7053
7054 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
7055 ///
7056 /// The error classes themselves arrive with the builtins milestone; what
7057 /// matters here is that the thrown value stringifies the way a script printing
7058 /// the caught value expects.
7059 pub fn make_error(&self, name: &str, message: &str) -> Value {
7060 let proto = self
7061 .realm
7062 .errors
7063 .get(name)
7064 .map(|constructor| self.prototype_of(constructor))
7065 .unwrap_or_else(|| self.realm.error_proto.clone());
7066 let error = self.new_object(Some(proto));
7067 // `name` and `message` are own properties of the instance, which is what
7068 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
7069 // `Error`.
7070 error.define(
7071 "name",
7072 Property::with_attributes(self.string(name), true, false),
7073 );
7074 error.define(
7075 "message",
7076 Property::with_attributes(self.string(message), true, false),
7077 );
7078 // The internal class, which is what tells a printer this is an error rather than a
7079 // plain object with `name` and `message` properties. The constructor path sets it
7080 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
7081 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
7082 // literally `"Error"` in both places — the *name* is read from `name`, which is why
7083 // a `RangeError` still prints as `RangeError`.
7084 self.internal_set(&error, "_class", self.string("Error"));
7085 // The trace is captured where the error is *made*, which is where the reference
7086 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
7087 // way out, so a caught engine error already has its stack even if the handler
7088 // never rethrows it.
7089 self.add_stack(&error);
7090 Value::Object(error)
7091 }
7092
7093 /// Give an error object its `stack` property, from the current frame stack.
7094 ///
7095 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
7096 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
7097 /// `stack` a script set, is not rewritten.
7098 pub fn add_stack(&self, object: &Gc<JsObject>) {
7099 self.add_stack_skipping(object, 0);
7100 }
7101
7102 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
7103 ///
7104 /// An `Error` constructor passes 1: the reference builds those traces with
7105 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
7106 /// constructor itself, while a `RangeError` raised inside `toISOString` does
7107 /// report `at toISOString (native)`.
7108 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
7109 if object.has_own("stack") {
7110 return;
7111 }
7112 let trace = self.stack_trace_skipping(skip);
7113 let text = self.string(trace);
7114 object.define("stack", Property::with_attributes(text, true, true));
7115 }
7116
7117 /// The function object currently being called, if any.
7118 ///
7119 /// A native function is a bare `fn` pointer, so it cannot capture which class
7120 /// it belongs to; it reads that from the callee instead. This is also what a
7121 /// stack trace would use.
7122 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
7123 match &self.frames.last()?.callee {
7124 Value::Object(object) => Some(object.clone()),
7125 _ => None,
7126 }
7127 }
7128
7129 /// The `prototype` property of a constructor, falling back to
7130 /// `Object.prototype` for anything that is not shaped like one.
7131 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
7132 constructor
7133 .own_property("prototype")
7134 .and_then(|property| property.value)
7135 .and_then(|value| value.as_object().cloned())
7136 .unwrap_or_else(|| self.realm.object_proto.clone())
7137 }
7138
7139 /// Throw a `TypeError` carrying `message`.
7140 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
7141 Signal::Throw(self.make_error("TypeError", message.as_ref()))
7142 }
7143
7144 /// Throw a `RangeError` carrying `message`.
7145 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
7146 Signal::Throw(self.make_error("RangeError", message.as_ref()))
7147 }
7148
7149 /// The `ReferenceError` a read of an uninitialised binding raises.
7150 /// The name of the binding `slot` refers to, for an error message.
7151 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
7152 match kind {
7153 VarSlot::Loc => self
7154 .frame()
7155 .code
7156 .code
7157 .vars
7158 .get(slot)
7159 .map(|v| v.name.clone()),
7160 VarSlot::Closure => self
7161 .frame()
7162 .code
7163 .code
7164 .closure_vars
7165 .get(slot)
7166 .map(|c| c.name.clone()),
7167 }
7168 .unwrap_or_default()
7169 }
7170
7171 /// Whether `slot` names a `const` binding, which rejects every store after its
7172 /// initialiser.
7173 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
7174 match kind {
7175 VarSlot::Loc => self
7176 .frame()
7177 .code
7178 .code
7179 .vars
7180 .get(slot)
7181 .is_some_and(|v| v.is_const),
7182 VarSlot::Closure => self
7183 .frame()
7184 .code
7185 .code
7186 .closure_vars
7187 .get(slot)
7188 .is_some_and(|c| c.is_const),
7189 }
7190 }
7191
7192 /// The `TypeError` a store to a `const` binding raises.
7193 ///
7194 /// `const` is enforced here rather than at compile time because the binding can be
7195 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
7196 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
7197 /// both halves of what "checked store" means: the dead zone is over, and the
7198 /// binding is writable.
7199 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
7200 let name = self.binding_name(slot, kind);
7201 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
7202 }
7203
7204 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
7205 let name = match kind {
7206 VarSlot::Loc => self
7207 .frame()
7208 .code
7209 .code
7210 .vars
7211 .get(slot)
7212 .map(|v| v.name.clone()),
7213 VarSlot::Closure => self
7214 .frame()
7215 .code
7216 .code
7217 .closure_vars
7218 .get(slot)
7219 .map(|c| c.name.clone()),
7220 }
7221 .unwrap_or_default();
7222 Signal::Throw(self.make_error(
7223 "ReferenceError",
7224 &format!("cannot access '{name}' before initialization"),
7225 ))
7226 }
7227
7228 fn throw_reference(&self, name: &str) -> Signal {
7229 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
7230 }
7231
7232 // -- the instruction loop -----------------------------------------------
7233
7234 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
7235 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
7236 // measured at 16% of a tight arithmetic loop's total time.
7237 #[inline(always)]
7238 fn step(&mut self) -> JsResult<Step> {
7239 // The instruction is already decoded (see [`crate::insn`]), so this is an index
7240 // and a `Copy` read rather than a table lookup plus a width switch. Only the
7241 // borrow lives across the boundary; nothing is cloned.
7242 // **One** borrow of the frame: fetch the record, then advance in the same scope.
7243 // The obvious version borrowed it three times (`last` to read, `last_mut` to
7244 // write, and once more inside the handler), and each is a bounds check plus an
7245 // `Option` unwrap — on the one path every instruction takes.
7246 let Some((insn, next)) = ({
7247 let frame = self
7248 .frames
7249 .last_mut()
7250 .expect("step() is only called with a live frame");
7251 // Past the last instruction is a normal return: the compiler ends a function
7252 // with `return`, and a jump to the end of a block lands here.
7253 let insn = frame.insns().get(frame.pc).copied();
7254 match insn {
7255 None => None,
7256 Some(insn) => {
7257 // A fused record stands for the next few instructions, so the next
7258 // `pc` is its width ahead — the instructions it replaces are never
7259 // dispatched. `at` is the byte offset a stack trace reports; it stays
7260 // an offset because the line table is keyed by bytes.
7261 frame.at = insn.offset as usize;
7262 frame.pc += insn.width();
7263 Some((insn, frame.pc))
7264 }
7265 }
7266 }) else {
7267 return Ok(Step::Return(Value::Undefined));
7268 };
7269 self.check_memory()?;
7270 if insn.fused == crate::insn::Fused::None {
7271 self.execute_instruction(insn.op, insn.a, insn.b, next)
7272 } else {
7273 self.execute_fused(insn)
7274 }
7275 }
7276
7277 /// Run a fused instruction: several bytecode instructions in one dispatch.
7278 ///
7279 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
7280 /// it cannot throw and cannot allocate — and anything else falls back to the real
7281 /// instructions, in their real order, so an exception leaves the operand stack
7282 /// exactly as it would have been.
7283 #[inline]
7284 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
7285 use crate::insn::Fused;
7286 let slot = insn.a as usize;
7287 match insn.fused {
7288 // `x = k`: `push k; put_loc x`.
7289 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
7290 // `x += k`: `get_loc x; push k; add; put_loc x`.
7291 Fused::AddImmLoc => {
7292 let delta = insn.b as i32;
7293 match self.get_loc(slot) {
7294 Value::Int(left) => {
7295 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
7296 // that built two `Value`s, called a function, and matched on them
7297 // again to reach this same `checked_add`. It is the innermost
7298 // operation of every accumulator in every program.
7299 let answer = match left.checked_add(delta) {
7300 Some(sum) => Value::Int(sum),
7301 None => Value::Float(left as f64 + delta as f64),
7302 };
7303 self.put_loc(slot, answer);
7304 }
7305 other => {
7306 self.push(other);
7307 self.push(Value::Int(delta));
7308 self.binary_add()?;
7309 let value = self.pop();
7310 self.put_loc(slot, value);
7311 }
7312 }
7313 }
7314 // `x += "literal"` and `x += y`: the two shapes that can append in place.
7315 Fused::AddAtomLoc => {
7316 let text = self.atom_text(insn.b as usize);
7317 let right = self.string(text);
7318 self.add_into_loc(slot, right)?;
7319 }
7320 Fused::AddLocLoc => {
7321 let source = (insn.a & 0xFFFF) as usize;
7322 let target = (insn.a >> 16) as usize;
7323 let right = self.get_loc(source);
7324 self.add_into_loc(target, right)?;
7325 }
7326 Fused::AddArgLoc => {
7327 let source = (insn.a & 0xFFFF) as usize;
7328 let target = (insn.a >> 16) as usize;
7329 let right = self.get_arg(source);
7330 self.add_into_loc(target, right)?;
7331 }
7332 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
7333 Fused::PostIncLoc => match self.get_loc(slot) {
7334 Value::Int(left) => {
7335 let answer = match left.checked_add(1) {
7336 Some(sum) => Value::Int(sum),
7337 None => Value::Float(left as f64 + 1.0),
7338 };
7339 self.put_loc(slot, answer);
7340 }
7341 other => {
7342 self.push(other);
7343 let raw = self.pop();
7344 let (old, updated) = self.advance_numeric(raw, true)?;
7345 self.push(old);
7346 self.push(updated);
7347 let value = self.pop();
7348 self.put_loc(slot, value);
7349 self.pop();
7350 }
7351 },
7352 // `if (!(x < arg)) goto target`: a loop header.
7353 //
7354 // The comparison is computed rather than replayed on the operand stack. That
7355 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
7356 // that throws: the effects happen in the same order, and a handler truncates
7357 // the stack down to its marker, so the intermediate values are unobservable.
7358 Fused::LtLocArgJump => {
7359 let loc = (insn.a >> 16) as usize;
7360 let arg = (insn.a & 0xFFFF) as usize;
7361 let left = self.get_loc(loc);
7362 let right = self.get_arg(arg);
7363 let taken = match (&left, &right) {
7364 (Value::Int(left), Value::Int(right)) => !(left < right),
7365 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
7366 };
7367 if taken {
7368 self.frame_mut().pc = insn.b as usize;
7369 }
7370 }
7371 // `i < k` in a loop header, where `k` is an integer literal.
7372 Fused::LtLocImmJump => {
7373 let left = self.get_loc(insn.a as usize);
7374 let right = Value::Int(insn.imm as i32);
7375 let taken = match &left {
7376 Value::Int(left) => !(*left < insn.imm as i32),
7377 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
7378 };
7379 if taken {
7380 self.frame_mut().pc = insn.b as usize;
7381 }
7382 }
7383 Fused::None => unreachable!("only called for a fused record"),
7384 }
7385 Ok(Step::Continue)
7386 }
7387
7388 /// Run records that cannot call script, cannot throw and cannot change frames.
7389 ///
7390 /// Returns `Some(value)` when the function ran off the end of its instructions (a
7391 /// normal return), and `None` when it stopped in front of an instruction the slow path
7392 /// has to handle — `pc` is written back either way, so `step` resumes at the right
7393 /// place.
7394 ///
7395 /// **The invariant is the whole point.** Every arm here is restricted to work that
7396 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
7397 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
7398 /// that the memory limit has to see. An opcode whose operands turn out to need any of
7399 /// that **stops the loop** instead of trying, so the slow path gets the instruction
7400 /// untouched and with its operands still on the stack. That is why the fallback is a
7401 /// `break` and not a duplicated slow arm: a second implementation of the same
7402 /// semantics is how a wrong answer gets in with no test noticing.
7403 ///
7404 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
7405 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
7406 fn run_fast(&mut self) -> Option<Value> {
7407 use crate::insn::Fused;
7408 // One reference-count bump per *slow* instruction (a call, an allocation, a
7409 // property access), never one per instruction — that distinction is worth
7410 // two orders of magnitude and was measured as such.
7411 let (code, mut pc) = {
7412 let frame = self.frame();
7413 (frame.code.clone(), frame.pc)
7414 };
7415 let insns = &code.insns;
7416 loop {
7417 let Some(insn) = insns.get(pc).copied() else {
7418 self.frame_mut().pc = pc;
7419 return Some(Value::Undefined);
7420 };
7421 match insn.fused {
7422 // `x = k`
7423 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
7424 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
7425 // object — stops the loop so `binary_add` can decide.
7426 Fused::AddImmLoc => {
7427 let slot = insn.a as usize;
7428 let delta = insn.b as i32;
7429 let Value::Int(left) = self.get_loc(slot) else {
7430 return self.stop(pc);
7431 };
7432 let sum = match left.checked_add(delta) {
7433 Some(sum) => Value::Int(sum),
7434 None => Value::Float(left as f64 + delta as f64),
7435 };
7436 self.put_loc(slot, sum);
7437 }
7438 // `x += "literal"` / `x += y`: the operand is a string, so the append
7439 // either allocates one or grows one. Both are the slow path's business;
7440 // the fusion's job is only to make the *slot* the sole owner, which is what
7441 // `execute_fused` needs and what `get_loc` alone destroys.
7442 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => return self.stop(pc),
7443 // `x++` on an integer, old value dropped.
7444 Fused::PostIncLoc => {
7445 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
7446 // value is read in place and overwritten in place, so the reference
7447 // count it held is released by the same assignment that stores the
7448 // new one. `get_loc` plus `put_loc` did two borrows, two table
7449 // lookups and a clone, and this arm is the whole body of a counting
7450 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
7451 let slot = insn.a as usize;
7452 let frame = self.frames.last_mut().expect("a frame is live");
7453 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
7454 let target = if cell < 0 {
7455 frame.locals.get_mut(slot)
7456 } else {
7457 None
7458 };
7459 let Some(target) = target else {
7460 return self.stop(pc);
7461 };
7462 let Value::Int(left) = *target else {
7463 return self.stop(pc);
7464 };
7465 *target = match left.checked_add(1) {
7466 Some(sum) => Value::Int(sum),
7467 None => Value::Float(left as f64 + 1.0),
7468 };
7469 }
7470 // A loop header, `if (!(x < arg)) goto target`, with both sides already
7471 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
7472 // bound stayed small integers.
7473 Fused::LtLocArgJump => {
7474 let loc = (insn.a >> 16) as usize;
7475 let arg = (insn.a & 0xFFFF) as usize;
7476 let (left, right) = (self.get_loc(loc), self.get_arg(arg));
7477 // Heavily measured: the bound is very often a `Float` even when the
7478 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
7479 // `JSON.parse` or a division is one — so requiring both sides to be
7480 // `Int` sent every iteration of those loops down the slow path. The
7481 // comparison below is the same one `relational` makes for two numbers.
7482 if !is_number(&left) || !is_number(&right) {
7483 return self.stop(pc);
7484 }
7485 // `if_false` branches on the comparison being false, which is **not**
7486 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
7487 // `>=` is also false and would keep it running forever. Clippy wants the
7488 // negation folded; that would be a wrong answer.
7489 let ordered = left.to_number() < right.to_number();
7490 let take_branch = !ordered;
7491 if take_branch {
7492 pc = insn.b as usize;
7493 continue;
7494 }
7495 }
7496 // The same header with a literal bound: `if (!(x < k)) goto target`.
7497 // The bound is an immediate, so only the counter needs a type test.
7498 #[allow(clippy::neg_cmp_op_on_partial_ord)]
7499 Fused::LtLocImmJump => {
7500 let left = self.get_loc(insn.a as usize);
7501 if !is_number(&left) {
7502 return self.stop(pc);
7503 }
7504 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
7505 if take_branch {
7506 pc = insn.b as usize;
7507 continue;
7508 }
7509 }
7510 Fused::None => match insn.op {
7511 // -- branches ---------------------------------------------------
7512 // A jump is an assignment now, because the target is an instruction
7513 // index. No arithmetic, no resolution table.
7514 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
7515 pc = insn.a as usize;
7516 continue;
7517 }
7518 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
7519 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
7520 let taken = self.pop().to_boolean();
7521 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
7522 if taken == want {
7523 pc = insn.a as usize;
7524 continue;
7525 }
7526 }
7527 // -- slot access -------------------------------------------------
7528 // A load's slot is already an operand (see `insn::implicit_operand`);
7529 // a captured one goes through its cell, which runs no script.
7530 Opcode::GetLoc
7531 | Opcode::GetLoc8
7532 | Opcode::GetLoc0
7533 | Opcode::GetLoc1
7534 | Opcode::GetLoc2
7535 | Opcode::GetLoc3 => {
7536 let value = self.get_loc(insn.a as usize);
7537 self.push(value);
7538 }
7539 Opcode::PutLoc
7540 | Opcode::PutLoc8
7541 | Opcode::PutLoc0
7542 | Opcode::PutLoc1
7543 | Opcode::PutLoc2
7544 | Opcode::PutLoc3 => {
7545 let value = self.pop();
7546 self.put_loc(insn.a as usize, value);
7547 }
7548 Opcode::GetArg
7549 | Opcode::GetArg0
7550 | Opcode::GetArg1
7551 | Opcode::GetArg2
7552 | Opcode::GetArg3 => {
7553 let value = self.get_arg(insn.a as usize);
7554 self.push(value);
7555 }
7556 Opcode::PutArg
7557 | Opcode::PutArg0
7558 | Opcode::PutArg1
7559 | Opcode::PutArg2
7560 | Opcode::PutArg3 => {
7561 let value = self.pop();
7562 self.put_arg(insn.a as usize, value);
7563 }
7564 // `a[i]` with an integer index on a dense array: see `fast_array_get`
7565 // for why a non-hole own element is exactly the slow path's answer.
7566 // The two operands are *peeked*, so a miss leaves the stack as the
7567 // slow path expects to find it.
7568 Opcode::GetArrayEl => {
7569 // One lookup, not two. The guard used `if …is_some()` and the arm
7570 // then called it again to get the value — two `peek`s, two
7571 // `array_get`s and two `Value` clones for one element.
7572 // `fast_array_get` was 13.1% of `array:indexed`, and the same
7573 // double call was the first version of the `get_field` fast path.
7574 let Some(value) = self.fast_array_get() else {
7575 return self.stop(pc);
7576 };
7577 // `a[i]` consumes both operands and leaves the element in their
7578 // place: one `truncate` and one write, no `pop`/`push` pair.
7579 let frame = self.frame_mut();
7580 frame.stack.truncate(frame.stack.len() - 2);
7581 frame.stack.push(value);
7582 }
7583 // `a[i] = v` on a dense array with an integer index: see
7584 // `fast_array_set` for why the whole store is one step.
7585 Opcode::PutArrayEl if self.fast_array_set() => {}
7586 // `o.x` resolved from the inline cache without leaving the loop.
7587 //
7588 // The cache is keyed by `(receiver identity, atom, site)` and a
7589 // monomorphic read re-validates the same chain every iteration, so
7590 // each one used to cost a `stop(pc)` — a write of `pc` into the
7591 // frame, a return out of this loop, a re-dispatch through `step` and
7592 // a re-entry. `property:monomorphic` spent 18% in
7593 // `read_field_cached` and 21% in `push`, both across that boundary.
7594 //
7595 // The site is `pc + width`, which is exactly the `next` the slow arm
7596 // passes — the two must agree or every fast lookup misses and
7597 // re-records the same entry forever.
7598 //
7599 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
7600 // slow arm finds the receiver where it expects it.
7601 // `name` resolved from the global-variable cache inside the loop.
7602 //
7603 // Same shape as `get_field` above and for the same reason: `get_var`
7604 // was not in the fast loop, so reading a global — which `fib` does
7605 // once per recursive call, for its own name — cost a `stop(pc)`, a
7606 // return out of the loop, a `step` re-dispatch and a re-entry, before
7607 // `get_global` even started its `scopes_are_plain` checks.
7608 //
7609 // Everything here is exactly `get_global`'s first branch: not lexical,
7610 // no `eval` scope, cache hit. Anything else leaves the stack untouched
7611 // and lets the slow arm decide.
7612 Opcode::GetVar => {
7613 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
7614 return self.stop(pc);
7615 };
7616 self.push(value);
7617 }
7618 Opcode::GetField | Opcode::GetField2 => {
7619 let Some(value) = self.fast_field_get(insn.a as usize, pc + insn.width())
7620 else {
7621 return self.stop(pc);
7622 };
7623 if insn.op == Opcode::GetField2 {
7624 // `get_field2` keeps the receiver for the `call_method` that
7625 // follows.
7626 self.push(value);
7627 } else {
7628 // `get_field` replaces the receiver, so this is one store over
7629 // the top slot rather than a `pop` and a `push`: the length
7630 // never changes, so neither `Vec` arm has a capacity check or a
7631 // drop to run beyond the one the overwrite itself does.
7632 let frame = self.frame_mut();
7633 match frame.stack.last_mut() {
7634 Some(slot) => *slot = value,
7635 None => return self.stop(pc),
7636 }
7637 }
7638 }
7639 // -- constants ---------------------------------------------------
7640 Opcode::PushMinus1
7641 | Opcode::Push0
7642 | Opcode::Push1
7643 | Opcode::Push2
7644 | Opcode::Push3
7645 | Opcode::Push4
7646 | Opcode::Push5
7647 | Opcode::Push6
7648 | Opcode::Push7
7649 | Opcode::PushI8
7650 | Opcode::PushI16
7651 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
7652 // -- stack shuffling ---------------------------------------------
7653 Opcode::Drop => {
7654 self.pop();
7655 }
7656 // -- arithmetic on two integers ----------------------------------
7657 //
7658 // The operands are *looked at* before they are popped, so a non-integer
7659 // pair leaves the stack exactly as the slow path expects to find it.
7660 Opcode::Add if self.numeric_pair() => {
7661 let right = self.pop();
7662 let left = self.pop();
7663 // Exactly [`add_numbers`], which is what the slow arm reaches.
7664 let answer = match (&left, &right) {
7665 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
7666 Some(sum) => Value::Int(sum),
7667 None => Value::Float(*a as f64 + *b as f64),
7668 },
7669 _ => Value::Float(left.to_number() + right.to_number()),
7670 };
7671 self.push(answer);
7672 }
7673 Opcode::Sub
7674 | Opcode::And
7675 | Opcode::Or
7676 | Opcode::Xor
7677 | Opcode::Shl
7678 | Opcode::Sar
7679 | Opcode::Shr
7680 if self.numeric_pair() =>
7681 {
7682 let right = self.pop();
7683 let left = self.pop();
7684 let answer =
7685 arithmetic(insn.op, left, right).expect("numbers cannot throw");
7686 self.push(answer);
7687 }
7688 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte if self.numeric_pair() => {
7689 let right = self.pop();
7690 let left = self.pop();
7691 let answer = self
7692 .relational(insn.op, left, right)
7693 .expect("numbers cannot throw");
7694 self.push(answer);
7695 }
7696 // -- return ------------------------------------------------------
7697 Opcode::Return => {
7698 let value = self.pop();
7699 self.frame_mut().pc = pc + insn.width();
7700 return Some(value);
7701 }
7702 Opcode::ReturnUndef => {
7703 self.frame_mut().pc = pc + insn.width();
7704 return Some(Value::Undefined);
7705 }
7706 // Everything else needs the slow path.
7707 _ => return self.stop(pc),
7708 },
7709 }
7710 pc += insn.width();
7711 }
7712 }
7713
7714 /// Whether the top two operand-stack values are both numbers.
7715 ///
7716 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
7717 /// cannot run script, so the arm may not throw and may not change frames.
7718 fn numeric_pair(&self) -> bool {
7719 is_number(&self.peek(0)) && is_number(&self.peek(1))
7720 }
7721
7722 /// `a[i]` for a dense array and an integer index, without the string round trip.
7723 ///
7724 /// The slow path answers this by turning `i` into a string (`propkey` →
7725 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
7726 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
7727 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
7728 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
7729 /// without even the cheap `Int` formatting.
7730 ///
7731 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
7732 /// unambiguously the one the slow path would give:
7733 ///
7734 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
7735 /// `2^32-1` is the length, not an index),
7736 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
7737 /// typed array or an ordinary object, all of which have their own rules),
7738 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
7739 /// starts walking the prototype chain, and `a[i]` on a hole must find
7740 /// `Array.prototype[i]` if it exists rather than `undefined`.
7741 ///
7742 /// The last condition is the one that makes this safe rather than merely fast: an own
7743 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
7744 /// `get_var` answered from the global-variable cache, or `None`.
7745 ///
7746 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
7747 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
7748 /// records nothing — the slow arm is about to walk the chain and record it.
7749 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
7750 let frame = self.frame();
7751 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
7752 // "Lexical" is presence in the realm's table, not the closure var's flag: a
7753 // `GlobalRef` forwarded through a nested function has its flags cleared.
7754 if self.realm.globals.contains_key(name) {
7755 return None;
7756 }
7757 if !self.scopes_are_plain() {
7758 return None;
7759 }
7760 let object = &self.realm.global;
7761 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
7762 let cached = self.global_cache[site].as_ref()?;
7763 if !object.upgrades_to(&cached.object) {
7764 return None;
7765 }
7766 object.data_property_at(cached.index, name)
7767 }
7768
7769 /// `o.x` answered entirely from the inline cache, or `None`.
7770 ///
7771 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
7772 /// about to do exactly that and recording it twice would rebuild the chain for every
7773 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
7774 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
7775 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
7776 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
7777 // an object receiver is a reference-count bump that the answer never needs.
7778 let frame = self.frame();
7779 let object = frame.stack.last()?;
7780 let Value::Object(target) = object else {
7781 return None;
7782 };
7783 // A proxy traps the lookup, so no cache entry ever describes it.
7784 if target.proxy_state().is_some() {
7785 return None;
7786 }
7787 let key = frame.code.atom_keys.get(atom)?;
7788 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
7789 if cached.key != *key {
7790 return None;
7791 }
7792 Self::cached_hit(target, cached)
7793 }
7794
7795 fn fast_array_get(&self) -> Option<Value> {
7796 let Value::Int(index) = self.peek(0) else {
7797 return None;
7798 };
7799 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
7800 // set for an `i32`.
7801 if index < 0 {
7802 return None;
7803 }
7804 let Value::Object(object) = self.peek(1) else {
7805 return None;
7806 };
7807 match object.array_get(index as usize) {
7808 Some(value) if !matches!(value, Value::Hole) => Some(value),
7809 _ => None,
7810 }
7811 }
7812
7813 /// `a[i] = v` on a dense array with an integer index, as one store.
7814 ///
7815 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
7816 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
7817 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
7818 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
7819 /// reference at the time it was measured (14.7x).
7820 ///
7821 /// Every condition here is one the slow path would also have to satisfy before
7822 /// storing into the element vector:
7823 ///
7824 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
7825 /// accepts as an index;
7826 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
7827 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
7828 /// one inside a recorded descriptor, reports `false` and the caller stops.
7829 ///
7830 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
7831 /// writes the own element too once `array_set` says it did.
7832 fn fast_array_set(&mut self) -> bool {
7833 // Every test runs *before* anything is popped: a refusal has to leave the stack
7834 // exactly as the slow path expects to find it. Popping first and reporting the
7835 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
7836 // then ran the slow path with nothing to write.
7837 let Value::Int(index) = self.peek(1) else {
7838 return false;
7839 };
7840 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
7841 if index < 0 {
7842 return false;
7843 }
7844 // Only a real array: a typed array's elements live in its buffer, a string-like
7845 // object has no element vector, and `array_set` on either does nothing.
7846 let Value::Object(object) = self.peek(2) else {
7847 return false;
7848 };
7849 if !object.is_array() || !object.elements_writable() {
7850 return false;
7851 }
7852 // A non-extensible array reports `false` here, but the *slow* path has to decide
7853 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
7854 // that with the key and the stack still intact.
7855 if !object.is_extensible() {
7856 return false;
7857 }
7858 // Inside the logical length, so the store cannot change `length`. Combined with
7859 // extensibility above, the only growth left for `array_set` is filling a hole in
7860 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
7861 // shape this fast path exists for. A store past the length would grow the array,
7862 // and whether that is allowed is the slow path's question.
7863 if index as usize >= object.array_length().unwrap_or(0) {
7864 return false;
7865 }
7866 // The bound `array_set` refuses past. Checking it here keeps that arm from having
7867 // to report a failure after the operands are gone.
7868 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
7869 return false;
7870 }
7871 let value = self.pop();
7872 self.pop();
7873 self.pop();
7874 object.array_store(self.heap, index as usize, value)
7875 }
7876
7877 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
7878 fn stop(&mut self, pc: usize) -> Option<Value> {
7879 self.frame_mut().pc = pc;
7880 None
7881 }
7882
7883 fn push(&mut self, value: Value) {
7884 self.frame_mut().stack.push(value);
7885 }
7886
7887 fn pop(&mut self) -> Value {
7888 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
7889 }
7890
7891 fn pop_n(&mut self, count: usize) -> Vec<Value> {
7892 let frame = self.frame_mut();
7893 let start = frame.stack.len().saturating_sub(count);
7894 frame.stack.split_off(start)
7895 }
7896
7897 fn peek(&self, back: usize) -> Value {
7898 let frame = self.frame();
7899 frame
7900 .stack
7901 .get(frame.stack.len().wrapping_sub(1 + back))
7902 .cloned()
7903 .unwrap_or(Value::Undefined)
7904 }
7905
7906 #[allow(clippy::too_many_lines)]
7907 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
7908 use Opcode::*;
7909 match op {
7910 // -- constants and stack shuffling -----------------------------
7911 Nop => {}
7912 PushMinus1 => self.push(Value::Int(-1)),
7913 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
7914 let value = match op {
7915 Push0 => 0,
7916 Push1 => 1,
7917 Push2 => 2,
7918 Push3 => 3,
7919 Push4 => 4,
7920 Push5 => 5,
7921 Push6 => 6,
7922 _ => 7,
7923 };
7924 self.push(Value::Int(value));
7925 }
7926 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
7927 PushBigintI32 => {
7928 // The immediate form of a `BigInt` literal; the reference has the same
7929 // split between this and a constant-pool entry.
7930 let value = crate::bigint::BigInt::from_i64(a as i64);
7931 self.push(self.bigint(value));
7932 }
7933 PushTrue => self.push(Value::Bool(true)),
7934 PushFalse => self.push(Value::Bool(false)),
7935 PushEmptyString => self.push(self.string("")),
7936 Undefined => self.push(Value::Undefined),
7937 Null => self.push(Value::Null),
7938 Object => {
7939 let proto = self.realm.object_proto.clone();
7940 self.push(Value::Object(self.new_object(Some(proto))));
7941 }
7942 PushThis => {
7943 let this = self.frame().this.clone();
7944 self.push(this);
7945 }
7946 PushConst | PushConst8 => {
7947 let value = self.constant(a as usize)?;
7948 self.push(value);
7949 }
7950 PushAtomValue => {
7951 let text = self.atom_text(a as usize);
7952 self.push(self.string(text));
7953 }
7954 Dup => {
7955 let value = self.peek(0);
7956 self.push(value);
7957 }
7958 Dup2 => {
7959 // `a b -> a b a b`
7960 let b = self.peek(0);
7961 let a = self.peek(1);
7962 self.push(a);
7963 self.push(b);
7964 }
7965 Dup3 => {
7966 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
7967 // prototype and key while reading the current value through them.
7968 let c = self.peek(0);
7969 let b = self.peek(1);
7970 let a = self.peek(2);
7971 self.push(a);
7972 self.push(b);
7973 self.push(c);
7974 }
7975 Swap => {
7976 // `a b -> b a`
7977 let bottom = self.pop();
7978 let top = self.pop();
7979 self.push(bottom);
7980 self.push(top);
7981 }
7982 Perm3 => {
7983 // `a b c -> b a c`, the reference's reordering for a spread method
7984 // call: `obj func array` becomes the `func this array` that `apply`
7985 // takes.
7986 let c = self.pop();
7987 let b = self.pop();
7988 let a = self.pop();
7989 self.push(b);
7990 self.push(a);
7991 self.push(c);
7992 }
7993 Dup1 => {
7994 let value = self.peek(1);
7995 self.push(value);
7996 }
7997 Drop => {
7998 self.pop();
7999 }
8000 Nip => {
8001 // `a b -> b`
8002 let top = self.pop();
8003 self.pop();
8004 self.push(top);
8005 }
8006 Perm4 => {
8007 // `obj prop a b -> a obj prop b`, the reference's reordering for a
8008 // postfix update of a computed element: it puts the *old* value
8009 // underneath the receiver and key so `put_array_el` can consume them
8010 // and leave the old value as the expression's result.
8011 let d = self.pop();
8012 let c = self.pop();
8013 let b = self.pop();
8014 let a = self.pop();
8015 self.push(c);
8016 self.push(a);
8017 self.push(b);
8018 self.push(d);
8019 }
8020 Insert2 => {
8021 // `obj a -> a obj a`
8022 let value = self.pop();
8023 let object = self.pop();
8024 self.push(value.clone());
8025 self.push(object);
8026 self.push(value);
8027 }
8028 Insert3 => {
8029 // `obj prop a -> a obj prop a`
8030 let value = self.pop();
8031 let key = self.pop();
8032 let object = self.pop();
8033 self.push(value.clone());
8034 self.push(object);
8035 self.push(key);
8036 self.push(value);
8037 }
8038 Insert4 => {
8039 // `this obj prop a -> a this obj prop a`
8040 //
8041 // `put_super_value` consumes all four and yields nothing, so the copy
8042 // underneath is what leaves the assignment an expression value.
8043 let value = self.pop();
8044 let key = self.pop();
8045 let object = self.pop();
8046 let receiver = self.pop();
8047 self.push(value.clone());
8048 self.push(receiver);
8049 self.push(object);
8050 self.push(key);
8051 self.push(value);
8052 }
8053 Swap2 => {
8054 // `a b c d -> c d a b`
8055 let d = self.pop();
8056 let c = self.pop();
8057 let b = self.pop();
8058 let a = self.pop();
8059 self.push(c);
8060 self.push(d);
8061 self.push(a);
8062 self.push(b);
8063 }
8064 Rot3l => {
8065 // `x a b -> a b x`
8066 let b = self.pop();
8067 let a = self.pop();
8068 let x = self.pop();
8069 self.push(a);
8070 self.push(b);
8071 self.push(x);
8072 }
8073 Rot3r => {
8074 // `a b c -> c a b`
8075 let c = self.pop();
8076 let b = self.pop();
8077 let a_value = self.pop();
8078 self.push(c);
8079 self.push(a_value);
8080 self.push(b);
8081 }
8082
8083 Rest => {
8084 // `...rest` in a parameter list: the arguments from index `a` on, as a
8085 // real array. It takes nothing off the stack — the arguments are in the
8086 // frame, not on it.
8087 let frame = self.frame();
8088 let from = a as usize;
8089 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
8090 let array = self.new_array(collected);
8091 self.push(Value::Object(array));
8092 }
8093
8094 // -- slots ------------------------------------------------------
8095 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
8096 let slot = self.slot_operand(op, a);
8097 let value = self.get_loc(slot);
8098 self.push(value);
8099 }
8100 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
8101 let slot = self.slot_operand(op, a);
8102 let value = self.pop();
8103 self.put_loc(slot, value);
8104 }
8105 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
8106 let slot = self.slot_operand(op, a);
8107 let value = self.pop();
8108 self.put_loc(slot, value.clone());
8109 self.push(value);
8110 }
8111 // The `_check` forms are the temporal dead zone: they throw when the
8112 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
8113 // *reads*, so only the two writes may pop — mishandling that quietly
8114 // consumes the value the caller pushed just before.
8115 GetLocCheck => {
8116 let slot = self.slot_operand(op, a);
8117 let value = self.get_loc(slot);
8118 if matches!(value, Value::Uninitialized) {
8119 return Err(self.dead_zone(slot, VarSlot::Loc));
8120 }
8121 self.push(value);
8122 }
8123 PutLocCheck | SetLocCheck => {
8124 let slot = self.slot_operand(op, a);
8125 let value = self.pop();
8126 if matches!(value, Value::Uninitialized) {
8127 return Err(self.dead_zone(slot, VarSlot::Loc));
8128 }
8129 // The initialiser goes through `put_loc`, not this, so any store that
8130 // reaches here is a later assignment — which a `const` refuses.
8131 if self.is_read_only(slot, VarSlot::Loc) {
8132 return Err(self.read_only(slot, VarSlot::Loc));
8133 }
8134 if op == SetLocCheck {
8135 self.put_loc(slot, value.clone());
8136 self.push(value);
8137 } else {
8138 self.put_loc(slot, value);
8139 }
8140 }
8141 PutLocCheckInit => {
8142 // The one store that *initialises* a lexical slot: `this` in a derived
8143 // constructor, which only exists after `super()` has run. A second
8144 // initialisation is the error the reference reports as
8145 // "'this' can be initialized only once".
8146 let slot = self.slot_operand(op, a);
8147 let value = self.pop();
8148 if !matches!(self.get_loc(slot), Value::Uninitialized) {
8149 return Err(Signal::Throw(self.make_error(
8150 "ReferenceError",
8151 "'this' can be initialized only once",
8152 )));
8153 }
8154 self.put_loc(slot, value);
8155 }
8156 CheckCtor => {
8157 // A class constructor may only run under `new`, which is what makes
8158 // `class A {}; A()` a TypeError.
8159 if matches!(self.frame().new_target, Value::Undefined) {
8160 return Err(Signal::Throw(self.make_error(
8161 "TypeError",
8162 "class constructors must be invoked with 'new'",
8163 )));
8164 }
8165 }
8166 InitCtor => {
8167 // The body a derived class gets when it declares no constructor:
8168 // forward every argument to the parent constructor, keeping `new.target`.
8169 if matches!(self.frame().new_target, Value::Undefined) {
8170 return Err(Signal::Throw(self.make_error(
8171 "TypeError",
8172 "class constructors must be invoked with 'new'",
8173 )));
8174 }
8175 let Some(callee) = self.current_callee() else {
8176 return Err(Signal::Throw(
8177 self.make_error("TypeError", "no constructor to inherit from"),
8178 ));
8179 };
8180 let parent = callee.proto().map_or(Value::Null, Value::Object);
8181 let new_target = self.frame().new_target.clone();
8182 let args = self.frame().passed().to_vec();
8183 let result = self.construct(parent, new_target, args)?;
8184 self.push(result);
8185 }
8186 SetLocUninitialized => {
8187 let slot = self.slot_operand(op, a);
8188 self.put_loc(slot, Value::Uninitialized);
8189 }
8190 CloseLoc => {
8191 // "Close" a binding: give it a *fresh* cell holding the current
8192 // value. Closures created before this point keep the old cell and the
8193 // ones created after see the new one, which is what makes every
8194 // iteration of `for (let i ...)` capture its own `i`, and what freezes
8195 // a block-scoped binding when the block ends.
8196 //
8197 // Clearing the slot instead (which this used to do) broke both: a
8198 // closure over a captured block variable read `undefined`, and a loop
8199 // terminated after one iteration.
8200 let slot = self.slot_operand(op, a);
8201 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
8202 if index >= 0 {
8203 let current = self.frame().cells[index as usize].get();
8204 let fresh = self.new_cell(current);
8205 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
8206 *cell = fresh;
8207 }
8208 }
8209 }
8210 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
8211 let slot = self.slot_operand(op, a);
8212 let value = self.get_arg(slot);
8213 self.push(value);
8214 }
8215 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
8216 let slot = self.slot_operand(op, a);
8217 let value = self.pop();
8218 self.put_arg(slot, value);
8219 }
8220 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
8221 let slot = self.slot_operand(op, a);
8222 let value = self.pop();
8223 self.put_arg(slot, value.clone());
8224 self.push(value);
8225 }
8226
8227 // -- closure variables ------------------------------------------
8228 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
8229 let slot = self.slot_operand(op, a);
8230 // A name a direct `eval` created shadows the binding the compiler chose.
8231 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
8232 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
8233 // and only a runtime lookup can know that.
8234 if let Some(cell) = self.eval_created_local(slot) {
8235 self.push(cell.get());
8236 return self.step();
8237 }
8238 let value = self.cell_value(slot)?;
8239 self.push(value);
8240 }
8241 GetVarRefCheck => {
8242 let slot = self.slot_operand(op, a);
8243 let value = self.cell_value(slot)?;
8244 if matches!(value, Value::Uninitialized) {
8245 return Err(self.dead_zone(slot, VarSlot::Closure));
8246 }
8247 self.push(value);
8248 }
8249 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
8250 let slot = self.slot_operand(op, a);
8251 let value = self.pop();
8252 if let Some(cell) = self.eval_created_local(slot) {
8253 cell.set(value);
8254 return self.step();
8255 }
8256 // Same rule as `PutLocCheck`: a checked store to a captured binding
8257 // refuses a `const` once its initialiser has run.
8258 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
8259 return Err(self.read_only(slot, VarSlot::Closure));
8260 }
8261 self.set_cell(slot, value)?;
8262 }
8263 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
8264 let slot = self.slot_operand(op, a);
8265 let value = self.pop();
8266 if let Some(cell) = self.eval_created_local(slot) {
8267 cell.set(value.clone());
8268 self.push(value);
8269 return self.step();
8270 }
8271 self.set_cell(slot, value.clone())?;
8272 self.push(value);
8273 }
8274
8275 // -- globals ----------------------------------------------------
8276 GetVar => {
8277 let value = self.get_global(a as usize)?;
8278 self.push(value);
8279 }
8280 GetVarUndef => {
8281 let value = self
8282 .get_global(a as usize)
8283 .or_else(|_| Ok(Value::Undefined))?;
8284 self.push(value);
8285 }
8286 DeleteVar => {
8287 // `delete name` for a name that is not a declared binding. A lexical
8288 // global lives in the reference table and cannot be deleted; anything
8289 // reachable only as a property of the global object is *implicit* —
8290 // `x = 1` with no declaration — and goes away if it is configurable,
8291 // which is what `delete` on an implicit global answers.
8292 let name = self.atom_text(a as usize);
8293 let global = self.realm.global.clone();
8294 let deleted = if self.realm.globals.contains_key(&name) {
8295 false
8296 } else if global.own_property(&name).is_some() {
8297 self.delete_property(&global, &name)?
8298 } else {
8299 true
8300 };
8301 self.push(Value::Bool(deleted));
8302 }
8303 PutVar => {
8304 let value = self.pop();
8305 self.put_global(a as usize, value)?;
8306 }
8307 PutVarInit => {
8308 let slot = a as usize;
8309 let value = self.pop();
8310 self.init_global(slot, value)?;
8311 }
8312
8313 // -- arithmetic -------------------------------------------------
8314 Add => self.binary_add()?,
8315 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
8316 let raw_right = self.pop();
8317 let raw_left = self.pop();
8318 // BigInt arithmetic is a separate path, and not only for the type of the
8319 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
8320 // rather than a silent conversion.
8321 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
8322 let left = self.primitive_of(raw_left)?;
8323 let right = self.primitive_of(raw_right)?;
8324 let value = self.bigint_arithmetic(op, left, right)?;
8325 self.push(value);
8326 } else {
8327 let right = self.numeric(raw_right)?;
8328 let left = self.numeric(raw_left)?;
8329 self.push(arithmetic(op, left, right)?);
8330 }
8331 }
8332 Neg => {
8333 let raw = self.pop();
8334 match raw {
8335 // A bigint negates exactly, however wide it is.
8336 Value::BigInt(big) => {
8337 let negated = big.negate();
8338 self.push(self.bigint(negated));
8339 }
8340 other => {
8341 let value = self.numeric(other)?;
8342 self.push(negate(value));
8343 }
8344 }
8345 }
8346 Plus => {
8347 let value = self.pop();
8348 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
8349 // unary plus is defined to produce a *number*, which a bigint cannot
8350 // become without loss. It used to fall through to `NaN`.
8351 if matches!(value, Value::BigInt(_)) {
8352 return Err(self.type_error("cannot convert bigint to number"));
8353 }
8354 let numeric = self.numeric_of(value)?;
8355 self.push(numeric);
8356 }
8357 Inc => {
8358 let raw = self.pop();
8359 let (_, updated) = self.advance_numeric(raw, true)?;
8360 self.push(updated);
8361 }
8362 Dec => {
8363 let raw = self.pop();
8364 let (_, updated) = self.advance_numeric(raw, false)?;
8365 self.push(updated);
8366 }
8367 PostInc | PostDec => {
8368 // `x -> x x+1`: the *new* value ends up on top, so the store the
8369 // compiler emits right after (`put_var`) writes the incremented
8370 // one, while the old value stays underneath for the expression's
8371 // own result. Getting this backwards makes `i++` a no-op, which
8372 // turns `while (i < 3)` into an infinite loop.
8373 let raw = self.pop();
8374 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
8375 self.push(old);
8376 self.push(updated);
8377 }
8378 Not => {
8379 let raw = self.pop();
8380 match raw {
8381 // `~x` on a bigint is `-x - 1`, exact at any width.
8382 Value::BigInt(big) => {
8383 let inverted = big.bitnot();
8384 self.push(self.bigint(inverted));
8385 }
8386 other => {
8387 let value = self.numeric(other)?;
8388 self.push(Value::Int(!value.to_int32()));
8389 }
8390 }
8391 }
8392 Lnot => {
8393 let value = self.pop();
8394 self.push(Value::Bool(!value.to_boolean()));
8395 }
8396
8397 // -- comparison -------------------------------------------------
8398 Lt | Lte | Gt | Gte => {
8399 let right = self.pop();
8400 let left = self.pop();
8401 let answer = self.relational(op, left, right)?;
8402 self.push(answer);
8403 }
8404 Eq | Neq => {
8405 let right = self.pop();
8406 let left = self.pop();
8407 let equal = self.abstract_equals(left, right)?;
8408 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
8409 }
8410 StrictEq => {
8411 let right = self.pop();
8412 let left = self.pop();
8413 self.push(Value::Bool(left.strict_equals(&right)));
8414 }
8415 StrictNeq => {
8416 let right = self.pop();
8417 let left = self.pop();
8418 self.push(Value::Bool(!left.strict_equals(&right)));
8419 }
8420 IsUndefined => {
8421 // `=== undefined`, which is what a destructuring default tests. It is
8422 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
8423 let value = self.pop();
8424 self.push(Value::Bool(matches!(value, Value::Undefined)));
8425 }
8426 IsUndefinedOrNull => {
8427 let value = self.pop();
8428 self.push(Value::Bool(value.is_nullish()));
8429 }
8430 Typeof => {
8431 let value = self.pop();
8432 self.push(self.string(value.type_of()));
8433 }
8434 ToObject => {
8435 // A destructuring *object* pattern starts here, which is why
8436 // `var {} = null` throws. Only `undefined` and `null` are refused; a
8437 // primitive is boxed.
8438 let value = self.pop();
8439 let object = self.object_from(&value)?;
8440 self.push(Value::Object(object));
8441 }
8442 Instanceof => {
8443 let constructor = self.pop();
8444 let object = self.pop();
8445 let answer = self.instance_of(&object, &constructor)?;
8446 self.push(Value::Bool(answer));
8447 }
8448 In => {
8449 let object = self.pop();
8450 let key = self.pop();
8451 let answer = self.has_property(&key, &object)?;
8452 self.push(Value::Bool(answer));
8453 }
8454
8455 // -- control flow -----------------------------------------------
8456 Goto | Goto8 | Goto16 => {
8457 self.frame_mut().pc = a as usize;
8458 }
8459 IfTrue | IfTrue8 => {
8460 let value = self.pop();
8461 if value.to_boolean() {
8462 self.frame_mut().pc = a as usize;
8463 }
8464 }
8465 IfFalse | IfFalse8 => {
8466 let value = self.pop();
8467 if !value.to_boolean() {
8468 self.frame_mut().pc = a as usize;
8469 }
8470 }
8471 Catch => {
8472 // Pushes the handler target onto the value stack; `unwind` finds it.
8473 self.push(Value::CatchOffset(a));
8474 }
8475 Gosub => {
8476 self.push(Value::ReturnAddress(next as u32));
8477 self.frame_mut().pc = a as usize;
8478 }
8479 Ret => {
8480 let value = self.pop();
8481 match value {
8482 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
8483 _ => {
8484 return Err(Signal::Throw(
8485 self.make_error("InternalError", "invalid return address"),
8486 ));
8487 }
8488 }
8489 }
8490 NipCatch => {
8491 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
8492 // including the marker, keeping the top value.
8493 let top = self.pop();
8494 loop {
8495 match self.pop() {
8496 Value::CatchOffset(_) | Value::Undefined => break,
8497 _ => {}
8498 }
8499 if self.frame().stack.is_empty() {
8500 break;
8501 }
8502 }
8503 self.push(top);
8504 }
8505 Throw => {
8506 let value = self.pop();
8507 return Err(Signal::Throw(value));
8508 }
8509 ThrowError => {
8510 let name = self.atom_text(a as usize);
8511 let (class, message) = match b {
8512 0 => ("TypeError", format!("'{name}' is read-only")),
8513 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
8514 2 => ("ReferenceError", format!("'{name}' is not initialized")),
8515 // `delete super.x` is a syntax-level mistake the reference reports
8516 // with this wording, not a property-access failure.
8517 3 => (
8518 "ReferenceError",
8519 "unsupported reference to 'super'".to_string(),
8520 ),
8521 4 => (
8522 "TypeError",
8523 "iterator does not have a throw method".to_string(),
8524 ),
8525 5 => (
8526 "ReferenceError",
8527 "invalid assignment left-hand side".to_string(),
8528 ),
8529 _ => ("TypeError", format!("invalid operation on '{name}'")),
8530 };
8531 return Err(Signal::Throw(self.make_error(class, &message)));
8532 }
8533 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
8534 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
8535 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
8536 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
8537 Await => return Ok(Step::Suspend(SuspendKind::Await)),
8538 ReturnAsync => {
8539 // The reference's `return_async` returns `undefined` and lets the resume
8540 // machinery pick the real value off `sp[-1]`, which is how it tells a
8541 // completion from a suspension. Carrying the value explicitly says the
8542 // same thing without the implicit stack slot.
8543 let value = self.pop();
8544 return Ok(Step::Return(value));
8545 }
8546 Return => {
8547 let value = self.pop();
8548 return Ok(Step::Return(value));
8549 }
8550 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
8551
8552 // -- calls ------------------------------------------------------
8553 Call | Call0 | Call1 | Call2 | Call3 => {
8554 let argc = self.argc_operand(op, a);
8555 let args = self.pop_n(argc);
8556 let callee = self.pop();
8557 // A plain call has no receiver; the callee decides what to do with
8558 // `undefined` (a sloppy function substitutes the global object).
8559 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
8560 self.push(result);
8561 }
8562 }
8563 CallConstructor => {
8564 // `constructor this_obj args… -> object`. The duplicated
8565 // constructor is `new.target`; this milestone does not expose it,
8566 // so the extra copy is simply consumed here.
8567 let argc = a as usize;
8568 let args = self.pop_n(argc);
8569 let new_target = self.pop();
8570 let callee = self.pop();
8571 let result = self.construct(callee, new_target, args)?;
8572 self.push(result);
8573 }
8574 CallMethod => {
8575 let argc = a as usize;
8576 let args = self.pop_n(argc);
8577 let callee = self.pop();
8578 let this = self.pop();
8579 if let Some(result) = self.call_or_push(callee, this, args)? {
8580 self.push(result);
8581 }
8582 }
8583 Apply => {
8584 // `func this array -> result`, the spread-call form: the compiler
8585 // builds one array of arguments, and all that is left here is to
8586 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
8587 let array = self.pop();
8588 let this = self.pop();
8589 let callee = self.pop();
8590 let args = self.array_like_to_args(&array)?;
8591 if a & 1 != 0 {
8592 let result = self.construct(callee, this, args)?;
8593 self.push(result);
8594 } else if let Some(result) = self.call_or_push(callee, this, args)? {
8595 self.push(result);
8596 }
8597 }
8598 TailCall | TailCallMethod => {
8599 // `tail_call` is `call` whose result is returned immediately — the
8600 // reference jumps straight to `done` instead of storing the value and
8601 // running on. The callee still gets its own frame, so deep tail
8602 // recursion hits the stack limit exactly like plain recursion does;
8603 // marking this frame lets the return path unwind without needing
8604 // instructions after the call.
8605 let argc = if op == TailCallMethod {
8606 a as usize
8607 } else {
8608 self.argc_operand(op, a)
8609 };
8610 let args = self.pop_n(argc);
8611 let callee = self.pop();
8612 let this = if op == TailCallMethod {
8613 self.pop()
8614 } else {
8615 Value::Undefined
8616 };
8617 if let Value::Object(function) = &callee
8618 && let Some((code, env)) = bytecode_of(function)
8619 {
8620 // A generator or async body is not run here at all: calling it only
8621 // *creates* the generator/coroutine, so it must not inherit this
8622 // frame. Doing so made `function f(){ return g() }` push `g`'s body
8623 // onto `f`'s frame, and the first `yield`/`await` then reported
8624 // "a generator body ran as an ordinary call".
8625 if code.code.kind.is_generator() || code.code.kind.is_async() {
8626 let value = self.call_value(callee, this, args)?;
8627 return Ok(Step::Return(value));
8628 }
8629 self.frame_mut().tail = true;
8630 self.push_frame(code, env, this, args, callee)?;
8631 return Ok(Step::Continue);
8632 }
8633 // A native callee has no frame to reuse, so its value is simply
8634 // returned.
8635 let value = self.call_value(callee, this, args)?;
8636 return Ok(Step::Return(value));
8637 }
8638
8639 // -- objects ----------------------------------------------------
8640 SpecialObject => {
8641 let value = self.special_object(a)?;
8642 self.push(value);
8643 }
8644 PrivateSymbol => {
8645 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
8646 // symbol each time it is evaluated, which is why the compiler evaluates it
8647 // once (at class definition) and stores it in a class-scope binding.
8648 let name = self.atom_text(a as usize);
8649 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
8650 self.push(Value::Symbol(symbol));
8651 }
8652 GetPrivateField => {
8653 // `obj symbol -> value`. A missing private field is a TypeError, which is what
8654 // makes `#x` inaccessible on any object not built by this class.
8655 let symbol = self.pop();
8656 let object = self.pop();
8657 let value = self.read_private_field(&object, &symbol)?;
8658 self.push(value);
8659 }
8660 PutPrivateField => {
8661 // `obj value symbol ->`, and the store is a plain assignment to a property the
8662 // class already created, so there is no setter to consult.
8663 let symbol = self.pop();
8664 let value = self.pop();
8665 let object = self.pop();
8666 self.write_private_field(&object, &symbol, value)?;
8667 }
8668 DefinePrivateField => {
8669 // `obj symbol value -> obj`: a field initialiser creates the property, and
8670 // redefining one is a TypeError ("already exists").
8671 let value = self.pop();
8672 let symbol = self.pop();
8673 let object = self.pop();
8674 self.define_private_field(&object, &symbol, value)?;
8675 self.push(object);
8676 }
8677 PrivateIn => {
8678 // `obj key -> bool`: `#x in o`. The second operand decides which question is
8679 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
8680 // is a field, so this is an own-property test; a *function* is a method or
8681 // accessor, so this is a brand check.
8682 let key = self.pop();
8683 let object = self.pop();
8684 let Some(target) = object.as_object() else {
8685 return Err(Signal::Throw(
8686 self.make_error("TypeError", "invalid 'in' operand"),
8687 ));
8688 };
8689 let present = match &key {
8690 Value::Object(_) => self.check_brand(target, &key)?,
8691 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
8692 };
8693 self.push(Value::Bool(present));
8694 }
8695 AddBrand => {
8696 // `obj home ->`: create the class brand on `home` if it has none, then give
8697 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
8698 // class definition: only the prototype's copy of the symbol is wanted.
8699 let home = self.pop();
8700 let object = self.pop();
8701 self.add_brand(&object, &home)?;
8702 }
8703 CheckBrand => {
8704 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
8705 // Both stay, because the caller needs them — `nip` halves a read into its
8706 // value and `call_method` uses the pair as receiver and callee.
8707 let function = self.peek(0);
8708 let object = self.peek(1);
8709 let Some(target) = object.as_object() else {
8710 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
8711 };
8712 if !self.check_brand(target, &function)? {
8713 return Err(Signal::Throw(
8714 self.make_error("TypeError", "invalid brand on object"),
8715 ));
8716 }
8717 }
8718 GetLength => {
8719 // `get_length` is the `.length` read; an array and a string answer
8720 // from their own length, anything else from the property.
8721 let target = self.pop();
8722 let value = match &target {
8723 Value::Object(object) => match object.array_length() {
8724 Some(length) => crate::object::length_value(length),
8725 None => self.read_field(&target, "length")?,
8726 },
8727 Value::String(text) => Value::Int(text.utf16_len() as i32),
8728 _ => self.read_field(&target, "length")?,
8729 };
8730 self.push(value);
8731 }
8732 GetField | GetField2 => {
8733 let object = self.pop();
8734 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
8735 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
8736 // just below is what lets the borrow outlive the `&mut self` the lookup
8737 // needs — one refcount bump instead of a key clone plus its drop, on the
8738 // hottest property path there is: every `o.x` and every `o.m()` receiver.
8739 let code = self.frame().code.clone();
8740 let key = &code.atom_keys[a as usize];
8741 let value = self.read_field_cached(&object, key, next)?;
8742 if op == GetField2 {
8743 self.push(object);
8744 }
8745 self.push(value);
8746 }
8747 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
8748 let key = self.pop();
8749 let object = self.pop();
8750 let key = self.propkey(&key)?;
8751 let value = self.read_field_key(&object, &key)?;
8752 if matches!(op, GetArrayEl2 | GetArrayEl3) {
8753 self.push(object);
8754 }
8755 if op == GetArrayEl3 {
8756 // The key goes back in its *value* form, which the compiler stores
8757 // into the target of a destructuring assignment.
8758 self.push(match &key {
8759 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
8760 PropertyKey::String(text) => self.string_wtf8(text.clone()),
8761 });
8762 }
8763 self.push(value);
8764 }
8765 PutField => {
8766 let value = self.pop();
8767 let object = self.pop();
8768 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
8769 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
8770 // only reads. `this.value = …` is the write half of the hottest loop in
8771 // `property:method-call`, and `own_property_key` was 4.8% of the case.
8772 let code = self.frame().code.clone();
8773 let key = &code.atom_keys[a as usize];
8774 self.write_field_key(&object, key, value)?;
8775 }
8776 PutArrayEl => {
8777 let value = self.pop();
8778 let key = self.pop();
8779 let object = self.pop();
8780 let key = self.propkey(&key)?;
8781 self.write_field_key(&object, &key, value)?;
8782 }
8783 DefineField => {
8784 let value = self.pop();
8785 let object = self.pop();
8786 let key = self.atom_text(a as usize);
8787 // No naming here. `{m: function(){}}` is named by the *compiler*, which
8788 // emits `set_name` — and only where `NamedEvaluation` applies, so
8789 // `{m: (0, function(){})}` stays anonymous. Naming every function that
8790 // reaches a property definition got that case wrong, and the compiler is
8791 // the only place that can tell the two apart.
8792 if let Some(target) = object.as_object() {
8793 // Only an *array* stores into the element vector. A numeric key
8794 // on an ordinary object is an ordinary property, which is what
8795 // makes `{1: 'a'}` iterate as a key rather than disappear.
8796 let stored = target.is_array()
8797 && array_index(&key).is_some_and(|index| {
8798 target.array_set(self.heap, index as usize, value.clone())
8799 });
8800 if !stored {
8801 target.define_data(&key, value);
8802 }
8803 }
8804 self.push(object);
8805 }
8806 DefineArrayEl => {
8807 // `obj key value -> obj key`. The *value* form of the key is what goes
8808 // back on the stack — the compiler stores it into the pattern's binding —
8809 // so the symbol is not stringified on the way through.
8810 let value = self.pop();
8811 let key_value = self.pop();
8812 let object = self.peek(0);
8813 let key = self.propkey(&key_value)?;
8814 self.write_field_key(&object, &key, value)?;
8815 self.push(key_value);
8816 }
8817 SetHomeObject => {
8818 // `obj func -> obj func`: records the object a method was defined on so
8819 // `super` inside it resolves against that object's prototype.
8820 let function = self.peek(0);
8821 let home = self.peek(1);
8822 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
8823 function.set_home_object(Some(home.clone()));
8824 }
8825 }
8826 Regexp => {
8827 // `pattern flags -> regexp`. A literal compiles here rather than through the
8828 // constructor, which is both what the reference's dedicated opcode is for
8829 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
8830 let flags = self.pop();
8831 let pattern = self.pop();
8832 let pattern = self.to_js_string(&pattern)?;
8833 let flags = self.to_js_string(&flags)?;
8834 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
8835 self.push(Value::Object(object));
8836 }
8837 UsingDisposeInit => {
8838 // The error state a disposal accumulates into. Uninitialised means "no
8839 // failure yet"; anything else is the exception being propagated.
8840 self.push(Value::Uninitialized);
8841 }
8842 UsingCheck => {
8843 // `value -> value, method`: validate and snapshot the disposer now, so a
8844 // later change to `Symbol.dispose` cannot change what gets called, and so a
8845 // value that is not disposable fails before the body runs.
8846 let value = self.pop();
8847 let method = self.using_method_for(&value, a as u8 == 1)?;
8848 self.push(value);
8849 self.push(method);
8850 }
8851 UsingDispose => {
8852 // `error_state -> error_state'`: dispose the variable at `slot` — its value
8853 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
8854 // the pending error.
8855 let slot = self.slot_operand(op, a);
8856 let error_state = self.pop();
8857 let merged = self.using_dispose_once(slot, error_state)?;
8858 self.push(merged);
8859 }
8860 UsingDisposeMerge => {
8861 let new_error = self.pop();
8862 let error_state = self.pop();
8863 let merged = self.merge_dispose_error(new_error, error_state);
8864 self.push(merged);
8865 }
8866 UsingDisposeEnd => {
8867 // A disposal that failed replaces the block's normal completion, so the
8868 // error state becomes a real throw here rather than at the call site.
8869 let error_state = self.pop();
8870 if !matches!(error_state, Value::Uninitialized) {
8871 return Err(Signal::Throw(error_state));
8872 }
8873 }
8874 UsingDisposeAsync => {
8875 // `await using` needs a promise to await and this runtime has no
8876 // `Promise` builtin, so the disposer is called synchronously and its result
8877 // discarded. That is correct for a disposer that returns nothing and is
8878 // reported as a gap rather than silently skipped.
8879 let slot = self.slot_operand(op, a);
8880 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
8881 self.push(error_state);
8882 }
8883 GetSuper => {
8884 // `obj -> obj's prototype`: the starting point of a `super` lookup.
8885 let object = self.pop();
8886 let proto = match &object {
8887 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
8888 _ => Value::Null,
8889 };
8890 self.push(proto);
8891 }
8892 GetSuperValue => {
8893 // `receiver proto key -> value`, searching from `proto` but reporting to
8894 // `receiver`, which is what `super.g` must do for a getter to see `this`.
8895 //
8896 // Three values in, one out: the receiver is *consumed*, not left under the
8897 // result. Leaving it there was invisible for `super.x` in `return` or
8898 // statement position (the result is what gets popped) and corrupted the
8899 // frame everywhere else — `print(super.x)` left the class where the call
8900 // opcode looks for the receiver and called the class itself.
8901 let key = self.pop();
8902 let proto = self.pop();
8903 let receiver = self.pop();
8904 let value = self.super_read(&receiver, &proto, &key)?;
8905 self.push(value);
8906 }
8907 PutSuperValue => {
8908 // `receiver proto key value ->`: a store that starts at `proto` but
8909 // assigns to `receiver`.
8910 let value = self.pop();
8911 let key = self.pop();
8912 let proto = self.pop();
8913 let receiver = self.pop();
8914 self.super_write(&receiver, &proto, &key, value)?;
8915 }
8916 DefineClass => {
8917 // `parent ctor -> ctor proto`: the constructor becomes the class and a
8918 // fresh prototype object lands on top for the methods to go on.
8919 let name = self.atom_text(a as usize);
8920 let (ctor, proto) = self.define_class(&name, b)?;
8921 self.push(ctor);
8922 self.push(Value::Object(proto));
8923 }
8924 DefineClassComputed => {
8925 // `parent ctor key -> ctor proto key`: the computed name stays put so
8926 // `define_field`-style consumers can still read it.
8927 let key = self.pop();
8928 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
8929 let (ctor, proto) = self.define_class(&name, b)?;
8930 self.push(ctor);
8931 self.push(Value::Object(proto));
8932 self.push(key);
8933 }
8934 DefineMethod => {
8935 let function = self.pop();
8936 let object = self.pop();
8937 let key = self.atom_text(a as usize);
8938 // A method's `[[HomeObject]]` is the object it was defined on, which is
8939 // what `super` inside it resolves against.
8940 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
8941 function.set_home_object(Some(object.clone()));
8942 }
8943 self.set_function_name(&function, &key_with_accessor_prefix(&key, b));
8944 if let Some(array) = object.as_object() {
8945 define_function_property(array, &PropertyKey::from(key.as_str()), function, b);
8946 }
8947 self.push(object);
8948 }
8949 DefineMethodComputed => {
8950 let function = self.pop();
8951 let key = self.pop();
8952 let object = self.pop();
8953 let key = self.propkey(&key)?;
8954 self.set_function_name(&function, &key_with_accessor_prefix(&key.to_string(), a));
8955 if let Some(array) = object.as_object() {
8956 define_function_property(array, &key, function, a);
8957 }
8958 self.push(object);
8959 }
8960 SetProto => {
8961 let proto = self.pop();
8962 let object = self.pop();
8963 if let Some(target) = object.as_object() {
8964 target.set_proto(proto.as_object().cloned());
8965 }
8966 self.push(object);
8967 }
8968 CopyDataProperties => {
8969 let exclusion = self.pop();
8970 let source = self.pop();
8971 let target = self.peek(0);
8972 self.copy_properties(&target, &source, &exclusion)?;
8973 self.push(source);
8974 self.push(exclusion);
8975 }
8976 ToPropkey => {
8977 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
8978 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
8979 // ordinary `"Symbol(b)"` property.
8980 let value = self.pop();
8981 let key = match self.propkey(&value)? {
8982 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
8983 PropertyKey::String(text) => self.string_wtf8(text),
8984 };
8985 self.push(key);
8986 }
8987 SetName => {
8988 let function = self.peek(0);
8989 let name = self.atom_text(a as usize);
8990 self.set_function_name(&function, &name);
8991 }
8992 SetNameComputed => {
8993 let key = self.peek(1);
8994 let function = self.peek(0);
8995 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
8996 self.set_function_name(&function, &name);
8997 }
8998
8999 // -- arrays -----------------------------------------------------
9000 ArrayFrom => {
9001 let count = a as usize;
9002 let elements = self.pop_n(count);
9003 let array = self.new_array(elements);
9004 self.push(Value::Object(array));
9005 }
9006 Append => {
9007 // `array index iterable -> array new_index`
9008 let iterable = self.pop();
9009 self.pop();
9010 let array = self.peek(0);
9011 let added = self.append_enumerate(&array, &iterable)?;
9012 self.push(Value::Int(added));
9013 }
9014
9015 // -- iteration --------------------------------------------------
9016 ForInStart => {
9017 let value = self.pop();
9018 let record = self.for_in_record(&value)?;
9019 self.push(Value::Object(record));
9020 }
9021 ForInNext => {
9022 // `record -> record key done`. The flag is *done*, not "found":
9023 // the compiler tests it with `if_false` to jump back into the body,
9024 // so reporting `true` while keys remain would end the loop at once.
9025 let record = self.peek(0);
9026 match self.for_in_advance(&record)? {
9027 Some(key) => {
9028 let text = self.string(key);
9029 self.push(text);
9030 self.push(Value::Bool(false));
9031 }
9032 None => {
9033 self.push(Value::Undefined);
9034 self.push(Value::Bool(true));
9035 }
9036 }
9037 }
9038 ForOfStart => {
9039 let value = self.pop();
9040 let iterator = self.get_iterator(&value)?;
9041 self.push(iterator.object);
9042 self.push(iterator.next);
9043 self.push(Value::CatchOffset(0));
9044 }
9045 ForOfNext => {
9046 // `iter next catch_offset -> iter next catch_offset value done`.
9047 //
9048 // The operand is how many values sit *above* the iterator triple: a
9049 // destructuring rest element keeps its target array and running index
9050 // there while draining the iterator, so the triple is not at the top.
9051 let extra = a as usize;
9052 let iterator_slot = 2 + extra;
9053 // An exhausted iterator is replaced by `undefined` (see below), so a
9054 // second step must not call `next` again — `Array.from` and a
9055 // destructuring pattern both keep stepping past the end.
9056 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
9057 (Value::Undefined, true)
9058 } else {
9059 let iterator = Iterator {
9060 object: self.peek(iterator_slot),
9061 next: self.peek(1 + extra),
9062 };
9063 self.iterator_step(&iterator)?
9064 };
9065 if done {
9066 // The result's `value` is meaningless once the iterator is done:
9067 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
9068 // rather than binding the generator's return value.
9069 let top = self.frame().stack.len() - 1 - iterator_slot;
9070 self.frame_mut().stack[top] = Value::Undefined;
9071 self.push(Value::Undefined);
9072 self.push(Value::Bool(true));
9073 } else {
9074 self.push(value);
9075 self.push(Value::Bool(false));
9076 }
9077 }
9078 IteratorNext => {
9079 // `iter next catch val -> iter next catch val'`: replace the argument with
9080 // the result of `next(val)`. The triple below stays put, which is why the
9081 // three instructions of the `yield*` loop all address the stack the same way.
9082 let value = self.pop();
9083 let object = self.peek(2);
9084 let next = self.peek(1);
9085 let result = self.call_value(next, object, vec![value])?;
9086 self.push(result);
9087 }
9088 IteratorCall => {
9089 // `iter next catch val -> iter next catch val' flag`.
9090 //
9091 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
9092 // The flag is `true` when the method was missing, which is how the
9093 // caller learns that the inner iterator cannot take part in the
9094 // unwinding.
9095 let value = self.pop();
9096 let object = self.peek(2);
9097 let key = if a & 1 != 0 { "throw" } else { "return" };
9098 let method = self.read_field(&object, key)?;
9099 if matches!(method, Value::Undefined | Value::Null) {
9100 self.push(value);
9101 self.push(Value::Bool(true));
9102 } else {
9103 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
9104 let result = self.call_value(method, object, argument)?;
9105 self.push(result);
9106 self.push(Value::Bool(false));
9107 }
9108 }
9109 IteratorCheckObject => {
9110 if !matches!(self.peek(0), Value::Object(_)) {
9111 return Err(Signal::Throw(
9112 self.make_error("TypeError", "iterator must return an object"),
9113 ));
9114 }
9115 }
9116 IteratorClose => {
9117 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
9118 // calling the iterator's `return` so it can release whatever it holds.
9119 //
9120 // The catch offset goes first, so an exception from `return` is not caught
9121 // by the loop being abandoned. This used to pop the three operands and call
9122 // nothing at all, which made `break` out of a `for of` invisible to an
9123 // iterator with a `return` method.
9124 self.pop();
9125 self.pop();
9126 let iterator = self.pop();
9127 if !matches!(iterator, Value::Undefined) {
9128 let method = self.read_field(&iterator, "return")?;
9129 if !matches!(method, Value::Undefined | Value::Null) {
9130 let result = self.call_value(method, iterator.clone(), Vec::new())?;
9131 // §7.4.6: a `return` that answers a non-object is a TypeError.
9132 if !matches!(result, Value::Object(_)) {
9133 return Err(Signal::Throw(
9134 self.make_error("TypeError", "iterator must return an object"),
9135 ));
9136 }
9137 }
9138 }
9139 }
9140 Import => {
9141 // `import(specifier)`: the options slot is on top and is not read yet.
9142 let _options = self.pop();
9143 let specifier = self.pop();
9144 let promise = self.dynamic_import(specifier)?;
9145 self.push(promise);
9146 }
9147 ForAwaitOfStart => {
9148 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
9149 // `Symbol.iterator` fallback.
9150 let value = self.pop();
9151 let iterator = self.get_async_iterator(&value)?;
9152 self.push(iterator.object);
9153 self.push(iterator.next);
9154 self.push(Value::CatchOffset(0));
9155 }
9156 ForAwaitOfNext => {
9157 // `for await` steps the iterator and leaves the *result* wrapped in a
9158 // promise, so the `await` the compiler emits right after this can suspend
9159 // on it. Unwrapping happens in `iterator_get_value_done`.
9160 let extra = a as usize;
9161 let iterator_slot = 2 + extra;
9162 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
9163 Value::Undefined
9164 } else {
9165 let iterator = Iterator {
9166 object: self.peek(iterator_slot),
9167 next: self.peek(1 + extra),
9168 };
9169 let next = iterator.next.clone();
9170 self.call_value(next, iterator.object, Vec::new())?
9171 };
9172 let promise = self.promise_resolve_value(result)?;
9173 self.push(promise);
9174 }
9175 IteratorGetValueDone => {
9176 // `result -> value done`. A missing result object means the iterator was
9177 // already exhausted, which the loop treats as `done`.
9178 let result = self.pop();
9179 let done = match &result {
9180 Value::Object(object) => self
9181 .get_property(object, "done")?
9182 .is_some_and(|value| value.to_boolean()),
9183 _ => true,
9184 };
9185 if done {
9186 // Clear the iterator object so the `iterator_close` the loop emits on
9187 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
9188 // on normal completion, and this is where a normal completion is
9189 // recognised — the same trick `for_of_next` uses, which also replaces
9190 // the slot with `undefined`.
9191 //
9192 // The layout is fixed because only `for await` emits this opcode:
9193 // `iter next catch [result]`, so the iterator is three below the top.
9194 let depth = self.frame().stack.len();
9195 if depth >= 3 {
9196 self.frame_mut().stack[depth - 3] = Value::Undefined;
9197 }
9198 self.push(Value::Undefined);
9199 self.push(Value::Bool(true));
9200 } else {
9201 let Value::Object(object) = &result else {
9202 self.push(Value::Undefined);
9203 self.push(Value::Bool(true));
9204 return Ok(Step::Continue);
9205 };
9206 let value = self
9207 .get_property(object, "value")?
9208 .unwrap_or(Value::Undefined);
9209 self.push(value);
9210 self.push(Value::Bool(false));
9211 }
9212 }
9213
9214 Delete => {
9215 // `delete obj[key]`, where the key was just pushed. Deleting an array
9216 // index leaves a *hole* rather than closing the gap, and a
9217 // non-configurable property answers `false` and stays.
9218 let key = self.pop();
9219 let target = self.pop();
9220 let key = self.propkey(&key)?;
9221 let text_label = key.as_str().unwrap_or("").to_string();
9222 let deleted = match &target {
9223 Value::Object(object) => {
9224 let object = object.clone();
9225 self.delete_property_key(&object, &key)?
9226 }
9227 // A string's `length` and its index properties are
9228 // non-configurable, so deleting one answers `false`.
9229 Value::String(text) => {
9230 !(text_label == "length"
9231 || array_index(&text_label)
9232 .is_some_and(|index| (index as usize) < text.utf16_len()))
9233 }
9234 // "delete null.a" is a TypeError, not a no-op: the operator needs an
9235 // object to delete from, and only a *boxable* primitive has one.
9236 Value::Undefined | Value::Null => {
9237 return Err(Signal::Throw(
9238 self.make_error("TypeError", "cannot convert to object"),
9239 ));
9240 }
9241 // Any other primitive has no own properties; deleting nothing
9242 // succeeds.
9243 _ => true,
9244 };
9245 self.push(Value::Bool(deleted));
9246 }
9247
9248 // -- exceptions and bookkeeping ---------------------------------
9249 Fclosure | Fclosure8 => {
9250 let value = self.closure(a as usize)?;
9251 self.push(value);
9252 }
9253
9254 other => {
9255 let name = other.info().name;
9256 return Err(Signal::Throw(self.make_error(
9257 "InternalError",
9258 &format!("{name} is not implemented yet"),
9259 )));
9260 }
9261 }
9262 Ok(Step::Continue)
9263 }
9264
9265 // -- operand helpers ----------------------------------------------------
9266
9267 /// The slot index an operand names, taking short forms into account.
9268 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
9269 use Opcode::*;
9270 match op {
9271 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
9272 | SetVarRef0 => 0,
9273 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
9274 | SetVarRef1 => 1,
9275 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
9276 | SetVarRef2 => 2,
9277 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
9278 | SetVarRef3 => 3,
9279 _ => a as usize,
9280 }
9281 }
9282
9283 /// The argument count of a call, taking `call0`…`call3` into account.
9284 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
9285 use Opcode::*;
9286 match op {
9287 Call0 => 0,
9288 Call1 => 1,
9289 Call2 => 2,
9290 Call3 => 3,
9291 _ => a as usize,
9292 }
9293 }
9294
9295 /// The atom's name as a property key.
9296 ///
9297 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
9298 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
9299 /// `String::clone` was a heap allocation and a copy — per property access.
9300 /// The atom at `index`, as a property key.
9301 ///
9302 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
9303 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
9304 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
9305 /// 5.3% of `property:monomorphic`.
9306 fn atom_text(&self, index: usize) -> String {
9307 self.frame()
9308 .code
9309 .code
9310 .atoms
9311 .get(index)
9312 .map(|atom| match atom {
9313 Atom::Str(text) => text.clone(),
9314 Atom::Index(value) => value.to_string(),
9315 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
9316 // `throw_error`, `delete super.x`) never read it.
9317 Atom::Null => String::new(),
9318 })
9319 .unwrap_or_default()
9320 }
9321
9322 fn constant(&mut self, index: usize) -> JsResult<Value> {
9323 let constant = self.frame().code.code.cpool.get(index).cloned();
9324 Ok(match &constant {
9325 Some(Constant::Number(number)) => Value::Float(*number),
9326 Some(Constant::String(text)) => self.string(text.clone()),
9327 Some(Constant::BigInt { digits, radix }) => {
9328 match crate::bigint::BigInt::from_radix(digits, *radix) {
9329 Some(big) => self.bigint(big),
9330 // A literal the parser accepted is always parseable; a failure here
9331 // would be a compiler bug, so it reads as an `InternalError`.
9332 None => {
9333 return Err(Signal::Throw(
9334 self.make_error("InternalError", "unparseable bigint literal"),
9335 ));
9336 }
9337 }
9338 }
9339 Some(Constant::Function(_)) => {
9340 return Err(Signal::Throw(
9341 self.make_error("InternalError", "a bare function constant"),
9342 ));
9343 }
9344 // A tagged template's call site: a frozen array of the cooked chunks with a
9345 // frozen `raw` array beside it, which is what `String.raw` reads back.
9346 Some(Constant::Template { cooked, raw }) => {
9347 let cooked_values: Vec<Value> = cooked
9348 .iter()
9349 .map(|chunk| match chunk {
9350 Some(text) => self.string(text.clone()),
9351 None => Value::Undefined,
9352 })
9353 .collect();
9354 let raw_values: Vec<Value> =
9355 raw.iter().map(|text| self.string(text.clone())).collect();
9356 let raw_array = self.new_array(raw_values);
9357 raw_array.set_extensible(false);
9358 let template = self.new_array(cooked_values);
9359 template.define(
9360 "raw",
9361 Property::with_attributes(Value::Object(raw_array), false, false),
9362 );
9363 template.set_extensible(false);
9364 Value::Object(template)
9365 }
9366 _ => Value::Undefined,
9367 })
9368 }
9369
9370 /// The reference cell a closure-variable slot names.
9371 ///
9372 /// Two kinds of binding share this addressing: a genuine closure variable
9373 /// (captured from an enclosing function) lives in this frame's environment,
9374 /// while a *declared global* lives in the realm so that a script, a function
9375 /// declaration and their uses all see one binding. A plain `Global` — an
9376 /// undeclared name that may be satisfied by the global object — has no cell at
9377 /// all, which is how `typeof x` still works for a name that does not exist.
9378 /// The reference cell a closure-variable slot names.
9379 ///
9380 /// The environment is resolved once, when the closure is built, and this is
9381 /// just the lookup afterwards. A *declared global* is in there too, pointing at
9382 /// the realm's cell, so a script, a hoisted function declaration and their uses
9383 /// all share one binding. A plain `Global` — a name the script never declared —
9384 /// is read and written through `get_var`/`put_var` by name instead, which is
9385 /// what lets the global object satisfy it.
9386 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
9387 self.frame().env.cells.get(slot).cloned()
9388 }
9389
9390 /// Whether `slot` refers to a global binding through the reference table.
9391 ///
9392 /// A global's cell in the closure environment only exists so the slot has
9393 /// something to point at; the binding itself lives on the global object (a `var`)
9394 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
9395 /// be routed, not performed on the placeholder.
9396 fn is_global_slot(&self, slot: usize) -> bool {
9397 self.frame()
9398 .code
9399 .code
9400 .closure_vars
9401 .get(slot)
9402 .is_some_and(|c| {
9403 // A module's declarations and imports are *not* globals: their cells are
9404 // the module environment's, filled by the host, so the placeholder routing
9405 // must not apply to them.
9406 matches!(
9407 c.closure_type,
9408 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
9409 )
9410 })
9411 }
9412
9413 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
9414 if self.is_global_slot(slot) {
9415 return self.get_global(slot);
9416 }
9417 Ok(self
9418 .var_ref_cell(slot)
9419 .map(|cell| cell.get())
9420 .unwrap_or(Value::Undefined))
9421 }
9422
9423 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
9424 // A function declaration is hoisted by storing into a global reference before
9425 // the body runs, so this path is also what puts it on the global object.
9426 if self.is_global_slot(slot) {
9427 return self.put_global(slot, value);
9428 }
9429 if let Some(cell) = self.var_ref_cell(slot) {
9430 cell.set(value);
9431 }
9432 Ok(())
9433 }
9434
9435 // -- closures -----------------------------------------------------------
9436
9437 /// Build the closure for the function constant `index`.
9438 ///
9439 /// Every entry in the child's closure table names where its binding lives in
9440 /// *this* frame: a local or argument slot that was marked captured, or a cell
9441 /// this frame is itself holding. That is how a variable three functions deep
9442 /// stays one binding.
9443 fn closure(&mut self, index: usize) -> JsResult<Value> {
9444 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
9445 else {
9446 return Err(Signal::Throw(
9447 self.make_error("InternalError", "fclosure of a non-function"),
9448 ));
9449 };
9450 let mut cells = Vec::with_capacity(function.closure_vars.len());
9451 for closure_var in &function.closure_vars {
9452 let cell = match closure_var.closure_type {
9453 ClosureType::Arg => {
9454 let slot = closure_var.var_idx as usize;
9455 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
9456 }
9457 ClosureType::Local => {
9458 let slot = closure_var.var_idx as usize;
9459 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
9460 }
9461 ClosureType::Ref | ClosureType::GlobalRef => {
9462 // A `Ref` names a cell in this frame's own closure table; a
9463 // `GlobalRef` also starts there, then resolves by name below.
9464 let slot = closure_var.var_idx as usize;
9465 if let Some(cell) = self.frame().env.cells.get(slot) {
9466 cells.push(cell.clone());
9467 continue;
9468 }
9469 -1
9470 }
9471 _ => -1,
9472 };
9473 if cell >= 0 {
9474 let cell = self.frame().cells[cell as usize].clone();
9475 cells.push(cell);
9476 continue;
9477 }
9478 // A global: the cell is created on demand and shared through the realm,
9479 // so every function sees one binding.
9480 let name = closure_var.name.clone();
9481 let cell = match self.realm.globals.get(&name) {
9482 Some(cell) => cell.clone(),
9483 None => {
9484 let cell = self.new_cell(Value::Undefined);
9485 self.realm.globals.insert(name.clone(), cell.clone());
9486 cell
9487 }
9488 };
9489 cells.push(cell);
9490 }
9491 let name = function.name.clone();
9492 // `.length` is the arity before any default or rest parameter, not the number
9493 // of slots a pattern parameter needs.
9494 let length = function.defined_args;
9495 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
9496 // function and an arrow function do not. A *method* also does not, but that is not
9497 // known here — the method is marked when the `[[HomeObject]]` is attached (see
9498 // `set_home_object`), which is the moment it becomes a method.
9499 let function_kind = function.kind;
9500 let constructible =
9501 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
9502 let code = Gc::new(self.heap, CompiledCode::new(*function));
9503 // A closure built inside an `eval` inherits the eval's view of the enclosing
9504 // bindings, so it can still read them once the eval has returned.
9505 let eval_scope = self
9506 .active_eval_scope
9507 .clone()
9508 .or_else(|| self.frame().env.eval_scope.clone());
9509 // A closure sees the variables a direct `eval` declared in the frame it was
9510 // created in — the ones declared before *and after* it, so the same object is
9511 // shared; only the phase bounds which of them are visible.
9512 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
9513 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
9514 let env = Gc::new(
9515 self.heap,
9516 ClosureEnv {
9517 cells,
9518 eval_scope,
9519 local_vars,
9520 local_phase,
9521 },
9522 );
9523 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
9524 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
9525 // the only thing that carries `Symbol.toStringTag`, so without it
9526 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
9527 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
9528 let proto = match function_kind {
9529 js_compile::bytecode::FunctionKind::AsyncGenerator => self
9530 .realm
9531 .async_generator_function_proto
9532 .clone()
9533 .or_else(|| self.realm.function_proto.clone().into()),
9534 js_compile::bytecode::FunctionKind::Generator => self
9535 .realm
9536 .generator_function_proto
9537 .clone()
9538 .or_else(|| self.realm.function_proto.clone().into()),
9539 js_compile::bytecode::FunctionKind::Async => self
9540 .realm
9541 .async_function_proto
9542 .clone()
9543 .or_else(|| self.realm.function_proto.clone().into()),
9544 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
9545 };
9546 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
9547 object.set_constructible(constructible);
9548 object.define(
9549 "length",
9550 Property::name_or_length(Value::Int(length as i32)),
9551 );
9552 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
9553 // that checks the own-property descriptor fails if the property is missing.
9554 object.define("name", Property::name_or_length(self.string(name)));
9555 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
9556 // when `[[Construct]]` is created, so a generator, an async function and an arrow
9557 // function have none of their own. Installing it unconditionally gave
9558 // `Array.fromAsync` (an async function) an own `prototype` property, which
9559 // `builtin.js` checks for absence.
9560 if constructible {
9561 self.install_function_prototype(&object);
9562 }
9563 Ok(Value::Object(object))
9564 }
9565
9566 // -- conversions used by the operators ----------------------------------
9567
9568 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
9569 // `+x` is `ToNumber`, which for a string parses it and for an object runs
9570 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
9571 // string, which then behaves differently in every later comparison.
9572 match value {
9573 Value::Int(_) | Value::Float(_) => Ok(value),
9574 other => Ok(Value::Float(self.to_js_number(&other)?)),
9575 }
9576 }
9577
9578 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
9579 ///
9580 /// Returns the *converted* old value and the new one, because the two callers need
9581 /// different halves: `++x` yields the new value, while `x++` yields the old one and
9582 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
9583 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
9584 /// boolean.
9585 ///
9586 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
9587 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
9588 /// a bigint algorithm then ran exactly once.
9589 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
9590 if let Value::BigInt(big) = &value {
9591 let one = crate::bigint::BigInt::from_i64(1);
9592 let next = if up { big.add(&one) } else { big.sub(&one) };
9593 return Ok((value, self.bigint(next)));
9594 }
9595 let old = self.numeric(value)?;
9596 let new = if up {
9597 increment(old.clone())
9598 } else {
9599 decrement(old.clone())
9600 };
9601 Ok((old, new))
9602 }
9603
9604 fn numeric(&mut self, value: Value) -> JsResult<Value> {
9605 // `ToNumber` on an object runs `ToPrimitive` first, which is how
9606 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
9607 // heard at all. Reading the object's own tag instead (`other.to_number()`)
9608 // turned the whole operand into `NaN` and swallowed the exception.
9609 match value {
9610 Value::Int(_) | Value::Float(_) => Ok(value),
9611 other => Ok(Value::Float(self.to_js_number(&other)?)),
9612 }
9613 }
9614
9615 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
9616 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
9617 match value {
9618 Value::BigInt(big) => Ok((**big).clone()),
9619 // The reference words this the same way for every operator, so a failing
9620 // script reads identically; the operator itself adds nothing a caller can use.
9621 _ => Err(Signal::Throw(
9622 self.make_error("TypeError", "cannot convert bigint to number"),
9623 )),
9624 }
9625 }
9626
9627 /// Arithmetic where at least one operand is a `BigInt`.
9628 ///
9629 /// The two numeric types never mix, so a bigint paired with anything else is an error
9630 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
9631 /// that the relational operators handle it separately.
9632 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
9633 use Opcode::*;
9634 let a = self.bigint_operand(&left)?;
9635 let b = self.bigint_operand(&right)?;
9636 let result = match op {
9637 Add => a.add(&b),
9638 Sub => a.sub(&b),
9639 Mul => a.mul(&b),
9640 Div | Mod => {
9641 let Some((quotient, remainder)) = a.div_rem(&b) else {
9642 return Err(Signal::Throw(
9643 self.make_error("RangeError", "division by zero"),
9644 ));
9645 };
9646 if op == Div { quotient } else { remainder }
9647 }
9648 Pow => {
9649 let Some(value) = a.pow(&b) else {
9650 return Err(Signal::Throw(self.make_error(
9651 "RangeError",
9652 "BigInt exponent must be non-negative and not absurdly large",
9653 )));
9654 };
9655 value
9656 }
9657 And => a.bitand(&b),
9658 Or => a.bitor(&b),
9659 Xor => a.bitxor(&b),
9660 Shl | Sar => {
9661 // A shift count is a `BigInt` here, and both directions are exact; a
9662 // negative count would be the other direction, which the spec forbids.
9663 let Some(count) = b.to_i64() else {
9664 return Err(Signal::Throw(
9665 self.make_error("RangeError", "BigInt shift count is too large"),
9666 ));
9667 };
9668 if count < 0 {
9669 return Err(Signal::Throw(self.make_error(
9670 "RangeError",
9671 "BigInt shift count must be non-negative",
9672 )));
9673 }
9674 if op == Shl {
9675 a.shl(count as u64)
9676 } else {
9677 a.shr(count as u64)
9678 }
9679 }
9680 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
9681 _ => {
9682 return Err(Signal::Throw(self.make_error(
9683 "TypeError",
9684 "BigInts have no unsigned right shift, use >> instead",
9685 )));
9686 }
9687 };
9688 Ok(self.bigint(result))
9689 }
9690
9691 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
9692 ///
9693 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
9694 /// is on the mathematical values, and nothing is rounded first.
9695 /// `<`, `<=`, `>`, `>=`.
9696 ///
9697 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
9698 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
9699 /// It is a `?`-returning function for exactly that reason: an object operand can run
9700 /// script, and script can throw. The old version compared `to_number` of the raw
9701 /// values, which answered `false` for every object instead of calling `valueOf` —
9702 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
9703 /// never ran.
9704 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
9705 // The hot arm first: `i < n` with both sides already integers. No conversion, no
9706 // call, nothing that can throw.
9707 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
9708 let ordering = Some(left.cmp(right));
9709 return Ok(ordering_answer(op, ordering));
9710 }
9711 // Anything that can run script has to be converted first, in this order.
9712 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
9713 {
9714 (
9715 self.to_primitive(left, Hint::Number)?,
9716 self.to_primitive(right, Hint::Number)?,
9717 )
9718 } else {
9719 (left, right)
9720 };
9721 let ordering = match (&left, &right) {
9722 // The loop condition `i < n` is integer against integer, and it runs once
9723 // per iteration of every loop in every program. Without this arm it took the
9724 // `to_number` path twice, which is a `match` plus a conversion each.
9725 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
9726 (Value::String(a), Value::String(b)) => {
9727 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
9728 }
9729 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
9730 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
9731 // is true even though `2.5` has no bigint form.
9732 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
9733 let b = other.to_number();
9734 if b.is_nan() {
9735 None
9736 } else {
9737 compare_bigint_and_f64(a, b)
9738 }
9739 }
9740 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
9741 let a = other.to_number();
9742 if a.is_nan() {
9743 None
9744 } else {
9745 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
9746 }
9747 }
9748 _ => left.to_number().partial_cmp(&right.to_number()),
9749 };
9750 Ok(ordering_answer(op, ordering))
9751 }
9752
9753 fn binary_add(&mut self) -> JsResult<()> {
9754 let right = self.pop();
9755 let left = self.pop();
9756 // Two integers add without any of the machinery below: no `ToPrimitive` (an
9757 // `Int` is already primitive), no string check, no bigint check, no allocation.
9758 // `x += 1` in a loop is the single most common instruction sequence in real
9759 // script, and it used to walk every one of those checks before reaching the
9760 // same `checked_add`.
9761 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
9762 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
9763 return Ok(());
9764 }
9765 let left = self.primitive_of(left)?;
9766 let right = self.primitive_of(right)?;
9767 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
9768 // that check comes before the bigint one: `"" + 1n` is a string, not a
9769 // mixed-type error.
9770 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
9771 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
9772 // `TypeError`, the one place a symbol and a string do not mix.
9773 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
9774 // between a copy and a rope from their lengths, and a rope is what turns
9775 // `text += "abc"` in a loop from quadratic into linear.
9776 if let (Value::String(left), Value::String(right)) = (&left, &right) {
9777 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
9778 // reports as `InternalError: string too long`.
9779 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
9780 return Err(Signal::Throw(
9781 self.make_error("InternalError", "string too long"),
9782 ));
9783 };
9784 self.push(Value::String(Gc::new(self.heap, joined)));
9785 return Ok(());
9786 }
9787 // At least one operand was not a string, so `ToString` it. This rejects a
9788 // symbol, which is the one place a symbol and a string do not mix.
9789 let left = self.checked_to_wtf8(&left)?;
9790 let right = self.checked_to_wtf8(&right)?;
9791 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
9792 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
9793 let text = left.concat(&right);
9794 self.push(self.string_wtf8(text));
9795 return Ok(());
9796 }
9797 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
9798 // not a conversion.
9799 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
9800 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
9801 self.push(value);
9802 return Ok(());
9803 }
9804 let left = self.numeric(left)?;
9805 let right = self.numeric(right)?;
9806 self.push(add_numbers(left, right));
9807 Ok(())
9808 }
9809
9810 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
9811 self.to_primitive(value, Hint::Default)
9812 }
9813
9814 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
9815 ///
9816 /// The order depends on the hint: the "number" order tries `valueOf` first and
9817 /// `toString` second, the "string" order the other way round, and the default
9818 /// hint uses the number order. A result that is still an object is a `TypeError`,
9819 /// because no built-in `valueOf`/`toString` returns one.
9820 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
9821 let Value::Object(object) = &value else {
9822 return Ok(value);
9823 };
9824 // A Date overrides the default hint to mean "string", which is what
9825 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
9826 // this, `"" + new Date()` would print the milliseconds, not the date.
9827 let hint = if hint == Hint::Default && is_date_object(self, object) {
9828 Hint::String
9829 } else {
9830 hint
9831 };
9832 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
9833 // handed the hint as a string. This is the hook a Date uses for its default hint
9834 // and a script uses to take over conversion entirely.
9835 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
9836 if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
9837 if !function.is_callable() {
9838 return Err(self.type_error("Symbol.toPrimitive is not a function"));
9839 }
9840 let hint = match hint {
9841 Hint::String => "string",
9842 Hint::Number => "number",
9843 Hint::Default => "default",
9844 };
9845 let hint = self.string(hint);
9846 let result = self.call_value(
9847 Value::Object(function),
9848 Value::Object(object.clone()),
9849 vec![hint],
9850 )?;
9851 if matches!(result, Value::Object(_)) {
9852 return Err(self.type_error("cannot convert object to primitive value"));
9853 }
9854 return Ok(result);
9855 }
9856 let order: [&str; 2] = match hint {
9857 Hint::String => ["toString", "valueOf"],
9858 Hint::Number | Hint::Default => ["valueOf", "toString"],
9859 };
9860 let receiver = object.clone();
9861 for method in order {
9862 if let Some(function) = self.get_property(&receiver, method)?
9863 && matches!(&function, Value::Object(object) if object.is_callable())
9864 {
9865 let result =
9866 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
9867 if !matches!(result, Value::Object(_)) {
9868 return Ok(result);
9869 }
9870 }
9871 }
9872 Err(self.type_error("cannot convert object to primitive value"))
9873 }
9874
9875 /// `ToString` with the object case going through `ToPrimitive`.
9876 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
9877 if matches!(value, Value::Object(_)) {
9878 let primitive = self.to_primitive(value.clone(), Hint::String)?;
9879 return Ok(primitive.to_js_string());
9880 }
9881 Ok(value.to_js_string())
9882 }
9883
9884 /// `ToString` that keeps the string's code units instead of flattening them.
9885 ///
9886 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
9887 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
9888 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
9889 if matches!(value, Value::Symbol(_)) {
9890 return Err(Signal::Throw(
9891 self.make_error("TypeError", "cannot convert symbol to string"),
9892 ));
9893 }
9894 // An object runs `ToPrimitive` first, which may itself produce a symbol.
9895 let value = self.to_primitive(value.clone(), Hint::String)?;
9896 match value {
9897 Value::Symbol(_) => Err(Signal::Throw(
9898 self.make_error("TypeError", "cannot convert symbol to string"),
9899 )),
9900 Value::String(text) => Ok(text.wtf8().clone()),
9901 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
9902 }
9903 }
9904
9905 /// `ToNumber` with the object case going through `ToPrimitive`.
9906 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
9907 let value = if matches!(value, Value::Object(_)) {
9908 self.to_primitive(value.clone(), Hint::Number)?
9909 } else {
9910 value.clone()
9911 };
9912 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
9913 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
9914 // `NaN` to stay total, and the operators check for the bigint themselves — but
9915 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
9916 // refuse, and answering `NaN` made them silently wrong instead.
9917 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
9918 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
9919 match value {
9920 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
9921 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
9922 other => Ok(other.to_number()),
9923 }
9924 }
9925
9926 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
9927 /// [`ElementType::write`].
9928 ///
9929 /// This is separated from the write because both conversions are observable script —
9930 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
9931 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
9932 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
9933 /// setters, and a plain `a[i] = v`.
9934 pub(crate) fn element_value(
9935 &mut self,
9936 element: crate::builtins::typedarray::ElementType,
9937 value: Value,
9938 ) -> JsResult<Value> {
9939 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
9940 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
9941 let primitive = match &value {
9942 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
9943 _ => value,
9944 };
9945 if element.is_bigint() {
9946 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
9947 Ok(Value::BigInt(Gc::new(self.heap, big)))
9948 } else {
9949 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
9950 Ok(Value::Float(self.to_js_number(&primitive)?))
9951 }
9952 }
9953
9954 /// `ToPropertyKey`: what a computed member access uses as its key.
9955 ///
9956 /// A symbol is returned as itself, never stringified — that is what keeps
9957 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
9958 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
9959 match value {
9960 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
9961 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
9962 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
9963 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
9964 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
9965 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
9966 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
9967 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
9968 other.to_js_string(),
9969 ))),
9970 },
9971 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
9972 }
9973 }
9974
9975 /// `ToPropertyKey` for the callers that can only use a string key.
9976 ///
9977 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
9978 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
9979 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
9980 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
9981 /// program continues with a value nobody asked for.
9982 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
9983 use crate::value::Wtf8;
9984 Ok(match value {
9985 // A string key keeps its code units. Going through a lossy `String` would make
9986 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
9987 Value::String(text) => text.wtf8().clone(),
9988 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
9989 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
9990 // falling back to its `ToString` would print `[object Object]`.
9991 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
9992 Value::String(text) => text.wtf8().clone(),
9993 other => Wtf8::new(other.to_js_string()),
9994 },
9995 other => Wtf8::new(other.to_js_string()),
9996 })
9997 }
9998
9999 // -- object operations used by instructions -----------------------------
10000
10001 /// Read `object[key]`, returning `undefined` when the property is missing.
10002 ///
10003 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
10004 /// primitive (looking through its prototype) as well as an object — which is what
10005 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
10006 /// argument needs too.
10007 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
10008 self.read_field_key(object, &PropertyKey::from(key))
10009 }
10010
10011 /// [`Interp::read_field`] with a key that may be a symbol.
10012 ///
10013 /// A symbol key never reaches the string shortcuts: a string's `length` and its
10014 /// indices are string properties, and a symbol named `length` is a different
10015 /// property that a string primitive cannot have.
10016 /// [`Interp::read_field_key`], with an inline cache in front of it.
10017 ///
10018 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
10019 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
10020 /// without this the engine walked the chain and compared ~40 property names on each
10021 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
10022 ///
10023 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
10024 /// missing property. Those answers depend on running code or on state the guard below
10025 /// does not cover, and a wrong answer here is far more expensive than a lookup.
10026 ///
10027 /// A hit is re-validated against the *whole* walked chain, not just the level that
10028 /// answered: the receiver and every prototype down to that level must still be the same
10029 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
10030 /// property-table *lengths* — which is what catches a property appearing on an
10031 /// intermediate prototype and shadowing the cached one.
10032 pub fn read_field_cached(
10033 &mut self,
10034 object: &Value,
10035 key: &PropertyKey,
10036 slot: usize,
10037 ) -> JsResult<Value> {
10038 let index = Self::field_cache_slot(object, key, slot);
10039 let Value::Object(target) = object else {
10040 return self.read_field_key(object, key);
10041 };
10042 if target.proxy_state().is_some() {
10043 return self.read_field_key(object, key);
10044 }
10045 if let Some(cached) = &self.field_cache[index]
10046 && cached.key == *key
10047 && let Some(value) = Self::cached_hit(target, cached)
10048 {
10049 return Ok(value);
10050 }
10051 let value = self.read_field_key(object, key)?;
10052 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
10053 Ok(value)
10054 }
10055
10056 /// Whether a cache entry still describes this lookup, and if so the value.
10057 ///
10058 /// The guard is the whole point of the entry: identity plus property-table length for
10059 /// every level walked. Re-checked per level rather than once at the receiving end,
10060 /// because a shadowing property can appear anywhere along the chain.
10061 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
10062 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
10063 // starts with: a clone is a reference-count bump and a drop, and for
10064 // `property:monomorphic` every single hit takes only this arm.
10065 let (weak, len) = cached.chain[0].as_ref()?;
10066 if !target.upgrades_to(weak) {
10067 return None;
10068 }
10069 if cached.level == 0 {
10070 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
10071 return target.cached_property_at(cached.index, &cached.key, *len);
10072 }
10073 if target.props_len() != *len {
10074 return None;
10075 }
10076 let mut level = 1;
10077 let mut current = target.proto()?;
10078 loop {
10079 let (weak, len) = cached.chain[level].as_ref()?;
10080 if !current.upgrades_to(weak) || current.props_len() != *len {
10081 return None;
10082 }
10083 if level == cached.level as usize {
10084 // The level that answered: the value is only reusable while the key is
10085 // still there and still a plain data property.
10086 return current.cached_data_property(cached.index, &cached.key);
10087 }
10088 current = current.proto()?;
10089 level += 1;
10090 }
10091 }
10092
10093 /// Build a cache entry for a lookup that just went through the slow path.
10094 ///
10095 /// Records the chain only when the answer came from a plain data property at a level
10096 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
10097 /// costs the next lookup the walk it would have cost anyway.
10098 fn record_field_lookup(
10099 target: &Gc<JsObject>,
10100 key: &PropertyKey,
10101 _value: Value,
10102 ) -> Option<FieldCache> {
10103 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
10104 [None, None, None];
10105 let mut current = target.clone();
10106 for level in 0..MAX_CACHED_CHAIN {
10107 chain[level] = Some((current.downgrade(), current.props_len()));
10108 if let Some((found, _)) = current.own_property_index(key) {
10109 // `own_property_index` declines an accessor and a hole, which is exactly
10110 // the set that must not be cached.
10111 return Some(FieldCache {
10112 key: key.clone(),
10113 index: found,
10114 level: level as u8,
10115 chain,
10116 });
10117 }
10118 current = current.proto()?;
10119 }
10120 None
10121 }
10122
10123 /// Which cache slot a lookup uses.
10124 ///
10125 /// Mixes the object's address, the name and the site, so that two properties of one
10126 /// object, and one property of two objects, land in different slots — which is what lets
10127 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
10128 /// other iteration.
10129 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
10130 let mut hash = match object {
10131 Value::Object(object) => object.address(),
10132 _ => 0,
10133 };
10134 hash = hash
10135 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
10136 .rotate_left(17)
10137 .wrapping_add(key.hash_code());
10138 hash = hash.wrapping_add(site.wrapping_mul(31));
10139 // The table is a power of two, so the low bits are the slot.
10140 hash & (FIELD_CACHE_SLOTS - 1)
10141 }
10142
10143 /// Read `key` from `object`, without the inline cache.
10144 ///
10145 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
10146 /// prototype chain, while the cached form answers an own data property from memory.
10147 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
10148 let text = key.as_str().unwrap_or("");
10149 let Value::Object(object) = object else {
10150 // Reading a property of `undefined`/`null` is the classic TypeError.
10151 if object.is_nullish() {
10152 return Err(Signal::Throw(self.make_error(
10153 "TypeError",
10154 &format!("cannot read property '{key}' of {}", object.to_js_string()),
10155 )));
10156 }
10157 // A string has `length` and index access without being boxed.
10158 if let Value::String(value) = object {
10159 if text == "length" {
10160 return Ok(Value::Int(value.utf16_len() as i32));
10161 }
10162 if let Some(index) = array_index(text) {
10163 return Ok(match value.wtf8().unit_at(index as usize) {
10164 Some(unit) => self.string_wtf8(unit),
10165 None => Value::Undefined,
10166 });
10167 }
10168 }
10169 // A property of a primitive is looked up on its prototype: this is what
10170 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
10171 let prototype = match object {
10172 Value::String(_) => self.realm.string_proto.clone(),
10173 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
10174 Value::Bool(_) => self.realm.boolean_proto.clone(),
10175 // A symbol's methods live on `Symbol.prototype`, reached the same way —
10176 // `sym.description` reads through the prototype, not off the symbol.
10177 Value::Symbol(_) => self.realm.symbol_proto.clone(),
10178 // …and a bigint's on `BigInt.prototype`, which is how
10179 // `(255n).toString(16)` reaches its method.
10180 Value::BigInt(_) => self.realm.bigint_proto.clone(),
10181 _ => None,
10182 };
10183 if let Some(prototype) = prototype
10184 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
10185 {
10186 return Ok(value);
10187 }
10188 return Ok(Value::Undefined);
10189 };
10190 Ok(self
10191 .get_property_key(object, key)?
10192 .unwrap_or(Value::Undefined))
10193 }
10194
10195 /// The `#name` a private symbol stands for, for error messages.
10196 ///
10197 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
10198 /// was made from.
10199 fn private_name(symbol: &Value) -> Option<String> {
10200 match symbol {
10201 Value::Symbol(symbol) if symbol.is_private() => Some(
10202 symbol
10203 .description()
10204 .map(|text| text.to_string())
10205 .unwrap_or_default(),
10206 ),
10207 _ => None,
10208 }
10209 }
10210
10211 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
10212 ///
10213 /// Every private-field opcode takes the symbol the class stored in its own scope; a
10214 /// non-symbol here would be a compiler bug, and the reference guards it with
10215 /// `JS_ThrowTypeErrorNotASymbol`.
10216 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
10217 match symbol {
10218 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
10219 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
10220 }
10221 }
10222
10223 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
10224 ///
10225 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
10226 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
10227 /// would hit if the parser did not reject it first.
10228 fn define_private_field(
10229 &mut self,
10230 object: &Value,
10231 symbol: &Value,
10232 value: Value,
10233 ) -> JsResult<()> {
10234 let key = self.private_key(symbol)?;
10235 let Some(target) = object.as_object() else {
10236 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10237 };
10238 if !target.is_extensible() {
10239 return Err(Signal::Throw(
10240 self.make_error("TypeError", "object is not extensible"),
10241 ));
10242 }
10243 if target.own_property_key(&key).is_some() {
10244 let name = Self::private_name(symbol).unwrap_or_default();
10245 return Err(Signal::Throw(self.make_error(
10246 "TypeError",
10247 &format!("private class field '{name}' already exists"),
10248 )));
10249 }
10250 target.define_data_key(&key, value);
10251 Ok(())
10252 }
10253
10254 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
10255 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
10256 let key = self.private_key(symbol)?;
10257 let Some(target) = object.as_object() else {
10258 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10259 };
10260 match target.own_property_key(&key) {
10261 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
10262 None => {
10263 let name = Self::private_name(symbol).unwrap_or_default();
10264 Err(Signal::Throw(self.make_error(
10265 "TypeError",
10266 &format!("private class field '{name}' does not exist"),
10267 )))
10268 }
10269 }
10270 }
10271
10272 /// `JS_SetPrivateField`: the store half of the same rule.
10273 fn write_private_field(
10274 &mut self,
10275 object: &Value,
10276 symbol: &Value,
10277 value: Value,
10278 ) -> JsResult<()> {
10279 let key = self.private_key(symbol)?;
10280 let Some(target) = object.as_object() else {
10281 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10282 };
10283 if target.write_value_key(&key, value) {
10284 return Ok(());
10285 }
10286 let name = Self::private_name(symbol).unwrap_or_default();
10287 Err(Signal::Throw(self.make_error(
10288 "TypeError",
10289 &format!("private class field '{name}' does not exist"),
10290 )))
10291 }
10292
10293 /// The `in` half: does `object` have this private field?
10294 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
10295 ///
10296 /// The symbol is created once per class — the first `add_brand` on a given home object
10297 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
10298 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
10299 /// emit for the *instance* brand passes null because all it wants is the symbol.
10300 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
10301 let Some(home_object) = home.as_object() else {
10302 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10303 };
10304 let symbol = match home_object.private_brand() {
10305 Some(symbol) => symbol,
10306 None => {
10307 let symbol = Gc::new(
10308 self.heap,
10309 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
10310 );
10311 home_object.set_private_brand(symbol.clone());
10312 symbol
10313 }
10314 };
10315 let Some(target) = object.as_object() else {
10316 // Not an object: nothing to brand. The reference does the same, and `undefined`
10317 // here would otherwise turn a field initialiser into a TypeError.
10318 return Ok(());
10319 };
10320 if !target.is_extensible() {
10321 return Err(Signal::Throw(
10322 self.make_error("TypeError", "object is not extensible"),
10323 ));
10324 }
10325 if target.carries_brand(&symbol) {
10326 return Err(Signal::Throw(
10327 self.make_error("TypeError", "private method is already present"),
10328 ));
10329 }
10330 target.add_brand(symbol);
10331 Ok(())
10332 }
10333
10334 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
10335 ///
10336 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
10337 /// decides whether to throw.
10338 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
10339 let Some(function) = function.as_object() else {
10340 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10341 };
10342 let Some(home) = function.home_object() else {
10343 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
10344 };
10345 let Some(brand) = home.private_brand() else {
10346 return Err(Signal::Throw(
10347 self.make_error("TypeError", "expecting <brand> private field"),
10348 ));
10349 };
10350 Ok(object.carries_brand(&brand))
10351 }
10352
10353 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
10354 let Value::Object(object) = object else {
10355 return Err(Signal::Throw(self.make_error(
10356 "TypeError",
10357 &format!("cannot set property '{key}' of {}", object.to_js_string()),
10358 )));
10359 };
10360 // The write half of the property inline cache, in effect: an own, writable,
10361 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
10362 // decide — no prototype walk (an own property shadows the chain before a setter
10363 // there could matter), no extensibility check (the object already has the key),
10364 // and no `[[DefineOwnProperty]]`.
10365 //
10366 // `this.value = …` inside a method is the whole write side of
10367 // `property:method-call`, and it was reaching `set_property_with_key` with its
10368 // proxy test, its typed-array test, its array-index test and finally a linear
10369 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
10370 //
10371 // Every disqualifier is checked here: a proxy traps the set, an array index and
10372 // `length` live outside the property table, and a typed array's element is stored
10373 // through its view's element type.
10374 if object.proxy_state().is_none()
10375 && !object.is_array()
10376 && object.typed_array_element_type().is_none()
10377 && object.write_value_key(key, value.clone())
10378 {
10379 return Ok(());
10380 }
10381 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
10382 let on_failure = if self.frame().code.code.strict {
10383 DeleteFailure::Throw
10384 } else {
10385 DeleteFailure::Ignore
10386 };
10387 self.set_property_with_key(object, key, value, on_failure)
10388 }
10389
10390 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
10391 ///
10392 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
10393 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
10394 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
10395 /// `Number.parseInt(sym)` — so those callers use this instead.
10396 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
10397 if matches!(value, Value::Symbol(_)) {
10398 return Err(Signal::Throw(
10399 self.make_error("TypeError", "cannot convert symbol to string"),
10400 ));
10401 }
10402 // An object runs `ToPrimitive` first, which may itself produce a symbol —
10403 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
10404 let value = self.to_primitive(value.clone(), Hint::String)?;
10405 if matches!(value, Value::Symbol(_)) {
10406 return Err(Signal::Throw(
10407 self.make_error("TypeError", "cannot convert symbol to string"),
10408 ));
10409 }
10410 Ok(value.to_js_string())
10411 }
10412
10413 /// `ToPropertyKey` for a builtin that takes a key argument.
10414 ///
10415 /// Fallible: a key whose `toString` throws has to propagate that error, both for
10416 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
10417 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
10418 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
10419 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
10420 self.propkey(value)
10421 }
10422
10423 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
10424 ///
10425 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
10426 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
10427 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
10428 /// `RangeError` — and why this cannot be a plain `ToNumber`.
10429 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
10430 let number = match value {
10431 Value::Int(number) => *number as f64,
10432 Value::Float(number) => *number,
10433 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
10434 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
10435 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
10436 // reference answers 0.
10437 Value::Null | Value::Bool(_) => value.to_number(),
10438 _ => {
10439 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
10440 match primitive {
10441 Value::Int(number) => number as f64,
10442 Value::Float(number) => number,
10443 other => {
10444 // `ToString` then `ToNumber`, so a string length goes through the
10445 // full numeric-literal grammar: `"0x00B"` is 11 and `" 5 "` is 5.
10446 // `Value::to_number` on the string already implements exactly that.
10447 let text = self.to_js_string(&other)?;
10448 crate::value::string_to_number(&text)
10449 }
10450 }
10451 }
10452 };
10453 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
10454 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
10455 // is a `RangeError`, not `0`.
10456 if !number.is_finite()
10457 || number.fract() != 0.0
10458 || !(0.0..=u32::MAX as f64).contains(&number)
10459 {
10460 return Err(self.range_error("invalid array length"));
10461 }
10462 Ok(number as u32)
10463 }
10464
10465 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
10466 /// `Object.getOwnPropertySymbols` put in their result array.
10467 pub fn key_value(&self, key: &PropertyKey) -> Value {
10468 match key {
10469 PropertyKey::String(text) => self.string_wtf8(text.clone()),
10470 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
10471 }
10472 }
10473
10474 /// Fill in a String exotic object: `_value`, `length` and the index properties.
10475 ///
10476 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
10477 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
10478 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
10479 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
10480 /// the two paths had drifted; this is the one both now use.
10481 ///
10482 /// The indices are *code units*, so an astral character occupies two of them — the
10483 /// same rule `s.length` and `s[i]` follow.
10484 /// Give an already-created object the internal slot that makes it a wrapper of
10485 /// `value`, so the primitive's prototype methods work on it.
10486 ///
10487 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
10488 /// which are wrappers of their own type holding the empty value.
10489 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
10490 self.internal_set(object, "_value", value);
10491 }
10492
10493 pub(crate) fn init_string_wrapper(
10494 &mut self,
10495 object: &Gc<JsObject>,
10496 text: &Gc<crate::value::JsString>,
10497 ) {
10498 object.define(
10499 "length",
10500 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
10501 );
10502 for index in 0..text.utf16_len() {
10503 if let Some(unit) = text.wtf8().unit_at(index) {
10504 object.define(
10505 &index.to_string(),
10506 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
10507 Property::with_attributes(self.string_wtf8(unit), false, true),
10508 );
10509 }
10510 }
10511 object.define_key(
10512 &self.internal_slot("_value"),
10513 Property::with_attributes(Value::String(text.clone()), false, false),
10514 );
10515 }
10516
10517 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
10518 ///
10519 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
10520 /// throws. The wrapper carries its primitive in `_value` — the same slot
10521 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
10522 /// on a boxed value no constructor ever built.
10523 pub(crate) fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
10524 let (prototype, primitive) = match value {
10525 Value::Object(object) => return Ok(object.clone()),
10526 Value::String(text) => {
10527 let object = self.new_object(self.realm.string_proto.clone());
10528 self.init_string_wrapper(&object, text);
10529 return Ok(object);
10530 }
10531 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
10532 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
10533 // A symbol and a bigint box into wrappers whose methods live on
10534 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
10535 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
10536 // branch below instead produced an object with *no* prototype, so those
10537 // methods were unreachable on a box.
10538 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
10539 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
10540 Value::Undefined | Value::Null => {
10541 return Err(Signal::Throw(self.make_error(
10542 "TypeError",
10543 &format!("cannot convert {} to object", value.to_js_string()),
10544 )));
10545 }
10546 _ => (None, value.clone()),
10547 };
10548 let object = self.new_object(prototype);
10549 self.internal_set(&object, "_value", primitive);
10550 Ok(object)
10551 }
10552
10553 /// `a == b`, the coercing comparison.
10554 ///
10555 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
10556 /// which is what makes `[] == ""` true: `[]` becomes `""` via
10557 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
10558 /// because the conversion is allowed to call script code, so the two primitive
10559 /// operands are handed back to it.
10560 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
10561 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
10562 return Ok(left.loose_equals(&right));
10563 }
10564 // `null == undefined` holds even though neither is an object.
10565 if matches!(left, Value::Undefined | Value::Null)
10566 && matches!(right, Value::Undefined | Value::Null)
10567 {
10568 return Ok(true);
10569 }
10570 if matches!(left, Value::Undefined | Value::Null)
10571 || matches!(right, Value::Undefined | Value::Null)
10572 {
10573 return Ok(false);
10574 }
10575 // Two objects compare by identity. Only an object *against a primitive* is
10576 // converted, which is why `{} == {}` is false while `[] == ""` is true.
10577 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
10578 return Ok(a.ptr_eq(b));
10579 }
10580 let left = self.to_primitive(left, Hint::Default)?;
10581 let right = self.to_primitive(right, Hint::Default)?;
10582 Ok(left.loose_equals(&right))
10583 }
10584
10585 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
10586 let Value::Object(object) = object else {
10587 return Err(Signal::Throw(
10588 self.make_error("TypeError", "cannot use 'in' on a non-object"),
10589 ));
10590 };
10591 let key = self.propkey(key)?;
10592 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
10593 // trap. One implementation, so an array's derived `length` and its inherited holes
10594 // cannot be right in one caller and wrong in another.
10595 self.has_own_or_inherited(object, &key)
10596 }
10597
10598 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
10599 let Value::Object(target) = object else {
10600 return Ok(false);
10601 };
10602 let Value::Object(function) = constructor else {
10603 return Err(Signal::Throw(self.make_error(
10604 "TypeError",
10605 "right-hand side of 'instanceof' is not callable",
10606 )));
10607 };
10608 let prototype = self.get_property(function, "prototype")?;
10609 let Some(Value::Object(prototype)) = prototype else {
10610 return Ok(false);
10611 };
10612 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
10613 // which is also what makes `proxyOfInstance instanceof C` work.
10614 let mut current = Some(target.clone());
10615 while let Some(object) = current {
10616 if object.ptr_eq(&prototype) {
10617 return Ok(true);
10618 }
10619 current = self.object_prototype_of(&object)?;
10620 }
10621 Ok(false)
10622 }
10623
10624 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
10625 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
10626 if let Some(proto) = self.proxy_get_prototype_of(object)? {
10627 return Ok(proto);
10628 }
10629 Ok(object.proto())
10630 }
10631
10632 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
10633 pub fn object_set_prototype_of(
10634 &mut self,
10635 object: &Gc<JsObject>,
10636 proto: Option<Gc<JsObject>>,
10637 ) -> JsResult<bool> {
10638 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
10639 return Ok(answer);
10640 }
10641 object.set_proto(proto);
10642 Ok(true)
10643 }
10644
10645 /// `[[IsExtensible]]`, with the proxy trap when there is one.
10646 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
10647 if let Some(answer) = self.proxy_is_extensible(object)? {
10648 return Ok(answer);
10649 }
10650 Ok(object.is_extensible())
10651 }
10652
10653 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
10654 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
10655 if let Some(answer) = self.proxy_prevent_extensions(object)? {
10656 return Ok(answer);
10657 }
10658 object.set_extensible(false);
10659 Ok(true)
10660 }
10661
10662 fn copy_properties(
10663 &mut self,
10664 target: &Value,
10665 source: &Value,
10666 exclusion: &Value,
10667 ) -> JsResult<()> {
10668 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
10669 // does contribute: its index properties are own, enumerable and writable, which
10670 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
10671 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
10672 // is a no-op.
10673 let Some(target) = target.as_object() else {
10674 return Ok(());
10675 };
10676 let source_object = match source {
10677 Value::Object(object) => object.clone(),
10678 Value::String(text) => {
10679 // Untaken keys are the string's indices, which are code units.
10680 for index in 0..text.utf16_len() {
10681 if let Some(unit) = text.wtf8().unit_at(index) {
10682 target.define_data(&index.to_string(), self.string_wtf8(unit));
10683 }
10684 }
10685 return Ok(());
10686 }
10687 _ => return Ok(()),
10688 };
10689 // An object *rest* element passes the keys already taken by the literal part as
10690 // an array of strings; a spread passes `null`, which excludes nothing. Only the
10691 // string keys of the exclusion array are meaningful, so an array is read by its
10692 // elements rather than by its own property names.
10693 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
10694 if let Value::Object(list) = exclusion
10695 && let Some(length) = list.array_length()
10696 {
10697 for index in 0..length {
10698 if let Some(value) = list.array_get(index) {
10699 excluded.push(self.propkey_of(&value)?);
10700 }
10701 }
10702 }
10703 let source = &source_object;
10704 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
10705 // Reading the property table directly made every spread of a proxy empty.
10706 let keys = self.object_own_property_keys(source)?;
10707 for as_key in keys {
10708 if as_key.is_symbol() {
10709 // A spread copies string-keyed properties only.
10710 continue;
10711 }
10712 if excluded.contains(&crate::value::Wtf8::new(
10713 as_key.as_str().unwrap_or_default(),
10714 )) {
10715 continue;
10716 }
10717 let enumerable = self
10718 .object_get_own_property(source, &as_key)?
10719 .is_some_and(|property| property.enumerable);
10720 if !enumerable {
10721 continue;
10722 }
10723 let value = self
10724 .get_property_key(source, &as_key)?
10725 .unwrap_or(Value::Undefined);
10726 target.define_data_key(&as_key, value);
10727 }
10728 Ok(())
10729 }
10730
10731 // -- iteration ---------------------------------------------------------
10732
10733 /// One object's own keys in enumeration order: array indices ascending, then the
10734 /// rest in insertion order.
10735 ///
10736 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
10737 /// whether the key is enumerable, which the caller resolves per key because an
10738 /// array's elements are not in the same store as its named properties.
10739 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
10740 // An index can arrive twice, once from the array's element store and once from
10741 // its property map, so the numeric keys go through a map that keeps the
10742 // enumerable answer if either source gave one.
10743 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
10744 for (key, enumerable) in &own {
10745 if let Some(index) = key.as_str().and_then(array_index) {
10746 let entry = numeric.entry(index).or_insert(false);
10747 *entry = *entry || *enumerable;
10748 }
10749 }
10750 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
10751 .into_iter()
10752 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
10753 .collect();
10754 ordered.extend(
10755 own.into_iter()
10756 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
10757 );
10758 ordered
10759 }
10760
10761 /// Build the key list a `for-in` loop walks.
10762 ///
10763 /// The order is the specification's: own properties before inherited ones, and
10764 /// within one object the integer-like keys in ascending numeric order ahead of the
10765 /// string keys in insertion order. A shadowed key only appears once, and a key that
10766 /// is a non-enumerable own property anywhere nearer is skipped entirely.
10767 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
10768 let record = self.new_object(None);
10769 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
10770 // A proxy supplies its own key list, and — the reason this is not just another
10771 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
10772 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
10773 // descriptor there.
10774 if let Value::Object(object) = value
10775 && object.proxy_state().is_some()
10776 {
10777 let own = self
10778 .proxy_own_keys(object)?
10779 .unwrap_or_else(|| object.own_property_keys());
10780 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
10781 let mut numeric: Vec<u32> = Vec::new();
10782 let mut rest: Vec<PropertyKey> = Vec::new();
10783 for key in own {
10784 match key.as_str().and_then(array_index) {
10785 Some(index) => numeric.push(index),
10786 None => rest.push(key),
10787 }
10788 }
10789 numeric.sort_unstable();
10790 ordered.extend(
10791 numeric
10792 .into_iter()
10793 .map(|index| PropertyKey::from(index.to_string())),
10794 );
10795 ordered.extend(rest);
10796 for (index, key) in ordered.into_iter().enumerate() {
10797 record.define_data(&index.to_string(), self.key_value(&key));
10798 }
10799 record.define_data("__index", Value::Int(0));
10800 // The mark that makes `for_in_advance` re-ask the proxy per key.
10801 record.define_data("__proxy", Value::Object(object.clone()));
10802 return Ok(record);
10803 }
10804 if let Value::Object(object) = value {
10805 let mut chain = vec![object.clone()];
10806 chain.extend(object.chain());
10807 // Every own string key the walk has seen, enumerable or not. A
10808 // non-enumerable own property still hides a same-named enumerable one
10809 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
10810 // keeps `x` out of the loop even when the prototype has one.
10811 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
10812 for object in chain {
10813 let mut own: Vec<(crate::value::Wtf8, bool)> = object
10814 .own_property_keys()
10815 .iter()
10816 .filter_map(|key| key.as_wtf8().cloned())
10817 .map(|key| {
10818 let enumerable = object
10819 .own_property(&key.to_string_lossy())
10820 .map(|property| property.enumerable)
10821 .unwrap_or(false);
10822 (key, enumerable)
10823 })
10824 .collect();
10825 if let Some(length) = object.array_length() {
10826 own.retain(|(key, _)| key.as_str() != Some("length"));
10827 for index in 0..length {
10828 if object.array_get(index).is_some() {
10829 own.push((crate::value::Wtf8::new(index.to_string()), true));
10830 }
10831 }
10832 }
10833 // Integer-like keys come first in ascending order, then the rest in
10834 // insertion order — and the ordering is *per object*, not for the chain
10835 // as a whole: one pass over every collected key lifted a prototype's
10836 // `"4"` above the target's own `x`/`y`, which is not the order
10837 // `for…in` reports.
10838 for (key, enumerable) in Self::order_own_keys(own) {
10839 if visited.contains(&key) {
10840 continue;
10841 }
10842 visited.push(key.clone());
10843 if enumerable {
10844 keys.push(key);
10845 }
10846 }
10847 }
10848 }
10849 for (index, key) in keys.into_iter().enumerate() {
10850 record.define_data(&index.to_string(), self.string_wtf8(key));
10851 }
10852 record.define_data("__index", Value::Int(0));
10853 Ok(record)
10854 }
10855
10856 /// The next key of a `for…in` record, `None` when the loop is done.
10857 ///
10858 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
10859 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
10860 /// the loop reaches it, so a handler that stops reporting a key partway through drops
10861 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
10862 /// key the handler had already withdrawn.
10863 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
10864 let Value::Object(record) = record else {
10865 return Ok(None);
10866 };
10867 let proxy = record
10868 .own_property("__proxy")
10869 .and_then(|property| property.value);
10870 loop {
10871 let index = record
10872 .own_property("__index")
10873 .and_then(|property| property.value)
10874 .map(|value| value.to_int32())
10875 .unwrap_or(0);
10876 let Some(candidate) = record
10877 .own_property(&index.to_string())
10878 .and_then(|property| property.value)
10879 else {
10880 return Ok(None);
10881 };
10882 record.define_data("__index", Value::Int(index + 1));
10883 let text = candidate.to_js_string();
10884 let Some(Value::Object(proxy)) = &proxy else {
10885 return Ok(Some(text));
10886 };
10887 // The candidate is already a key string here, so the lookup does not need a
10888 // second `ToPropertyKey` conversion.
10889 let key = PropertyKey::from(text.as_str());
10890 let live = match self.proxy_get_own_property(proxy, &key)? {
10891 Some(descriptor) => descriptor,
10892 // Not a proxy after all, or it lost its state: fall back to the target.
10893 None => proxy.own_property_key(&key),
10894 };
10895 if live.is_some_and(|property| property.enumerable) {
10896 return Ok(Some(text));
10897 }
10898 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
10899 // next one.
10900 }
10901 }
10902
10903 /// The iterator for `for-of`: the object and its `next` method.
10904 ///
10905 /// An object that already carries a `next` method is used as it is — that is what
10906 /// `arr.values()` returns — and only arrays and strings get the built-in
10907 /// sequence iterator.
10908 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
10909 ///
10910 /// Callers that must choose between the iterable and the array-like protocol — the
10911 /// typed-array constructor is the main one — need to ask *before* committing to one.
10912 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
10913 let key = self.realm.well_known_key(WellKnown::Iterator);
10914 let method = self.read_field_key(value, &key)?;
10915 if matches!(method, Value::Undefined | Value::Null) {
10916 return Ok(false);
10917 }
10918 if !matches!(&method, Value::Object(object) if object.is_callable()) {
10919 return Err(Signal::Throw(
10920 self.make_error("TypeError", "Symbol.iterator is not callable"),
10921 ));
10922 }
10923 Ok(true)
10924 }
10925
10926 /// Collect everything an iterable yields, closing it if the walk is abandoned.
10927 ///
10928 /// The cap is a guard against a generator that never ends: an unbounded collect would
10929 /// be an out-of-memory abort rather than a catchable error.
10930 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
10931 const MAX_ITEMS: usize = 1 << 24;
10932 let iterator = self.get_iterator(value)?;
10933 let mut out = Vec::new();
10934 loop {
10935 let (element, done) = self.iterator_step(&iterator)?;
10936 if done {
10937 return Ok(out);
10938 }
10939 out.push(element);
10940 if out.len() > MAX_ITEMS {
10941 return Err(self.range_error("iterable is too long to collect"));
10942 }
10943 }
10944 }
10945
10946 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
10947 ///
10948 /// A native constructor calls this once it has validated its arguments, which is the
10949 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
10950 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
10951 /// never reached. The prototype comes from `new.target` when it is an object, and from
10952 /// `default_proto` otherwise.
10953 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
10954 let Some(target) = self.pending_new_target.clone() else {
10955 return Ok(self.new_object(Some(default_proto)));
10956 };
10957 let Some(target) = target.as_object().cloned() else {
10958 return Ok(self.new_object(Some(default_proto)));
10959 };
10960 let proto = match self.get_property(&target, "prototype")? {
10961 Some(Value::Object(proto)) => proto,
10962 _ => default_proto,
10963 };
10964 Ok(self.new_object(Some(proto)))
10965 }
10966
10967 /// Whether this call is a construction, i.e. `new.target` is defined.
10968 ///
10969 /// A native constructor receives `this = undefined` (it builds its own instance), so it
10970 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
10971 /// The native function currently executing, if any.
10972 pub fn current_native(&self) -> Option<Gc<JsObject>> {
10973 self.current_native.clone()
10974 }
10975
10976 /// Whether this call is a construction, i.e. `new.target` is defined.
10977 pub fn is_constructing(&self) -> bool {
10978 self.pending_new_target.is_some()
10979 }
10980
10981 /// The `TypeError` a constructor too primitive to have a wrapper raises.
10982 ///
10983 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
10984 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
10985 /// happens inside the native function, which is why the trace carries an
10986 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
10987 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
10988 /// constructor`, and an unnamed one reports the leading space of `" is not a
10989 /// constructor"` because the reference formats the empty name as it is.
10990 ///
10991 /// It is also the answer for a `new.target` that cannot be named at all — not a
10992 /// function, or a throwing `name` getter — where the reference falls back to the bare
10993 /// `not a constructor`.
10994 pub fn not_a_constructor_error(&mut self) -> Signal {
10995 let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
10996 self.not_a_constructor_error_for(target)
10997 }
10998
10999 /// The same `TypeError` for an explicit target, for the callers that check
11000 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
11001 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
11002 let target = match target {
11003 Value::Object(target) if target.is_callable() => target,
11004 _ => return self.type_error("not a constructor"),
11005 };
11006 let name = match self.get_property(&target, "name") {
11007 Ok(Some(value)) => value.to_js_string(),
11008 _ => return self.type_error("not a constructor"),
11009 };
11010 self.type_error(format!("{name} is not a constructor"))
11011 }
11012
11013 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
11014 ///
11015 /// True whenever `new.target` is not the callee itself, or when it has no usable
11016 /// `prototype` — the cases where reading the property is observable at all.
11017 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
11018 match &self.pending_new_target {
11019 Some(Value::Object(target)) => !target.ptr_eq(callee),
11020 Some(_) => true,
11021 None => false,
11022 }
11023 }
11024
11025 /// The symbol key for one of the engine's own hidden slots.
11026 ///
11027 /// Cached on the realm, so every object of a kind shares one key and a slot can be
11028 /// read back by name.
11029 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
11030 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
11031 return PropertyKey::Symbol(symbol.clone());
11032 }
11033 let symbol = Gc::new(
11034 self.heap,
11035 crate::value::JsSymbol::new(Some(name.to_string())),
11036 );
11037 self.realm
11038 .internal_slots
11039 .borrow_mut()
11040 .insert(name, Value::Symbol(symbol.clone()));
11041 PropertyKey::Symbol(symbol)
11042 }
11043
11044 /// Read a hidden slot, or `None` when the object has none of that name.
11045 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
11046 let slots = self.realm.internal_slots.borrow();
11047 let Value::Symbol(symbol) = slots.get(name)? else {
11048 return None;
11049 };
11050 object
11051 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
11052 .and_then(|property| property.value)
11053 }
11054
11055 /// Define a hidden slot.
11056 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
11057 let key = self.internal_slot(name);
11058 object.define_key(&key, Property::with_attributes(value, false, false));
11059 }
11060
11061 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
11062 ///
11063 /// The method is looked up on the value (through its prototype), called with no
11064 /// arguments, and its result becomes the iterator. A generator gets here through
11065 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
11066 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
11067 ///
11068 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
11069 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
11070 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
11071 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
11072 /// does, and a user-defined iterable works without a special case.
11073 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
11074 /// `Symbol.iterator`.
11075 ///
11076 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
11077 /// iterable is legal there, and each value it produces is simply already settled by
11078 /// the time the `await` around it runs.
11079 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
11080 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
11081 let method = self.read_field_key(value, &async_key)?;
11082 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
11083 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
11084 // is *present but not callable* is a TypeError — it does not mean "try the other
11085 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
11086 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
11087 // guard is there to catch.
11088 let absent = matches!(method, Value::Undefined | Value::Null);
11089 if !absent {
11090 let Value::Object(object) = &method else {
11091 return Err(Signal::Throw(
11092 self.make_error("TypeError", "value is not iterable"),
11093 ));
11094 };
11095 if !object.is_callable() {
11096 return Err(Signal::Throw(
11097 self.make_error("TypeError", "value is not iterable"),
11098 ));
11099 }
11100 }
11101 if absent {
11102 return self.get_iterator(value);
11103 }
11104 let iterator = self.call_value(method, value.clone(), Vec::new())?;
11105 if !matches!(iterator, Value::Object(_)) {
11106 return Err(Signal::Throw(
11107 self.make_error("TypeError", "iterator is not an object"),
11108 ));
11109 }
11110 let next = self.read_field(&iterator, "next")?;
11111 Ok(Iterator {
11112 object: iterator,
11113 next,
11114 })
11115 }
11116
11117 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
11118 let key = self.realm.well_known_key(WellKnown::Iterator);
11119 let method = self.read_field_key(value, &key)?;
11120 let Value::Object(function) = &method else {
11121 return Err(Signal::Throw(self.make_error(
11122 "TypeError",
11123 &format!("{} is not iterable", value.to_js_string()),
11124 )));
11125 };
11126 if !function.is_callable() {
11127 return Err(Signal::Throw(self.make_error(
11128 "TypeError",
11129 &format!("{} is not iterable", value.to_js_string()),
11130 )));
11131 }
11132 let iterator = self.call_value(method, value.clone(), Vec::new())?;
11133 // The spec requires an object here; a primitive iterator has no `next` to call
11134 // and would fail one step later with a confusing message.
11135 if !matches!(iterator, Value::Object(_)) {
11136 return Err(Signal::Throw(
11137 self.make_error("TypeError", "iterator is not an object"),
11138 ));
11139 }
11140 let next = self.read_field(&iterator, "next")?;
11141 Ok(Iterator {
11142 object: iterator,
11143 next,
11144 })
11145 }
11146
11147 /// Drain anything with a `Symbol.iterator` method, or answer `None` when the value is
11148 /// not iterable.
11149 ///
11150 /// Shared so that `Array.from`, the `Promise` combinators and `for…of` all agree on
11151 /// what "iterable" means. A `Map` and a `Set` have no `length`, so an array-like-only
11152 /// reader silently produced an empty array for both — `Array.from(new Set([1,2]))`
11153 /// was `[]`.
11154 pub fn iterable_values(&mut self, value: &Value) -> JsResult<Option<Vec<Value>>> {
11155 let key = self.realm.well_known_key(WellKnown::Iterator);
11156 let method = self.read_field_key(value, &key)?;
11157 if !matches!(&method, Value::Object(object) if object.is_callable()) {
11158 return Ok(None);
11159 }
11160 let iterator = self.get_iterator(value)?;
11161 let mut out = Vec::new();
11162 loop {
11163 let (element, done) = self.iterator_step(&iterator)?;
11164 if done {
11165 return Ok(Some(out));
11166 }
11167 out.push(element);
11168 }
11169 }
11170
11171 /// One step of an internal iterator: the value and whether it is exhausted.
11172 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
11173 // A real iterator (`next` is a function) answers with a result object.
11174 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
11175 let result =
11176 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
11177 let Some(result) = result.as_object().cloned() else {
11178 return Err(self.type_error("iterator result is not an object"));
11179 };
11180 let done = self
11181 .get_property(&result, "done")?
11182 .is_some_and(|value| value.to_boolean());
11183 let value = self
11184 .get_property(&result, "value")?
11185 .unwrap_or(Value::Undefined);
11186 return Ok((value, done));
11187 }
11188 // An iterator whose `next` is not callable is treated as exhausted, which is
11189 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
11190 // that are not iterable at all.
11191 Ok((Value::Undefined, true))
11192 }
11193
11194 /// `[...iterable]`: append everything the iterator yields, and answer the next
11195 /// index.
11196 ///
11197 /// This goes through the same iterator machinery `for-of` uses rather than copying
11198 /// an array's elements, because a spread source is any iterable: a string spreads
11199 /// into its characters and an array iterator spreads into its results. Handling
11200 /// only arrays made `[..."ab"]` come out empty with no error at all.
11201 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
11202 let Some(target) = array.as_object().cloned() else {
11203 return Ok(0);
11204 };
11205 let start = target.array_length().unwrap_or(0);
11206 let mut added = 0;
11207 let iterator = self.get_iterator(iterable)?;
11208 loop {
11209 let (value, done) = self.iterator_step(&iterator)?;
11210 if done {
11211 break;
11212 }
11213 target.array_set(self.heap, start + added, value);
11214 added += 1;
11215 }
11216 Ok((start + added) as i32)
11217 }
11218
11219 /// How an uncaught exception is reported.
11220 ///
11221 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
11222 /// with `ToString` — `js_std_dump_error` is three lines that end in
11223 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
11224 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
11225 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
11226 ///
11227 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
11228 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
11229 /// `toString`"; it does call it, but only for objects of a class it does not know how
11230 /// to walk, and never for errors, arrays or plain objects.
11231 ///
11232 /// A printer that fails must not take the reporter down with it, so that case falls
11233 /// back to the `ToString` rendering.
11234 pub fn describe_exception(&mut self, value: &Value) -> String {
11235 match crate::print::sprint(self, value) {
11236 Ok(text) => text,
11237 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
11238 }
11239 }
11240
11241 /// The file name of whatever is running, innermost frame first.
11242 ///
11243 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
11244 /// innermost frame's file name, without distinguishing a module body from a plain
11245 /// script. `import()` uses it as the base for a relative specifier, which is why
11246 /// `import('./x.js')` inside a script resolves next to the script and not next to the
11247 /// process's working directory.
11248 pub fn script_or_module_name(&self) -> Option<String> {
11249 self.frames
11250 .iter()
11251 .rev()
11252 .find_map(|frame| frame.code.code.filename.clone())
11253 }
11254
11255 /// The current call stack, formatted the way `qjs` prints `error.stack`.
11256 ///
11257 /// One ` at name (file:line:col)` line per active frame, innermost first. The
11258 /// position is the one recorded for the instruction each frame is stopped on, which
11259 /// is why the compiler builds a pc-to-position table per function: without it a
11260 /// trace could only name the function, not the line inside it.
11261 ///
11262 /// A frame whose code has no positions prints just `(file)`, matching the
11263 /// reference's output for stripped bytecode.
11264 pub fn stack_trace(&self) -> String {
11265 self.stack_trace_skipping(0)
11266 }
11267
11268 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
11269 fn stack_trace_skipping(&self, skip: usize) -> String {
11270 // One ordered list, innermost first, so `skip` counts the same thing whether the
11271 // frames it leaves out are native or bytecode. Indices rather than references: a
11272 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
11273 let depth = self.frames.len();
11274 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
11275 // A native entered while `at` bytecode frames were live was called *from* the
11276 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
11277 // entered at the current depth are therefore innermost of all.
11278 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
11279 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
11280 if *at == wanted {
11281 order.push((true, index));
11282 }
11283 }
11284 };
11285 push_natives(&mut order, depth);
11286 for index in (0..depth).rev() {
11287 order.push((false, index));
11288 push_natives(&mut order, index);
11289 }
11290 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
11291 // barrier. Natives entered at exactly the barrier depth are the eval entry point
11292 // itself (`evalScript (native)`), and the reference leaves those out too.
11293 if let Some(barrier) = self.trace_barriers.last().copied() {
11294 order.retain(|(is_native, index)| match is_native {
11295 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
11296 false => *index >= barrier,
11297 });
11298 }
11299
11300 let mut out = String::new();
11301 for (is_native, index) in order.into_iter().skip(skip) {
11302 match is_native {
11303 true => {
11304 out.push_str(" at ");
11305 let (native, _) = &self.native_frames[index];
11306 let name = native
11307 .own_property("name")
11308 .and_then(|property| property.value)
11309 .map(|value| value.to_js_string())
11310 .unwrap_or_default();
11311 out.push_str(&name);
11312 out.push_str(" (native)\n");
11313 }
11314 false => {
11315 let frame = &self.frames[index];
11316 let code = &frame.code.code;
11317 let file = code.filename.as_deref().unwrap_or("<input>");
11318 // The name comes from the function *object*, not from the compiled code:
11319 // an anonymous function expression is named by the property it is stored
11320 // in (`{valueOf: function(){}}`), which only the object knows.
11321 let bound_name = match &frame.callee {
11322 Value::Object(object) => {
11323 object
11324 .own_property("name")
11325 .and_then(|property| match property.value {
11326 Some(Value::String(text)) if !text.wtf8().is_empty() => {
11327 Some(text.to_string_lossy().into_owned())
11328 }
11329 _ => None,
11330 })
11331 }
11332 _ => None,
11333 };
11334 // No callee object means the body was entered by the host, so the
11335 // name has to come from the compiled code. Two cases differ:
11336 //
11337 // * an *unnamed* function of any kind — the reference reads the
11338 // `name` property, finds it empty, and prints `<anonymous>`;
11339 // * a *module* body, which has no `name` property at all: the
11340 // reference builds that function object with `js_closure2` and
11341 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
11342 // so a trace reaching it also prints `<anonymous>` — while a
11343 // *script* body prints `<eval>`, its `name`.
11344 let unnamed = code.name.is_empty() || code.module.is_some();
11345 out.push_str(" at ");
11346 match bound_name.as_deref() {
11347 Some(name) => out.push_str(name),
11348 None if unnamed => out.push_str("<anonymous>"),
11349 None => out.push_str(&code.name),
11350 }
11351 match code.position_at(frame.at as u32) {
11352 Some((line, column)) => {
11353 out.push_str(&format!(" ({file}:{line}:{column})\n"));
11354 }
11355 None => out.push_str(&format!(" ({file})\n")),
11356 }
11357 }
11358 }
11359 }
11360 out
11361 }
11362
11363 /// Give an anonymous function the name of the property it is stored in.
11364 ///
11365 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
11366 /// enumerable and not configurable, and a function that already has a real name
11367 /// keeps it.
11368 ///
11369 /// "Already named" means a *non-empty* name: every function object is created with
11370 /// a `name` of `""` so the property exists on all of them, and treating that empty
11371 /// string as a name left every anonymous function nameless — which is how a stack
11372 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
11373 fn set_function_name(&mut self, function: &Value, name: &str) {
11374 let Value::Object(object) = function else {
11375 return;
11376 };
11377 // `SetFunctionName` applies to *functions* and classes only, and only when they are
11378 // anonymous. Without the callability guard, `{value: someObject}` renamed
11379 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
11380 // on the right-hand side of a property. That is how a `zipKeyed` result object
11381 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
11382 // has no `NamedEvaluation` at all.
11383 if !object.is_callable() {
11384 return;
11385 }
11386 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
11387 && !existing.wtf8().is_empty()
11388 {
11389 return;
11390 }
11391 let text = self.string(name);
11392 object.define("name", Property::name_or_length(text));
11393 }
11394
11395 // -- global declarations -----------------------------------------------
11396
11397 /// Declare a global binding, creating its reference cell.
11398 /// Declare a `var` or function global, whose home is the global object.
11399 ///
11400 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
11401 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
11402 /// such as `print`, or a redeclaration — is left alone.
11403 pub fn declare_var_global(&mut self, name: &str) {
11404 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
11405 // global object is exactly the leak `typeof my_var === "undefined"` after
11406 // `eval("var my_var=2")` rules out.
11407 if let Some(scope) = self.eval_scope.as_mut() {
11408 scope.entry(name.to_string()).or_insert(Value::Undefined);
11409 return;
11410 }
11411 // A sloppy direct eval declares into its *caller's* variable environment. Doing
11412 // this on the global object instead made `eval("var c = 1")` inside a parameter
11413 // list overwrite a global `c`, and made two calls to the same function share one
11414 // binding.
11415 if let Some(cell) = self.declare_eval_local(name) {
11416 cell.set(Value::Undefined);
11417 return;
11418 }
11419 let global = self.realm.global.clone();
11420 if global.own_property(name).is_some() {
11421 return;
11422 }
11423 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
11424 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
11425 // whole point of that trick and what lets `Object.defineProperty` reshape it
11426 // afterwards. `eval_scope` is `Some` while an eval is running.
11427 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
11428 global.define(
11429 name,
11430 Property {
11431 value: Some(Value::Undefined),
11432 writable: true,
11433 enumerable: true,
11434 configurable: from_eval,
11435 ..Property::default()
11436 },
11437 );
11438 }
11439
11440 /// Declare a *lexical* global binding, which starts in its dead zone.
11441 ///
11442 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
11443 /// global object and is created when its initialiser runs.
11444 pub fn declare_global(&mut self, name: &str, is_const: bool) {
11445 if is_const {
11446 self.realm.lexical_consts.insert(name.to_string());
11447 }
11448 if !self.realm.globals.contains_key(name) {
11449 // `Uninitialized` rather than `Undefined`: the binding exists but is not
11450 // readable until its initialiser runs, and that is what `let x` before
11451 // `x = 1` has to observe.
11452 let cell = self.new_cell(Value::Uninitialized);
11453 self.realm.globals.insert(name.to_string(), cell);
11454 self.realm.declared.push(name.to_string());
11455 }
11456 }
11457}
11458
11459/// The bytecode and environment of a function object, if it is a bytecode function.
11460///
11461/// Extracted before a call so no borrow of the object is held across it.
11462fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
11463 function.with(|data| match &data.kind {
11464 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
11465 _ => None,
11466 })
11467}
11468
11469/// A native call target, extracted before the call so no borrow is held.
11470enum NativeCall {
11471 Native(NativeFn),
11472 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
11473 /// not hold that object's `RefCell` borrow.
11474 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
11475 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
11476 Bound {
11477 target: Value,
11478 this: Value,
11479 leading: Vec<Value>,
11480 },
11481 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
11482 Revoker(crate::object::ProxyRef),
11483 /// A promise's `resolve`.
11484 PromiseResolve(Gc<JsObject>),
11485 /// A promise's `reject`.
11486 PromiseReject(Gc<JsObject>),
11487 /// One continuation of an `await`.
11488 AwaitResume {
11489 coroutine: Gc<JsObject>,
11490 promise: Gc<JsObject>,
11491 kind: ResumeKind,
11492 },
11493 /// One element of a `Promise` combinator settling.
11494 CombinatorSettle {
11495 state: Gc<JsObject>,
11496 index: usize,
11497 fulfilled: bool,
11498 },
11499 /// One of `Promise.prototype.finally`'s two shims.
11500 FinallyShim {
11501 callback: Option<Value>,
11502 fulfilled: bool,
11503 },
11504 /// Settle a promise with a fixed outcome.
11505 SettlePromise {
11506 promise: Gc<JsObject>,
11507 value: Value,
11508 rejected: bool,
11509 },
11510 /// Continue an async generator after its `await` settled.
11511 GeneratorResume {
11512 generator: Gc<JsObject>,
11513 promise: Gc<JsObject>,
11514 kind: ResumeKind,
11515 },
11516 /// Read a module namespace's binding out of its cell.
11517 ModuleBinding(Gc<Cell>),
11518 /// Finish a completed async generator's `return(v)` once `v` has settled.
11519 CompletedReturn {
11520 generator: Gc<JsObject>,
11521 promise: Gc<JsObject>,
11522 rejected: bool,
11523 },
11524 /// Answer a pending async-generator method with `{value, done}`.
11525 YieldResult {
11526 generator: Gc<JsObject>,
11527 promise: Gc<JsObject>,
11528 done: bool,
11529 },
11530 /// One step of `AsyncDisposableStack.disposeAsync`.
11531 DisposeStep {
11532 remaining: Gc<JsObject>,
11533 promise: Gc<JsObject>,
11534 error: Value,
11535 rejected: bool,
11536 },
11537}
11538
11539/// What a store does when the object refuses the write.
11540#[derive(Clone, Copy, PartialEq, Eq)]
11541pub enum DeleteFailure {
11542 /// Raise a `TypeError`, which is what strict mode and every built-in does.
11543 Throw,
11544 /// Ignore the write, which is what a sloppy-mode assignment does.
11545 Ignore,
11546}
11547
11548/// Whether `object` is a `Date` instance, by the class tag it carries.
11549///
11550/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
11551/// builtins module depending on the interpreter's conversion order.
11552fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
11553 interp
11554 .internal_get(object, "_class")
11555 .is_some_and(|value| value.to_js_string() == "Date")
11556}
11557
11558/// Which type `ToPrimitive` prefers when it converts an object.
11559#[derive(Clone, Copy, PartialEq, Eq)]
11560pub enum Hint {
11561 /// The default hint, which behaves like [`Hint::Number`].
11562 Default,
11563 /// `Number(obj)` and the arithmetic operators.
11564 Number,
11565 /// `String(obj)` and `ToPropertyKey`.
11566 String,
11567}
11568
11569/// Which table a binding slot indexes, for the messages that name it.
11570#[derive(Clone, Copy)]
11571enum VarSlot {
11572 Loc,
11573 Closure,
11574}
11575
11576/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
11577fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
11578 Ok(this)
11579}
11580
11581/// An internal iterator: the sequence plus a cursor.
11582pub(crate) struct Iterator {
11583 pub(crate) object: Value,
11584 pub(crate) next: Value,
11585}
11586
11587/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
11588/// and plain `a` for a method.
11589///
11590/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
11591/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
11592/// reads `at get a (file:1:2)`.
11593fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
11594 match flags & 3 {
11595 1 => format!("get {key}"),
11596 2 => format!("set {key}"),
11597 _ => key.to_string(),
11598 }
11599}
11600
11601/// Define a method or accessor property, per the `define_method` flag byte.
11602///
11603/// The low two bits pick value/getter/setter and bit 2 marks the property
11604/// enumerable.
11605///
11606/// A getter and a setter arrive as two separate `define_method` instructions, and the
11607/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
11608/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
11609/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
11610/// `JS_DefineProperty`, which leaves the other half alone.
11611fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
11612 let enumerable = flags & 4 != 0;
11613 let kind = flags & 3;
11614 let existing = object.own_property_key(key);
11615 let property = match kind {
11616 1 => Property {
11617 getter: Some(function),
11618 // The setter half, if this literal already defined one.
11619 setter: existing
11620 .filter(Property::is_accessor)
11621 .and_then(|p| p.setter),
11622 enumerable,
11623 configurable: true,
11624 ..Property::default()
11625 },
11626 2 => Property {
11627 getter: existing
11628 .filter(Property::is_accessor)
11629 .and_then(|p| p.getter),
11630 setter: Some(function),
11631 enumerable,
11632 configurable: true,
11633 ..Property::default()
11634 },
11635 _ => Property {
11636 value: Some(function),
11637 writable: true,
11638 enumerable,
11639 configurable: true,
11640 ..Property::default()
11641 },
11642 };
11643 object.define_key(key, property);
11644}
11645
11646// ---------------------------------------------------------------------------
11647// Operand decoding
11648// ---------------------------------------------------------------------------
11649
11650/// How `print` renders a value: the reference's `JS_PrintValue`.
11651///
11652/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
11653/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
11654/// The format is reproduced closely because the test suite compares output text:
11655///
11656/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
11657/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
11658/// * a cycle prints `[circular N]` with `N` the stack index of the object;
11659/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
11660/// end print as `<N empty item(s)>`;
11661/// * a string is quoted inside a container but raw at the top level, which is why
11662/// `print("x")` and `print(["x"])` differ.
11663pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
11664 // A string argument is printed raw: `js_print` converts it with `ToString`
11665 // instead of dumping it, and the quoting only appears inside a container.
11666 if let Value::String(text) = value {
11667 return text.to_string_lossy().into_owned();
11668 }
11669 let mut printer = Printer {
11670 interp,
11671 out: String::new(),
11672 stack: Vec::new(),
11673 };
11674 printer.value(value, 0);
11675 printer.out
11676}
11677
11678/// The internal class name an object carries, when it has one.
11679fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
11680 interp
11681 .internal_get(object, "_class")
11682 .map(|value| value.to_js_string())
11683}
11684
11685/// A string property, looked up the way `GetProperty` does: own first, then the
11686/// prototype chain. Needed because the print formatter holds the interpreter
11687/// immutably and so cannot run getters.
11688fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
11689 let mut current = Some(object.clone());
11690 // Bounded, because a prototype cycle would otherwise loop forever.
11691 for _ in 0..100 {
11692 let node = current?;
11693 if let Some(property) = node.own_property(name)
11694 && let Some(value) = property.value
11695 {
11696 return Some(value.to_js_string());
11697 }
11698 current = node.with(|data| data.proto.clone());
11699 }
11700 None
11701}
11702
11703/// The `JS_PrintValue` state: output, and the objects currently being printed.
11704struct Printer<'a, 'rt> {
11705 /// Kept for the class-name lookups that typed arrays and `Date` will need.
11706 #[allow(dead_code)]
11707 interp: &'a Interp<'rt>,
11708 out: String,
11709 stack: Vec<Gc<JsObject>>,
11710}
11711
11712impl Printer<'_, '_> {
11713 /// Depth past which a container is summarised by its class name.
11714 const MAX_DEPTH: usize = 2;
11715
11716 fn value(&mut self, value: &Value, level: usize) {
11717 match value {
11718 Value::Undefined
11719 | Value::Uninitialized
11720 | Value::Hole
11721 | Value::CatchOffset(_)
11722 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
11723 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
11724 // The printer writes a bigint the way the language spells one, so a dump is
11725 // unambiguous about which kind of number it is showing.
11726 Value::BigInt(big) => {
11727 self.out.push_str(&big.to_decimal_string());
11728 self.out.push('n');
11729 }
11730 Value::Null => self.out.push_str("null"),
11731 Value::Bool(true) => self.out.push_str("true"),
11732 Value::Bool(false) => self.out.push_str("false"),
11733 Value::Int(number) => self.out.push_str(&number.to_string()),
11734 Value::Float(number) => {
11735 self.out
11736 .push_str(&crate::value::number_to_string_for_print(*number));
11737 }
11738 Value::String(text) => self.print_string(&text.to_string_lossy()),
11739 Value::Object(object) => self.object(object, level),
11740 }
11741 }
11742
11743 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
11744 // A cycle is reported rather than followed; the index is where the object
11745 // already sits in the print stack, which is what the reference shows.
11746 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
11747 self.out.push_str(&format!("[circular {index}]"));
11748 return;
11749 }
11750 if object.is_callable() {
11751 let name = object
11752 .own_property("name")
11753 .and_then(|property| property.value)
11754 .map(|value| value.to_js_string())
11755 .unwrap_or_default();
11756 if name.is_empty() {
11757 self.out.push_str("[Function (anonymous)]");
11758 } else {
11759 self.out.push_str(&format!("[Function {name}]"));
11760 }
11761 return;
11762 }
11763 if level >= Self::MAX_DEPTH {
11764 let class = if object.is_array() { "Array" } else { "Object" };
11765 self.out.push_str(&format!("[{class}]"));
11766 return;
11767 }
11768 // `Date` and `Error` print as themselves rather than as bags of properties:
11769 // the ISO string, and `Name: message` followed by the trace.
11770 if let Some(class) = class_of(self.interp, object) {
11771 if class == "Date" {
11772 self.date(object);
11773 return;
11774 }
11775 if class == "Error" {
11776 self.error(object);
11777 return;
11778 }
11779 }
11780 self.stack.push(object.clone());
11781 if object.is_array() {
11782 self.array(object, level);
11783 } else {
11784 self.plain_object(object, level);
11785 }
11786 self.stack.pop();
11787 }
11788
11789 /// A Date prints as its ISO string; an invalid one falls through to the plain
11790 /// object form, the way the reference falls back when `toISOString` throws.
11791 fn date(&mut self, object: &Gc<JsObject>) {
11792 let value = self
11793 .interp
11794 .internal_get(object, "_date_value")
11795 .map(|value| value.to_number());
11796 match value.and_then(crate::builtins::date::iso_string) {
11797 Some(text) => self.out.push_str(&text),
11798 None => self.plain_object(object, 0),
11799 }
11800 }
11801
11802 /// `Name: message`, then the trace with its trailing newline removed.
11803 fn error(&mut self, object: &Gc<JsObject>) {
11804 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
11805 self.out.push_str(&name);
11806 if let Some(message) = inherited(object, "message")
11807 && !message.is_empty()
11808 {
11809 self.out.push_str(": ");
11810 self.out.push_str(&message);
11811 }
11812 if let Some(stack) = inherited(object, "stack") {
11813 self.out.push('\n');
11814 self.out.push_str(stack.trim_end_matches('\n'));
11815 }
11816 }
11817
11818 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
11819 let elements = object.array_elements().unwrap_or_default();
11820 self.out.push_str("[ ");
11821 // An interior hole means the array is "sparse": the reference prints those
11822 // as `index: value` pairs and says nothing about the holes themselves, while
11823 // a hole run at the end becomes a single `<N empty items>` note.
11824 let last_present = elements
11825 .iter()
11826 .rposition(|value| !matches!(value, Value::Hole));
11827 let has_interior_hole = match last_present {
11828 Some(last) => elements[..last]
11829 .iter()
11830 .any(|value| matches!(value, Value::Hole)),
11831 None => false,
11832 };
11833 let mut first = true;
11834 if has_interior_hole {
11835 let mut index = 0;
11836 while index < elements.len() {
11837 let value = &elements[index];
11838 if matches!(value, Value::Hole) {
11839 index += 1;
11840 continue;
11841 }
11842 if !first {
11843 self.out.push_str(", ");
11844 }
11845 first = false;
11846 self.out.push_str(&format!("{index}: "));
11847 self.value(value, level + 1);
11848 index += 1;
11849 }
11850 } else {
11851 for (index, value) in elements.iter().enumerate() {
11852 if matches!(value, Value::Hole) {
11853 continue;
11854 }
11855 if !first {
11856 self.out.push_str(", ");
11857 }
11858 first = false;
11859 let _ = index;
11860 self.value(value, level + 1);
11861 }
11862 if let Some(last) = last_present {
11863 let trailing = elements.len() - last - 1;
11864 if trailing > 0 {
11865 if !first {
11866 self.out.push_str(", ");
11867 }
11868 self.out.push_str(&format!(
11869 "<{trailing} empty item{}>",
11870 if trailing > 1 { "s" } else { "" }
11871 ));
11872 }
11873 } else if !elements.is_empty() {
11874 let count = elements.len();
11875 self.out.push_str(&format!(
11876 "<{count} empty item{}>",
11877 if count > 1 { "s" } else { "" }
11878 ));
11879 }
11880 }
11881 self.out.push_str(" ]");
11882 }
11883
11884 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
11885 self.out.push_str("{ ");
11886 let mut first = true;
11887 for key in object.own_keys() {
11888 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
11889 continue;
11890 };
11891 if !property.enumerable {
11892 continue;
11893 }
11894 if !first {
11895 self.out.push_str(", ");
11896 }
11897 first = false;
11898 self.out
11899 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
11900 &key.to_string_lossy(),
11901 )));
11902 self.out.push_str(": ");
11903 // An accessor has no value to dump; the reference names the half that
11904 // exists instead of calling it.
11905 if property.is_accessor() {
11906 let text = match (property.getter.is_some(), property.setter.is_some()) {
11907 (true, true) => "[Getter/Setter]",
11908 (false, true) => "[Setter]",
11909 _ => "[Getter]",
11910 };
11911 self.out.push_str(text);
11912 } else {
11913 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
11914 }
11915 }
11916 self.out.push_str(" }");
11917 }
11918
11919 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
11920 fn print_string(&mut self, text: &str) {
11921 self.out.push('"');
11922 for character in text.chars() {
11923 match character {
11924 '"' => self.out.push_str("\\\""),
11925 '\\' => self.out.push_str("\\\\"),
11926 '\n' => self.out.push_str("\\n"),
11927 '\r' => self.out.push_str("\\r"),
11928 '\t' => self.out.push_str("\\t"),
11929 c if (c as u32) < 0x20 => {
11930 self.out.push_str(&format!("\\u{:04x}", c as u32));
11931 }
11932 c => self.out.push(c),
11933 }
11934 }
11935 self.out.push('"');
11936 }
11937}
11938
11939/// How `print` renders a value.
11940///
11941/// `ToString`, except that negative zero keeps its sign — the reference's host
11942/// printer does that while `String(-0)` is `"0"`.
11943pub fn display(value: &Value) -> String {
11944 match value {
11945 Value::Float(number) => crate::value::number_to_string_for_print(*number),
11946 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
11947 "undefined".to_string()
11948 }
11949 other => other.to_js_string(),
11950 }
11951}
11952
11953// ---------------------------------------------------------------------------
11954// Numeric operators
11955// ---------------------------------------------------------------------------
11956
11957/// `a + b` keeping the `Int` representation when it fits.
11958fn add_numbers(left: Value, right: Value) -> Value {
11959 match (&left, &right) {
11960 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
11961 Some(sum) => Value::Int(sum),
11962 None => Value::Float(*a as f64 + *b as f64),
11963 },
11964 _ => Value::Float(left.to_number() + right.to_number()),
11965 }
11966}
11967
11968/// The arithmetic operators other than `+`, which needs string concatenation.
11969fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
11970 use Opcode::*;
11971 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
11972 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
11973 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
11974 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
11975 return Ok(match op {
11976 And => Value::Int(x & y),
11977 Or => Value::Int(x | y),
11978 Xor => Value::Int(x ^ y),
11979 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
11980 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
11981 Shr => match (*x as u32) >> ((*y as u32) & 31) {
11982 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
11983 shifted => Value::Float(shifted as f64),
11984 },
11985 Sub => match x.checked_sub(*y) {
11986 Some(value) => Value::Int(value),
11987 None => Value::Float(*x as f64 - *y as f64),
11988 },
11989 _ => return arithmetic_slow(op, left, right),
11990 });
11991 }
11992 arithmetic_slow(op, left, right)
11993}
11994
11995/// [`arithmetic`] for everything the integer fast path above does not take.
11996fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
11997 use Opcode::*;
11998 let (a, b) = (left.to_number(), right.to_number());
11999 Ok(match op {
12000 Sub => match (&left, &right) {
12001 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
12002 Some(value) => Value::Int(value),
12003 None => Value::Float(a - b),
12004 },
12005 _ => Value::Float(a - b),
12006 },
12007 Mul => Value::Float(a * b),
12008 Div => Value::Float(a / b),
12009 Mod => Value::Float(js_mod(a, b)),
12010 Pow => Value::Float(a.powf(b)),
12011 And => Value::Int(left.to_int32() & right.to_int32()),
12012 Or => Value::Int(left.to_int32() | right.to_int32()),
12013 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
12014 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
12015 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
12016 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
12017 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
12018 // fits the small-integer representation stays an `Int`; the rest become a
12019 // float, which is how the reference keeps `n >>> 0` non-negative.
12020 Shr => {
12021 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
12022 match i32::try_from(shifted) {
12023 Ok(value) => Value::Int(value),
12024 Err(_) => Value::Float(shifted as f64),
12025 }
12026 }
12027 _ => Value::Float(a),
12028 })
12029}
12030
12031/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
12032///
12033/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
12034/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
12035/// slow path where the rules live.
12036fn is_number(value: &Value) -> bool {
12037 matches!(value, Value::Int(_) | Value::Float(_))
12038}
12039
12040/// The `Value::Bool` a comparison operator answers for `ordering`.
12041///
12042/// `None` is the unordered case — a `NaN` on either side — and every operator answers
12043/// false for it, including `<=` and `>=`.
12044fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
12045 use Opcode::*;
12046 let answer = match (op, ordering) {
12047 (_, None) => false,
12048 (Lt, Some(ordering)) => ordering.is_lt(),
12049 (Lte, Some(ordering)) => ordering.is_le(),
12050 (Gt, Some(ordering)) => ordering.is_gt(),
12051 (Gte, Some(ordering)) => ordering.is_ge(),
12052 _ => false,
12053 };
12054 Value::Bool(answer)
12055}
12056
12057/// `%`, which follows the sign of the dividend rather than Rust's.
12058fn js_mod(left: f64, right: f64) -> f64 {
12059 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
12060 return f64::NAN;
12061 }
12062 if right.is_infinite() {
12063 return left;
12064 }
12065 let remainder = left % right;
12066 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
12067 // the spec makes the sign match the dividend.
12068 if remainder == 0.0 {
12069 0.0f64.copysign(left)
12070 } else {
12071 remainder
12072 }
12073}
12074
12075fn negate(value: Value) -> Value {
12076 match value {
12077 Value::Int(0) => Value::Float(-0.0),
12078 Value::Int(i) => Value::Int(-i),
12079 other => Value::Float(-other.to_number()),
12080 }
12081}
12082
12083fn increment(value: Value) -> Value {
12084 match value {
12085 Value::Int(i) => match i.checked_add(1) {
12086 Some(next) => Value::Int(next),
12087 None => Value::Float(i as f64 + 1.0),
12088 },
12089 other => Value::Float(other.to_number() + 1.0),
12090 }
12091}
12092
12093fn decrement(value: Value) -> Value {
12094 match value {
12095 Value::Int(i) => match i.checked_sub(1) {
12096 Some(next) => Value::Int(next),
12097 None => Value::Float(i as f64 - 1.0),
12098 },
12099 other => Value::Float(other.to_number() - 1.0),
12100 }
12101}
12102
12103/// Compare a `BigInt` with an `f64` on their mathematical values.
12104///
12105/// Neither side is rounded to the other's precision: the number is split into its integer
12106/// part (compared as an exact bigint) and its fraction, which is what decides the answer
12107/// when the integer parts are equal. An infinite value is larger than every bigint.
12108fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
12109 use std::cmp::Ordering;
12110 if number.is_nan() {
12111 return None;
12112 }
12113 if number.is_infinite() {
12114 return Some(if number > 0.0 {
12115 Ordering::Less
12116 } else {
12117 Ordering::Greater
12118 });
12119 }
12120 let truncated = number.trunc();
12121 // A number wider than `i128` still has an exact integer part, but no bigint form we can
12122 // build cheaply; the sign of the difference is all that is needed, so compare against
12123 // the bigint's own magnitude instead.
12124 if truncated.abs() >= 1.7e38 {
12125 let big_as_f64 = big.to_f64();
12126 return big_as_f64.partial_cmp(&number);
12127 }
12128 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
12129 match big.cmp(&integer) {
12130 Ordering::Equal => {
12131 // Same integer part: the fraction decides, and a negative number's fraction is
12132 // below the integer (`-1.5` truncates to `-1`).
12133 if number > truncated {
12134 Some(Ordering::Less)
12135 } else if number < truncated {
12136 Some(Ordering::Greater)
12137 } else {
12138 Some(Ordering::Equal)
12139 }
12140 }
12141 other => Some(other),
12142 }
12143}