quickjs/interp.rs
1//! The bytecode interpreter.
2//!
3//! The machine is the same shape as the reference's: a value stack per frame, a
4//! program counter into `js_compile`'s resolved bytecode, and a frame chain. Two
5//! properties of that design are worth stating up front because they are visible
6//! everywhere below.
7//!
8//! **Frames are explicit, not recursive.** A JavaScript call pushes a frame onto
9//! [`Interp::frames`] and the loop continues; it never recurses in Rust. Deep
10//! JavaScript recursion therefore costs heap, not C stack, and the depth limit is
11//! ours to enforce rather than the host's to crash.
12//!
13//! **Exceptions live on the value stack.** `catch` pushes a [`Value::CatchOffset`]
14//! marker and an exception is found by walking the frame's stack downwards looking
15//! for the innermost one. There is no side table, which is why a `try` inside a
16//! loop costs nothing until it throws.
17
18use std::collections::{BTreeMap, BTreeSet};
19
20use js_compile::bytecode::{Atom, ClosureType, Constant, Function as CompiledFunction};
21use js_compile::opcode::Opcode;
22use js_gc::{Gc, Heap, WeakGc};
23
24use crate::object::{
25 Callable, ClassDef, ClassId, ClosureEnv, CompiledCode, EvalScope, JsObject, LocalVars,
26 NativeFn, ObjectKind, Opaque, Property, PropertyKey, array_index, has_own, lookup_key,
27 lookup_key_above, same_proto,
28};
29use crate::value::{Cell, Value, number_to_string};
30
31/// Why execution stopped.
32#[derive(Debug, Clone)]
33pub enum Signal {
34 /// A JavaScript exception carrying the thrown value.
35 Throw(Value),
36 /// The runtime ran out of memory.
37 OutOfMemory,
38}
39
40/// What an execution step produced.
41pub type JsResult<T> = std::result::Result<T, Signal>;
42
43/// The result of one instruction.
44enum Step {
45 /// Keep executing the current frame.
46 Continue,
47 /// The current frame returned this value.
48 Return(Value),
49 /// The frame parked at a suspension point, with the yielded value on its stack.
50 ///
51 /// Only a generator or an async function can produce this, and only its own frame —
52 /// a nested ordinary call cannot contain a `yield`. The frame is not popped: it is
53 /// detached and handed to the generator object, which is what lets it resume later
54 /// with its locals and operand stack intact.
55 Suspend(SuspendKind),
56}
57
58/// Why a frame parked, which decides how the resumption is delivered.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum SuspendKind {
61 /// `initial_yield`: the body has not started. The first `next()` resumes *after* it
62 /// without passing a value, because there is no `yield` expression to receive one.
63 Initial,
64 /// `yield expr`: the value is on the stack and the caller gets `{value, done:false}`.
65 Yield,
66 /// `yield* expr` in a *sync* generator: like `Yield`, but the value is already an
67 /// `{value, done}` object from the inner iterator and is handed straight back.
68 YieldStar,
69 /// `yield* expr` in an *async* generator: the compiled shape extracts `.value` first, so
70 /// what was yielded is the plain value and still has to be awaited and wrapped —
71 /// `AsyncGeneratorYield` does `Await(value)` before handing it out. Sharing `YieldStar`
72 /// made it pass a bare value through as if it were an iterator result, so
73 /// `async function* g(){ yield* [1] }` answered `{value: {value: 1, done: false}}`.
74 AsyncYieldStar,
75 /// `await expr`: the value is a promise the async machinery has to settle first.
76 Await,
77}
78
79/// Everything one JavaScript realm owns.
80///
81/// A realm is the set of objects a script can reach without naming them: the global
82/// object, the prototype chain roots, and the global binding cells.
83pub struct Realm {
84 /// The global object.
85 pub global: Gc<JsObject>,
86 /// `Object.prototype`.
87 pub object_proto: Gc<JsObject>,
88 /// `Function.prototype`, which is itself callable.
89 pub function_proto: Gc<JsObject>,
90 /// `Array.prototype`.
91 pub array_proto: Gc<JsObject>,
92 /// The `%Array%` constructor, so `ArraySpeciesCreate` can recognise "the default".
93 pub array_constructor: Option<Gc<JsObject>>,
94 /// The `%Promise%` constructor, for the same reason in `NewPromiseCapability`.
95 pub promise_constructor: Option<Gc<JsObject>>,
96 /// Reference cells for globals declared by the script.
97 ///
98 /// A declared global is read with `get_var` (by name) but written with
99 /// `put_var_ref` (through the cell), so the cell is what makes a function
100 /// declaration and its uses agree on one binding.
101 pub globals: BTreeMap<String, Gc<Cell>>,
102 /// Names of the globals that came from a *declaration*, which are
103 /// non-configurable properties of the global object.
104 pub declared: Vec<String>,
105 /// Names among the lexical globals that are `const`.
106 ///
107 /// `const`-ness cannot be read back off the bytecode in every case: a closure that
108 /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
109 /// path does not carry, so a store through it would look like a plain `let`. The
110 /// realm records it once, at declaration, and answers for every reader.
111 pub lexical_consts: BTreeSet<String>,
112 /// The error constructors by class name, so a runtime error can throw a real
113 /// `TypeError` instance rather than a look-alike object.
114 pub errors: BTreeMap<&'static str, Gc<JsObject>>,
115 /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
116 pub string_proto: Option<Gc<JsObject>>,
117 /// `Number.prototype`.
118 pub number_proto: Option<Gc<JsObject>>,
119 /// `Boolean.prototype`.
120 pub boolean_proto: Option<Gc<JsObject>>,
121 /// `BigInt.prototype`.
122 pub bigint_proto: Option<Gc<JsObject>>,
123 /// `Error.prototype`, the prototype of every error instance.
124 pub error_proto: Gc<JsObject>,
125 /// `Date.prototype`, so the constructor can build an instance in the
126 /// function-call form (`Date()` returns a string) without going through `new`.
127 pub date_proto: Gc<JsObject>,
128 /// `%GeneratorPrototype%`, the prototype of every generator object.
129 pub generator_proto: Gc<JsObject>,
130 /// `Promise.prototype`, the prototype of every promise.
131 pub promise_proto: Option<Gc<JsObject>>,
132 /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
133 pub async_generator_proto: Option<Gc<JsObject>>,
134 /// `Symbol.prototype`.
135 pub symbol_proto: Option<Gc<JsObject>>,
136 /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
137 /// `_date_value`.
138 ///
139 /// These are *symbol* keys on purpose. A `"_value"` property is visible to
140 /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
141 /// language does not have and `new Error()` listed `_class` beside `message` and
142 /// `stack` — and a caller that copies every own property (which
143 /// `Object.create(null, props)` effectively does) tried to write an internal name and
144 /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
145 /// and `JSON.stringify`, while remaining an ordinary traced property.
146 ///
147 /// `RefCell` because interning is memoisation rather than observable state: filling the
148 /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
149 /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
150 /// built while reporting a failure must not require an exclusive borrow.
151 pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
152
153 /// The `Symbol.for` registry: `key -> symbol`.
154 ///
155 /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
156 /// symbol every time within one script while a fresh realm starts empty.
157 pub symbol_registry: BTreeMap<String, Value>,
158 /// `RegExp.prototype`, filled in by the `RegExp` builtin.
159 pub regexp_proto: Option<Gc<JsObject>>,
160 /// The `RegExp` constructor.
161 pub regexp_ctor: Option<Gc<JsObject>>,
162 /// `SuppressedError.prototype`, which `using` builds its aggregates from.
163 ///
164 /// The prototype rather than the constructor on purpose: a script that replaces
165 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
166 /// error wrapping, which the `using` test suite checks explicitly.
167 pub suppressed_error_proto: Option<Gc<JsObject>>,
168 /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
169 pub disposable_stack_proto: Option<Gc<JsObject>>,
170 /// `Map.prototype`.
171 pub map_proto: Option<Gc<JsObject>>,
172 /// `Set.prototype`.
173 pub set_proto: Option<Gc<JsObject>>,
174 /// Every live `FinalizationRegistry`, held weakly.
175 ///
176 /// The cleanup callback has to run from a *safe point* — a place where script is not
177 /// already executing and no engine borrow is held — and the collector cannot enumerate
178 /// heap objects by type. Registering each registry here gives the drain a list to walk.
179 ///
180 /// The handles are weak on purpose: a registry the script dropped must be collectable,
181 /// and it must not be resurrected merely because the drain knew about it. Entries whose
182 /// target has expired are swept out as the drain walks, so the vector does not grow
183 /// without bound in a program that creates many short-lived registries.
184 pub finalization_registries: Vec<WeakGc<JsObject>>,
185 /// `ArrayBuffer.prototype`.
186 pub array_buffer_proto: Option<Gc<JsObject>>,
187 /// `%TypedArray%.prototype`, the prototype every view type inherits from.
188 pub typed_array_proto: Option<Gc<JsObject>>,
189 /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
190 ///
191 /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
192 /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
193 /// `"Object"` and `r instanceof Int32Array` is false.
194 pub typed_array_protos: Vec<Gc<JsObject>>,
195 /// `DataView.prototype`.
196 pub data_view_proto: Option<Gc<JsObject>>,
197 /// The `AsyncDisposableStack` prototype.
198 pub async_disposable_stack_proto: Option<Gc<JsObject>>,
199 /// `Iterator.prototype`.
200 pub iterator_proto: Option<Gc<JsObject>>,
201 /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
202 ///
203 /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
204 /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
205 /// `[object Iterator Helper]`).
206 pub iterator_helper_proto: Option<Gc<JsObject>>,
207 /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
208 /// that was not already an `Iterator`.
209 ///
210 /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
211 /// untouched and does *not* override `@@toStringTag`, so
212 /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
213 pub iterator_wrap_proto: Option<Gc<JsObject>>,
214 /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
215 pub generator_function_proto: Option<Gc<JsObject>>,
216 /// `%AsyncFunction.prototype%`.
217 pub async_function_proto: Option<Gc<JsObject>>,
218 /// `%AsyncGeneratorFunction.prototype%`.
219 pub async_generator_function_proto: Option<Gc<JsObject>>,
220 /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
221 ///
222 /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
223 /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
224 /// prototype per iterator made every array iterator's prototype distinct.
225 pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
226 /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
227 ///
228 /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
229 /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
230 /// both faster and impossible to break from a script.
231 well_known_symbols: WellKnownSymbols,
232 /// The classes the host registered, and the prototype each one hands its instances.
233 pub host_classes: HostClasses,
234}
235
236/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
237///
238/// One per realm, because a class id is only meaningful within the runtime that handed it
239/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
240/// a host class cannot collide.
241pub struct HostClasses {
242 /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
243 /// `JS_GetOpaque(val, 0)` has to match nothing.
244 next_id: u32,
245 /// What each registered class does.
246 defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
247 /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
248 ///
249 /// A strong reference, so the prototype a host installed outlives every script
250 /// reference to it — which is what `JS_SetClassProto` promises.
251 protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
252}
253
254impl HostClasses {
255 fn new() -> HostClasses {
256 HostClasses {
257 next_id: 1,
258 defs: std::collections::BTreeMap::new(),
259 protos: std::collections::BTreeMap::new(),
260 }
261 }
262
263 /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
264 pub fn register(&mut self, def: ClassDef) -> ClassId {
265 let id = ClassId::from_raw(self.next_id);
266 self.next_id += 1;
267 self.defs.insert(id, std::rc::Rc::new(def));
268 id
269 }
270
271 /// Register `def` under an id the caller already has (`JS_NewClass`).
272 ///
273 /// The C API splits "get an id" from "register a class" because a module may be
274 /// initialised lazily; registering twice under one id replaces the definition, and an
275 /// object created under the old one keeps the old behaviour, since it carries its own
276 /// reference.
277 pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
278 if !id.is_valid() {
279 return false;
280 }
281 // Keep the counter past any id handed out explicitly, so a later `register` cannot
282 // reuse one.
283 self.next_id = self.next_id.max(id.get() + 1);
284 self.defs.insert(id, std::rc::Rc::new(def));
285 true
286 }
287
288 /// What `id` was registered with.
289 pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
290 self.defs.get(&id).cloned()
291 }
292
293 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
294 pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
295 self.protos.insert(id, proto);
296 }
297
298 /// The prototype installed for `id`, if the host installed one.
299 pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
300 self.protos.get(&id).cloned()
301 }
302
303 /// How many classes the host registered.
304 pub fn len(&self) -> usize {
305 self.defs.len()
306 }
307
308 /// Whether no class has been registered.
309 pub fn is_empty(&self) -> bool {
310 self.defs.is_empty()
311 }
312}
313
314impl Default for HostClasses {
315 fn default() -> HostClasses {
316 HostClasses::new()
317 }
318}
319
320/// One binding of the frame that called `eval`, so the eval'd code can read and
321/// write it by name.
322struct EvalBinding {
323 /// The name it was declared with.
324 name: String,
325 /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
326 /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
327 /// a function that declares `a` must find that `a`.
328 frame: usize,
329 /// Which table of that frame it lives in.
330 slot: EvalSlot,
331 /// The slot index within that table.
332 index: usize,
333}
334
335/// Which table of a frame an [`EvalBinding`] indexes.
336#[derive(Clone, Copy)]
337enum EvalSlot {
338 Arg,
339 Local,
340}
341
342/// One activation record.
343struct Frame {
344 /// The bytecode being run.
345 code: Gc<CompiledCode>,
346 /// The cells this closure captured.
347 env: Gc<ClosureEnv>,
348 /// The `this` binding.
349 this: Value,
350 /// Argument slots, sized to the declared parameter count.
351 args: Vec<Value>,
352 /// How many values the caller actually passed, which is what `arguments.length`
353 /// reports and what `...rest` slices from.
354 passed_count: usize,
355 /// The passed values, **only when they do not fit in [`Self::args`]**.
356 ///
357 /// `args` is sized to the declared parameters, so a call that passes no more than
358 /// that already holds every passed value in its first `passed_count` slots — copying
359 /// them here as well was two writes and a buffer per call, on the hottest path in
360 /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
361 /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
362 /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
363 /// its own copy.
364 ///
365 /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
366 /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
367 /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
368 /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
369 /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
370 /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
371 #[allow(clippy::box_collection)]
372 passed_overflow: Option<Box<Vec<Value>>>,
373 /// Local slots.
374 locals: Vec<Value>,
375 /// Reference cells for this frame's own captured bindings.
376 cells: Vec<Gc<Cell>>,
377 /// The operand stack.
378 stack: Vec<Value>,
379 /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
380 local_vars: Option<Gc<LocalVars>>,
381
382 /// Index of the next instruction, not a byte offset.
383 ///
384 /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
385 /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
386 /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
387 /// `Frame`, and `frames.push` copies the whole struct on every call.
388 pc: usize,
389 /// Byte offset of the instruction being executed, which is what a stack trace
390 /// reports. `pc` has already moved past it by the time an instruction runs.
391 ///
392 /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
393 at: usize,
394 /// The callee, so a native builtin can tell which constructor it is.
395 callee: Value,
396 /// `new.target`: the constructor under `new`, `undefined` for a plain call.
397 new_target: Value,
398 /// What this frame costs against [`Interp::stack_limit`], in bytes.
399 ///
400 /// Cached rather than recomputed because it is charged on every call and a call is the
401 /// hottest thing in the interpreter.
402 cost: usize,
403 /// [`Interp::stack_used`] before this frame was pushed.
404 ///
405 /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
406 /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
407 /// leave the counter wrong. There are eight places that drop frames; one subtraction
408 /// forgotten in any of them would leak budget until the depth limit moved.
409 stack_base: usize,
410 /// Whether this frame's body ended in a `tail_call`.
411 ///
412 /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
413 /// with its own frame just like `call` does and only skips storing the result
414 /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
415 /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
416 /// pushed as usual, and this marker makes its return value the *caller's* return
417 /// value without running the instructions after the call.
418 tail: bool,
419}
420
421impl Frame {
422 /// Read a local slot, taking the frame as `self`.
423 ///
424 /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
425 /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
426 /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
427 /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
428 /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
429 #[inline]
430 fn read_loc(&self, slot: usize) -> Value {
431 let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
432 if cell == -1 {
433 return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
434 }
435 match self.cells.get(cell as usize) {
436 Some(cell) => cell.get(),
437 None => Value::Undefined,
438 }
439 }
440
441 /// [`Self::read_loc`] for an argument slot.
442 #[inline]
443 fn read_arg(&self, slot: usize) -> Value {
444 let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
445 if cell == -1 {
446 return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
447 }
448 match self.cells.get(cell as usize) {
449 Some(cell) => cell.get(),
450 None => Value::Undefined,
451 }
452 }
453
454 /// The values the caller actually passed, which is what `arguments` exposes.
455 ///
456 /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
457 fn passed(&self) -> &[Value] {
458 match &self.passed_overflow {
459 Some(values) => values,
460 None => &self.args[..self.passed_count],
461 }
462 }
463
464 /// The decoded instructions of the function this frame runs.
465 ///
466 /// A method rather than `frame.code.insns` at the call site so that the borrow is
467 /// obviously of the frame — the dispatch loop holds one across a `get`.
468 fn insns(&self) -> &[crate::insn::Insn] {
469 &self.code.insns
470 }
471}
472
473impl js_gc::Trace for Frame {
474 fn trace(&self, tracer: &mut js_gc::Tracer) {
475 self.code.trace(tracer);
476 self.env.trace(tracer);
477 self.this.trace(tracer);
478 for value in &self.args {
479 value.trace(tracer);
480 }
481 for value in self.passed() {
482 value.trace(tracer);
483 }
484 for value in &self.locals {
485 value.trace(tracer);
486 }
487 for cell in &self.cells {
488 cell.trace(tracer);
489 }
490 if let Some(local_vars) = &self.local_vars {
491 tracer.visit(local_vars);
492 }
493 for value in &self.stack {
494 value.trace(tracer);
495 }
496 self.callee.trace(tracer);
497 self.new_target.trace(tracer);
498 }
499}
500
501/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
502/// emitted `if_false` treats as "keep going".
503/// How many finished frames' value buffers are kept for reuse.
504const RECYCLE_SLOTS: usize = 8;
505
506/// The largest buffer worth keeping. See [`Interp::free_values`].
507const RECYCLE_MAX_CAPACITY: usize = 4096;
508
509const RESUME_NEXT: i32 = 0;
510/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
511/// generator fall into its `return_async`.
512const RESUME_RETURN: i32 = 1;
513/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
514/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
515/// must forward the exception into the inner iterator rather than finish.
516const RESUME_THROW: i32 = 2;
517
518/// One microtask.
519///
520/// The queue holds *data* rather than closures because its contents are GC values: a
521/// closure would be invisible to the collector, and a pending reaction is exactly the
522/// kind of thing that must keep its handlers and its promise alive.
523pub enum Job {
524 /// A `then` reaction about to run.
525 Reaction {
526 /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
527 handler: Option<Value>,
528 /// The value or reason to call it with.
529 argument: Value,
530 /// Whether the source promise rejected, which decides the pass-through kind.
531 rejected: bool,
532 /// The promise the answer settles.
533 promise: Gc<JsObject>,
534 },
535 /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
536 Thenable {
537 /// The `then` that was found on the value.
538 then: Value,
539 /// The thenable itself, which becomes `then`'s `this`.
540 value: Value,
541 /// The promise being resolved.
542 promise: Gc<JsObject>,
543 },
544 /// A pending `import(specifier)`.
545 Import {
546 /// The specifier, already converted to a string.
547 specifier: String,
548 /// The module that asked, which the specifier resolves against.
549 referrer: String,
550 /// The promise `import()` handed back.
551 promise: Gc<JsObject>,
552 },
553 /// An async generator resuming after the value it awaited settled.
554 GeneratorResume {
555 /// The async generator to continue.
556 generator: Gc<JsObject>,
557 /// The promise the pending method returned.
558 promise: Gc<JsObject>,
559 /// Whether this delivers the value or raises the reason.
560 kind: ResumeKind,
561 /// The settled value, or the rejection reason.
562 value: Value,
563 },
564 /// An async function resuming after the value it awaited settled.
565 Resume {
566 /// The body, parked in a coroutine.
567 coroutine: Gc<JsObject>,
568 /// The promise the async function handed its caller.
569 promise: Gc<JsObject>,
570 /// Whether this resumption delivers a value or raises one.
571 kind: ResumeKind,
572 /// The settled value, or the rejection reason.
573 value: Value,
574 },
575}
576
577/// One macro-task: work the event loop owes the script but has not run yet.
578///
579/// The microtask queue ([`Job`]) is different: those run before the host regains control.
580/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
581/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
582/// logic: the engine decides *what* is due, the host decides *how to wait*.
583///
584/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
585/// reference counting even though nothing else references it — the same rule the `HostFn`
586/// documentation states from the other side (a host closure must not hold a `Gc`, so the
587/// `Gc` lives here instead).
588pub enum Task {
589 /// A `setTimeout` that is due at `due_at`.
590 ///
591 /// There is no `setInterval` variant because the reference has no `os.setInterval` at
592 /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
593 /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
594 /// would give this engine a timer the reference cannot produce, with nothing to
595 /// compare it against.
596 Timer {
597 /// The id `setTimeout` returned, for `clearTimeout`.
598 id: i32,
599 /// What to call when it fires.
600 callback: Value,
601 /// When it becomes runnable, as a monotonic instant.
602 due_at: std::time::Instant,
603 },
604}
605
606/// A descriptor the host has to poll, and which directions have a handler.
607///
608/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
609/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
610/// blocks on it, and the host reports back through [`Interp::fire_fd`].
611#[derive(Debug, Clone, Copy, PartialEq, Eq)]
612pub struct FdInterest {
613 /// The descriptor to watch.
614 pub fd: i32,
615 /// Whether `os.setReadHandler` registered a callback.
616 pub read: bool,
617 /// Whether `os.setWriteHandler` registered a callback.
618 pub write: bool,
619}
620
621/// The callbacks registered for one descriptor, per direction.
622#[derive(Default)]
623pub(crate) struct FdHandlers {
624 /// `os.setReadHandler`'s callback.
625 pub read: Option<Value>,
626 /// `os.setWriteHandler`'s callback.
627 pub write: Option<Value>,
628}
629
630/// The file name `eval` reports, which the reference does not inherit from the caller.
631///
632/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
633/// reference and the names show up in stack traces.
634/// The description of the private symbol a class brand is made from.
635///
636/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
637/// place no script can reach, since no expression can name a private symbol.
638const BRAND_DESCRIPTION: &str = "brand";
639
640/// One validated property lookup.
641///
642/// Covers both own-property hits and prototype hits. The second kind was deliberately left
643/// uncached at first ("a prototype hit depends on more than the object and the name"), and
644/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
645/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
646/// names on every iteration (measured: 100 ns per call over an empty loop).
647pub struct FieldCache {
648 /// The name, so two different properties of one object do not collide.
649 key: PropertyKey,
650 /// Where the value was found, relative to the chain below.
651 index: usize,
652 /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
653 level: u8,
654 /// The receiver and every prototype down to (and including) the level that answered,
655 /// each with the length of its property table at the time.
656 ///
657 /// That length is the whole guard, and it is sufficient for the ways the answer can
658 /// change without a lookup: adding or deleting any property moves it, and a
659 /// same-length rewrite is caught by `cached_data_property` re-checking the key and
660 /// refusing an accessor. Storing the *whole* chain — not just the object that answered
661 /// — is what catches a property appearing on an *intermediate* prototype and shadowing
662 /// the one that was cached.
663 ///
664 /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
665 /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
666 chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
667}
668
669/// How many links of a prototype chain a [`FieldCache`] remembers.
670///
671/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
672/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
673/// at three.
674const MAX_CACHED_CHAIN: usize = 3;
675
676/// A remembered global-variable lookup.
677///
678/// A `var` global is an ordinary property of the global object, so reading one walks the
679/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
680/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
681/// fixed by the bytecode, and the slot in the object's table only changes if the global
682/// object is mutated, which the index-and-name check below catches.
683pub struct GlobalCache {
684 /// The global object the lookup was resolved on, weakly.
685 object: js_gc::WeakGc<JsObject>,
686 /// Index of the data property in the global object's table.
687 index: usize,
688}
689
690/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
691const GLOBAL_CACHE_SLOTS: usize = 1024;
692
693/// How many property lookups are remembered.
694///
695/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
696/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
697/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
698/// lookup itself. Making it bigger stops helping: the working set of a real program's
699/// property sites is bounded by its code size.
700const FIELD_CACHE_SLOTS: usize = 4096;
701
702/// How much the heap may grow past the last `out of memory` before saying it again.
703///
704/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
705/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
706/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
707/// because it looks like it works. The reference gets this for free: it fails inside
708/// `js_malloc`, and its printing path happens not to allocate.
709///
710/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
711/// allocating is stopped within a rounding error of the limit) and far above what a
712/// handler needs.
713const OOM_HYSTERESIS: usize = 64 * 1024;
714
715/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
716pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
717
718/// How many instructions run between polls of [`Interp::interrupt`].
719///
720/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
721/// order of magnitude on both implementations — which is what lets a C driver compare its
722/// output byte for byte (see `scripts/m15-capi.sh --embed`).
723pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
724
725/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
726///
727/// Chosen so that the byte budget is what actually decides for every ordinary
728/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
729/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
730/// millions of frames.
731pub const MAX_FRAMES: usize = 200_000;
732
733const EVAL_FILE: &str = "<input>";
734
735/// The file name `std.evalScript` reports.
736const EVAL_SCRIPT_FILE: &str = "<evalScript>";
737
738/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
739///
740/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
741/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
742fn clamp_delay(delay_ms: f64) -> std::time::Duration {
743 // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
744 // on a float, which reads as a typo even when it is deliberate. Both NaN and a
745 // non-positive delay mean "due now".
746 if delay_ms.is_nan() || delay_ms <= 0.0 {
747 return std::time::Duration::ZERO;
748 }
749 std::time::Duration::from_secs_f64(delay_ms / 1000.0)
750}
751
752impl js_gc::Trace for Task {
753 fn trace(&self, tracer: &mut js_gc::Tracer) {
754 let Task::Timer { callback, .. } = self;
755 callback.trace(tracer);
756 }
757}
758
759/// What one turn of the event loop did, so the caller cannot spin by accident.
760///
761/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
762/// core until the timer is due. Naming the three cases makes the wait explicit.
763#[derive(Debug, Clone, Copy, PartialEq, Eq)]
764pub enum Turn {
765 /// Something ran. Call again immediately — there may be more ready work.
766 Ran,
767 /// Nothing is runnable, but descriptors are registered: the host must poll
768 /// [`Interp::pending_fds`] for at most this long, then report readiness with
769 /// [`Interp::fire_fd`].
770 ///
771 /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
772 /// the failure this project treats as worst — a handler that silently never fires —
773 /// so the two cannot be confused by accident.
774 Poll(std::time::Duration),
775 /// Nothing is runnable yet, but something is pending. Block at most this long, then
776 /// call again.
777 Wait(std::time::Duration),
778 /// Nothing is pending at all: the loop is done.
779 Done,
780}
781
782impl js_gc::Trace for Job {
783 fn trace(&self, tracer: &mut js_gc::Tracer) {
784 match self {
785 Job::Reaction {
786 handler,
787 argument,
788 promise,
789 ..
790 } => {
791 if let Some(handler) = handler {
792 handler.trace(tracer);
793 }
794 argument.trace(tracer);
795 tracer.visit(promise);
796 }
797 Job::Thenable {
798 then,
799 value,
800 promise,
801 } => {
802 then.trace(tracer);
803 value.trace(tracer);
804 tracer.visit(promise);
805 }
806 Job::Resume {
807 coroutine,
808 promise,
809 value,
810 ..
811 } => {
812 tracer.visit(coroutine);
813 tracer.visit(promise);
814 value.trace(tracer);
815 }
816 Job::Import { promise, .. } => tracer.visit(promise),
817 Job::GeneratorResume {
818 generator,
819 promise,
820 value,
821 ..
822 } => {
823 tracer.visit(generator);
824 tracer.visit(promise);
825 value.trace(tracer);
826 }
827 }
828 }
829}
830
831/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
832#[derive(Debug, Clone, Copy, PartialEq, Eq)]
833pub enum ResumeKind {
834 /// The generator was just created and is being run to its first suspension.
835 Start,
836 /// `next(v)`.
837 Next,
838 /// `return(v)`.
839 Return,
840 /// `throw(e)`.
841 Throw,
842}
843
844/// A generator object's saved execution.
845///
846/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
847/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
848/// separately allocated buffers.
849pub struct GeneratorState {
850 /// The detached frame, or `None` once the generator has finished or while it runs.
851 frame: Option<Frame>,
852 /// How far it got.
853 phase: GeneratorPhase,
854 /// Whether the last suspension was an `await` rather than a `yield`.
855 ///
856 /// The two resume with *different stack shapes*: a `yield` is re-entered with the
857 /// value and a magic number, because the emitted code branches on which method
858 /// resumed it, while an `await` simply continues with its value. Getting this wrong
859 /// leaves an extra value on the operand stack that the next instruction then
860 /// consumes — a wrong answer rather than a crash.
861 parked_on_await: bool,
862 /// Whether the last suspension was a `yield*` rather than a plain `yield`.
863 ///
864 /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
865 /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
866 /// has to be forwarded into the inner iterator's `throw` method instead — which is the
867 /// `rethrow` branch the compiled delegation emits — because that is the whole point of
868 /// delegating. Tracking it as part of the phase, the way the reference splits
869 /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
870 /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
871 /// exception and never reached `xs.throw`.
872 parked_on_yield_star: bool,
873 /// Pending `next`/`return`/`throw` calls, oldest first.
874 ///
875 /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
876 /// called back to back must answer in that order, with the second call's value
877 /// arriving at the *second* `yield`. Running each call straight into the body — which
878 /// is what this engine did before — delivered the last queued value to whichever
879 /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
880 /// `a === b ===` the final argument.
881 ///
882 /// The front entry is the one being served; it stays there (with `async_busy` set)
883 /// until its promise settles, because an `await` inside the body is a suspension of
884 /// the *driver*, not the end of the request.
885 requests: std::collections::VecDeque<AsyncRequest>,
886 /// Whether the front request is in flight.
887 async_busy: bool,
888}
889
890/// How one async-generator request ended.
891enum AsyncOutcome {
892 /// The method answered this `{value, done}`.
893 Value(Value),
894 /// The body threw.
895 Error(Value),
896}
897
898/// One queued `next`/`return`/`throw` on an async generator: the reference's
899/// `JSAsyncGeneratorRequest`.
900pub struct AsyncRequest {
901 /// Which method was called.
902 kind: ResumeKind,
903 /// Its argument.
904 value: Value,
905 /// The promise the method answered.
906 promise: Gc<JsObject>,
907}
908
909/// Which of §27.5.3.3's states a generator is in.
910#[derive(Debug, Clone, Copy, PartialEq, Eq)]
911enum GeneratorPhase {
912 /// Created, `initial_yield` reached, body not entered.
913 SuspendedStart,
914 /// Parked at a `yield`.
915 SuspendedYield,
916 /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
917 Executing,
918 /// Finished; the frame is gone.
919 Completed,
920}
921
922impl js_gc::Trace for GeneratorState {
923 fn trace(&self, tracer: &mut js_gc::Tracer) {
924 if let Some(frame) = &self.frame {
925 frame.trace(tracer);
926 }
927 for request in &self.requests {
928 request.value.trace(tracer);
929 tracer.visit(&request.promise);
930 }
931 }
932}
933
934/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
935/// them in.
936///
937/// Each is a field rather than a map entry because the runtime reads them on hot paths
938/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
939/// failure — reaching a default here means the builtin did not install, and every
940/// accessor panics rather than silently answering `undefined`.
941///
942/// [`builtins::symbol`]: crate::builtins::symbol
943#[derive(Default)]
944pub struct WellKnownSymbols {
945 /// The symbol values, positionally. Empty until `Symbol` installs.
946 symbols: Vec<Value>,
947}
948
949/// Which well-known symbol a caller wants.
950///
951/// A typed accessor beats passing a name around: a typo is a compile error rather than
952/// an `undefined` key that quietly matches nothing.
953#[derive(Debug, Clone, Copy, PartialEq, Eq)]
954pub enum WellKnown {
955 /// `Symbol.toPrimitive`.
956 ToPrimitive,
957 /// `Symbol.iterator`.
958 Iterator,
959 /// `Symbol.match`.
960 Match,
961 /// `Symbol.matchAll`.
962 MatchAll,
963 /// `Symbol.replace`.
964 Replace,
965 /// `Symbol.search`.
966 Search,
967 /// `Symbol.split`.
968 Split,
969 /// `Symbol.toStringTag`.
970 ToStringTag,
971 /// `Symbol.isConcatSpreadable`.
972 IsConcatSpreadable,
973 /// `Symbol.hasInstance`.
974 HasInstance,
975 /// `Symbol.species`.
976 Species,
977 /// `Symbol.unscopables`.
978 Unscopables,
979 /// `Symbol.asyncIterator`.
980 AsyncIterator,
981 /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
982 Disposable,
983 /// `Symbol.asyncDispose` — the awaited form.
984 AsyncDisposable,
985}
986
987impl WellKnown {
988 /// The index `Symbol`'s installer creates this symbol at.
989 fn index(self) -> usize {
990 match self {
991 WellKnown::ToPrimitive => 0,
992 WellKnown::Iterator => 1,
993 WellKnown::Match => 2,
994 WellKnown::MatchAll => 3,
995 WellKnown::Replace => 4,
996 WellKnown::Search => 5,
997 WellKnown::Split => 6,
998 WellKnown::ToStringTag => 7,
999 WellKnown::IsConcatSpreadable => 8,
1000 WellKnown::HasInstance => 9,
1001 WellKnown::Species => 10,
1002 WellKnown::Unscopables => 11,
1003 WellKnown::AsyncIterator => 12,
1004 WellKnown::Disposable => 13,
1005 WellKnown::AsyncDisposable => 14,
1006 }
1007 }
1008}
1009
1010impl Realm {
1011 /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1012 pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1013 self.well_known_symbols.symbols = symbols;
1014 }
1015
1016 /// A well-known symbol.
1017 pub fn well_known(&self, which: WellKnown) -> Value {
1018 self.well_known_symbols
1019 .symbols
1020 .get(which.index())
1021 .cloned()
1022 .unwrap_or(Value::Undefined)
1023 }
1024
1025 /// The well-known symbol as a property key.
1026 pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1027 match self.well_known(which) {
1028 Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1029 // Unreachable once `Symbol` has installed; an empty string key matches
1030 // nothing, which degrades to "the object has no such method".
1031 _ => PropertyKey::from(String::new()),
1032 }
1033 }
1034}
1035
1036/// The interpreter: a realm plus a frame stack.
1037pub struct Interp<'a> {
1038 /// The heap everything is allocated on.
1039 pub heap: &'a Heap,
1040 /// The realm.
1041 pub realm: Realm,
1042 /// Active frames, outermost first.
1043 frames: Vec<Frame>,
1044 /// Value buffers from frames that have finished, reused by the next call.
1045 ///
1046 /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1047 /// the locals and the operand stack — and free all four on return. `call:recursion`
1048 /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1049 /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1050 ///
1051 /// Bounded in both directions: a few buffers per kind, and none larger than
1052 /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1053 /// and keeping its buffer would pin that memory for the rest of the run.
1054 free_values: Vec<Vec<Value>>,
1055 /// A strict-mode `eval`'s own variable scope, while its script runs.
1056 ///
1057 /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1058 /// become a global. Name lookups still fall through to the realm, which is why
1059 /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1060 eval_scope: Option<BTreeMap<String, Value>>,
1061 /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1062 /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1063 eval_depth: usize,
1064 /// The calling frame's own bindings, which the running `eval` can read and write.
1065 ///
1066 /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1067 /// come from the frame, and a write is applied back to the frame (or to the cell
1068 /// the frame captured) when the eval finishes. That is what makes
1069 /// `f("a = 3")` visible to the caller as `a === 3`.
1070 eval_bindings: Vec<EvalBinding>,
1071 /// The calling frame's `arguments`, while an `eval` runs.
1072 ///
1073 /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1074 /// own yet still has to see the caller's `arguments`.
1075 eval_arguments: Option<Value>,
1076 /// The `with` objects live at the moment the running `eval` started, innermost first.
1077 ///
1078 /// `None` outside an eval, which is what keeps a finished block's object from
1079 /// shadowing ordinary bytecode reads.
1080 eval_with: Option<Vec<Gc<JsObject>>>,
1081 /// The bindings the running direct `eval` makes visible, as name → cell.
1082 ///
1083 /// Set for the duration of an eval and then restored, but every closure created
1084 /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1085 /// `eval("f = () => i")` work after the eval has returned.
1086 active_eval_scope: Option<Gc<EvalScope>>,
1087 /// The frame that called the direct `eval` currently running, if any.
1088 ///
1089 /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1090 /// on the global object, which is what keeps
1091 /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1092 /// gives each call its own `x`.
1093 eval_caller: Option<Option<usize>>,
1094 /// The caller's `new.target`, while an `eval` runs.
1095 ///
1096 /// The eval'd code is a script with no constructor of its own, so it inherits the
1097 /// one the enclosing function was called with.
1098 eval_new_target: Option<Value>,
1099 /// `new.target` for the frame about to be pushed.
1100 ///
1101 /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1102 /// value reaches the frame without threading a parameter through every call site.
1103 pending_new_target: Option<Value>,
1104 /// Names of the native functions currently executing, outermost first.
1105 ///
1106 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1107 /// trace still names it with `(native)` instead of a position, so the names are
1108 /// tracked separately and stitched into [`Interp::stack_trace`].
1109 ///
1110 /// The third field is how many bytecode frames were live when the native was entered,
1111 /// which is what places it *among* them rather than before all of them. Native
1112 /// functions used to be emitted up front on the grounds that they never re-enter
1113 /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1114 /// The natives currently running, innermost last: the function object and the
1115 /// depth it was entered at.
1116 ///
1117 /// The *name* is deliberately not stored. It used to be, read with
1118 /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1119 /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1120 /// benchmark. A stack trace is built rarely; it can read the name then.
1121 native_frames: Vec<(Gc<JsObject>, usize)>,
1122 /// The native function currently executing, for the ones that have to know *which*
1123 /// function they are — a typed-array constructor reads its element type off itself.
1124 ///
1125 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1126 /// reports whatever the enclosing bytecode frame was called with.
1127 current_native: Option<Gc<JsObject>>,
1128 /// Text written by `print` and friends, in order.
1129 ///
1130 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1131 /// once at the end, which is also when upstream's line buffering becomes
1132 /// visible for the cases compared here.
1133 pub output: String,
1134 /// Where `print` also writes, as it goes. `output` keeps the full log for
1135 /// [`crate::Context::output`]; this is the live copy, flushed per line.
1136 ///
1137 /// Both exist on purpose. A host that gives a script a sink sees output *when it
1138 /// happens* — which is what a timer callback's `console.log` has to do, and what the
1139 /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1140 /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1141 /// would show a script's output all at once when it finished.
1142 pub output_sink: Option<Box<dyn std::io::Write>>,
1143 /// Where recent property reads found their value.
1144 ///
1145 /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1146 /// table remembering *which object* and *which entry of its property table* answered a
1147 /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1148 /// can move; the property can become an accessor), which is what makes a stale entry a
1149 /// miss rather than a wrong answer.
1150 ///
1151 /// The object is held weakly: a cache that held it strongly would keep up to
1152 /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1153 /// program cannot see and cannot work around.
1154 pub field_cache: Vec<Option<FieldCache>>,
1155 /// Global lookups, by binding slot. See [`GlobalCache`].
1156 global_cache: Vec<Option<GlobalCache>>,
1157 /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1158 /// under its limit. See [`Interp::check_memory`].
1159 pub oom_reported_at: usize,
1160 /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1161 /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1162 ///
1163 /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1164 /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1165 /// host that wants to stop a runaway script must not have to wait for it to return.
1166 ///
1167 /// Two things this cannot do, both of them differences a host can observe:
1168 ///
1169 /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1170 /// uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1171 /// needs a signal that the `catch` machinery does not see, which is a change to
1172 /// [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1173 /// a host that stops the script itself.
1174 /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1175 /// also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1176 /// both, so the difference is when the counter hits zero, not whether it will.
1177 pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1178 /// Instructions until the next [`Interp::interrupt`] poll.
1179 pub interrupt_counter: u32,
1180 /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1181 ///
1182 /// A separate field from [`Interp::uncatchable`] because the two live for different
1183 /// spans. This one is the host's standing request; it survives the start of an
1184 /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1185 /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1186 /// for both was the first attempt and it did nothing at all: the outermost `execute`
1187 /// cleared it before the script it was set for had a chance to throw.
1188 pub uncatchable_next: bool,
1189 /// Whether the exception now unwinding may be caught by a `catch`.
1190 ///
1191 /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1192 /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1193 /// a host stopping a runaway loop is not fought by the loop.
1194 ///
1195 /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1196 /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1197 /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1198 /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1199 pub uncatchable: bool,
1200 /// The most stack a JavaScript call chain may use, in bytes of frame state.
1201 ///
1202 /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1203 /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1204 /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1205 /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1206 /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1207 /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1208 ///
1209 /// The numbers come out close for the same reason a C frame and a heap frame of this
1210 /// shape cost about the same (both are a few hundred bytes, dominated by the value
1211 /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1212 /// and this engine lands in the same neighbourhood — measured, not fudged, by
1213 /// `crates/quickjs-cli/tests/limits.rs`.
1214 pub stack_limit: usize,
1215 /// The most frames that may be live at once, whatever the byte budget says.
1216 ///
1217 /// A second bound for a reason the reference does not have: our frames cost less than
1218 /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1219 /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1220 /// `--stack-size 1G` from being a memory bomb.
1221 pub max_frames: usize,
1222 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1223 ///
1224 /// Script execution does not return until this has drained, which is what makes
1225 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1226 /// than never. Reactions append to it while it drains, so the loop is a `while` and
1227 /// not a `for`.
1228 pub(crate) jobs: std::collections::VecDeque<Job>,
1229 /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1230 ///
1231 /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1232 /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1233 pub(crate) tasks: Vec<Task>,
1234 /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1235 /// barrier'd evaluation started.
1236 ///
1237 /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1238 /// lets a REPL report an error from the line it just evaluated without also reporting
1239 /// its own readline loop.
1240 trace_barriers: Vec<usize>,
1241 /// `os.signal` handlers, keyed by signal number.
1242 ///
1243 /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1244 /// a handler cannot be freed while it is still registered.
1245 pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1246 /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1247 ///
1248 /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1249 /// that is only reachable from a host closure could be freed while still registered.
1250 pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1251 /// The next timer id.
1252 ///
1253 /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1254 /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1255 next_timer_id: i32,
1256 /// Errors thrown by timer callbacks, already rendered.
1257 ///
1258 /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1259 /// that throws has no promise behind it. Both are reported by the host at the end of
1260 /// the loop, but only one is fixed up by a later `.catch`.
1261 timer_errors: Vec<String>,
1262 /// The module registry, keyed by canonical name.
1263 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1264 /// How the host turns a specifier into bytes.
1265 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1266 /// The module the host was asked to run, for `import.meta.main`.
1267 pub main_module_name: Option<String>,
1268 /// Module bodies currently running, innermost last.
1269 ///
1270 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1271 /// this is the only place that knows which module that is.
1272 pub module_stack: Vec<String>,
1273 /// Rejections that no handler has claimed, with the promise they belong to.
1274 ///
1275 /// A `then` registered later prunes its entry, which is why the promise is kept: the
1276 /// reason alone cannot say whether somebody eventually listened.
1277 unhandled: Vec<(Gc<JsObject>, Value)>,
1278}
1279
1280impl<'a> Interp<'a> {
1281 /// Build an interpreter over `heap`, with a fresh realm.
1282 pub fn new(heap: &'a Heap) -> Interp<'a> {
1283 let object_proto = JsObject::ordinary(heap, None);
1284 let function_proto = JsObject::function(
1285 heap,
1286 Some(object_proto.clone()),
1287 Callable::Native {
1288 func: |_, _, _| Ok(Value::Undefined),
1289 own_instance: false,
1290 },
1291 );
1292 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1293 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1294 let mut interp = Interp {
1295 heap,
1296 realm: Realm {
1297 global,
1298 object_proto,
1299 function_proto,
1300 array_proto,
1301 array_constructor: None,
1302 promise_constructor: None,
1303 globals: BTreeMap::new(),
1304 declared: Vec::new(),
1305 lexical_consts: BTreeSet::new(),
1306 errors: BTreeMap::new(),
1307 string_proto: None,
1308 number_proto: None,
1309 boolean_proto: None,
1310 bigint_proto: None,
1311 error_proto: JsObject::ordinary(heap, None),
1312 date_proto: JsObject::ordinary(heap, None),
1313 generator_proto: JsObject::ordinary(heap, None),
1314 promise_proto: None,
1315 async_generator_proto: None,
1316 symbol_proto: None,
1317 symbol_registry: BTreeMap::new(),
1318 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1319 regexp_proto: None,
1320 regexp_ctor: None,
1321 suppressed_error_proto: None,
1322 disposable_stack_proto: None,
1323 map_proto: None,
1324 set_proto: None,
1325 finalization_registries: Vec::new(),
1326 array_buffer_proto: None,
1327 typed_array_proto: None,
1328 typed_array_protos: Vec::new(),
1329 data_view_proto: None,
1330 async_disposable_stack_proto: None,
1331 iterator_proto: None,
1332 iterator_helper_proto: None,
1333 iterator_wrap_proto: None,
1334 generator_function_proto: None,
1335 async_function_proto: None,
1336 async_generator_function_proto: None,
1337 iterator_protos: std::collections::BTreeMap::new(),
1338 well_known_symbols: WellKnownSymbols::default(),
1339 host_classes: HostClasses::new(),
1340 },
1341 frames: Vec::new(),
1342 free_values: Vec::new(),
1343 global_cache: {
1344 let mut cache = Vec::new();
1345 cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1346 cache
1347 },
1348 eval_scope: None,
1349 eval_depth: 0,
1350 eval_bindings: Vec::new(),
1351 eval_arguments: None,
1352 eval_with: None,
1353 active_eval_scope: None,
1354 eval_caller: None,
1355 pending_new_target: None,
1356 eval_new_target: None,
1357 native_frames: Vec::new(),
1358 current_native: None,
1359 output: String::new(),
1360 output_sink: None,
1361 field_cache: {
1362 let mut cache = Vec::new();
1363 cache.resize_with(FIELD_CACHE_SLOTS, || None);
1364 cache
1365 },
1366 oom_reported_at: 0,
1367 interrupt: None,
1368 interrupt_counter: INTERRUPT_POLL_INTERVAL,
1369 uncatchable_next: false,
1370 uncatchable: false,
1371 // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1372 // absent.
1373 stack_limit: DEFAULT_STACK_SIZE,
1374 max_frames: MAX_FRAMES,
1375 jobs: std::collections::VecDeque::new(),
1376 tasks: Vec::new(),
1377 trace_barriers: Vec::new(),
1378 signal_handlers: std::collections::BTreeMap::new(),
1379 fd_handlers: std::collections::BTreeMap::new(),
1380 next_timer_id: 1,
1381 timer_errors: Vec::new(),
1382 modules: std::collections::BTreeMap::new(),
1383 module_loader: None,
1384 main_module_name: None,
1385 module_stack: Vec::new(),
1386 unhandled: Vec::new(),
1387 };
1388 crate::builtins::install(&mut interp);
1389 interp
1390 }
1391
1392 // -- allocation helpers -------------------------------------------------
1393
1394 /// A new string value.
1395 /// A `BigInt` value from a computed big integer.
1396 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1397 Value::BigInt(Gc::new(self.heap, value))
1398 }
1399
1400 /// A string value from bytes that are already WTF-8, which is how a string with an
1401 /// unpaired surrogate reaches a `Value`.
1402 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1403 Value::string_wtf8(self.heap, text)
1404 }
1405
1406 /// A new string value, from text that is valid UTF-8.
1407 pub fn string(&self, text: impl Into<String>) -> Value {
1408 Value::string(self.heap, text)
1409 }
1410
1411 /// A new ordinary object with the given prototype.
1412 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1413 JsObject::ordinary(self.heap, proto)
1414 }
1415
1416 // -- host classes -------------------------------------------------------
1417
1418 /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1419 pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1420 self.realm.host_classes.register(def)
1421 }
1422
1423 /// Register `def` under an id the host already holds (`JS_NewClass`).
1424 ///
1425 /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1426 /// `JS_NewClass`.
1427 pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1428 self.realm.host_classes.define(id, def)
1429 }
1430
1431 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1432 pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1433 self.realm.host_classes.set_proto(id, proto);
1434 }
1435
1436 /// The prototype installed for `id`, if any.
1437 pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1438 self.realm.host_classes.proto(id)
1439 }
1440
1441 /// A new instance of `id` (`JS_NewObjectProtoClass`).
1442 ///
1443 /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1444 /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1445 /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1446 /// host installed none.
1447 ///
1448 /// Answers `None` for an id that was never registered: the C API would return an
1449 /// exception, and silently making an ordinary object instead would move the failure to
1450 /// the first `JS_GetOpaque` that no longer matches.
1451 pub fn new_host_object(
1452 &mut self,
1453 proto: Option<Gc<JsObject>>,
1454 class_id: ClassId,
1455 ) -> Option<Gc<JsObject>> {
1456 let class = self.realm.host_classes.def(class_id)?;
1457 let proto = proto
1458 .or_else(|| self.realm.host_classes.proto(class_id))
1459 .or_else(|| Some(self.realm.object_proto.clone()));
1460 Some(JsObject::host_object(self.heap, proto, class_id, class))
1461 }
1462
1463 /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1464 ///
1465 /// `None` covers both answers the C API gives as a null pointer — the value is not an
1466 /// object, it is an object of another class, or the class never got a payload. A host
1467 /// that has to tell them apart uses [`JsObject::host_class_id`].
1468 pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1469 let object = value.as_object()?;
1470 if object.host_class_id()? != class_id {
1471 return None;
1472 }
1473 object.host_opaque()
1474 }
1475
1476 /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1477 pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1478 match value.as_object() {
1479 Some(object) => object.set_host_opaque(opaque),
1480 None => false,
1481 }
1482 }
1483
1484 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1485 ///
1486 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1487 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1488 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1489 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1490 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1491 /// said `[object Object]` instead of `[object Array Iterator]`.
1492 ///
1493 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1494 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1495 /// its own.
1496 pub fn new_iterator_prototype(
1497 &mut self,
1498 tag: &str,
1499 next: crate::object::NativeFn,
1500 ) -> Gc<JsObject> {
1501 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1502 return existing.clone();
1503 }
1504 let parent = self.realm.iterator_proto.clone();
1505 let proto = self.new_object(parent);
1506 let next = self.new_native("next", 0, next);
1507 proto.define(
1508 "next",
1509 Property::with_attributes(Value::Object(next), true, false),
1510 );
1511 let key = self.realm.well_known_key(WellKnown::Iterator);
1512 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1513 proto.define_key(
1514 &key,
1515 Property::with_attributes(Value::Object(identity), true, false),
1516 );
1517 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1518 let tag_value = self.string(tag);
1519 // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1520 // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1521 // checks it.
1522 proto.define_key(&tag_key, Property::configurable_only(tag_value));
1523 self.realm
1524 .iterator_protos
1525 .insert(tag.to_string(), proto.clone());
1526 proto
1527 }
1528
1529 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1530 ///
1531 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1532 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1533 /// produced. That is why the two branches are not merged.
1534 pub fn object_own_property_keys(
1535 &mut self,
1536 object: &Gc<JsObject>,
1537 ) -> JsResult<Vec<PropertyKey>> {
1538 if let Some(keys) = self.proxy_own_keys(object)? {
1539 return Ok(keys);
1540 }
1541 // Integer-like keys ascending, then the string keys in insertion order, then the
1542 // symbols — the order every schema that walks an object expects.
1543 let entries = object.property_entries();
1544 let mut numeric: Vec<u32> = Vec::new();
1545 // An integer-indexed exotic object reports its indices as own keys even though they
1546 // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1547 // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1548 // order). The length is asked per call, so a resizable buffer's view reports the
1549 // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1550 if object.typed_array_parts().is_some() {
1551 for index in 0..object.typed_array_length().unwrap_or(0) {
1552 // `u32::try_from` cannot fail for a real length, but the length is a
1553 // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1554 // as an array index and one element beyond is not.
1555 match u32::try_from(index) {
1556 Ok(index) => numeric.push(index),
1557 Err(_) => break,
1558 }
1559 }
1560 }
1561 let mut strings: Vec<PropertyKey> = Vec::new();
1562 let mut symbols: Vec<PropertyKey> = Vec::new();
1563 for (key, _) in entries {
1564 match &key {
1565 // A class-private name is never reported by any enumeration: that is the
1566 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1567 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1568 // symbol skip, `Object.assign`) therefore cannot see it.
1569 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1570 PropertyKey::Symbol(_) => symbols.push(key),
1571 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1572 Some(index) => {
1573 if !numeric.contains(&index) {
1574 numeric.push(index);
1575 }
1576 }
1577 None => strings.push(key),
1578 },
1579 }
1580 }
1581 numeric.sort_unstable();
1582 let mut keys: Vec<PropertyKey> = numeric
1583 .into_iter()
1584 .map(|index| PropertyKey::from(index.to_string()))
1585 .collect();
1586 keys.extend(strings);
1587 keys.extend(symbols);
1588 Ok(keys)
1589 }
1590
1591 /// The state behind a promise object, or `None` when `object` is not one.
1592 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1593 object.with(|data| match &data.kind {
1594 ObjectKind::Promise(state) => Some(state.clone()),
1595 _ => None,
1596 })
1597 }
1598
1599 /// A new pending promise.
1600 pub fn new_promise(&mut self) -> Gc<JsObject> {
1601 // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1602 // the one place every promise is built, and a subclass that builds its instances
1603 // somewhere else would be invisible to `instanceof`.
1604 let default = self.realm.promise_proto.clone();
1605 // A throwing `new.target.prototype` getter cannot be reported from here — this is
1606 // the raw promise constructor and its result is not `JsResult` — so the rejection is
1607 // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1608 // `prototype` getter therefore still gets a working promise; the alternative is a
1609 // panic, and the throwing path is covered by `Promise`'s own argument validation.
1610 let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1611 let promise = JsObject::ordinary(self.heap, proto);
1612 promise.with_mut(|data| {
1613 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1614 crate::object::PromiseState::default(),
1615 )));
1616 });
1617 promise
1618 }
1619
1620 /// Fulfil `promise`, unless it has already settled.
1621 ///
1622 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1623 /// after `reject`, changes nothing.
1624 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1625 let Some(state) = self.promise_state(promise) else {
1626 return;
1627 };
1628 let reactions = {
1629 let mut state = state.borrow_mut();
1630 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1631 return;
1632 }
1633 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1634 std::mem::take(&mut state.reactions)
1635 };
1636 self.queue_reactions(reactions, value, false);
1637 }
1638
1639 /// Reject `promise`, unless it has already settled.
1640 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1641 let Some(state) = self.promise_state(promise) else {
1642 return;
1643 };
1644 let reactions = {
1645 let mut state = state.borrow_mut();
1646 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1647 return;
1648 }
1649 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1650 std::mem::take(&mut state.reactions)
1651 };
1652 // Remember it only when nothing is listening *now*; a `then` registered later
1653 // prunes the entry in `perform_then`.
1654 if reactions.is_empty() {
1655 self.unhandled.push((promise.clone(), reason.clone()));
1656 }
1657 self.queue_reactions(reactions, reason, true);
1658 }
1659
1660 /// Queue one job per reaction.
1661 ///
1662 /// This is what makes `then` asynchronous even on an already-settled promise:
1663 /// `p.then(f); g()` calls `g` first.
1664 fn queue_reactions(
1665 &mut self,
1666 reactions: Vec<crate::object::PromiseReaction>,
1667 argument: Value,
1668 rejected: bool,
1669 ) {
1670 for reaction in reactions {
1671 let handler = if rejected {
1672 reaction.on_rejected.clone()
1673 } else {
1674 reaction.on_fulfilled.clone()
1675 };
1676 self.jobs.push_back(Job::Reaction {
1677 handler,
1678 argument: argument.clone(),
1679 rejected,
1680 promise: reaction.promise,
1681 });
1682 }
1683 }
1684
1685 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1686 /// resolve/reject pair.
1687 ///
1688 /// The pair are callable objects rather than Rust closures, because the script gets
1689 /// them and may stash them for later.
1690 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1691 let promise = self.new_promise();
1692 // Both handlers are built-ins with an empty name and length 1, in
1693 // `length`-then-`name` order — `reject-function-property-order` reads the order back
1694 // off `Object.getOwnPropertyNames`.
1695 let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1696 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1697 (promise, Value::Object(resolve), Value::Object(reject))
1698 }
1699
1700 /// §27.2.1.5 `NewPromiseCapability(C)`.
1701 ///
1702 /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1703 /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1704 /// decide what capability it hands back. That is the whole mechanism behind subclassing
1705 /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1706 /// silently ignored argument.
1707 ///
1708 /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1709 /// the engine's own executor is exactly what `new_promise_capability` builds.
1710 pub fn new_promise_capability_for(
1711 &mut self,
1712 constructor: &Value,
1713 ) -> JsResult<(Value, Value, Value)> {
1714 let Some(object) = constructor.as_object().cloned() else {
1715 return Err(self.type_error("promise constructor is not a constructor"));
1716 };
1717 if !object.is_constructor() {
1718 return Err(self.type_error("promise constructor is not a constructor"));
1719 }
1720 if self
1721 .realm
1722 .promise_constructor
1723 .as_ref()
1724 .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1725 {
1726 let (promise, resolve, reject) = self.new_promise_capability();
1727 return Ok((Value::Object(promise), resolve, reject));
1728 }
1729 let state = self.new_object(Some(self.realm.object_proto.clone()));
1730 let executor = self.builtin_function(
1731 "",
1732 1,
1733 Callable::CapabilityExecutor {
1734 state: state.clone(),
1735 },
1736 );
1737 let promise = self.construct(
1738 Value::Object(object.clone()),
1739 Value::Object(object),
1740 vec![Value::Object(executor)],
1741 )?;
1742 // The pair is read *after* the constructor returns, so a constructor that never
1743 // called its executor, or called it with non-callables, is the spec's step 11
1744 // `TypeError` — not something the engine can paper over.
1745 let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1746 return Err(self.type_error("promise executor never ran"));
1747 };
1748 let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1749 return Err(self.type_error("promise executor never ran"));
1750 };
1751 for handler in [&resolve, &reject] {
1752 if !matches!(handler, Value::Object(object) if object.is_callable()) {
1753 return Err(self.type_error("promise capability handler is not callable"));
1754 }
1755 }
1756 Ok((promise, resolve, reject))
1757 }
1758
1759 /// §27.2.3.1 `PromiseResolve(C, x)`.
1760 ///
1761 /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1762 /// an `x` that is already a promise of exactly this constructor is handed back
1763 /// unchanged, and anything else gets a fresh capability from `C`.
1764 pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1765 if let Value::Object(object) = &value
1766 && self.promise_state(object).is_some()
1767 {
1768 // `x.constructor === C` means "already the right kind", so no capability is
1769 // built — which is observable through a `resolve` that counts its calls.
1770 let x_constructor = self.get_property(object, "constructor")?;
1771 let same = match (
1772 x_constructor.as_ref().and_then(Value::as_object),
1773 constructor.as_object(),
1774 ) {
1775 (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1776 _ => false,
1777 };
1778 if same {
1779 return Ok(value);
1780 }
1781 }
1782 let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1783 self.call_value(resolve, Value::Undefined, vec![value])?;
1784 Ok(promise)
1785 }
1786
1787 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1788 /// promise, as `{ value: completion }`.
1789 ///
1790 /// The three cases are the reference's, and they differ on purpose:
1791 ///
1792 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1793 /// exception before any promise exists;
1794 /// * a **runtime** error rejects the returned promise;
1795 /// * success resolves it with `{ value }`, where the value is the script's completion
1796 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1797 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1798 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1799 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1800 ///
1801 /// # What this does not do
1802 ///
1803 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1804 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1805 /// the parser and the suspension machinery to accept a suspended top-level script, and
1806 /// is not implemented — such source is a syntax error here. Everything else about the
1807 /// flag is reproduced.
1808 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1809 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1810 // too, and the reference truncates that one at the same place as a runtime failure.
1811 if barrier {
1812 let depth = self.frames.len();
1813 self.trace_barriers.push(depth);
1814 }
1815 // Compiled before the promise exists, so a parse failure propagates as a throw
1816 // instead of being folded into a rejection.
1817 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1818 Ok(compiled) => compiled,
1819 Err(error) => {
1820 if barrier {
1821 self.trace_barriers.pop();
1822 }
1823 return Err(error);
1824 }
1825 };
1826 // An async body answers its own promise, and that promise is what the reference
1827 // hands back — the same object, not a wrapper around it. Its resolution value is
1828 // the `{value}` object the compiled epilogue built.
1829 if compiled.kind.is_async() {
1830 let strict = compiled.strict;
1831 let promise = self.run_eval_script(compiled, strict)?;
1832 if barrier {
1833 self.trace_barriers.pop();
1834 }
1835 return Ok(promise);
1836 }
1837 let (promise, resolve, reject) = self.new_promise_capability();
1838 let strict = compiled.strict;
1839 match self.run_eval_script(compiled, strict) {
1840 Ok(value) => {
1841 // `{ value }` is a plain object, so resolving with it adopts nothing even
1842 // when the completion value is itself a promise.
1843 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1844 self.set_property(&wrapped, "value", value)?;
1845 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1846 }
1847 Err(Signal::Throw(error)) => {
1848 self.call_value(reject, Value::Undefined, vec![error])?;
1849 }
1850 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1851 }
1852 if barrier {
1853 self.trace_barriers.pop();
1854 }
1855 Ok(Value::Object(promise))
1856 }
1857
1858 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1859 ///
1860 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1861 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1862 /// timer table, where the collector already scans it.
1863 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1864 let (promise, resolve, _reject) = self.new_promise_capability();
1865 let resolve = self.new_host_function(
1866 "resolve",
1867 1,
1868 Box::new(
1869 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1870 let value = args.first().cloned().unwrap_or(Value::Undefined);
1871 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1872 },
1873 ),
1874 );
1875 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1876 // timer table is part of what the collector walks.
1877 self.schedule_timer(Value::Object(resolve), delay_ms);
1878 Ok(Value::Object(promise))
1879 }
1880
1881 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1882 /// new promise resolved with it.
1883 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1884 if let Value::Object(object) = &value
1885 && self.promise_state(object).is_some()
1886 {
1887 return Ok(value);
1888 }
1889 let promise = self.new_promise();
1890 self.resolve_promise_with(&promise, value)?;
1891 Ok(Value::Object(promise))
1892 }
1893
1894 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1895 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1896 // Resolving a promise with itself is a `TypeError`. The check exists because the
1897 // alternative is a chain of self-reactions that never settles.
1898 if let Value::Object(object) = &value
1899 && object.ptr_eq(promise)
1900 {
1901 // The spec rejects *and* throws, so both the promise and the caller see it.
1902 let thrown = self.type_error("cannot resolve a promise with itself");
1903 let Signal::Throw(error) = thrown.clone() else {
1904 unreachable!("type_error always throws")
1905 };
1906 self.reject_promise(promise, error);
1907 return Err(thrown);
1908 }
1909 let then = match &value {
1910 Value::Object(object) => self.get_property(object, "then")?,
1911 _ => None,
1912 };
1913 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1914 if !callable_then {
1915 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1916 self.fulfill_promise(promise, value);
1917 return Ok(());
1918 }
1919 // Adopting a thenable is asynchronous — `then` is called from a job, never from
1920 // inside `resolve`, so a script cannot make a promise settle synchronously.
1921 self.jobs.push_back(Job::Thenable {
1922 then: then.expect("checked callable"),
1923 value,
1924 promise: promise.clone(),
1925 });
1926 Ok(())
1927 }
1928
1929 /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
1930 ///
1931 /// `C.resolve` is user code and may answer a plain thenable rather than one of this
1932 /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
1933 ///
1934 /// The property read is **not** short-circuitable even for a real promise: the spec says
1935 /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
1936 /// expects it to run. Skipping the read for promises not only lost the throw, it made
1937 /// the combinator's loop infinite — the test's iterator never sets `done`.
1938 pub fn invoke_then(
1939 &mut self,
1940 thenable: Value,
1941 on_fulfilled: Value,
1942 on_rejected: Value,
1943 ) -> JsResult<()> {
1944 let then = match &thenable {
1945 Value::Object(object) => self.get_property(object, "then")?,
1946 primitive => {
1947 let boxed = self.object_from(primitive)?;
1948 self.get_property(&boxed, "then")?
1949 }
1950 };
1951 let Some(then) = then else {
1952 return Err(self.type_error("thenable has no then method"));
1953 };
1954 if !matches!(&then, Value::Object(object) if object.is_callable()) {
1955 return Err(self.type_error("then is not a function"));
1956 }
1957 self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
1958 Ok(())
1959 }
1960
1961 /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
1962 ///
1963 /// `Promise.prototype.then` in one step: register a reaction and answer the derived
1964 /// promise.
1965 pub fn perform_then(
1966 &mut self,
1967 promise: &Gc<JsObject>,
1968 on_fulfilled: Option<Value>,
1969 on_rejected: Option<Value>,
1970 ) -> JsResult<Value> {
1971 let Some(state) = self.promise_state(promise) else {
1972 return Err(self.type_error("not a promise"));
1973 };
1974 // Whether a rejection handler is being attached decides whether a recorded
1975 // rejection stops being unhandled, so it is read before the values are moved.
1976 let has_rejection_handler = on_rejected.is_some();
1977 let derived = self.new_promise();
1978 let reaction = crate::object::PromiseReaction {
1979 on_fulfilled,
1980 on_rejected,
1981 promise: derived.clone(),
1982 };
1983 let settled = {
1984 let mut state = state.borrow_mut();
1985 // A rejection somebody reacts to is no longer unhandled.
1986 state.handled = true;
1987 match &state.status {
1988 crate::object::PromiseStatus::Pending => {
1989 state.reactions.push(reaction.clone());
1990 None
1991 }
1992 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
1993 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
1994 }
1995 };
1996 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
1997 // later, means somebody is listening after all.
1998 if has_rejection_handler {
1999 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2000 }
2001 if let Some((argument, rejected)) = settled {
2002 let handler = if rejected {
2003 reaction.on_rejected
2004 } else {
2005 reaction.on_fulfilled
2006 };
2007 self.jobs.push_back(Job::Reaction {
2008 handler,
2009 argument,
2010 rejected,
2011 promise: reaction.promise,
2012 });
2013 }
2014 Ok(Value::Object(derived))
2015 }
2016
2017 /// The rejections nobody listened to, formatted the way the reference reports them.
2018 ///
2019 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2020 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2021 /// unhandled at the point the queue drains, because a `then` may still be attached
2022 /// before the host acts on it.
2023 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2024 let entries = std::mem::take(&mut self.unhandled);
2025 // Somebody may have attached a handler after the rejection was recorded, so the
2026 // promise is the authority rather than the list.
2027 let still_unhandled: Vec<Value> = entries
2028 .into_iter()
2029 .filter_map(|(promise, reason)| {
2030 let handled = self
2031 .promise_state(&promise)
2032 .map(|state| state.borrow().handled)
2033 .unwrap_or(true);
2034 (!handled).then_some(reason)
2035 })
2036 .collect();
2037 still_unhandled
2038 .into_iter()
2039 .map(|reason| {
2040 let text = self.describe_exception(&reason);
2041 let stack = match &reason {
2042 Value::Object(object) => self
2043 .get_property(object, "stack")
2044 .ok()
2045 .flatten()
2046 .map(|value| value.to_js_string())
2047 // `stack` carries a trailing newline of its own, which would leave
2048 // a blank line between two reported rejections.
2049 .map(|text| text.trim_end().to_string())
2050 .unwrap_or_default(),
2051 _ => String::new(),
2052 };
2053 if stack.is_empty() {
2054 format!("Possibly unhandled promise rejection: {text}")
2055 } else {
2056 format!("Possibly unhandled promise rejection: {text}\n{stack}")
2057 }
2058 })
2059 .collect()
2060 }
2061
2062 /// Run the microtask queue to exhaustion.
2063 ///
2064 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2065 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2066 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2067 ///
2068 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2069 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2070 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2071 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2072 crate::builtins::json::parse_text(self, text, true)
2073 }
2074
2075 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2076 ///
2077 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2078 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2079 /// immediately, and `setTimeout(f, -1)` is ordinary code.
2080 ///
2081 /// The callback is called with **no arguments**. The reference stores only the function
2082 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2083 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2084 /// extra arguments arrive as `undefined`.
2085 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2086 let id = self.next_timer_id;
2087 // Wrap rather than grow: the id reaches the script as an `Int32`.
2088 self.next_timer_id = if self.next_timer_id == i32::MAX {
2089 1
2090 } else {
2091 self.next_timer_id + 1
2092 };
2093 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2094 self.tasks.push(Task::Timer {
2095 id,
2096 callback,
2097 due_at,
2098 });
2099 id
2100 }
2101
2102 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2103 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2104 pub fn cancel_timer(&mut self, id: i32) -> bool {
2105 let before = self.tasks.len();
2106 self.tasks.retain(|task| match task {
2107 Task::Timer { id: task_id, .. } => *task_id != id,
2108 });
2109 self.tasks.len() != before
2110 }
2111
2112 /// How long until the earliest pending timer, or `None` when none is pending.
2113 pub fn next_timeout(&self) -> Option<std::time::Duration> {
2114 let now = std::time::Instant::now();
2115 self.tasks
2116 .iter()
2117 .map(|task| match task {
2118 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2119 })
2120 .min()
2121 }
2122
2123 /// Run one turn of the event loop.
2124 ///
2125 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2126 /// run at most one due timer, then drain again. The blocking belongs to the caller
2127 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2128 /// is how it asks.
2129 ///
2130 /// One timer per turn rather than all of them: a timer callback may schedule another
2131 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2132 /// starve the microtask queue.
2133 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2134 self.drain_jobs()?;
2135 let now = std::time::Instant::now();
2136 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2137 // followed by `setTimeout(g, 1)` must run `g` first.
2138 let due = self
2139 .tasks
2140 .iter()
2141 .enumerate()
2142 .filter(|(_, task)| match task {
2143 Task::Timer { due_at, .. } => *due_at <= now,
2144 })
2145 .min_by_key(|(_, task)| match task {
2146 Task::Timer { due_at, .. } => *due_at,
2147 })
2148 .map(|(index, _)| index);
2149 let Some(index) = due else {
2150 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2151 // descriptor is registered but no timer is closer, so a script that never
2152 // touches the descriptor still gets control back. Without a cap a handler on a
2153 // descriptor that is never ready would block for as long as the host allows.
2154 let timeout = self
2155 .next_timeout()
2156 .unwrap_or(std::time::Duration::from_secs(10))
2157 .min(std::time::Duration::from_secs(10));
2158 if !self.fd_handlers.is_empty() {
2159 // Blocking on a timer while descriptors are registered would starve them,
2160 // and blocking on the descriptors while a timer is due would delay it; the
2161 // host polls with the earlier of the two deadlines, which this timeout is.
2162 return Ok(Turn::Poll(timeout));
2163 }
2164 return Ok(match self.next_timeout() {
2165 Some(wait) => Turn::Wait(wait),
2166 None => Turn::Done,
2167 });
2168 };
2169 let Task::Timer { callback, .. } = self.tasks.remove(index);
2170 let this = Value::Undefined;
2171 // A throwing timer callback must not stop the loop: the reference reports it and
2172 // keeps going, because the alternative is that one bad timer silently stops every
2173 // later one.
2174 // No arguments: see `schedule_timer` — the reference calls the callback bare.
2175 match self.call_value(callback, this, Vec::new()) {
2176 Ok(_) => {}
2177 Err(Signal::Throw(value)) => {
2178 let text = self.describe_exception(&value);
2179 self.timer_errors.push(text);
2180 }
2181 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2182 }
2183 self.drain_jobs()?;
2184 Ok(Turn::Ran)
2185 }
2186
2187 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2188 ///
2189 /// `callback` of `None` unregisters that direction, and an entry with neither direction
2190 /// left is removed — the reference does the same, so a script can rely on
2191 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2192 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2193 let entry = self.fd_handlers.entry(fd).or_default();
2194 if readable {
2195 entry.read = callback;
2196 } else {
2197 entry.write = callback;
2198 }
2199 if entry.read.is_none() && entry.write.is_none() {
2200 self.fd_handlers.remove(&fd);
2201 }
2202 }
2203
2204 /// Register or clear an `os.signal` handler.
2205 ///
2206 /// `None` removes it; the host separately restores the default disposition or sets
2207 /// ignore, because which of those happened is the script's choice (`null` versus
2208 /// `undefined`) and not something this table can express.
2209 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2210 match handler {
2211 Some(handler) => {
2212 self.signal_handlers.insert(signal, handler);
2213 }
2214 None => {
2215 self.signal_handlers.remove(&signal);
2216 }
2217 }
2218 }
2219
2220 /// Run the handler for `signal`, reporting whether one ran.
2221 ///
2222 /// A throwing handler is reported and the loop continues, like a timer's.
2223 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2224 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2225 return Ok(false);
2226 };
2227 match self.call_value(handler, Value::Undefined, Vec::new()) {
2228 Ok(_) => {}
2229 Err(Signal::Throw(value)) => {
2230 let text = self.describe_exception(&value);
2231 self.timer_errors.push(text);
2232 }
2233 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2234 }
2235 self.drain_jobs()?;
2236 Ok(true)
2237 }
2238
2239 /// The descriptors the host has to poll, and in which direction.
2240 ///
2241 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2242 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2243 /// `os_poll` asks for.
2244 pub fn pending_fds(&self) -> Vec<FdInterest> {
2245 self.fd_handlers
2246 .iter()
2247 .map(|(fd, entry)| FdInterest {
2248 fd: *fd,
2249 read: entry.read.is_some(),
2250 write: entry.write.is_some(),
2251 })
2252 .collect()
2253 }
2254
2255 /// Call the handler registered for `fd`, reporting whether one ran.
2256 ///
2257 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2258 /// poll iteration and then restarts the loop, because the handler may have changed the
2259 /// registration list underneath it; doing the same here keeps a handler that
2260 /// unregisters itself from being called with stale state.
2261 ///
2262 /// A throwing handler is reported and the loop continues — a bad handler must not stop
2263 /// every later one, exactly as with timers.
2264 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2265 let Some(entry) = self.fd_handlers.get(&fd) else {
2266 return Ok(false);
2267 };
2268 let callback = if readable {
2269 entry.read.clone()
2270 } else if writable {
2271 entry.write.clone()
2272 } else {
2273 None
2274 };
2275 let Some(callback) = callback else {
2276 return Ok(false);
2277 };
2278 self.drain_jobs()?;
2279 match self.call_value(callback, Value::Undefined, Vec::new()) {
2280 Ok(_) => {}
2281 Err(Signal::Throw(value)) => {
2282 let text = self.describe_exception(&value);
2283 self.timer_errors.push(text);
2284 }
2285 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2286 }
2287 self.drain_jobs()?;
2288 Ok(true)
2289 }
2290
2291 /// Take the errors timer callbacks threw, leaving the list empty.
2292 pub fn take_timer_errors(&mut self) -> Vec<String> {
2293 std::mem::take(&mut self.timer_errors)
2294 }
2295
2296 /// Whether anything is still pending: a microtask or a timer.
2297 pub fn has_pending_work(&self) -> bool {
2298 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2299 }
2300
2301 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2302 pub fn has_pending_timers_or_jobs(&self) -> bool {
2303 !self.jobs.is_empty() || !self.tasks.is_empty()
2304 }
2305
2306 /// Run every queued microtask, including ones queued while draining.
2307 pub fn drain_jobs(&mut self) -> JsResult<()> {
2308 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2309 // would spin forever, so the drain is bounded the way the call stack is.
2310 let mut budget = 1_000_000usize;
2311 while let Some(job) = self.jobs.pop_front() {
2312 if budget == 0 {
2313 return Err(Signal::Throw(
2314 self.make_error("InternalError", "promise job queue did not drain"),
2315 ));
2316 }
2317 budget -= 1;
2318 self.run_job(job)?;
2319 // `FinalizationRegistry` at the job boundary: this is the safe point where the
2320 // engine may run script that the script itself did not ask for. Doing it here
2321 // rather than from a drop hook is what keeps the callback out of arbitrary
2322 // engine bookkeeping — see `builtins::weak`'s header.
2323 crate::builtins::weak::drain_finalizers(self)?;
2324 }
2325 // A script that queued no jobs may still have dropped targets, so the checkpoint
2326 // runs once more after the queue empties.
2327 crate::builtins::weak::drain_finalizers(self)?;
2328 Ok(())
2329 }
2330
2331 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2332 ///
2333 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2334 /// `None` and is swept out here. This is also where the realm learns that a registry
2335 /// died, which is why it is a mutation rather than a read.
2336 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2337 let handles = std::mem::take(&mut self.realm.finalization_registries);
2338 let mut live = Vec::with_capacity(handles.len());
2339 for handle in handles {
2340 let Some(object) = handle.upgrade() else {
2341 continue;
2342 };
2343 let Some(state) = object.finalization_state() else {
2344 continue;
2345 };
2346 live.push((object.clone(), *state));
2347 self.realm.finalization_registries.push(object.downgrade());
2348 }
2349 live
2350 }
2351
2352 /// Run one microtask.
2353 fn run_job(&mut self, job: Job) -> JsResult<()> {
2354 match job {
2355 Job::Reaction {
2356 handler: None,
2357 argument,
2358 rejected,
2359 promise,
2360 } => {
2361 // No handler: the settlement passes straight through to the derived
2362 // promise, which is why `p.catch(f)` ignores fulfilments.
2363 if rejected {
2364 self.reject_promise(&promise, argument);
2365 } else {
2366 self.fulfill_promise(&promise, argument);
2367 }
2368 Ok(())
2369 }
2370 Job::Reaction {
2371 handler: Some(handler),
2372 argument,
2373 promise,
2374 ..
2375 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2376 Ok(answer) => {
2377 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2378 self.reject_promise(&promise, error);
2379 }
2380 Ok(())
2381 }
2382 Err(Signal::Throw(reason)) => {
2383 self.reject_promise(&promise, reason);
2384 Ok(())
2385 }
2386 Err(other) => Err(other),
2387 },
2388 Job::Thenable {
2389 then,
2390 value,
2391 promise,
2392 } => {
2393 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2394 // the value it produces settles `promise`.
2395 // The thenable's `then` gets this promise's own pair, so whatever it
2396 // produces settles `promise`.
2397 let resolve = JsObject::function(
2398 self.heap,
2399 Some(self.realm.function_proto.clone()),
2400 Callable::PromiseResolve(promise.clone()),
2401 );
2402 let reject = JsObject::function(
2403 self.heap,
2404 Some(self.realm.function_proto.clone()),
2405 Callable::PromiseReject(promise.clone()),
2406 );
2407 match self.call_value(
2408 then,
2409 value,
2410 vec![Value::Object(resolve), Value::Object(reject)],
2411 ) {
2412 Ok(_) => Ok(()),
2413 Err(Signal::Throw(reason)) => {
2414 self.reject_promise(&promise, reason);
2415 Ok(())
2416 }
2417 Err(other) => Err(other),
2418 }
2419 }
2420 Job::Resume {
2421 coroutine,
2422 promise,
2423 kind,
2424 value,
2425 } => self.drive_async(&coroutine, &promise, kind, value),
2426 Job::GeneratorResume {
2427 generator,
2428 promise,
2429 kind,
2430 value,
2431 } => self.step_async_generator(&generator, &promise, kind, value),
2432 Job::Import {
2433 specifier,
2434 referrer,
2435 promise,
2436 } => {
2437 self.run_dynamic_import(&specifier, &referrer, &promise);
2438 Ok(())
2439 }
2440 }
2441 }
2442
2443 /// One element of a `Promise` combinator settled.
2444 ///
2445 /// The shared state object holds the result array, the number still outstanding, and
2446 /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2447 /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2448 /// to settle, only whatever `Sub` said a capability is.
2449 ///
2450 /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2451 /// and `any` must ignore every later settlement, and `all` must not report a second
2452 /// rejection after the first.
2453 fn settle_combinator(
2454 &mut self,
2455 state: &Gc<JsObject>,
2456 index: usize,
2457 fulfilled: bool,
2458 value: Value,
2459 ) -> JsResult<()> {
2460 let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2461 // Each element settles at most once: a thenable may call `onFulfilled` twice
2462 // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2463 // call a no-op. Without it the second call decremented `remaining` again and settled
2464 // `all` with a short values array (`call-resolve-element-items`).
2465 let done = field("done");
2466 let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2467 let settled = field("settled").is_some_and(|value| value.to_boolean());
2468 if settled {
2469 return Ok(());
2470 }
2471 if let Some(Value::Object(done)) = &done {
2472 if done
2473 .array_get(index)
2474 .is_some_and(|value| value.to_boolean())
2475 {
2476 return Ok(());
2477 }
2478 done.array_set(self.heap, index, Value::Bool(true));
2479 }
2480 let resolve = field("resolve");
2481 let reject = field("reject");
2482 let results = field("results").and_then(|value| value.as_object().cloned());
2483 // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2484 // promise: the handler is a plain function the constructor chose.
2485 let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2486 if let Some(handler) = handler {
2487 interp.call_value(handler, Value::Undefined, vec![value])?;
2488 }
2489 Ok(())
2490 };
2491 match kind {
2492 // `race`: the first settlement wins and stops the rest.
2493 3 => {
2494 state.define_data("settled", Value::Bool(true));
2495 let handler = if fulfilled { resolve } else { reject };
2496 settle_with(self, handler, value)?;
2497 return Ok(());
2498 }
2499 // `all`: the first rejection wins outright.
2500 0 if !fulfilled => {
2501 state.define_data("settled", Value::Bool(true));
2502 settle_with(self, reject, value)?;
2503 return Ok(());
2504 }
2505 // `any`: the first fulfilment wins.
2506 2 if fulfilled => {
2507 state.define_data("settled", Value::Bool(true));
2508 settle_with(self, resolve, value)?;
2509 return Ok(());
2510 }
2511 _ => {}
2512 }
2513 let Some(results) = &results else {
2514 return Ok(());
2515 };
2516 match kind {
2517 0 => {
2518 results.array_set(self.heap, index, value);
2519 }
2520 // `allSettled` never rejects; each slot records what happened.
2521 1 => {
2522 let record = self.new_object(Some(self.realm.object_proto.clone()));
2523 if fulfilled {
2524 record.define_data("status", self.string("fulfilled"));
2525 record.define_data("value", value);
2526 } else {
2527 record.define_data("status", self.string("rejected"));
2528 record.define_data("reason", value);
2529 }
2530 results.array_set(self.heap, index, Value::Object(record));
2531 }
2532 // `any`: a rejection is parked in the errors array and the sweep continues.
2533 2 => {
2534 results.array_set(self.heap, index, value);
2535 }
2536 _ => {}
2537 }
2538 let remaining = field("remaining")
2539 .map(|value| value.to_int32())
2540 .unwrap_or(0);
2541 let left = remaining - 1;
2542 state.define_data("remaining", Value::Int(left));
2543 if left != 0 {
2544 return Ok(());
2545 }
2546 state.define_data("settled", Value::Bool(true));
2547 match kind {
2548 0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2549 2 => {
2550 // The rejection is an `AggregateError` whose `errors` is the results array
2551 // itself — the slots are the reasons, in input order.
2552 let errors = results.array_elements().unwrap_or_default();
2553 let error = self.aggregate_error(errors, "all promises were rejected");
2554 settle_with(self, reject, error)?;
2555 }
2556 _ => {}
2557 }
2558 Ok(())
2559 }
2560
2561 /// Build an async function's result: a promise whose body runs as a coroutine.
2562 pub fn new_async_function(
2563 &mut self,
2564 function: Value,
2565 this: Value,
2566 args: Vec<Value>,
2567 ) -> JsResult<Value> {
2568 let promise = self.new_promise();
2569 let coroutine = self.new_coroutine(function, this, args)?;
2570 if let Err(Signal::Throw(reason)) =
2571 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2572 {
2573 self.reject_promise(&promise, reason);
2574 }
2575 Ok(Value::Object(promise))
2576 }
2577
2578 /// The coroutine an async body runs in.
2579 ///
2580 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2581 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2582 /// than growing a second state machine. The difference is only in the ending — a
2583 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2584 /// Run `code` as an async function body, answering the promise it settles.
2585 ///
2586 /// Used for a module with top-level `await`: its body is an async function whose
2587 /// caller is the host, so there is no function object to pass through
2588 /// [`Interp::new_async_function`].
2589 pub fn run_async_body(
2590 &mut self,
2591 code: Gc<CompiledCode>,
2592 env: Gc<ClosureEnv>,
2593 this: Value,
2594 ) -> JsResult<Value> {
2595 let promise = self.new_promise();
2596 let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2597 if let Err(Signal::Throw(reason)) =
2598 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2599 {
2600 self.reject_promise(&promise, reason);
2601 }
2602 Ok(Value::Object(promise))
2603 }
2604
2605 fn new_coroutine(
2606 &mut self,
2607 function: Value,
2608 this: Value,
2609 args: Vec<Value>,
2610 ) -> JsResult<Gc<JsObject>> {
2611 let Some(object) = function.as_object().cloned() else {
2612 return Err(self.type_error("not a function"));
2613 };
2614 let Some((code, env)) = bytecode_of(&object) else {
2615 return Err(self.type_error("not a function"));
2616 };
2617 self.new_coroutine_from(code, env, this, args)
2618 }
2619
2620 /// Build a coroutine over an already-resolved body.
2621 fn new_coroutine_from(
2622 &mut self,
2623 code: Gc<CompiledCode>,
2624 env: Gc<ClosureEnv>,
2625 this: Value,
2626 args: Vec<Value>,
2627 ) -> JsResult<Gc<JsObject>> {
2628 let function = Value::Undefined;
2629 self.push_frame(code, env, this, args, function)?;
2630 let frame = self.frames.pop().expect("push_frame just pushed it");
2631 let state = GeneratorState {
2632 frame: Some(frame),
2633 phase: GeneratorPhase::SuspendedStart,
2634 parked_on_await: false,
2635 parked_on_yield_star: false,
2636 requests: std::collections::VecDeque::new(),
2637 async_busy: false,
2638 };
2639 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2640 coroutine.with_mut(|data| {
2641 data.kind = ObjectKind::Generator(Box::new(state));
2642 });
2643 Ok(coroutine)
2644 }
2645
2646 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2647 /// `await` and `value` is what it awaited.
2648 fn resume_coroutine(
2649 &mut self,
2650 coroutine: &Gc<JsObject>,
2651 kind: ResumeKind,
2652 value: Value,
2653 ) -> JsResult<(Value, bool)> {
2654 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2655 ObjectKind::Generator(state) => Some(std::mem::replace(
2656 state.as_mut(),
2657 GeneratorState {
2658 frame: None,
2659 phase: GeneratorPhase::Executing,
2660 parked_on_await: false,
2661 parked_on_yield_star: false,
2662 requests: std::collections::VecDeque::new(),
2663 async_busy: false,
2664 },
2665 )),
2666 _ => None,
2667 }) else {
2668 return Err(self.type_error("not a coroutine"));
2669 };
2670 let result = self.step_generator(&mut state, kind, value);
2671 coroutine.with_mut(|data| {
2672 data.kind = ObjectKind::Generator(Box::new(state));
2673 });
2674 let (value, done, _ready, _reason) = result?;
2675 Ok((value, done))
2676 }
2677
2678 /// Advance an async body and settle its promise with the outcome.
2679 fn drive_async(
2680 &mut self,
2681 coroutine: &Gc<JsObject>,
2682 promise: &Gc<JsObject>,
2683 kind: ResumeKind,
2684 value: Value,
2685 ) -> JsResult<()> {
2686 match self.resume_coroutine(coroutine, kind, value) {
2687 Ok((value, true)) => {
2688 // `Ok` with `done` means the body finished *normally*, even when it was
2689 // resumed by a `throw` — `try { await p } catch {}` completes by
2690 // returning. Only the `Err` arm below is a rejection.
2691 //
2692 // Resolving rather than fulfilling matters: `return promise` in an async
2693 // body adopts the inner promise, so `async function f(){ return
2694 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2695 // promise.
2696 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2697 self.reject_promise(promise, reason);
2698 }
2699 Ok(())
2700 }
2701 Ok((value, false)) => {
2702 // Parked on `await`: follow what it awaited and resume with the outcome.
2703 let awaited = match self.promise_resolve_value(value) {
2704 Ok(awaited) => awaited,
2705 Err(Signal::Throw(error)) => {
2706 self.reject_promise(promise, error);
2707 return Ok(());
2708 }
2709 Err(other) => return Err(other),
2710 };
2711 self.hook_await(awaited, coroutine, promise)
2712 }
2713 Err(Signal::Throw(reason)) => {
2714 self.reject_promise(promise, reason);
2715 Ok(())
2716 }
2717 Err(other) => Err(other),
2718 }
2719 }
2720
2721 /// Arrange for `coroutine` to resume when `awaited` settles.
2722 fn hook_await(
2723 &mut self,
2724 awaited: Value,
2725 coroutine: &Gc<JsObject>,
2726 promise: &Gc<JsObject>,
2727 ) -> JsResult<()> {
2728 let resumed = JsObject::function(
2729 self.heap,
2730 Some(self.realm.function_proto.clone()),
2731 Callable::AwaitResume {
2732 coroutine: coroutine.clone(),
2733 promise: promise.clone(),
2734 kind: ResumeKind::Next,
2735 },
2736 );
2737 let raised = JsObject::function(
2738 self.heap,
2739 Some(self.realm.function_proto.clone()),
2740 Callable::AwaitResume {
2741 coroutine: coroutine.clone(),
2742 promise: promise.clone(),
2743 kind: ResumeKind::Throw,
2744 },
2745 );
2746 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2747 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2748 let Value::Object(awaited) = &awaited else {
2749 self.jobs.push_back(Job::Resume {
2750 coroutine: coroutine.clone(),
2751 promise: promise.clone(),
2752 kind: ResumeKind::Next,
2753 value: awaited,
2754 });
2755 return Ok(());
2756 };
2757 self.perform_then(
2758 awaited,
2759 Some(Value::Object(resumed)),
2760 Some(Value::Object(raised)),
2761 )?;
2762 Ok(())
2763 }
2764
2765 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2766 /// things an engine keeps outside it — array elements and an array's `length`.
2767 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2768 if let Some(property) = object.own_property_key(key) {
2769 return Some(property);
2770 }
2771 // An array's elements live in their own vector rather than the property table, so
2772 // a descriptor for one has to be synthesized — with the attributes an element has.
2773 if let Some(index) = key.as_str().and_then(array_index)
2774 && let Some(value) = object.array_get(index as usize)
2775 && !matches!(value, Value::Hole)
2776 {
2777 return Some(Property::data(value));
2778 }
2779 // `length` is an own property of an array that is not in its property table
2780 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2781 // and non-enumerable.
2782 if key.as_str() == Some("length")
2783 && let Some(length) = object.array_length()
2784 {
2785 return Some(Property {
2786 value: Some(crate::object::length_value(length)),
2787 writable: object.length_writable(),
2788 enumerable: false,
2789 configurable: false,
2790 getter: None,
2791 setter: None,
2792 });
2793 }
2794 None
2795 }
2796
2797 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2798 pub fn object_get_own_property(
2799 &mut self,
2800 object: &Gc<JsObject>,
2801 key: &PropertyKey,
2802 ) -> JsResult<Option<Property>> {
2803 if let Some(answer) = self.proxy_get_own_property(object, key)? {
2804 return Ok(answer);
2805 }
2806 if let Some(exotic) = object.exotic()
2807 && let Some(answer) = exotic.get_own_property(self, object, key)?
2808 {
2809 return Ok(answer);
2810 }
2811 // A mapped `arguments` index is a data property as far as script can see: the
2812 // accessor pair that aliases the parameter is plumbing, and exposing it would
2813 // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
2814 // report a `get` where the spec has a `[[Value]]`.
2815 if let Some(index) = key.as_str().and_then(crate::object::array_index)
2816 && let Some(cell) = object.mapped_argument_cell(index as usize)
2817 {
2818 // Non-configurable is *not* the default: an ordinary mapped index is
2819 // configurable, and only becomes non-configurable once something
2820 // redefines it. Preserve whatever the property table currently says.
2821 // The attributes come from whatever the property table holds, because they
2822 // can be changed independently of the mapping; only the *value* and the
2823 // data-property *kind* are the accessor's secret.
2824 let flags = Self::ordinary_own_property(object, key);
2825 if let Some(existing) = &flags
2826 && !existing.is_accessor()
2827 {
2828 // Already demapped: the table entry is the answer, not the cell.
2829 return Ok(flags);
2830 }
2831 return Ok(Some(Property {
2832 value: Some(cell.get()),
2833 writable: true,
2834 enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
2835 configurable: flags.as_ref().is_some_and(|p| p.configurable),
2836 ..Property::default()
2837 }));
2838 }
2839 Ok(Self::ordinary_own_property(object, key))
2840 }
2841
2842 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
2843 pub fn object_define_own_property(
2844 &mut self,
2845 object: &Gc<JsObject>,
2846 key: &PropertyKey,
2847 property: Property,
2848 ) -> JsResult<bool> {
2849 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
2850 return Ok(accepted);
2851 }
2852 // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
2853 // non-extensible object. The check lives here rather than in the callers because
2854 // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
2855 // `Array.prototype.filter` uses to store its result, and a species object made
2856 // non-extensible by its own constructor must make that a `TypeError`
2857 // (`target-array-non-extensible`).
2858 if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
2859 return Ok(false);
2860 }
2861 // A host class that intercepts definitions owns the attributes of the properties it
2862 // defines: `_class`-style storage on the native side is the usual reason.
2863 if let Some(exotic) = object.exotic()
2864 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
2865 {
2866 return Ok(accepted);
2867 }
2868 // An array index is stored in the element vector, which can hold a plain value and
2869 // nothing else. An accessor — or a data property with non-default attributes —
2870 // therefore has to live in the property table, and the element slot is blanked so
2871 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
2872 // {get})` stored the accessor where no read ever looked, and the array kept
2873 // answering its old value.
2874 // An array's `length` is not stored in the property table, so defining it has to
2875 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
2876 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
2877 // {value: 1})` reported success and changed nothing.
2878 if key.as_str() == Some("length") && object.is_array() {
2879 // `{writable: false}` on `length` does not change the length, but it does make
2880 // it read-only — after which neither a later `{writable: true}` nor a store
2881 // past the end may succeed.
2882 if property.value.is_none() {
2883 if !object.length_writable() && property.writable {
2884 return Ok(false);
2885 }
2886 object.set_length_writable(property.writable);
2887 return Ok(true);
2888 }
2889 if !object.length_writable() {
2890 return Ok(false);
2891 }
2892 }
2893 if key.as_str() == Some("length")
2894 && object.is_array()
2895 && let Some(value) = property.value.clone()
2896 {
2897 let requested = value.to_number();
2898 let valid = requested.is_finite()
2899 && requested >= 0.0
2900 && requested.fract() == 0.0
2901 && requested <= u32::MAX as f64;
2902 if !valid {
2903 return Err(self.range_error("invalid array length"));
2904 }
2905 // Truncating deletes the elements above the new length, and a non-configurable
2906 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
2907 // makes `a.length = 2` fail rather than quietly drop it.
2908 let current = object.array_length().unwrap_or(0);
2909 let requested = requested as usize;
2910 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
2911 return Ok(false);
2912 }
2913 object.array_set_length(self.heap, requested);
2914 return Ok(true);
2915 }
2916 let plain = property.writable
2917 && property.enumerable
2918 && property.configurable
2919 && !property.is_accessor();
2920 if let Some(index) = key.as_str().and_then(array_index)
2921 && object.is_array()
2922 {
2923 // Growing the array needs a writable `length`: after
2924 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
2925 // be added.
2926 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
2927 return Ok(false);
2928 }
2929 if plain && property.value.is_some() {
2930 // An ordinary element: the vector is where a read looks first, so it has
2931 // to be the vector that changes — unless the index is too far out to be
2932 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
2933 // one property, because past its own limit it stores the index as an
2934 // ordinary key. Falling through to `define_key` below is the same choice,
2935 // and the alternative was worse: the store used to be *dropped* and the
2936 // length left at 0, which is a silent wrong answer.
2937 let value = property.value.clone().unwrap_or(Value::Undefined);
2938 object.delete_key(key);
2939 if object.array_set(self.heap, index as usize, value) {
2940 return Ok(true);
2941 }
2942 // Past the dense limit the element lives in the table like any property.
2943 object.note_element_descriptor();
2944 object.define_key(key, property);
2945 // A sparse store past the dense limit still extends `length`, which is what
2946 // `a[a.length] = v` relies on — but only extends: shortening would delete
2947 // the sparse properties above the index, including this one.
2948 if index as usize + 1 > object.array_length().unwrap_or(0) {
2949 object.array_set_length(self.heap, index as usize + 1);
2950 }
2951 return Ok(true);
2952 }
2953 // A non-plain element — an accessor, or an attribute that is not the default —
2954 // lives in the table while the slot becomes a hole. Recording it keeps every
2955 // later `a[i] = v` off the dense path, where the write would have shadowed the
2956 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
2957 // replace the accessor with a plain data property.
2958 object.note_element_descriptor();
2959 object.define_key(key, property);
2960 // The slot stays, so `length` does not shrink; a hole is not an element, so
2961 // the table entry is now what a read finds.
2962 object.array_set(self.heap, index as usize, Value::Hole);
2963 return Ok(true);
2964 }
2965 object.define_key(key, property);
2966 Ok(true)
2967 }
2968
2969 /// Build a proxy object over `target`, with its traps read from `handler`.
2970 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
2971 JsObject::proxy(self.heap, target, handler)
2972 }
2973
2974 /// The `revoke` function for a proxy's slots.
2975 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
2976 JsObject::function(
2977 self.heap,
2978 Some(self.realm.function_proto.clone()),
2979 Callable::Revoker(slots),
2980 )
2981 }
2982
2983 /// A new array.
2984 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
2985 let array = JsObject::array(
2986 self.heap,
2987 Some(self.realm.array_proto.clone()),
2988 elements.len(),
2989 );
2990 for (index, element) in elements.into_iter().enumerate() {
2991 array.array_set(self.heap, index, element);
2992 }
2993 array
2994 }
2995
2996 /// A new native function object.
2997 ///
2998 /// The observable `name` and `length` are installed as properties here, which is
2999 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3000 /// so `f.name = "x"` behaves like the writable property it is.
3001 /// A native constructor that builds its own instance after validating its arguments.
3002 ///
3003 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3004 /// check runs before `new.target.prototype` is read.
3005 pub fn new_native_ctor(
3006 &self,
3007 name: impl Into<String>,
3008 length: u32,
3009 func: NativeFn,
3010 ) -> Gc<JsObject> {
3011 let function = JsObject::function(
3012 self.heap,
3013 Some(self.realm.function_proto.clone()),
3014 Callable::Native {
3015 func,
3016 own_instance: true,
3017 },
3018 );
3019 function.set_constructible(true);
3020 function.define(
3021 "length",
3022 Property::name_or_length(Value::Int(length as i32)),
3023 );
3024 function.define("name", Property::name_or_length(self.string(name)));
3025 function
3026 }
3027
3028 /// A native constructor that lets `new` build the instance first.
3029 ///
3030 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3031 /// validation that must precede reading `new.target.prototype`, so the object can be
3032 /// created before the implementation runs. Distinct from [`Interp::new_native`],
3033 /// which makes a *method* and therefore not a constructor at all.
3034 pub fn new_native_constructor(
3035 &self,
3036 name: impl Into<String>,
3037 length: u32,
3038 func: NativeFn,
3039 ) -> Gc<JsObject> {
3040 let function = self.new_native(name, length, func);
3041 function.set_constructible(true);
3042 function
3043 }
3044
3045 /// A new host function object: a native closure that carries its own state.
3046 ///
3047 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3048 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3049 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3050 /// this safe: the closure must not capture a `Gc`.
3051 pub fn new_host_function(
3052 &self,
3053 name: impl Into<String>,
3054 length: u32,
3055 func: crate::object::HostFn,
3056 ) -> Gc<JsObject> {
3057 self.new_host_inner(name.into(), length, func, false)
3058 }
3059
3060 /// A host constructor: `new` hands it `this = undefined`, so it validates its
3061 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3062 pub fn new_host_ctor(
3063 &self,
3064 name: impl Into<String>,
3065 length: u32,
3066 func: crate::object::HostFn,
3067 ) -> Gc<JsObject> {
3068 let function = self.new_host_inner(name.into(), length, func, true);
3069 function.set_constructible(true);
3070 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3071 // installs its own methods on it, so it starts as a plain object.
3072 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3073 function.define(
3074 "prototype",
3075 Property {
3076 value: Some(Value::Object(proto)),
3077 writable: true,
3078 enumerable: false,
3079 configurable: false,
3080 ..Property::default()
3081 },
3082 );
3083 function
3084 }
3085
3086 fn new_host_inner(
3087 &self,
3088 name: String,
3089 length: u32,
3090 func: crate::object::HostFn,
3091 own_instance: bool,
3092 ) -> Gc<JsObject> {
3093 let function = JsObject::function(
3094 self.heap,
3095 Some(self.realm.function_proto.clone()),
3096 Callable::Host {
3097 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3098 own_instance,
3099 },
3100 );
3101 function.define(
3102 "length",
3103 Property::name_or_length(Value::Int(length as i32)),
3104 );
3105 function.define("name", Property::name_or_length(self.string(name)));
3106 function
3107 }
3108
3109 /// A callable object with the `length`/`name` a built-in function has, in that order.
3110 ///
3111 /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3112 /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3113 /// [`JsObject::function`] defines neither, which is why every capability helper built
3114 /// with it reported no own `length` and no own `name` at all.
3115 ///
3116 /// The attributes are the spec's for a built-in: not writable, not enumerable,
3117 /// configurable.
3118 pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3119 let function =
3120 JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3121 function.define(
3122 "length",
3123 Property::name_or_length(Value::Int(length as i32)),
3124 );
3125 function.define("name", Property::name_or_length(self.string(name)));
3126 function
3127 }
3128
3129 /// A new native function object.
3130 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3131 let function = JsObject::function(
3132 self.heap,
3133 Some(self.realm.function_proto.clone()),
3134 Callable::Native {
3135 func,
3136 own_instance: false,
3137 },
3138 );
3139 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3140 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3141 // `length,name` and this listed `name,length`. A bytecode function already gets it
3142 // the right way round; only native ones were built backwards.
3143 function.define(
3144 "length",
3145 Property::name_or_length(Value::Int(length as i32)),
3146 );
3147 function.define("name", Property::name_or_length(self.string(name)));
3148 function
3149 }
3150
3151 /// A new bound function.
3152 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3153 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3154 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3155 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3156 let constructible = target
3157 .as_object()
3158 .is_some_and(|target| target.is_constructor());
3159 let bound = JsObject::function(
3160 self.heap,
3161 Some(self.realm.function_proto.clone()),
3162 Callable::Bound { target, this, args },
3163 );
3164 bound.set_constructible(constructible);
3165 bound
3166 }
3167
3168 /// A new reference cell.
3169 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3170 Gc::new(self.heap, Cell::new(value))
3171 }
3172
3173 // -- running ------------------------------------------------------------
3174
3175 /// Evaluate `code` as a script body and return its completion value.
3176 /// Compile and run `source` for the engine's own use, returning its completion value.
3177 ///
3178 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3179 /// needs to be a real async function, and the engine already runs those as coroutines,
3180 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3181 ///
3182 /// Differences from [`Self::eval_in_global`], both deliberate:
3183 ///
3184 /// * It does **not** drain the microtask queue. Install runs while the realm is still
3185 /// being built, and the source is an IIFE that only constructs a closure, so there
3186 /// is nothing to drain — and draining here would run script-queued jobs in the
3187 /// middle of `install`.
3188 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3189 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3190 /// and it should not look like the user wrote something wrong.
3191 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3192 let program = match js_parse::parse_script(source) {
3193 Ok(program) => program,
3194 Err(error) => {
3195 let message = format!("builtin source does not parse: {error}");
3196 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3197 }
3198 };
3199 let mut code = match js_compile::compile_script_with_source(&program, source) {
3200 Ok(code) => code,
3201 Err(error) => {
3202 let message = format!("builtin source does not compile: {}", error.message);
3203 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3204 }
3205 };
3206 // The frame has to name something, and `<builtin>` is what a stack trace through
3207 // this code should say.
3208 code.set_filename("<builtin>");
3209 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3210 let closure_vars = compiled.code.closure_vars.clone();
3211 let env = self.global_env(&closure_vars);
3212 let this = Value::Object(self.realm.global.clone());
3213 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3214 }
3215
3216 /// Run an already-parsed script and drain the microtasks it queued.
3217 ///
3218 /// The drain is what lets an `async` function's body advance past its first `await`
3219 /// before the host sees the result: nothing else pumps the job queue.
3220 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3221 let this = Value::Object(self.realm.global.clone());
3222 self.run_script_with_this(code, this)
3223 }
3224
3225 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3226 ///
3227 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3228 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3229 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3230 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3231 /// state the next script evaluation tripped over.
3232 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3233 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3234 let closure_vars = compiled.code.closure_vars.clone();
3235 let env = self.global_env(&closure_vars);
3236 let callee = Value::Undefined;
3237 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3238 // The script is done, so the microtasks it queued run before the host sees the
3239 // result. Without this an `async` function's body would never advance past its
3240 // first `await`, because nothing else drains the queue.
3241 self.drain_jobs()?;
3242 Ok(result)
3243 }
3244
3245 /// Compile and run `source` in global scope, returning its completion value.
3246 ///
3247 /// This is what `eval` and `new Function` use. Running it as a script means it
3248 /// sees the global object and nothing else, which is right for `eval("1+1")` and
3249 /// for a `Function` body; a *direct* eval that reads a local variable would need
3250 /// the compiler to hand its variable environment over, which is not implemented.
3251 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3252 self.eval_in_global_named(source, EVAL_FILE, false)
3253 }
3254
3255 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3256 ///
3257 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3258 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3259 /// through the code, so they cannot share one constant.
3260 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3261 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3262 }
3263
3264 /// Evaluate `source` as a global script, reported under `file`.
3265 ///
3266 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3267 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3268 /// from inside a C callback, where the interpreter is the running one rather than a
3269 /// context's own.
3270 pub fn eval_in_global_named(
3271 &mut self,
3272 source: &str,
3273 file: &str,
3274 barrier: bool,
3275 ) -> JsResult<Value> {
3276 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3277 // eval-created global binding — configurable, unlike a script's own `var`.
3278 self.eval_depth += 1;
3279 if barrier {
3280 let depth = self.frames.len();
3281 self.trace_barriers.push(depth);
3282 }
3283 let result = self.eval_in_global_inner(source, file);
3284 if barrier {
3285 self.trace_barriers.pop();
3286 }
3287 self.eval_depth -= 1;
3288 result
3289 }
3290
3291 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3292 let compiled = self.compile_global_script(source, file, false)?;
3293 let strict = compiled.strict;
3294 self.run_eval_script(compiled, strict)
3295 }
3296
3297 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3298 ///
3299 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3300 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3301 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3302 /// direct eval's is.
3303 pub fn eval_script_with_this(
3304 &mut self,
3305 source: &str,
3306 file: &str,
3307 this: Value,
3308 ) -> JsResult<Value> {
3309 let program = match js_parse::parse_script(source) {
3310 Ok(program) => program,
3311 Err(error) => {
3312 return Err(Signal::Throw(self.syntax_error_at(
3313 file,
3314 error.span.start.line,
3315 error.span.start.column,
3316 &error.message,
3317 )));
3318 }
3319 };
3320 let mut compiled = match js_compile::compile_script(&program) {
3321 Ok(compiled) => compiled,
3322 Err(error) => {
3323 return Err(Signal::Throw(self.syntax_error_at(
3324 file,
3325 error.span.start.line,
3326 error.span.start.column,
3327 &error.message,
3328 )));
3329 }
3330 };
3331 compiled.set_filename(file);
3332 self.run_script_with_this(compiled, this)
3333 }
3334
3335 /// Parse and compile `source` as a global script, without running it.
3336 ///
3337 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3338 /// before a promise exists to reject — while still evaluating in the same eval context
3339 /// (direct-eval strictness, `new.target`, `super`).
3340 fn compile_global_script(
3341 &mut self,
3342 source: &str,
3343 file: &str,
3344 async_body: bool,
3345 ) -> JsResult<CompiledFunction> {
3346 // A *direct* eval inherits the strictness of the code that called it, which is
3347 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3348 // implicit global. The caller's frame is the innermost one here, because a
3349 // native function does not push a frame of its own.
3350 let strict = self.current_strict();
3351 // `eval` runs in the caller's function context, so `new.target` is legal here
3352 // even though the source is a bare script — and so is `super.x` when the caller
3353 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3354 // caller's, which is what `special_object 4` already does.
3355 let context = js_parse::EvalContext {
3356 in_method: self.enclosing_home_object().is_some(),
3357 // `super()` belongs to a derived constructor, and an eval'd body is not a
3358 // constructor at all: the caller frame's `this` is already built.
3359 in_derived_constructor: false,
3360 };
3361 // A *global* eval is not a function body: `new.target` and `super` are out of
3362 // reach there. Its `{async: true}` form differs in the other direction — the body
3363 // may `await` — so the two flags are independent and the reference sets both from
3364 // the eval type rather than from the caller.
3365 let parsed = if async_body {
3366 js_parse::parse_suspensible_global_eval(source, strict)
3367 } else {
3368 js_parse::parse_eval_script_in(source, strict, context)
3369 };
3370 let program = match parsed {
3371 Ok(program) => program,
3372 Err(error) => {
3373 // The message is bare: the position lives in `fileName`,
3374 // `lineNumber`, `columnNumber` and the stack frame above, which is where
3375 // the reference puts it. An `invalid source: L:C: ` prefix made
3376 // `e.message` differ from the reference while the stack already agreed.
3377 return Err(Signal::Throw(self.syntax_error_at(
3378 file,
3379 error.span.start.line,
3380 error.span.start.column,
3381 &error.message,
3382 )));
3383 }
3384 };
3385 let mut compiled = match if async_body {
3386 js_compile::compile_script_suspensible(&program)
3387 } else {
3388 js_compile::compile_script(&program)
3389 } {
3390 Ok(compiled) => compiled,
3391 // A construct the compiler does not handle yet is reported the same way a
3392 // parse error is: it happens before anything runs, so the trace is the
3393 // position in the source followed by the caller.
3394 Err(error) => {
3395 return Err(Signal::Throw(self.syntax_error_at(
3396 file,
3397 error.span.start.line,
3398 error.span.start.column,
3399 &error.message,
3400 )));
3401 }
3402 };
3403 compiled.set_filename(file);
3404 Ok(compiled)
3405 }
3406
3407 /// Run an `eval`'d script in the caller's scope.
3408 ///
3409 /// Three things have to come from the calling frame, because the eval'd code is a
3410 /// script and would otherwise see only the global object:
3411 ///
3412 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3413 /// * `arguments`, exposed as a binding of the eval's own scope, so
3414 /// `f("arguments.length", 1)` sees the caller's arguments;
3415 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3416 /// `eval("var v = 1")` into the global object.
3417 ///
3418 /// Locals of the calling function are *not* reachable: that needs the compiler to
3419 /// hand its variable environment over, which this milestone does not do.
3420 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3421 // `this` and `arguments` come from the innermost frame only — those are not
3422 // lexical — while the name bindings come from the whole chain of frames, part
3423 // of it being ordinary scope resolution.
3424 // An arrow has no `this` of its own, so an `eval` inside one inherits the
3425 // enclosing function's receiver — the lexical `this` the arrow was compiled to
3426 // read from its closure.
3427 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3428 // variable environment is the innermost frame of all: an arrow's own body is where
3429 // `var`s declared by an `eval` inside it belong.
3430 let caller_index = self
3431 .frames
3432 .iter()
3433 .rposition(|frame| !frame.code.code.is_arrow)
3434 .or_else(|| self.frames.len().checked_sub(1));
3435 let env_index = self.frames.len().checked_sub(1);
3436 let caller = caller_index.and_then(|index| self.frames.get(index));
3437 let (this, passed) = match caller {
3438 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3439 // No frame at all: the eval is running at the top level, so there is
3440 // nothing to inherit and the global receiver is right.
3441 None => (Value::Object(self.realm.global.clone()), Vec::new()),
3442 };
3443 // Innermost frame first, so the first binding found for a name is the one that
3444 // shadows the rest. A script frame (`<eval>`) contributes nothing.
3445 let mut bindings: Vec<EvalBinding> = Vec::new();
3446 // The calling function's own bindings, resolved by the compiler at the call
3447 // site. That table is the only reliable answer when a name is declared twice in
3448 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3449 // body means, and guessing by declaration order picks the wrong one as soon as
3450 // two loops in a row use the same name.
3451 // Only a *direct* eval sees the caller's scope. The compiler records a site for
3452 // every direct call — a bare `eval(...)` callee — so finding one at the current
3453 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3454 // callee to a value first and leave no site behind.
3455 let mut direct = false;
3456 let mut resolved_here = false;
3457 if let Some(frame) = self.frames.last() {
3458 let (line, column) = frame
3459 .code
3460 .code
3461 .position_at(frame.at as u32)
3462 .unwrap_or_default();
3463 // The nearest site at or before the current position, not an exact match:
3464 // the recorded position of the `call` instruction is the callee's, which
3465 // sits a few columns inside the call expression the compiler recorded. A
3466 // site is unique per call, so "the closest one behind us" identifies it.
3467 if let Some(site) = frame
3468 .code
3469 .code
3470 .eval_sites
3471 .iter()
3472 .filter(|site| (site.line, site.column) <= (line, column))
3473 .max_by_key(|site| (site.line, site.column))
3474 {
3475 direct = true;
3476 resolved_here = true;
3477 for binding in &site.bindings {
3478 // An enclosing function's frame sits `owner` levels below the one
3479 // running the call.
3480 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3481 else {
3482 continue;
3483 };
3484 bindings.push(EvalBinding {
3485 name: binding.name.clone(),
3486 frame,
3487 slot: if binding.is_arg {
3488 EvalSlot::Arg
3489 } else {
3490 EvalSlot::Local
3491 },
3492 index: binding.index as usize,
3493 });
3494 }
3495 }
3496 }
3497 for frame_index in (0..self.frames.len()).rev() {
3498 // Skip the innermost frame's flat scan when the compiler already answered
3499 // for it; an enclosing frame still needs one, because the eval resolves
3500 // those names dynamically.
3501 if resolved_here && frame_index == self.frames.len() - 1 {
3502 continue;
3503 }
3504 let frame = &self.frames[frame_index];
3505 for (index, arg) in frame.code.code.args.iter().enumerate() {
3506 bindings.push(EvalBinding {
3507 name: arg.name.clone(),
3508 frame: frame_index,
3509 slot: EvalSlot::Arg,
3510 index,
3511 });
3512 }
3513 for (index, local) in frame.code.code.vars.iter().enumerate() {
3514 bindings.push(EvalBinding {
3515 name: local.name.clone(),
3516 frame: frame_index,
3517 slot: EvalSlot::Local,
3518 index,
3519 });
3520 }
3521 }
3522 let mut seen = BTreeSet::new();
3523 bindings.retain(|binding| seen.insert(binding.name.clone()));
3524
3525 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
3526 // elements is all the spec's ordinary uses need.
3527 //
3528 // Known divergence: this is bound for a *global* eval too, where there is no
3529 // caller and the reference throws `'arguments' is not defined`. Deciding properly
3530 // needs "does the calling frame have an `arguments` of its own", which is not
3531 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
3532 // script or eval body does not, and `eval(b)` passes the callee as a value so even
3533 // the call-site detection does not answer it. Modelled as a binding in the caller's
3534 // variable environment, this would fall out; that is a larger change than the one
3535 // this comment is attached to.
3536 let arguments = Value::Object(self.new_array(passed));
3537
3538 // Only a *strict* eval gets a variable environment of its own. A sloppy one
3539 // declares its `var`s in the caller's — which for a top-level eval is the global
3540 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
3541 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
3542 // vanish into a scope nobody reads back from.
3543 let previous_scope = if code_strict {
3544 self.eval_scope.replace(BTreeMap::new())
3545 } else {
3546 None
3547 };
3548 let previous_arguments = self.eval_arguments.replace(arguments);
3549 let previous_with = self.eval_with.replace(self.with_objects());
3550 let inherited_new_target = self
3551 .frames
3552 .iter()
3553 .rev()
3554 .find(|frame| !frame.code.code.is_arrow)
3555 .map(|frame| frame.new_target.clone());
3556 let previous_new_target = self
3557 .eval_new_target
3558 .replace(inherited_new_target.unwrap_or(Value::Undefined));
3559 let eval_cells = self.eval_cells_for(&bindings);
3560 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
3561 // A sloppy direct eval declares its `var`s in the caller's variable environment;
3562 // `declare_eval_local` needs to know which frame that is.
3563 // An indirect eval gets the global environment, so nothing of the caller's is
3564 // recorded as the place its `var`s belong.
3565 let previous_caller = self
3566 .eval_caller
3567 .replace(if direct { env_index } else { None });
3568 // The cell-based view of the same bindings, which is what a closure created
3569 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3570 // whose compiler did not put a binding in a cell simply does not appear here —
3571 // reads and writes still work through `eval_bindings`, they just cannot outlive
3572 // the eval.
3573 let previous_eval_scope = self
3574 .active_eval_scope
3575 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3576 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3577 let closure_vars = compiled.code.closure_vars.clone();
3578 let env = self.global_env(&closure_vars);
3579 let callee = Value::Undefined;
3580 // An async body does not run here: it becomes a coroutine and answers a promise,
3581 // which is what makes `await` legal in it. `this` still has to be the caller's
3582 // (for a global eval, the global object), because `this` is not part of `await`.
3583 let result = if compiled.code.kind.is_async() {
3584 self.run_async_body(compiled, env, this)
3585 } else {
3586 self.execute(compiled, env, this, Vec::new(), callee)
3587 };
3588 self.eval_scope = previous_scope;
3589 self.eval_arguments = previous_arguments;
3590 self.eval_with = previous_with;
3591 self.eval_new_target = previous_new_target;
3592 self.eval_bindings = previous_bindings;
3593 self.eval_caller = previous_caller;
3594 self.active_eval_scope = previous_eval_scope;
3595 result
3596 }
3597
3598 /// The cell-backed subset of `bindings`, in the same priority order.
3599 ///
3600 /// Both lookup routes have to agree — the eval's own reads go through
3601 /// [`Interp::eval_binding_value`] and the closures it builds go through
3602 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
3603 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
3604 /// is not in a cell simply does not appear: reads and writes still work, they just
3605 /// cannot be handed to a closure that outlives the eval.
3606 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
3607 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
3608 for binding in bindings {
3609 let Some(frame) = self.frames.get(binding.frame) else {
3610 continue;
3611 };
3612 let cell = match binding.slot {
3613 EvalSlot::Arg => frame
3614 .code
3615 .arg_cell
3616 .get(binding.index)
3617 .copied()
3618 .unwrap_or(-1),
3619 EvalSlot::Local => frame
3620 .code
3621 .loc_cell
3622 .get(binding.index)
3623 .copied()
3624 .unwrap_or(-1),
3625 };
3626 if cell < 0 {
3627 continue;
3628 }
3629 if let Some(cell) = frame.cells.get(cell as usize) {
3630 names.push((binding.name.clone(), cell.clone()));
3631 }
3632 }
3633 names
3634 }
3635
3636 /// A `SyntaxError` that reports where in the source it happened.
3637 ///
3638 /// Compile-time failures never run, so they have no frame of their own; the
3639 /// reference still puts the position first in the trace, with no function name and
3640 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
3641 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
3642 /// reference borrows), which is how a script reads the position without parsing
3643 /// the trace.
3644 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
3645 ///
3646 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
3647 /// `columnNumber`, which is how the reference prints one. A positionless error
3648 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
3649 /// the reference raises it from `js_resolve_module`, where there is no position.
3650 pub(crate) fn syntax_error_plain(
3651 &mut self,
3652 error: &js_parse::SyntaxError,
3653 file: &str,
3654 ) -> Value {
3655 if error.positionless {
3656 return self.make_error("SyntaxError", &error.message);
3657 }
3658 self.syntax_error_at(
3659 file,
3660 error.span.start.line,
3661 error.span.start.column,
3662 &error.message,
3663 )
3664 }
3665
3666 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
3667 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
3668 let value = self.make_error("SyntaxError", message);
3669 if let Value::Object(object) = &value {
3670 let text = self.string(blamed);
3671 // `stack` is an own data property, and the reference keeps it
3672 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
3673 object.define("stack", Property::with_attributes(text, true, false));
3674 let name = self.string(file);
3675 object.define("fileName", Property::with_attributes(name, true, true));
3676 object.define(
3677 "lineNumber",
3678 Property::with_attributes(Value::Int(line as i32), true, true),
3679 );
3680 object.define(
3681 "columnNumber",
3682 Property::with_attributes(Value::Int(column as i32), true, true),
3683 );
3684 }
3685 value
3686 }
3687
3688 /// Run a compiled script whose completion value is a function, returning it.
3689 ///
3690 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
3691 /// get the closure out, which keeps the constant-pool plumbing in one place.
3692 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
3693 self.run_script(code)
3694 }
3695
3696 /// The environment of a script or of any function compiled at global scope:
3697 /// every entry is a global binding, so each one resolves to the realm's cell.
3698 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
3699 let mut cells = Vec::with_capacity(closure_vars.len());
3700 for closure_var in closure_vars {
3701 let cell = match closure_var.closure_type {
3702 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
3703 if closure_var.is_lexical =>
3704 {
3705 // A lexical declaration: the cell is created here holding the
3706 // dead-zone marker, which is what makes the binding exist and
3707 // unreadable before its initialiser runs.
3708 self.declare_global(&closure_var.name, closure_var.is_const);
3709 self.realm.globals[&closure_var.name].clone()
3710 }
3711 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
3712 // A `var` or function declaration becomes a property of the global
3713 // object, and it exists from here on — which is why
3714 // `print(v); var v = 1` prints `undefined` instead of raising.
3715 // Declaring it at instantiation time (rather than at the
3716 // initialiser) is also what makes it non-configurable: the store
3717 // then lands on an existing property instead of creating one.
3718 self.declare_var_global(&closure_var.name);
3719 // The cell is a placeholder that nothing indexes; it cannot be
3720 // omitted because the slot has to hold something.
3721 self.new_cell(Value::Undefined)
3722 }
3723 _ => {
3724 // An undeclared global is read by name; the cell is a
3725 // placeholder that nothing indexes.
3726 self.new_cell(Value::Undefined)
3727 }
3728 };
3729 cells.push(cell);
3730 }
3731 Gc::new(
3732 self.heap,
3733 ClosureEnv {
3734 cells,
3735 eval_scope: None,
3736 local_vars: None,
3737 local_phase: 1,
3738 },
3739 )
3740 }
3741
3742 /// Push a frame and run until it returns.
3743 pub(crate) fn execute(
3744 &mut self,
3745 code: Gc<CompiledCode>,
3746 env: Gc<ClosureEnv>,
3747 this: Value,
3748 args: Vec<Value>,
3749 callee: Value,
3750 ) -> JsResult<Value> {
3751 let depth = self.frames.len();
3752 if depth == 0 {
3753 // A throw that reached the host ends the *active* mode: the next one is catchable
3754 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
3755 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
3756 // for the throw that evaluation will raise.
3757 self.uncatchable = false;
3758 }
3759 self.push_frame(code, env, this, args, callee)?;
3760 loop {
3761 // The fast loop first: it runs whole runs of records with `pc` in a register.
3762 //
3763 // `step`'s `pc` lives in the frame, so every instruction writes it back and
3764 // reads it again — a store, a load and two bounds checks that a loop body does
3765 // not need, because nothing outside the loop can run in between. This is the
3766 // classic split: advance a register, and only spill it when leaving.
3767 //
3768 // `Some(value)` means the function ended by running off the end of its
3769 // instruction array, which is a normal return.
3770 let step = match self.run_fast() {
3771 Ok(Some(value)) => Ok(Step::Return(value)),
3772 Ok(None) => self.step(),
3773 Err(signal) => Err(signal),
3774 };
3775 match step {
3776 Ok(Step::Continue) => {}
3777 Ok(Step::Return(value)) => {
3778 self.pop_frame();
3779 // A frame that ended in a `tail_call` hands its value straight to
3780 // its caller: nothing after the call can run, so every frame above
3781 // the callee unwinds with the same value. See [`Frame::tail`] —
3782 // the reference does not reuse frames either, so recursion depth
3783 // and the stack-overflow limit behave the same way.
3784 while self.frames.len() > depth && self.frame().tail {
3785 self.pop_frame();
3786 }
3787 if self.frames.len() == depth {
3788 return Ok(value);
3789 }
3790 // The caller resumes with the value on its stack.
3791 self.frames
3792 .last_mut()
3793 .expect("a caller is live")
3794 .stack
3795 .push(value);
3796 }
3797 Err(Signal::Throw(value)) => {
3798 // The host's standing request becomes the active mode for this unwind,
3799 // and is consumed here so it does not leak into the next throw.
3800 if self.uncatchable_next {
3801 self.uncatchable_next = false;
3802 self.uncatchable = true;
3803 }
3804 // An uncatchable throw walks past every `catch` on the way out. The
3805 // frames are still popped, because the values they hold have to be
3806 // dropped — only the search for a handler is skipped.
3807 if self.uncatchable {
3808 while self.frames.len() > depth {
3809 self.frames.pop();
3810 }
3811 return Err(Signal::Throw(value));
3812 }
3813 // A handler lives on the stack of the frame that is throwing —
3814 // `catch` pushed it there — so this frame gets the first chance
3815 // to catch before it is popped.
3816 let value = value;
3817 loop {
3818 if self.frames.len() <= depth {
3819 return Err(Signal::Throw(value));
3820 }
3821 if self.catch_here(value.clone()).is_some() {
3822 break;
3823 }
3824 self.frames.pop();
3825 }
3826 }
3827 // A `yield` in a frame that `execute` is running directly means a
3828 // generator body was entered as an ordinary call, which only happens if
3829 // the generator check in `call_or_push` was bypassed.
3830 Ok(Step::Suspend(_)) => {
3831 return Err(Signal::Throw(self.make_error(
3832 "InternalError",
3833 "a generator body ran as an ordinary call",
3834 )));
3835 }
3836 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
3837 }
3838 }
3839 }
3840
3841 /// Install a handler for `value` if this frame has one, resuming at it.
3842 ///
3843 /// The scan is the reference's: walk the frame's stack downwards looking for the
3844 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
3845 /// `0` is an enumerator marker rather than a handler — it exists so that a
3846 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
3847 /// here and the unwinding continues.
3848 fn catch_here(&mut self, value: Value) -> Option<()> {
3849 let frame = self.frames.last_mut()?;
3850 while let Some(top) = frame.stack.pop() {
3851 if let Value::CatchOffset(offset) = top {
3852 if offset == 0 {
3853 continue;
3854 }
3855 frame.stack.push(value);
3856 frame.pc = offset as usize;
3857 return Some(());
3858 }
3859 }
3860 None
3861 }
3862
3863 fn push_frame(
3864 &mut self,
3865 code: Gc<CompiledCode>,
3866 env: Gc<ClosureEnv>,
3867 this: Value,
3868 mut args: Vec<Value>,
3869 callee: Value,
3870 ) -> JsResult<()> {
3871 // Two bounds, and the byte budget is the one that decides in practice. The
3872 // reference's message is `stack overflow` on an `InternalError`, not V8's
3873 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
3874 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
3875 let frame_cost = Self::frame_cost(&code);
3876 let stack_base = self.stack_used();
3877 if self.frames.len() >= self.max_frames
3878 || stack_base.saturating_add(frame_cost) > self.stack_limit
3879 {
3880 return Err(Signal::Throw(
3881 self.make_error("InternalError", "stack overflow"),
3882 ));
3883 }
3884 let arg_count = code.code.args.len();
3885 // How many were actually passed, which `arguments.length` reports and
3886 // `assert(x)` depends on: a call with one argument must not look like a call
3887 // with one argument and an explicit `undefined`.
3888 let passed = args.len();
3889 // Missing arguments are `undefined` in their slots; extra ones are dropped
3890 // from the slots but still reachable through `arguments`.
3891 //
3892 // A call that passes no more than the declared parameters needs **no** copy:
3893 // after the resize below, `args[..passed]` *is* the passed values. Only the
3894 // extra ones — which `truncate` is about to drop — have to be kept, and they are
3895 // the rare case. This used to copy every call: one `Value` clone per argument
3896 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
3897 let passed_overflow = (passed > arg_count).then(|| {
3898 let mut values = self.take_values(passed, Value::Undefined);
3899 values[..passed].clone_from_slice(&args[..passed]);
3900 values
3901 });
3902 // Only when the counts differ, which for the overwhelmingly common call — as many
3903 // arguments as parameters — is never. `resize` followed by `truncate` on equal
3904 // lengths is two length compares and nothing else, but this is the hottest few
3905 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
3906 if passed != arg_count {
3907 args.resize(arg_count, Value::Undefined);
3908 args.truncate(arg_count);
3909 }
3910 let cell_count = code.code.var_ref_count as usize;
3911 let mut cells = Vec::with_capacity(cell_count);
3912 for _ in 0..cell_count {
3913 cells.push(self.new_cell(Value::Undefined));
3914 }
3915 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
3916 // A captured argument lives in its cell, not in the argument slot, so the
3917 // incoming value has to be moved there before the body runs.
3918 for (slot, cell) in code.arg_cell.iter().enumerate() {
3919 if *cell >= 0
3920 && let Some(value) = args.get(slot).cloned()
3921 {
3922 cells[*cell as usize].set(value);
3923 }
3924 }
3925 // Sloppy mode substitutes the global object for a missing receiver and boxes a
3926 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
3927 // reports `object`. Strict mode passes the value through untouched.
3928 let this = if code.code.strict {
3929 this
3930 } else if this.is_nullish() {
3931 Value::Object(self.realm.global.clone())
3932 } else if matches!(this, Value::Object(_)) {
3933 this
3934 } else {
3935 match crate::builtins::this_object(self, &this) {
3936 Ok(boxed) => Value::Object(boxed),
3937 Err(_) => this,
3938 }
3939 };
3940 let stack_depth = code.code.stack_size as usize + 1;
3941 // Taken before the `push` borrows `self.frames`, because the operand stack comes
3942 // out of the same recycle pool the locals did.
3943 let stack = self.take_values(stack_depth, Value::Undefined);
3944 self.frames.push(Frame {
3945 code,
3946 env,
3947 this,
3948 args,
3949 passed_count: passed,
3950 passed_overflow: passed_overflow.map(Box::new),
3951 locals,
3952 cells,
3953 local_vars: None,
3954 // Exactly the depth the compiler computed, so the operand stack never
3955 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
3956 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
3957 // the buffer between calls, so "exactly" costs nothing after the first one.
3958 stack,
3959 pc: 0,
3960 at: 0,
3961 callee,
3962 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
3963 cost: frame_cost,
3964 stack_base,
3965 tail: false,
3966 });
3967 Ok(())
3968 }
3969
3970 /// A value buffer of `len` slots, from the recycle pool when there is one.
3971 ///
3972 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
3973 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
3974 // A frame with no locals asks for nothing, and that is most frames: taking a
3975 // buffer out of the pool, clearing it and resizing it to zero is four operations
3976 // and a pool pop for an empty `Vec`, which is free to construct.
3977 if len == 0 {
3978 return Vec::new();
3979 }
3980 let mut buffer = self.free_values.pop().unwrap_or_default();
3981 buffer.clear();
3982 buffer.resize(len, fill);
3983 buffer
3984 }
3985
3986 /// Return a finished frame's value buffers for the next call to reuse.
3987 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
3988 for mut buffer in [
3989 std::mem::take(&mut frame.locals),
3990 frame
3991 .passed_overflow
3992 .take()
3993 .map(|buffer| *buffer)
3994 .unwrap_or_default(),
3995 std::mem::take(&mut frame.stack),
3996 ] {
3997 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
3998 // GC root: it kept every value the frame held reachable, which is invisible
3999 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4000 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4001 // exactly that within one run — the target `{}` of a finished IIFE was still
4002 // in its operand stack, in the pool.
4003 buffer.clear();
4004 // A buffer with no capacity is what `Vec::new` is; putting it back would just
4005 // fill the pool with nothing to offer.
4006 if free_values.len() < RECYCLE_SLOTS
4007 && buffer.capacity() > 0
4008 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4009 {
4010 free_values.push(buffer);
4011 }
4012 }
4013 }
4014
4015 /// Pop a finished frame and keep its buffers.
4016 ///
4017 /// Every place that drops a frame goes through here: a recycled buffer is also where
4018 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4019 /// nothing but the reuse.
4020 fn pop_frame(&mut self) -> Option<()> {
4021 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4022 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4023 let last = self.frames.len().checked_sub(1)?;
4024 Self::recycle(&mut self.free_values, &mut self.frames[last]);
4025 self.frames.truncate(last);
4026 Some(())
4027 }
4028
4029 /// Poll the host's interrupt handler, if one is installed.
4030 ///
4031 /// The counter is what keeps this off the hot path when nobody asked: the early return is
4032 /// one `Option` test, and with no handler installed the whole function is that test —
4033 /// `check_memory` next door already costs more, so this cannot be what shows up in a
4034 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4035 #[inline]
4036 fn check_interrupt(&mut self) -> JsResult<()> {
4037 if self.interrupt.is_none() {
4038 return Ok(());
4039 }
4040 if self.interrupt_counter > 0 {
4041 self.interrupt_counter -= 1;
4042 return Ok(());
4043 }
4044 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4045 // The closure is taken out for the duration so that a handler which re-enters the
4046 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4047 let mut handler = self.interrupt.take().expect("checked above");
4048 let abort = handler();
4049 self.interrupt = Some(handler);
4050 if abort {
4051 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4052 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4053 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4054 // documentation says.
4055 self.uncatchable = true;
4056 return Err(Signal::Throw(
4057 self.make_error("InternalError", "interrupted"),
4058 ));
4059 }
4060 Ok(())
4061 }
4062
4063 /// A memory checkpoint: does the heap still fit under its limit?
4064 ///
4065 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4066 /// a `Cell` read and a predictable branch, and the point of asking that often is that
4067 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4068 /// only at calls would let it run until the machine died, which is the exact failure
4069 /// `--memory-limit` exists to prevent.
4070 ///
4071 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4072 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4073 /// script that catches it, drops the reference and carries on is legitimate: measured
4074 /// on `qjs --memory-limit 1M`, the engine recovers.
4075 fn check_memory(&mut self) -> JsResult<()> {
4076 // One `Cell` read and a predictable branch when no limit is set, and an integer
4077 // compare when one is. Containers report their own growth as it happens
4078 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4079 // walking it here was the first version and it was O(live) per 256 instructions,
4080 // which turned a 100k-element push loop into a five-minute one.
4081 let Some(limit) = self.heap.memory_limit() else {
4082 return Ok(());
4083 };
4084 let used = self.heap.used_bytes();
4085 if used <= limit {
4086 // Back under the limit — a collection or a dropped reference did it. The next
4087 // time it goes over is a new failure, not a repeat of this one.
4088 self.oom_reported_at = 0;
4089 return Ok(());
4090 }
4091 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4092 // block runs normally after `out of memory` — it allocates nothing, so nothing
4093 // fails. A check that re-fired on every instruction made the handler itself throw,
4094 // which is a dead end: the error became unobservable from script.
4095 //
4096 // Comparing against the total at the last report gives the same behaviour: the
4097 // handler runs while the total is unchanged, and the very next allocation over the
4098 // limit fails.
4099 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4100 {
4101 return Ok(());
4102 }
4103 self.oom_reported_at = used;
4104 Err(Signal::Throw(
4105 self.make_error("InternalError", "out of memory"),
4106 ))
4107 }
4108
4109 /// Fail before allocating `payload` bytes, if they would not fit.
4110 ///
4111 /// For the allocations whose size comes from script data — `new Array(n)`,
4112 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4113 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4114 /// answering NULL for the one big request.
4115 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4116 if self.heap.fits(payload) {
4117 return Ok(());
4118 }
4119 Err(Signal::Throw(
4120 self.make_error("InternalError", "out of memory"),
4121 ))
4122 }
4123
4124 /// Bytes of frame state the live call chain accounts for.
4125 pub fn stack_used(&self) -> usize {
4126 match self.frames.last() {
4127 Some(frame) => frame.stack_base + frame.cost,
4128 None => 0,
4129 }
4130 }
4131
4132 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4133 ///
4134 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4135 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4136 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4137 /// instead. That is the whole difference between the two models: it rations C stack, we
4138 /// ration frame state, and both quantities are dominated by the value slots — which is
4139 /// why the two depths come out comparable rather than merely proportional.
4140 fn frame_cost(code: &CompiledCode) -> usize {
4141 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4142 std::mem::size_of::<Frame>()
4143 + std::mem::size_of::<Value>() * slots
4144 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4145 }
4146
4147 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4148 ///
4149 /// Only names the eval created are here: a name the frame already declared statically
4150 /// is written through to its own slot instead, so this cannot shadow a real local.
4151 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4152 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4153 let (local_vars, phase) = self.visible_local_vars()?;
4154 if !local_vars.contains(name) {
4155 return None;
4156 }
4157 local_vars.get(name, phase)
4158 }
4159
4160 /// The variables a direct `eval` declared, as the code currently running sees them.
4161 ///
4162 /// Inside an eval that is the *caller's* set — the eval's own variable environment
4163 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4164 /// else it is the current frame's, falling back to the frame the closure was created
4165 /// in.
4166 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4167 ///
4168 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4169 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4170 /// refcount operations (the clone out of the frame, the drop at the end of the match)
4171 /// just to be asked `is_none`.
4172 fn has_visible_local_vars(&self) -> bool {
4173 let index = match self.eval_caller.flatten() {
4174 Some(caller) => caller,
4175 None => match self.frames.len().checked_sub(1) {
4176 Some(top) => top,
4177 None => return false,
4178 },
4179 };
4180 match self.frames.get(index) {
4181 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4182 None => false,
4183 }
4184 }
4185
4186 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4187 // While an `eval` runs, its own frame is on top but its variable environment is
4188 // the *caller's* — so the caller is what the lookup has to start from.
4189 let (index, phase) = match self.eval_caller.flatten() {
4190 Some(caller) => (
4191 caller,
4192 if self.in_parameter_list_at(caller) {
4193 0
4194 } else {
4195 1
4196 },
4197 ),
4198 None => (
4199 self.frames.len().checked_sub(1)?,
4200 if self.in_parameter_list() { 0 } else { 1 },
4201 ),
4202 };
4203 let frame = self.frames.get(index)?;
4204 // The frame's own variables, or — for an arrow, which has no variable environment
4205 // of its own — the one it was created in, which `ClosureEnv` carries.
4206 if let Some(local_vars) = frame.local_vars.clone() {
4207 return Some((local_vars, phase));
4208 }
4209 frame
4210 .env
4211 .local_vars
4212 .clone()
4213 .map(|local_vars| (local_vars, frame.env.local_phase))
4214 }
4215
4216 /// Whether the innermost frame is still evaluating its parameter list.
4217 ///
4218 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4219 /// and a closure created there may only see that much of [`LocalVars`].
4220 fn in_parameter_list(&self) -> bool {
4221 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4222 }
4223
4224 /// [`Interp::in_parameter_list`] for a specific frame.
4225 fn in_parameter_list_at(&self, frame: usize) -> bool {
4226 let Some(frame) = self.frames.get(frame) else {
4227 return false;
4228 };
4229 let code = &frame.code.code;
4230 if !code.has_parameter_expressions {
4231 return false;
4232 }
4233 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4234 // function as its body and let a direct `eval` act accordingly.
4235 if code.body_start == (0, 0) {
4236 return false;
4237 }
4238 match code.position_at(frame.at as u32) {
4239 Some(position) => position < code.body_start,
4240 None => false,
4241 }
4242 }
4243
4244 fn frame(&self) -> &Frame {
4245 self.frames.last().expect("a frame is live")
4246 }
4247
4248 fn frame_mut(&mut self) -> &mut Frame {
4249 self.frames.last_mut().expect("a frame is live")
4250 }
4251
4252 // -- slot access --------------------------------------------------------
4253
4254 /// Move a local's value out, leaving `undefined` in the slot.
4255 ///
4256 /// `None` for a captured slot: its value lives in a cell shared with every closure
4257 /// that closed over it, so it can never be exclusively ours and must not be taken.
4258 ///
4259 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4260 /// for every read and fatal for this one — a clone is exactly the second handle that
4261 /// rules out growing the string in place.
4262 fn take_loc(&mut self, slot: usize) -> Option<Value> {
4263 let frame = self.frames.last_mut()?;
4264 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4265 return None;
4266 }
4267 frame
4268 .locals
4269 .get_mut(slot)
4270 .map(|value| std::mem::replace(value, Value::Undefined))
4271 }
4272
4273 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4274 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4275 ///
4276 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4277 /// it** — the value is put back before the general path runs — so a `valueOf` that
4278 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4279 /// error as it would have without the fusion. This is why the in-place attempt is a
4280 /// `take` and not a `get`: an optimisation that changes what an exception observes is
4281 /// a wrong answer with a good excuse.
4282 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4283 // The take is `matches!`-guarded on the *right* operand only, and the taken value
4284 // is put back on every path that does not append. An earlier version wrote the two
4285 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4286 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4287 // through with its value already taken and dropped: the general path below then
4288 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4289 // A wrong answer, from an optimisation, with every test green.
4290 if matches!(right, Value::String(_))
4291 && let Some(taken) = self.take_loc(slot)
4292 {
4293 if let Value::String(mut left) = taken {
4294 let appended = match left.get_mut() {
4295 Some(string) => string.append_in_place(
4296 // The pattern is the one `matches!` just checked.
4297 match &right {
4298 Value::String(text) => text,
4299 _ => unreachable!("guarded above"),
4300 },
4301 ),
4302 None => None,
4303 };
4304 self.put_loc(slot, Value::String(left));
4305 if let Some(added) = appended {
4306 // The buffer grew where it stood, so the heap's running total has to
4307 // be told: `measure_used` would report the new length, and the two must
4308 // agree or the subtraction at free time leaves the counter wrong.
4309 self.heap.adjust_payload(added as isize);
4310 return Ok(());
4311 }
4312 } else {
4313 self.put_loc(slot, taken);
4314 }
4315 }
4316 // The two-number case, without an operand stack round trip. Everything below
4317 // this point is the *general* path: push both, call `binary_add`, pop the answer,
4318 // store it — five operations and two `Value` clones for what is one integer add.
4319 // `AddImmLoc` already answers this shape that way; the fusion above it was written
4320 // for string append and never got the numeric half, so `t += i` — a counting loop
4321 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4322 let left = self.get_loc(slot);
4323 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4324 self.put_loc(
4325 slot,
4326 match a.checked_add(*b) {
4327 Some(sum) => Value::Int(sum),
4328 None => Value::Float(*a as f64 + *b as f64),
4329 },
4330 );
4331 return Ok(());
4332 }
4333 self.push(left);
4334 self.push(right);
4335 self.binary_add()?;
4336 let value = self.pop();
4337 self.put_loc(slot, value);
4338 Ok(())
4339 }
4340
4341 fn get_arg(&self, slot: usize) -> Value {
4342 self.frame().read_arg(slot)
4343 }
4344
4345 fn put_arg(&mut self, slot: usize, value: Value) {
4346 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4347 if cell == -1 {
4348 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4349 *slot = value;
4350 }
4351 } else {
4352 self.frame().cells[cell as usize].set(value);
4353 }
4354 }
4355
4356 fn get_loc(&self, slot: usize) -> Value {
4357 // The cell mapping is `-1` for every slot that was not captured — which is all of
4358 // them in a function that creates no closure. `Frame::read_loc` tests that first,
4359 // so the common case is one array read and a clone: 20% of every loop iteration
4360 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4361 // sample of `dispatch:arith`).
4362 self.frame().read_loc(slot)
4363 }
4364
4365 fn put_loc(&mut self, slot: usize, value: Value) {
4366 // One borrow instead of three, and the cell check on the frame we already hold.
4367 let frame = self.frames.last_mut().expect("a frame is live");
4368 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4369 if cell < 0 {
4370 if let Some(slot) = frame.locals.get_mut(slot) {
4371 *slot = value;
4372 }
4373 } else if let Some(cell) = frame.cells.get(cell as usize) {
4374 cell.set(value);
4375 }
4376 }
4377
4378 // -- globals ------------------------------------------------------------
4379
4380 /// The name a global-slot operand refers to.
4381 fn global_name(&self, slot: usize) -> String {
4382 self.frame()
4383 .code
4384 .code
4385 .closure_vars
4386 .get(slot)
4387 .map(|c| c.name.clone())
4388 .unwrap_or_default()
4389 }
4390
4391 /// The facts about a global binding that decide where it lives.
4392 ///
4393 /// A script's globals split in two, and the split is observable: `var` and
4394 /// function declarations become properties of the global object (`globalThis.v`
4395 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4396 /// declarations live in the global *lexical* environment and are invisible there
4397 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4398 /// `is_lexical` flag means the answer is already in the bytecode.
4399 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4400 let name = self.global_name(slot);
4401 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4402 // while forwarding a reference through a nested function is built with the
4403 // flags cleared, so `const c` would look like an ordinary `var` from inside a
4404 // closure. Presence in the realm's lexical table is the same fact, recorded
4405 // once, and every slot sees it.
4406 let lexical = self.realm.globals.contains_key(&name);
4407 let is_const = self.realm.lexical_consts.contains(&name);
4408 (name, lexical, is_const)
4409 }
4410
4411 /// The value of `name` in the innermost active `with` object, if any.
4412 ///
4413 /// The active objects are the [`VarKind::With`] locals of every frame still running,
4414 /// innermost frame first and innermost block first within one. Walking frames rather
4415 /// than keeping a separate stack is what makes a closure called from inside a `with`
4416 /// see it, and what keeps the object alive only as long as the block is.
4417 /// The innermost active `with` object that has `name`, if any.
4418 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4419 let objects = self.eval_with.clone().unwrap_or_default();
4420 for object in objects {
4421 let key = self.string(name.to_string());
4422 if self
4423 .has_property(&key, &Value::Object(object.clone()))
4424 .ok()?
4425 {
4426 return Some(object);
4427 }
4428 }
4429 None
4430 }
4431
4432 /// Every active `with` object, innermost first.
4433 fn with_objects(&self) -> Vec<Gc<JsObject>> {
4434 let mut objects = Vec::new();
4435 for frame in self.frames.iter().rev() {
4436 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4437 if var.kind != js_compile::VarKind::With {
4438 continue;
4439 }
4440 // A captured binding lives in its cell and not in the slot list, so the
4441 // cell is consulted first — a closure created inside the block is exactly
4442 // what makes the object captured. Before the store runs the slot still
4443 // holds `undefined`, and a `with` object is always boxed, so a non-object
4444 // entry is simply not in scope yet.
4445 let value = frame
4446 .code
4447 .loc_cell
4448 .get(index)
4449 .copied()
4450 .filter(|cell| *cell >= 0)
4451 .and_then(|cell| frame.cells.get(cell as usize))
4452 .map(|cell| cell.get())
4453 .or_else(|| frame.locals.get(index).cloned());
4454 if let Some(Value::Object(object)) = value {
4455 objects.push(object);
4456 }
4457 }
4458 }
4459 objects
4460 }
4461
4462 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4463 for object in self.eval_with.clone().unwrap_or_default() {
4464 let key = self.string(name.to_string());
4465 if self.has_property(&key, &Value::Object(object.clone()))? {
4466 return Ok(Some(self.read_field(&Value::Object(object), name)?));
4467 }
4468 }
4469 Ok(None)
4470 }
4471
4472 /// Whether every scope between here and the global object is an ordinary one.
4473 ///
4474 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4475 /// bytecode resolved; when any is live the general path has to run in full order. When
4476 /// none is — every ordinary program — a global read is a property read and nothing
4477 /// else, and that is worth caching.
4478 fn scopes_are_plain(&self) -> bool {
4479 self.eval_caller.is_none()
4480 && self.eval_with.is_none()
4481 && self.eval_arguments.is_none()
4482 && self.eval_bindings.is_empty()
4483 && self.eval_scope.is_none()
4484 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4485 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4486 // its `ClosureEnv`, so the test has to be the same one the general path makes.
4487 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4488 // upstream corpus caught and no unit test did.
4489 && !self.has_visible_local_vars()
4490 && self.frame().env.eval_scope.is_none()
4491 }
4492
4493 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4494 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4495 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4496 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4497 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4498 // borrow outlive the `&mut self` the lookup needs.
4499 //
4500 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4501 // forwarded through a nested function has its flags cleared, so the flag cannot
4502 // be believed.
4503 let code = self.frame().code.clone();
4504 let name = code
4505 .code
4506 .closure_vars
4507 .get(slot)
4508 .map(|c| c.name.as_str())
4509 .unwrap_or_default();
4510 let lexical = self.realm.globals.contains_key(name);
4511 // The common case, first: an ordinary global `var`, with a cache in front of the
4512 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4513 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4514 // cache hit and return without touching any of it.
4515 if !lexical && self.scopes_are_plain() {
4516 return self.get_plain_global(name, slot);
4517 }
4518 if name == "arguments"
4519 && let Some(arguments) = &self.eval_arguments
4520 {
4521 return Ok(arguments.clone());
4522 }
4523 // A `with` block around the *call site* is part of the scope an `eval` sees, so
4524 // the objects live when the eval started are consulted before anything else. The
4525 // snapshot is taken at entry rather than scanning the frames on every read: a
4526 // block that has already finished still leaves its object in the slot, and a
4527 // bytecode read outside the block must not see it.
4528 if let Some(value) = self.with_lookup(name)? {
4529 return Ok(value);
4530 }
4531 // A variable a direct `eval` declared shadows everything the compiler resolved,
4532 // including an enclosing function's binding: the eval put it in the caller's own
4533 // variable environment, which is nearer than any captured scope.
4534 if let Some((local_vars, phase)) = self.visible_local_vars()
4535 && let Some(cell) = local_vars.get(name, phase)
4536 {
4537 return Ok(cell.get());
4538 }
4539 // The frame that called `eval` is the innermost scope the eval'd code sees, so
4540 // its local `a` wins over a global `a`.
4541 if let Some(value) = self.eval_binding_value(name) {
4542 return Ok(value);
4543 }
4544 // A closure created by an `eval` resolves its free names against the bindings
4545 // that eval saw, even after the eval (and its frames) are gone.
4546 if let Some(cell) = self
4547 .frame()
4548 .env
4549 .eval_scope
4550 .as_ref()
4551 .and_then(|scope| scope.get(name))
4552 {
4553 let value = cell.get();
4554 if matches!(value, Value::Uninitialized) {
4555 return Err(self.throw_reference(name));
4556 }
4557 return Ok(value);
4558 }
4559 // A binding declared by the strict `eval` currently running shadows anything
4560 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
4561 if let Some(scope) = &self.eval_scope
4562 && let Some(value) = scope.get(name)
4563 {
4564 return Ok(value.clone());
4565 }
4566 if lexical {
4567 // A lexical global is a binding in a side table, so the dead zone is
4568 // visible and it is nowhere on the global object.
4569 if let Some(cell) = self.realm.globals.get(name) {
4570 let value = cell.get();
4571 if matches!(value, Value::Uninitialized) {
4572 return Err(self.throw_reference(name));
4573 }
4574 return Ok(value);
4575 }
4576 return Err(self.throw_reference(name));
4577 }
4578 // A `var` global is an ordinary property, so the prototype chain and the
4579 // global object's own builtins are all reachable through it.
4580 match self.get_property(&self.realm.global.clone(), name)? {
4581 Some(value) => Ok(value),
4582 None => Err(self.throw_reference(name)),
4583 }
4584 }
4585
4586 /// Read a plain global `var`: a cached own data property, or the full lookup.
4587 ///
4588 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
4589 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
4590 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
4591 let object = self.realm.global.clone();
4592 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4593 if let Some(cached) = &self.global_cache[site]
4594 && object.upgrades_to(&cached.object)
4595 && let Some(value) = object.data_property_at(cached.index, name)
4596 {
4597 return Ok(value);
4598 }
4599 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
4600 // chain exactly as before, then remember the answer if it is worth remembering.
4601 let Some(value) = self.get_property(&object, name)? else {
4602 return Err(self.throw_reference(name));
4603 };
4604 if let Some(index) = object.own_data_index(name) {
4605 self.global_cache[site] = Some(GlobalCache {
4606 object: object.downgrade(),
4607 index,
4608 });
4609 }
4610 Ok(value)
4611 }
4612
4613 /// Store to a global binding.
4614 ///
4615 /// Returns a signal when the store is refused: a `const` global may only be
4616 /// written by its initialiser, and a non-configurable `var` global may not be
4617 /// deleted but is always writable.
4618 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4619 let (name, lexical, is_const) = self.global_binding(slot);
4620
4621 // An assignment inside a `with` writes through to the object that supplies the
4622 // name, which for an `eval` means consulting the same chain `get_global` does.
4623 if let Some(owner) = self.with_owner(&name) {
4624 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
4625 return Ok(());
4626 }
4627 // A variable the running eval *declared* takes the write before any caller
4628 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
4629 // environment even when an enclosing function has a `var c` of its own.
4630 if self.eval_caller.flatten().is_some()
4631 && let Some((local_vars, phase)) = self.visible_local_vars()
4632 && local_vars.contains(&name)
4633 && let Some(cell) = local_vars.get(&name, phase)
4634 {
4635 cell.set(value);
4636 return Ok(());
4637 }
4638 // A binding of the frame that called `eval` takes the write, which is what
4639 // makes `f("a = 3")` change the caller's `a`.
4640 if self.set_eval_binding(&name, &value)? {
4641 return Ok(());
4642 }
4643 // A closure that outlived its `eval` writes through to the same cell it reads.
4644 if let Some(cell) = self
4645 .frame()
4646 .env
4647 .eval_scope
4648 .as_ref()
4649 .and_then(|scope| scope.get(&name))
4650 .cloned()
4651 {
4652 cell.set(value);
4653 return Ok(());
4654 }
4655 // Inside a strict `eval`, a name it declared itself is stored there. An
4656 // *assignment* to a name nobody declared is not a declaration, so it falls
4657 // through: strict mode raises `ReferenceError` for it, which is what
4658 // `eval("1 + (@not_def = 1)")` has to do.
4659 if let Some(scope) = self.eval_scope.as_mut()
4660 && scope.contains_key(&name)
4661 {
4662 scope.insert(name, value);
4663 return Ok(());
4664 }
4665 if lexical {
4666 if let Some(cell) = self.realm.globals.get(&name).cloned() {
4667 if is_const && !matches!(cell.get(), Value::Uninitialized) {
4668 return Err(self.read_only_global(&name));
4669 }
4670 cell.set(value);
4671 return Ok(());
4672 }
4673 // Writing an undeclared lexical global is a `ReferenceError` in strict
4674 // mode and a silent global creation otherwise; creating the cell here
4675 // keeps both paths from losing the value.
4676 let cell = self.new_cell(value);
4677 self.realm.globals.insert(name, cell);
4678 return Ok(());
4679 }
4680 // A variable a direct `eval` declared in this call shadows the global object, even
4681 // when the global already has a property of that name — `var c = "global"` at the
4682 // top level must not capture `eval("var c = 1")` inside a function.
4683 if let Some((local_vars, phase)) = self.visible_local_vars()
4684 && local_vars.contains(&name)
4685 && let Some(cell) = local_vars.get(&name, phase)
4686 {
4687 cell.set(value);
4688 return Ok(());
4689 }
4690 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
4691 // remembered a global's slot index since M12b, but the *store* side never did: it
4692 // converted the name to a `PropertyKey` (two allocations) and then scanned the
4693 // global object's whole table — which holds every builtin — on every assignment to
4694 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
4695 // full global lookup per iteration; measured with a counter, `s` as a global made
4696 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
4697 //
4698 // Re-validated exactly like the read: same object, same index, still the name, and
4699 // — the one extra check a store needs — still writable. A global that is an
4700 // accessor, non-writable, or inherited fails here and falls through to the full
4701 // path below, which reports the failure the way it always did.
4702 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4703 let global = self.realm.global.clone();
4704 if let Some(cached) = &self.global_cache[site]
4705 && global.upgrades_to(&cached.object)
4706 && global.write_data_at(cached.index, &name, value.clone())
4707 {
4708 return Ok(());
4709 }
4710 match global.own_property(&name) {
4711 // A `var` global is writable, so the store goes straight through — but
4712 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
4713 // store (a non-writable or accessor-without-setter global) is a silent
4714 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
4715 // split every other assignment has.
4716 Some(_) => {
4717 let on_failure = if self.current_strict() {
4718 DeleteFailure::Throw
4719 } else {
4720 DeleteFailure::Ignore
4721 };
4722 let result = self.set_property_with(&global, &name, value, on_failure);
4723 // Teach the cache the slot for a plain writable own data property, which is
4724 // what a declared `var` is. Without this the fast path above could never
4725 // fire for a global that is only ever *written* — its entry would have to
4726 // be put there by a read of the same slot, and a write-only loop has none.
4727 if result.is_ok()
4728 && let Some(index) = global.own_data_index(&name)
4729 {
4730 self.global_cache[site] = Some(GlobalCache {
4731 object: global.downgrade(),
4732 index,
4733 });
4734 }
4735 result
4736 }
4737 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
4738 // declaration creates a *configurable* property, which is what makes it
4739 // deletable and is the one way a global differs from a declared `var`.
4740 // In strict mode the same store is a `ReferenceError` instead: that is the
4741 // whole point of strict mode, and creating the global silently meant
4742 // `"use strict"; x = 1` looked like it worked.
4743 None => {
4744 if self.current_strict() {
4745 return Err(self.throw_reference(&name));
4746 }
4747 // A direct eval declares here rather than on the global object: its
4748 // `var`s belong to the caller's variable environment. `declare_eval_local`
4749 // also covers a plain assignment to a variable an earlier eval made.
4750 if let Some(cell) = self.declare_eval_local(&name) {
4751 cell.set(value);
4752 return Ok(());
4753 }
4754 global.define_data(&name, value);
4755 Ok(())
4756 }
4757 }
4758 }
4759
4760 /// The value of a binding of the frame that called `eval`, if there is one.
4761 fn eval_binding_value(&self, name: &str) -> Option<Value> {
4762 let binding = self
4763 .eval_bindings
4764 .iter()
4765 .find(|binding| binding.name == name)?;
4766 let owner = self.frames.get(binding.frame)?;
4767 let (slot, index) = (binding.slot, binding.index);
4768 Some(match slot {
4769 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4770 cell if cell >= 0 => owner
4771 .cells
4772 .get(cell as usize)
4773 .map(|cell| cell.get())
4774 .unwrap_or(Value::Undefined),
4775 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
4776 },
4777 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4778 cell if cell >= 0 => owner
4779 .cells
4780 .get(cell as usize)
4781 .map(|cell| cell.get())
4782 .unwrap_or(Value::Undefined),
4783 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
4784 },
4785 })
4786 }
4787
4788 /// Write to a binding of the frame that called `eval`.
4789 ///
4790 /// `Ok(false)` means no binding matched and the caller should keep looking. A
4791 /// matched binding can still refuse the store, which is why this is fallible: a
4792 /// `const` is read-only everywhere, and a named function expression's own name is
4793 /// read-only in strict mode.
4794 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
4795 let Some(binding) = self
4796 .eval_bindings
4797 .iter()
4798 .find(|binding| binding.name == name)
4799 else {
4800 return Ok(false);
4801 };
4802 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
4803 let strict = self.current_strict();
4804 let Some(owner) = self.frames.get_mut(frame) else {
4805 return Ok(false);
4806 };
4807 match slot {
4808 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4809 cell if cell >= 0 => {
4810 if let Some(cell) = owner.cells.get(cell as usize) {
4811 cell.set(value.clone());
4812 }
4813 }
4814 _ => {
4815 if let Some(slot) = owner.args.get_mut(index) {
4816 *slot = value.clone();
4817 }
4818 }
4819 },
4820 EvalSlot::Local => {
4821 let declared = owner.code.code.vars.get(index);
4822 // A `const` is read-only even through `eval`. The realm records this for
4823 // globals (see `lexical_consts`), but a local's `const`-ness is only in
4824 // the bytecode, so this is where it has to be enforced.
4825 if declared.is_some_and(|var| var.is_const) {
4826 return Err(self.read_only_local(name));
4827 }
4828 // The name of a named function expression is read-only too, but only
4829 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
4830 // such a name is ignored, the same as a direct store would be.
4831 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
4832 return if strict {
4833 Err(self.read_only_local(name))
4834 } else {
4835 Ok(true)
4836 };
4837 }
4838 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4839 cell if cell >= 0 => {
4840 if let Some(cell) = owner.cells.get(cell as usize) {
4841 cell.set(value.clone());
4842 }
4843 }
4844 _ => {
4845 if let Some(slot) = owner.locals.get_mut(index) {
4846 *slot = value.clone();
4847 }
4848 }
4849 }
4850 }
4851 }
4852 Ok(true)
4853 }
4854
4855 /// The `TypeError` an assignment to a read-only binding raises.
4856 fn read_only_local(&self, name: &str) -> Signal {
4857 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4858 }
4859
4860 /// Declare `name` as a variable of the frame that called the running `eval`.
4861 ///
4862 /// `None` when there is no direct eval in progress, or it was called from the top
4863 /// level — then the caller's variable environment *is* the global one and the
4864 /// existing path is right.
4865 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
4866 let caller = self.eval_caller.flatten()?;
4867 // The bottom frame is the top-level script, whose variable environment *is* the
4868 // global one — so `eval("var x = 1")` at the top level still creates a global.
4869 if caller == 0 {
4870 return None;
4871 }
4872 // A name the eval's *own* variable environment already binds is not a new
4873 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
4874 // `arguments`, and creating a second binding would leave the first — the one
4875 // closures read — untouched. A binding of an *outer* frame does not count: a
4876 // declaration shadows it rather than writing through.
4877 if self
4878 .eval_bindings
4879 .iter()
4880 .any(|binding| binding.name == name && binding.frame == caller)
4881 {
4882 return None;
4883 }
4884 let phase = if self.in_parameter_list_at(caller) {
4885 0
4886 } else {
4887 1
4888 };
4889 self.frame_local_vars(caller)?;
4890 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
4891 if let Some(cell) = local_vars.get(name, 1) {
4892 return Some(cell);
4893 }
4894 let cell = self.new_cell(Value::Undefined);
4895 Some(local_vars.declare(name, phase, cell))
4896 }
4897
4898 /// Make sure `frame` has a `LocalVars`, creating it on demand.
4899 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
4900 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
4901 return Some(local_vars.clone());
4902 }
4903 let local_vars = Gc::new(self.heap, LocalVars::new());
4904 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
4905 Some(local_vars)
4906 }
4907
4908 /// Whether the realm already has a binding for `name`, lexically or as an *own*
4909 /// property of the global object. Used to decide whether a store inside an
4910 /// `eval` writes through to the realm or declares a binding of its own.
4911 ///
4912 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
4913 /// write to `Object.prototype.toString`, and must not shadow it either.
4914 fn global_knows(&mut self, name: &str) -> bool {
4915 if self.realm.globals.contains_key(name) {
4916 return true;
4917 }
4918 self.realm.global.own_property(name).is_some()
4919 }
4920
4921 /// Whether the code currently running is strict.
4922 ///
4923 /// Read off the frame's function, which is where the parser's answer ended up; a
4924 /// native function never runs strict-only checks, and there is no frame at all
4925 /// before the first script.
4926 pub fn current_strict(&self) -> bool {
4927 self.frames
4928 .last()
4929 .is_some_and(|frame| frame.code.code.strict)
4930 }
4931
4932 /// Initialise a declared global, which is what ends its dead zone.
4933 ///
4934 /// A `var` global becomes a property of the global object: writable, so a later
4935 /// assignment goes through, and non-configurable, so `delete` refuses.
4936 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4937 let (name, lexical, _) = self.global_binding(slot);
4938 // A `var` declared by the strict `eval` currently running belongs to the
4939 // eval's scope, not to the global object: `eval("var v = 1")` must not make
4940 // `typeof v` answer `"number"` afterwards. A name the realm already has is
4941 // initialised in place, which is what a re-declaration inside eval does.
4942 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
4943 self.eval_scope
4944 .as_mut()
4945 .expect("checked above")
4946 .insert(name, value);
4947 return Ok(());
4948 }
4949 if let Some(scope) = self.eval_scope.as_mut()
4950 && scope.contains_key(&name)
4951 {
4952 scope.insert(name, value);
4953 return Ok(());
4954 }
4955 if lexical {
4956 // The cell exists (created at declaration time) holding the dead-zone
4957 // marker; storing the value is what makes the binding readable.
4958 if let Some(cell) = self.realm.globals.get(&name).cloned() {
4959 cell.set(value);
4960 return Ok(());
4961 }
4962 let cell = self.new_cell(value);
4963 self.realm.globals.insert(name, cell);
4964 return Ok(());
4965 }
4966 let global = self.realm.global.clone();
4967 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
4968 // to answer `false` and leave the binding in place. `with_attributes` ties
4969 // `configurable` to `writable`, so the property is built field by field.
4970 global.define(
4971 &name,
4972 Property {
4973 value: Some(value),
4974 writable: true,
4975 enumerable: true,
4976 configurable: false,
4977 ..Property::default()
4978 },
4979 );
4980 Ok(())
4981 }
4982
4983 /// The `TypeError` a store to a `const` global raises.
4984 fn read_only_global(&self, name: &str) -> Signal {
4985 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4986 }
4987
4988 // -- properties ---------------------------------------------------------
4989
4990 /// Read `object[key]`, following the prototype chain.
4991 ///
4992 /// An inherited accessor runs with the *receiver* as `this`, which is why the
4993 /// lookup returns the owner rather than just the value.
4994 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
4995 self.get_property_key(object, &PropertyKey::from(key))
4996 }
4997
4998 /// [`Interp::get_property`] with a key that may be a symbol.
4999 pub fn get_property_key(
5000 &mut self,
5001 object: &Gc<JsObject>,
5002 key: &PropertyKey,
5003 ) -> JsResult<Option<Value>> {
5004 self.get_property_key_for(object, None, key)
5005 }
5006
5007 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5008 ///
5009 /// The receiver matters when the property is found on a *prototype*: a getter has to
5010 /// see the object the read started from. For a primitive that is the primitive
5011 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5012 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5013 /// the owner.
5014 pub fn get_property_key_for(
5015 &mut self,
5016 object: &Gc<JsObject>,
5017 receiver: Option<&Value>,
5018 key: &PropertyKey,
5019 ) -> JsResult<Option<Value>> {
5020 // A proxy answers for itself, before any of the shortcuts below: `new
5021 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5022 // have.
5023 if object.proxy_state().is_some() {
5024 let receiver = receiver
5025 .cloned()
5026 .unwrap_or_else(|| Value::Object(object.clone()));
5027 return self.proxy_get(object, &receiver, key);
5028 }
5029 // A host class's `get_property` trap replaces the whole read, prototype walk
5030 // included — that is what makes a native accessor free rather than a JavaScript
5031 // getter call.
5032 if let Some(exotic) = object.exotic() {
5033 let receiver_value = receiver
5034 .cloned()
5035 .unwrap_or_else(|| Value::Object(object.clone()));
5036 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5037 return Ok(Some(value));
5038 }
5039 // With no `get_property` trap, a `get_own_property` trap still answers for the
5040 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5041 // and the hook lives exactly there. A key the trap reports as absent is still
5042 // looked for on the prototype, which is why the search resumes *above*.
5043 if let Some(property) = exotic.get_own_property(self, object, key)? {
5044 return match property {
5045 Some(property) => self.read_property(property, object, receiver),
5046 None => match lookup_key_above(object, key) {
5047 Some((_, property)) => self.read_property(property, object, receiver),
5048 None => Ok(None),
5049 },
5050 };
5051 }
5052 }
5053 // The element-vector and `length` shortcuts are string-only: an array index
5054 // has no symbol spelling.
5055 if let Some(text) = key.as_str() {
5056 if let Some(value) = self.own_element(object, text) {
5057 return Ok(Some(value));
5058 }
5059 // `length` is not stored as a property: an array's length is its element
5060 // count, and keeping one copy of it is what makes `push`/`pop` and
5061 // `a.length = n` agree.
5062 if let Some(length) = object.array_length()
5063 && text == "length"
5064 {
5065 // Not `Value::Int(length as i32)`: see [`length_value`].
5066 return Ok(Some(crate::object::length_value(length)));
5067 }
5068 }
5069 match lookup_key(object, key) {
5070 Some((_, property)) => self.read_property(property, object, receiver),
5071 None => Ok(None),
5072 }
5073 }
5074
5075 /// The value a property read answers.
5076 ///
5077 /// One place rather than three, because an accessor has to run with the *receiver* as
5078 /// `this` whether the descriptor came from the property table, an exotic
5079 /// `get_own_property` trap, or a prototype above one.
5080 fn read_property(
5081 &mut self,
5082 property: Property,
5083 object: &Gc<JsObject>,
5084 receiver: Option<&Value>,
5085 ) -> JsResult<Option<Value>> {
5086 if property.is_accessor() {
5087 match &property.getter {
5088 Some(getter) if !matches!(getter, Value::Undefined) => {
5089 let receiver = receiver
5090 .cloned()
5091 .unwrap_or_else(|| Value::Object(object.clone()));
5092 self.call_value(getter.clone(), receiver, Vec::new())
5093 .map(Some)
5094 }
5095 // An accessor with no getter reads as `undefined`.
5096 _ => Ok(Some(Value::Undefined)),
5097 }
5098 } else {
5099 Ok(property.value)
5100 }
5101 }
5102
5103 /// `super.key` — start the search at `proto`, but report to `receiver`.
5104 ///
5105 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5106 /// found on the prototype of a class has to see the *instance* as `this`, and a
5107 /// plain property read off `proto` would lose that.
5108 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5109 let start = self.require_object(proto)?;
5110 let key = self.propkey(key)?;
5111 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5112 if matches!(proto, Value::Null) {
5113 return Ok(Value::Undefined);
5114 }
5115 match lookup_key(&start, &key) {
5116 Some((_, property)) if property.is_accessor() => match &property.getter {
5117 Some(getter) if !matches!(getter, Value::Undefined) => {
5118 self.call_value(getter.clone(), receiver.clone(), Vec::new())
5119 }
5120 _ => Ok(Value::Undefined),
5121 },
5122 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5123 None => Ok(Value::Undefined),
5124 }
5125 }
5126
5127 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5128 ///
5129 /// A setter found on the prototype runs with `receiver` as `this`; a data property
5130 /// is shadowed by a new own property on the receiver, the same rule an ordinary
5131 /// assignment follows.
5132 fn super_write(
5133 &mut self,
5134 receiver: &Value,
5135 proto: &Value,
5136 key: &Value,
5137 value: Value,
5138 ) -> JsResult<()> {
5139 let target = self.require_object(receiver)?;
5140 let key = self.propkey(key)?;
5141 if !matches!(proto, Value::Null)
5142 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5143 {
5144 if property.is_accessor() {
5145 if let Some(setter) = &property.setter
5146 && !matches!(setter, Value::Undefined)
5147 {
5148 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5149 }
5150 return Ok(());
5151 }
5152 // A data property on the prototype is writable or not; reading `owner` at
5153 // all is only for the attribute check.
5154 if !property.writable {
5155 return Err(self.type_error(format!("'{key}' is read-only")));
5156 }
5157 let _ = owner;
5158 }
5159 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5160 }
5161
5162 /// The object a `super` operation needs, or the `TypeError` the spec raises.
5163 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5164 match value.as_object() {
5165 Some(object) => Ok(object.clone()),
5166 None => Err(Signal::Throw(
5167 self.make_error("TypeError", "value is not an object"),
5168 )),
5169 }
5170 }
5171
5172 /// Build the class object `define_class` produces.
5173 ///
5174 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5175 /// whose prototype property is a fresh object inheriting from the parent's
5176 /// prototype, and whose own prototype is the parent constructor — which is what makes
5177 /// a static method inherited too.
5178 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5179 let ctor = self.pop();
5180 let parent = self.pop();
5181 let Value::Object(function) = &ctor else {
5182 return Err(Signal::Throw(
5183 self.make_error("TypeError", "class constructor must be a function"),
5184 ));
5185 };
5186 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5187 // but gives the instances no prototype at all.
5188 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5189 match &parent {
5190 Value::Null => (Some(self.realm.function_proto.clone()), None),
5191 Value::Object(parent_class) => {
5192 if !parent_class.is_callable() {
5193 return Err(Signal::Throw(
5194 self.make_error("TypeError", "parent class must be constructor"),
5195 ));
5196 }
5197 let proto = self.get_property(parent_class, "prototype")?;
5198 match proto {
5199 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5200 Some(Value::Null) => (Some(parent_class.clone()), None),
5201 _ => {
5202 return Err(Signal::Throw(self.make_error(
5203 "TypeError",
5204 "parent prototype must be an object or null",
5205 )));
5206 }
5207 }
5208 }
5209 _ => {
5210 return Err(Signal::Throw(
5211 self.make_error("TypeError", "parent class must be constructor"),
5212 ));
5213 }
5214 }
5215 } else {
5216 (
5217 Some(self.realm.function_proto.clone()),
5218 Some(self.realm.object_proto.clone()),
5219 )
5220 };
5221 let proto = self.new_object(parent_proto);
5222 function.set_proto(parent_ctor);
5223 // A class is not callable without `new`, and its `prototype` is not writable —
5224 // both follow from being a class and are what `class A {}; A()` throws on.
5225 function.set_class_constructor(true);
5226 function.set_home_object(None);
5227 self.set_function_name(&ctor, name);
5228 self.define_class_properties(function, &ctor, &proto)?;
5229 Ok((ctor, proto))
5230 }
5231
5232 /// Give the constructor its `prototype` and `length`, and the prototype its
5233 /// `constructor` back-pointer.
5234 fn define_class_properties(
5235 &mut self,
5236 function: &Gc<JsObject>,
5237 ctor: &Value,
5238 proto: &Gc<JsObject>,
5239 ) -> JsResult<()> {
5240 proto.define(
5241 "constructor",
5242 Property::with_attributes(ctor.clone(), true, false),
5243 );
5244 function.define(
5245 "prototype",
5246 Property::prototype_of(Value::Object(proto.clone()), false),
5247 );
5248 if let Some((code, _)) = bytecode_of(function) {
5249 let length = code.code.defined_args;
5250 function.define(
5251 "length",
5252 Property::name_or_length(Value::Int(length as i32)),
5253 );
5254 }
5255 Ok(())
5256 }
5257
5258 /// The own array element `key` names, if this object has one.
5259 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5260 let index = array_index(key)?;
5261 // A typed array's elements live in its buffer, not in a property list: reading one
5262 // goes through the view's element type so a bounds check and a detached buffer are
5263 // both handled there.
5264 if object.typed_array_parts().is_some() {
5265 return object.typed_array_element(index as usize);
5266 }
5267 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5268 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5269 // search early, which is why `Array.prototype[1] = 9` could not be seen through
5270 // `[1,,3][1]`.
5271 match object.array_get(index as usize) {
5272 Some(Value::Hole) | None => None,
5273 other => other,
5274 }
5275 }
5276
5277 /// Store `object[key] = value`, honouring setters and inherited properties.
5278 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5279 self.set_property_with(object, key, value, DeleteFailure::Throw)
5280 }
5281
5282 /// Store a property, choosing what to do when the object refuses.
5283 ///
5284 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5285 /// mode, which is the one place assignment differs by mode. Native code (the array
5286 /// methods, `JSON`) always asks for the throw.
5287 pub fn set_property_with(
5288 &mut self,
5289 object: &Gc<JsObject>,
5290 key: &str,
5291 value: Value,
5292 on_failure: DeleteFailure,
5293 ) -> JsResult<()> {
5294 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5295 }
5296
5297 /// [`Interp::set_property_with`] with a key that may be a symbol.
5298 pub fn set_property_with_key(
5299 &mut self,
5300 object: &Gc<JsObject>,
5301 key: &PropertyKey,
5302 value: Value,
5303 on_failure: DeleteFailure,
5304 ) -> JsResult<()> {
5305 self.set_property_with_key_receiver_aware(object, key, value, on_failure, true)
5306 }
5307
5308 /// As [`Interp::set_property_with_key`], with the receiver explicit.
5309 ///
5310 /// `same_receiver` is `SameValue(O, Receiver)` from §10.4.5.5 step 1.b.i, and the two
5311 /// branches it separates are observable in opposite directions: when the receiver *is*
5312 /// the view the element store converts `V` first and then asks whether the index is
5313 /// valid (`Set/resized-out-of-bounds-to-in-bounds-index`, where a `valueOf` puts the
5314 /// index back in bounds), and when it is not, an invalid index returns `true` without
5315 /// converting anything (`key-is-out-of-bounds-receiver-is-not-object`).
5316 fn set_property_with_key_receiver_aware(
5317 &mut self,
5318 object: &Gc<JsObject>,
5319 key: &PropertyKey,
5320 value: Value,
5321 on_failure: DeleteFailure,
5322 same_receiver: bool,
5323 ) -> JsResult<()> {
5324 // A proxy's `set` trap decides, and its `false` means the same thing an
5325 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5326 if object.proxy_state().is_some() {
5327 let receiver = Value::Object(object.clone());
5328 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5329 return match (accepted, on_failure) {
5330 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5331 (false, DeleteFailure::Throw) => {
5332 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5333 }
5334 };
5335 }
5336 }
5337 // A host class's `set_property` trap decides for itself. `Some(false)` is a
5338 // refusal and means exactly what a proxy's `false` means.
5339 if let Some(exotic) = object.exotic() {
5340 let receiver = Value::Object(object.clone());
5341 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5342 return match (accepted, on_failure) {
5343 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5344 (false, DeleteFailure::Throw) => {
5345 Err(self.type_error(format!("property '{key}' is read-only")))
5346 }
5347 };
5348 }
5349 }
5350 // The element and `length` shortcuts only exist for string keys: an array
5351 // index has no symbol spelling, and a symbol named `length` is an ordinary
5352 // property.
5353 let text = key.as_str();
5354 // A typed array's elements are a window onto its buffer: the store has to go
5355 // through the view's element type so the value is wrapped (or clamped) and so an
5356 // out-of-range or detached write is a silent no-op, as the spec says.
5357 if let Some(text) = text
5358 && let Some(index) = array_index(text)
5359 && let Some(element) = object.typed_array_element_type()
5360 {
5361 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5362 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5363 // in `Interp`, because it is script-observable and the storage borrow inside
5364 // `typed_array_set` must not be held across it.
5365 //
5366 // It runs even for an index that is out of bounds *now*, because `V` itself can
5367 // put it back in bounds: `TypedArraySetElement` converts first and asks
5368 // `IsValidIntegerIndex` afterwards, which is what
5369 // `Set/resized-out-of-bounds-to-in-bounds-index` asserts (a `valueOf` that
5370 // resizes a 0-byte buffer to 1 makes `ta[0] = value` store 100). The write is
5371 // still a no-op when the index stays out of bounds, which is why the extra
5372 // length check that used to guard this has no job left.
5373 if !same_receiver && index as usize >= object.typed_array_length().unwrap_or(0) {
5374 return Ok(());
5375 }
5376 let stored = self.element_value(element, value)?;
5377 if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
5378 return Err(self.type_error(reason));
5379 }
5380 return Ok(());
5381 }
5382 if let Some(text) = text
5383 && let Some(index) = array_index(text)
5384 && object.is_array()
5385 {
5386 // An accessor defined on an index lives in the property table while the
5387 // element slot is a hole, so the store has to go through the property first.
5388 // Writing the vector directly skipped the setter entirely.
5389 if let Some(existing) = object.own_property_key(key) {
5390 if existing.is_accessor() {
5391 return match existing.setter.clone() {
5392 Some(setter) if !matches!(setter, Value::Undefined) => {
5393 let receiver = Value::Object(object.clone());
5394 self.call_value(setter, receiver, vec![value]).map(|_| ())
5395 }
5396 _ => match on_failure {
5397 DeleteFailure::Throw => Err(self.type_error(format!(
5398 "cannot set property '{text}', it has only a getter"
5399 ))),
5400 DeleteFailure::Ignore => Ok(()),
5401 },
5402 };
5403 }
5404 if !existing.writable {
5405 return match on_failure {
5406 DeleteFailure::Throw => {
5407 Err(self.type_error(format!("'{text}' is read-only")))
5408 }
5409 DeleteFailure::Ignore => Ok(()),
5410 };
5411 }
5412 }
5413 {
5414 // Growing the array needs a writable `length`.
5415 if (index as usize) >= object.array_length().unwrap_or(0)
5416 && !object.length_writable()
5417 {
5418 return match on_failure {
5419 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5420 DeleteFailure::Ignore => Ok(()),
5421 };
5422 }
5423 // Adding an index past the end makes the array longer, which a
5424 // non-extensible array refuses.
5425 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5426 return match on_failure {
5427 DeleteFailure::Throw => Err(self.type_error(format!(
5428 "cannot add property '{key}', object is not extensible"
5429 ))),
5430 DeleteFailure::Ignore => Ok(()),
5431 };
5432 }
5433 if object.element_is_locked(index) {
5434 return match on_failure {
5435 DeleteFailure::Throw => {
5436 Err(self.type_error(format!("'{key}' is read-only")))
5437 }
5438 DeleteFailure::Ignore => Ok(()),
5439 };
5440 }
5441 // The element vector is only half of `[[Set]]` for an index: the
5442 // prototype chain is consulted first, and a setter there answers instead
5443 // of the element store. This branch used to write the element directly, so
5444 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5445 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5446 // the reference calls the setter and the array keeps no own index.
5447 if let Some((owner, property)) = lookup_key(object, key)
5448 && !owner.ptr_eq(object)
5449 {
5450 match &property {
5451 property if property.is_accessor() => {
5452 match &property.setter {
5453 Some(setter) if !matches!(setter, Value::Undefined) => {
5454 let receiver = Value::Object(object.clone());
5455 self.call_value(setter.clone(), receiver, vec![value])?;
5456 }
5457 _ => {
5458 return match on_failure {
5459 DeleteFailure::Throw => Err(self.type_error(format!(
5460 "cannot set property '{text}', it has only a getter"
5461 ))),
5462 DeleteFailure::Ignore => Ok(()),
5463 };
5464 }
5465 }
5466 return Ok(());
5467 }
5468 property if !property.writable => {
5469 return match on_failure {
5470 DeleteFailure::Throw => {
5471 Err(self.type_error(format!("'{text}' is read-only")))
5472 }
5473 DeleteFailure::Ignore => Ok(()),
5474 };
5475 }
5476 _ => {}
5477 }
5478 }
5479 if object.array_set(self.heap, index as usize, value.clone()) {
5480 return Ok(());
5481 }
5482 // Past the dense limit the slot is too far out to be worth one `Value`
5483 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
5484 // constant time by keeping the index as an ordinary property. The store
5485 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
5486 // to a legal program.
5487 object.define_key(key, Property::with_attributes(value, true, true));
5488 // Extend, never shorten: the index may be *inside* the current length (a
5489 // huge `length` with a sparse store), and shortening would delete the
5490 // sparse properties above it — including the one just stored.
5491 if index as usize + 1 > object.array_length().unwrap_or(0) {
5492 object.array_set_length(self.heap, index as usize + 1);
5493 }
5494 return Ok(());
5495 }
5496 }
5497 if text == Some("length") && object.is_array() {
5498 if !object.length_writable() {
5499 return match on_failure {
5500 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5501 DeleteFailure::Ignore => Ok(()),
5502 };
5503 }
5504 let length = value.to_number();
5505 if length.is_finite() && length >= 0.0 {
5506 let length = length as usize;
5507 // `a.length = n` with `n` below a non-configurable element cannot
5508 // drop that element, so the whole assignment fails. The spec makes
5509 // this a `TypeError` rather than a silent no-op, in any mode.
5510 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
5511 // Sloppy mode stops the truncation at the blocking element
5512 // instead of failing; strict mode raises.
5513 // Both modes stop at the blocking element; they differ in
5514 // whether that is reported. The reference truncates *then*
5515 // throws, so the array is left in the shortened state.
5516 object.array_truncate(self.heap, blocked + 1);
5517 return match on_failure {
5518 DeleteFailure::Throw => {
5519 Err(self.type_error(format!("cannot delete property '{blocked}'")))
5520 }
5521 DeleteFailure::Ignore => Ok(()),
5522 };
5523 }
5524 object.array_set_length(self.heap, length);
5525 return Ok(());
5526 }
5527 }
5528 if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
5529 {
5530 return match on_failure {
5531 DeleteFailure::Throw => Err(self.type_error(format!(
5532 "cannot add property {}, object is not extensible",
5533 key
5534 ))),
5535 DeleteFailure::Ignore => Ok(()),
5536 };
5537 }
5538 if let Some((owner, property)) = self.lookup_for_write(object, key)? {
5539 if property.is_accessor() {
5540 match &property.setter {
5541 Some(setter) if !matches!(setter, Value::Undefined) => {
5542 let receiver = Value::Object(object.clone());
5543 self.call_value(setter.clone(), receiver, vec![value])?;
5544 }
5545 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
5546 // Sloppy code swallows that refusal, strict code raises — the same
5547 // rule the read-only *data* property below follows, and skipping it
5548 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
5549 // return silently. The reference answers `TypeError: 'x' is
5550 // read-only`.
5551 _ => {
5552 return match on_failure {
5553 DeleteFailure::Throw => {
5554 Err(self.type_error(format!("'{key}' is read-only")))
5555 }
5556 DeleteFailure::Ignore => Ok(()),
5557 };
5558 }
5559 }
5560 return Ok(());
5561 }
5562 // A non-writable data property refuses the write, own **or inherited**: an
5563 // own one stops here because nothing may change it, and an inherited one
5564 // because §10.1.9.2 step 4 refuses to create the shadowing own property.
5565 //
5566 // The `ptr_eq` this used to carry meant an inherited read-only property fell
5567 // through to `define_data_key` and *did* create the shadow — `var o =
5568 // Object.create(Object.freeze({x: 1})); o.x = 9` answered `9` and
5569 // `o.hasOwnProperty('x')` answered `true`, where the reference answers `1`
5570 // and `false`.
5571 if !property.writable {
5572 return match on_failure {
5573 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
5574 DeleteFailure::Ignore => Ok(()),
5575 };
5576 }
5577 // An existing writable own property keeps its attributes: only the value
5578 // moves. Redefining instead would reset them, which is how a
5579 // non-configurable global `var` used to become deletable.
5580 if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
5581 return Ok(());
5582 }
5583 }
5584 // No own data property: create one, shadowing whatever the prototype holds.
5585 object.define_data_key(key, value);
5586 Ok(())
5587 }
5588
5589 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
5590 ///
5591 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
5592 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
5593 /// a virtual accessor gets its setter run without implementing `set_property` at all.
5594 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
5595 /// the prototype, so the walk resumes above the object.
5596 fn lookup_for_write(
5597 &mut self,
5598 object: &Gc<JsObject>,
5599 key: &PropertyKey,
5600 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
5601 let Some(exotic) = object.exotic() else {
5602 return Ok(lookup_key(object, key));
5603 };
5604 Ok(match exotic.get_own_property(self, object, key)? {
5605 Some(Some(property)) => Some((object.clone(), property)),
5606 Some(None) => lookup_key_above(object, key),
5607 None => lookup_key(object, key),
5608 })
5609 }
5610
5611 /// Delete `object[key]`.
5612 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
5613 self.delete_property_key(object, &PropertyKey::from(key))
5614 }
5615
5616 /// [`Interp::delete_property`] with a key that may be a symbol.
5617 pub fn delete_property_key(
5618 &mut self,
5619 object: &Gc<JsObject>,
5620 key: &PropertyKey,
5621 ) -> JsResult<bool> {
5622 // A proxy decides for itself, and may even throw; the invariant checks live in
5623 // `proxy_delete`.
5624 if let Some(answer) = self.proxy_delete(object, key)? {
5625 return Ok(answer);
5626 }
5627 // A host class's `delete_property` trap decides; `false` is a refusal, which the
5628 // caller reports as a failed delete.
5629 if let Some(exotic) = object.exotic()
5630 && let Some(answer) = exotic.delete_property(self, object, key)?
5631 {
5632 return Ok(answer);
5633 }
5634 let mapped_index = key.as_str().and_then(array_index);
5635 if let Some(index) = mapped_index
5636 && let Some(length) = object.array_length()
5637 && (index as usize) < length
5638 {
5639 // An accessor defined on an index lives in the property table rather than the
5640 // element vector, so both have to be cleared: `delete` after
5641 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
5642 object.delete_key(key);
5643 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
5644 // index stops answering `in`.
5645 if object.element_is_undeletable(index) {
5646 return Ok(false);
5647 }
5648 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
5649 // so a later `defineProperty(arguments, "0", {value})` writes to the object
5650 // and no longer through to the parameter. A refused delete leaves the
5651 // mapping alone.
5652 object.drop_mapped_argument(index as usize);
5653 object.array_set(self.heap, index as usize, Value::Hole);
5654 return Ok(true);
5655 }
5656 // The same for an object that is not an array: only a delete that actually
5657 // removed the property ends the alias.
5658 let deleted = object.delete_key(key);
5659 if deleted && let Some(index) = mapped_index {
5660 object.drop_mapped_argument(index as usize);
5661 }
5662 Ok(deleted)
5663 }
5664
5665 // -- proxy traps --------------------------------------------------------
5666 //
5667 // A proxy's internal methods all look the same: ask the handler for the trap, call it
5668 // with the target and the operation's own arguments, then check the answer against
5669 // the target. The checks are not decoration — they are what stops a proxy from
5670 // reporting a `non-configurable` property as missing, which would let a frozen object
5671 // be rewritten by standing in front of it.
5672
5673 /// The target and handler of `object`, or `None` when it is not a proxy.
5674 ///
5675 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
5676 /// one has to fail: the slots the traps would have been read from are gone.
5677 fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
5678 let Some(state) = object.proxy_state() else {
5679 return Ok(None);
5680 };
5681 let state = state.borrow();
5682 match (&state.target, &state.handler) {
5683 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
5684 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
5685 }
5686 }
5687
5688 /// Call `handler[name]`, or answer `None` when the trap is absent.
5689 ///
5690 /// A trap that is present but not callable is a `TypeError` rather than "no trap":
5691 /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
5692 /// back to the target.
5693 fn proxy_trap(
5694 &mut self,
5695 handler: &Value,
5696 name: &str,
5697 args: Vec<Value>,
5698 ) -> JsResult<Option<Value>> {
5699 let Value::Object(table) = handler else {
5700 return Err(self.type_error("proxy handler is not an object"));
5701 };
5702 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
5703 match trap {
5704 Value::Undefined => Ok(None),
5705 Value::Object(function) if function.is_callable() => {
5706 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
5707 Ok(Some(answer))
5708 }
5709 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
5710 }
5711 }
5712
5713 /// Whether `object`'s own property `key` is one the target refuses to lose.
5714 ///
5715 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
5716 /// its value behind the target's back. This goes through
5717 /// [`Self::ordinary_own_property`] rather than the property table so that an array's
5718 /// elements and its `length` — both fixed, both outside the table — are covered.
5719 fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
5720 Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
5721 }
5722
5723 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
5724 fn proxy_get(
5725 &mut self,
5726 object: &Gc<JsObject>,
5727 receiver: &Value,
5728 key: &PropertyKey,
5729 ) -> JsResult<Option<Value>> {
5730 let Some((target, handler)) = self.proxy_parts(object)? else {
5731 return Ok(None);
5732 };
5733 let key_value = self.key_value(key);
5734 let Some(result) = self.proxy_trap(
5735 &handler,
5736 "get",
5737 vec![Value::Object(target.clone()), key_value, receiver.clone()],
5738 )?
5739 else {
5740 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
5741 // inherited getter still sees the proxy.
5742 return Ok(Some(
5743 self.get_property_key_for(&target, Some(receiver), key)?
5744 .unwrap_or(Value::Undefined),
5745 ));
5746 };
5747 if let Some(fixed) = Self::is_fixed_property(&target, key) {
5748 if fixed.is_accessor() {
5749 // A fixed accessor with no getter must read as `undefined`.
5750 let has_getter = fixed
5751 .getter
5752 .as_ref()
5753 .is_some_and(|getter| !matches!(getter, Value::Undefined));
5754 if !has_getter && !matches!(result, Value::Undefined) {
5755 return Err(self.type_error(format!(
5756 "proxy 'get' must report undefined for the non-configurable property '{key}'"
5757 )));
5758 }
5759 } else if !fixed.writable {
5760 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5761 if !fixed_value.same_value(&result) {
5762 return Err(self.type_error(format!(
5763 "proxy 'get' disagrees with the non-configurable property '{key}'"
5764 )));
5765 }
5766 }
5767 }
5768 Ok(Some(result))
5769 }
5770
5771 /// `[[Set]]` on a proxy.
5772 ///
5773 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
5774 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
5775 /// read-only store has.
5776 fn proxy_set(
5777 &mut self,
5778 object: &Gc<JsObject>,
5779 key: &PropertyKey,
5780 value: Value,
5781 receiver: &Value,
5782 ) -> JsResult<Option<bool>> {
5783 let Some((target, handler)) = self.proxy_parts(object)? else {
5784 return Ok(None);
5785 };
5786 let key_value = self.key_value(key);
5787 let Some(result) = self.proxy_trap(
5788 &handler,
5789 "set",
5790 vec![
5791 Value::Object(target.clone()),
5792 key_value,
5793 value.clone(),
5794 receiver.clone(),
5795 ],
5796 )?
5797 else {
5798 // No trap: store on the target, which is where an ordinary proxy write lands.
5799 self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
5800 return Ok(Some(true));
5801 };
5802 if !result.to_boolean() {
5803 return Ok(Some(false));
5804 }
5805 if let Some(fixed) = Self::is_fixed_property(&target, key) {
5806 if fixed.is_accessor() {
5807 let has_setter = fixed
5808 .setter
5809 .as_ref()
5810 .is_some_and(|setter| !matches!(setter, Value::Undefined));
5811 if !has_setter {
5812 return Err(self.type_error(format!(
5813 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
5814 )));
5815 }
5816 } else if !fixed.writable {
5817 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5818 if !fixed_value.same_value(&value) {
5819 return Err(self.type_error(format!(
5820 "proxy 'set' changed the non-configurable property '{key}'"
5821 )));
5822 }
5823 }
5824 }
5825 // A new property cannot appear on a target that refuses new properties.
5826 if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
5827 return Err(self.type_error(format!(
5828 "proxy 'set' added '{key}' to a non-extensible target"
5829 )));
5830 }
5831 Ok(Some(true))
5832 }
5833
5834 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
5835 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5836 let Some((target, handler)) = self.proxy_parts(object)? else {
5837 return Ok(None);
5838 };
5839 let key_value = self.key_value(key);
5840 let Some(result) = self.proxy_trap(
5841 &handler,
5842 "has",
5843 vec![Value::Object(target.clone()), key_value],
5844 )?
5845 else {
5846 return Ok(Some(self.has_own_or_inherited(&target, key)?));
5847 };
5848 if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5849 return Err(self.type_error(format!(
5850 "proxy 'has' denied the non-configurable property '{key}'"
5851 )));
5852 }
5853 // A non-extensible target cannot grow, so every own property it *has* is fixed.
5854 if !result.to_boolean()
5855 && !target.is_extensible()
5856 && Self::ordinary_own_property(&target, key).is_some()
5857 {
5858 return Err(self.type_error(format!(
5859 "proxy 'has' denied the own property '{key}' of a non-extensible target"
5860 )));
5861 }
5862 Ok(Some(result.to_boolean()))
5863 }
5864
5865 /// `[[Delete]]` on a proxy.
5866 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5867 let Some((target, handler)) = self.proxy_parts(object)? else {
5868 return Ok(None);
5869 };
5870 let key_value = self.key_value(key);
5871 let Some(result) = self.proxy_trap(
5872 &handler,
5873 "deleteProperty",
5874 vec![Value::Object(target.clone()), key_value],
5875 )?
5876 else {
5877 return Ok(Some(self.delete_property_key(&target, key)?));
5878 };
5879 if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5880 return Err(self.type_error(format!(
5881 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
5882 )));
5883 }
5884 if result.to_boolean()
5885 && !target.is_extensible()
5886 && Self::ordinary_own_property(&target, key).is_some()
5887 {
5888 return Err(self.type_error(format!(
5889 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
5890 )));
5891 }
5892 Ok(Some(result.to_boolean()))
5893 }
5894
5895 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
5896 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
5897 let Some((target, handler)) = self.proxy_parts(object)? else {
5898 return Ok(None);
5899 };
5900 let Some(result) =
5901 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
5902 else {
5903 // No trap: the target's own keys, already in the order an object reports.
5904 return Ok(Some(self.object_own_property_keys(&target)?));
5905 };
5906 // `CreateListFromArrayLike` with the string-or-symbol restriction.
5907 let list = self.list_from_array_like(&result, true)?;
5908 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
5909 for value in list {
5910 let key = self.propkey(&value)?;
5911 if keys.contains(&key) {
5912 return Err(self.type_error(format!(
5913 "proxy 'ownKeys' returned the duplicate key '{key}'"
5914 )));
5915 }
5916 keys.push(key);
5917 }
5918 for (key, property) in target.property_entries() {
5919 if !property.configurable && !keys.contains(&key) {
5920 return Err(self.type_error(format!(
5921 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
5922 )));
5923 }
5924 if !target.is_extensible() && !keys.contains(&key) {
5925 return Err(self.type_error(format!(
5926 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
5927 )));
5928 }
5929 }
5930 if !target.is_extensible() {
5931 let own = target.property_entries().len();
5932 if keys.len() != own {
5933 return Err(
5934 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
5935 );
5936 }
5937 }
5938 Ok(Some(keys))
5939 }
5940
5941 /// `[[GetOwnProperty]]` on a proxy.
5942 fn proxy_get_own_property(
5943 &mut self,
5944 object: &Gc<JsObject>,
5945 key: &PropertyKey,
5946 ) -> JsResult<Option<Option<Property>>> {
5947 let Some((target, handler)) = self.proxy_parts(object)? else {
5948 return Ok(None);
5949 };
5950 let key_value = self.key_value(key);
5951 let Some(result) = self.proxy_trap(
5952 &handler,
5953 "getOwnPropertyDescriptor",
5954 vec![Value::Object(target.clone()), key_value],
5955 )?
5956 else {
5957 // No trap: the target's own descriptor is the answer. This has to go through
5958 // the same synthesis an ordinary object gets, because a proxy's own property
5959 // table is empty by design — reading it directly reported `undefined` for
5960 // every key, including an array's indices and `length`.
5961 return Ok(Some(Self::ordinary_own_property(&target, key)));
5962 };
5963 let answer = if matches!(result, Value::Undefined) {
5964 None
5965 } else {
5966 Some(self.property_from_descriptor(&result)?)
5967 };
5968 let fixed = Self::is_fixed_property(&target, key);
5969 match (&answer, &fixed) {
5970 // A non-configurable property cannot be reported as absent.
5971 (None, Some(_)) => {
5972 return Err(self.type_error(format!(
5973 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
5974 )));
5975 }
5976 (Some(descriptor), Some(fixed)) => {
5977 if descriptor.configurable {
5978 return Err(self.type_error(format!(
5979 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
5980 )));
5981 }
5982 if fixed.is_accessor() != descriptor.is_accessor() {
5983 return Err(self.type_error(format!(
5984 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
5985 )));
5986 }
5987 if !fixed.is_accessor() && !fixed.writable {
5988 let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
5989 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
5990 if !fixed_value.same_value(&reported) {
5991 return Err(self.type_error(format!(
5992 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
5993 )));
5994 }
5995 }
5996 }
5997 _ => {}
5998 }
5999 Ok(Some(answer))
6000 }
6001
6002 /// `[[DefineOwnProperty]]` on a proxy.
6003 fn proxy_define_property(
6004 &mut self,
6005 object: &Gc<JsObject>,
6006 key: &PropertyKey,
6007 property: Property,
6008 ) -> JsResult<Option<bool>> {
6009 let Some((target, handler)) = self.proxy_parts(object)? else {
6010 return Ok(None);
6011 };
6012 let key_value = self.key_value(key);
6013 let descriptor = self.descriptor_from_property(&property);
6014 let Some(result) = self.proxy_trap(
6015 &handler,
6016 "defineProperty",
6017 vec![Value::Object(target.clone()), key_value, descriptor],
6018 )?
6019 else {
6020 return Ok(None);
6021 };
6022 if !result.to_boolean() {
6023 return Ok(Some(false));
6024 }
6025 let fixed = Self::is_fixed_property(&target, key);
6026 let creating = Self::ordinary_own_property(&target, key).is_none();
6027 if creating && !target.is_extensible() {
6028 return Err(self.type_error(format!(
6029 "proxy 'defineProperty' added '{key}' to a non-extensible target"
6030 )));
6031 }
6032 if let Some(fixed) = fixed {
6033 if property.configurable {
6034 return Err(self.type_error(format!(
6035 "proxy 'defineProperty' made the non-configurable '{key}' configurable"
6036 )));
6037 }
6038 if !fixed.writable && property.writable && !fixed.is_accessor() {
6039 return Err(self.type_error(format!(
6040 "proxy 'defineProperty' made the read-only '{key}' writable"
6041 )));
6042 }
6043 }
6044 Ok(Some(true))
6045 }
6046
6047 /// `[[GetPrototypeOf]]` on a proxy.
6048 fn proxy_get_prototype_of(
6049 &mut self,
6050 object: &Gc<JsObject>,
6051 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
6052 let Some((target, handler)) = self.proxy_parts(object)? else {
6053 return Ok(None);
6054 };
6055 let Some(result) = self.proxy_trap(
6056 &handler,
6057 "getPrototypeOf",
6058 vec![Value::Object(target.clone())],
6059 )?
6060 else {
6061 return Ok(Some(target.proto()));
6062 };
6063 let proto = match &result {
6064 Value::Null => None,
6065 Value::Object(proto) => Some(proto.clone()),
6066 _ => {
6067 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
6068 }
6069 };
6070 if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
6071 return Err(self.type_error(
6072 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
6073 ));
6074 }
6075 Ok(Some(proto))
6076 }
6077
6078 /// `[[SetPrototypeOf]]` on a proxy.
6079 fn proxy_set_prototype_of(
6080 &mut self,
6081 object: &Gc<JsObject>,
6082 proto: Option<Gc<JsObject>>,
6083 ) -> JsResult<Option<bool>> {
6084 let Some((target, handler)) = self.proxy_parts(object)? else {
6085 return Ok(None);
6086 };
6087 let proto_value = match &proto {
6088 Some(proto) => Value::Object(proto.clone()),
6089 None => Value::Null,
6090 };
6091 let Some(result) = self.proxy_trap(
6092 &handler,
6093 "setPrototypeOf",
6094 vec![Value::Object(target.clone()), proto_value],
6095 )?
6096 else {
6097 target.set_proto(proto);
6098 return Ok(Some(true));
6099 };
6100 if result.to_boolean()
6101 && !target.is_extensible()
6102 && !same_proto(proto.as_ref(), target.proto().as_ref())
6103 {
6104 return Err(self.type_error(
6105 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
6106 ));
6107 }
6108 Ok(Some(result.to_boolean()))
6109 }
6110
6111 /// `[[IsExtensible]]` on a proxy.
6112 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6113 let Some((target, handler)) = self.proxy_parts(object)? else {
6114 return Ok(None);
6115 };
6116 let Some(result) = self.proxy_trap(
6117 &handler,
6118 "isExtensible",
6119 vec![Value::Object(target.clone())],
6120 )?
6121 else {
6122 return Ok(Some(target.is_extensible()));
6123 };
6124 // The answer is not the proxy's to invent: it must agree with the target, or a
6125 // script could learn `false` while the target keeps accepting new properties.
6126 if result.to_boolean() != target.is_extensible() {
6127 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
6128 }
6129 Ok(Some(result.to_boolean()))
6130 }
6131
6132 /// `[[PreventExtensions]]` on a proxy.
6133 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6134 let Some((target, handler)) = self.proxy_parts(object)? else {
6135 return Ok(None);
6136 };
6137 let Some(result) = self.proxy_trap(
6138 &handler,
6139 "preventExtensions",
6140 vec![Value::Object(target.clone())],
6141 )?
6142 else {
6143 target.set_extensible(false);
6144 return Ok(Some(true));
6145 };
6146 if result.to_boolean() && target.is_extensible() {
6147 return Err(self.type_error(
6148 "proxy 'preventExtensions' reported success but the target is still extensible",
6149 ));
6150 }
6151 Ok(Some(result.to_boolean()))
6152 }
6153
6154 /// `[[Call]]` on a proxy, through the `apply` trap.
6155 fn proxy_apply(
6156 &mut self,
6157 object: &Gc<JsObject>,
6158 this: Value,
6159 args: Vec<Value>,
6160 ) -> JsResult<Option<Value>> {
6161 let Some((target, handler)) = self.proxy_parts(object)? else {
6162 return Ok(None);
6163 };
6164 // The trap gets the arguments as one array, which is the shape the spec passes
6165 // and the shape `apply` traps are written against (`args[0]` is the first one).
6166 let arguments = self.new_array(args.clone());
6167 let this_for_trap = this.clone();
6168 let Some(result) = self.proxy_trap(
6169 &handler,
6170 "apply",
6171 vec![
6172 Value::Object(target.clone()),
6173 this_for_trap,
6174 Value::Object(arguments),
6175 ],
6176 )?
6177 else {
6178 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
6179 };
6180 Ok(Some(result))
6181 }
6182
6183 /// `[[Construct]]` on a proxy, through the `construct` trap.
6184 fn proxy_construct(
6185 &mut self,
6186 object: &Gc<JsObject>,
6187 args: Vec<Value>,
6188 new_target: &Value,
6189 ) -> JsResult<Option<Value>> {
6190 let Some((target, handler)) = self.proxy_parts(object)? else {
6191 return Ok(None);
6192 };
6193 if !target.is_callable() {
6194 return Err(self.type_error("proxy target is not a constructor"));
6195 }
6196 let arguments = self.new_array(args.clone());
6197 let Some(result) = self.proxy_trap(
6198 &handler,
6199 "construct",
6200 vec![
6201 Value::Object(target.clone()),
6202 Value::Object(arguments),
6203 new_target.clone(),
6204 ],
6205 )?
6206 else {
6207 return Ok(Some(self.construct(
6208 Value::Object(target),
6209 new_target.clone(),
6210 args,
6211 )?));
6212 };
6213 if !matches!(result, Value::Object(_)) {
6214 return Err(self.type_error("proxy 'construct' must return an object"));
6215 }
6216 Ok(Some(result))
6217 }
6218
6219 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
6220 pub(crate) fn has_own_or_inherited(
6221 &mut self,
6222 object: &Gc<JsObject>,
6223 key: &PropertyKey,
6224 ) -> JsResult<bool> {
6225 // The object itself first: it may be a proxy, and then the answer is its trap's.
6226 if let Some(answer) = self.proxy_has(object, key)? {
6227 return Ok(answer);
6228 }
6229 // An integer-indexed exotic object answers a canonical numeric index from
6230 // `IsValidIntegerIndex` alone (§10.4.5.4 step 1.b.i) — **without** walking the
6231 // prototype chain. That is observable: a view the buffer has been resized away from
6232 // has no indices, so `2 in view` is `false` even when
6233 // `Object.getPrototypeOf(view)[2]` exists. Falling through to the chain answered
6234 // `true`, which is what `TypedArray/out-of-bounds-behaves-like-detached` catches.
6235 // The `[[HasProperty]]` that `in` compiles to goes through here, which is why the
6236 // same rule is repeated in `has_property_key` rather than living only there.
6237 if object.typed_array_parts().is_some()
6238 && let Some(index) = key.as_str().and_then(array_index)
6239 {
6240 return Ok(object
6241 .typed_array_length()
6242 .is_some_and(|length| (index as usize) < length));
6243 }
6244 // A host class answers `in` for its own keys, which may live nowhere in a property
6245 // table — `"x" in point` is true because the class says so, not because a property
6246 // exists.
6247 if let Some(exotic) = object.exotic()
6248 && let Some(answer) = exotic.has_property(self, object, key)?
6249 {
6250 return Ok(answer);
6251 }
6252 // `has_own` rather than `own_property_key`: an array's elements and its derived
6253 // `length` are invisible to the property table, and `Array.prototype` is an array.
6254 // A host class's `get_own_property` counts too, because the reference's
6255 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
6256 // lives — a class with only `get_own_property` answers `in` through it.
6257 if self.exotic_has_own(object, key)? {
6258 return Ok(true);
6259 }
6260 // A hole is *not* the end of the search: the chain may still have the key, which
6261 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
6262 for ancestor in object.chain() {
6263 // A proxy further up the chain answers for itself.
6264 if let Some(answer) = self.proxy_has(&ancestor, key)? {
6265 return Ok(answer);
6266 }
6267 // Same for a host class: a prototype may be one, and `in` reaches it.
6268 if let Some(exotic) = ancestor.exotic()
6269 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
6270 {
6271 return Ok(answer);
6272 }
6273 if self.exotic_has_own(&ancestor, key)? {
6274 return Ok(true);
6275 }
6276 }
6277 Ok(false)
6278 }
6279
6280 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
6281 /// trap included.
6282 ///
6283 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
6284 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
6285 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
6286 if let Some(exotic) = object.exotic()
6287 && let Some(answer) = exotic.get_own_property(self, object, key)?
6288 {
6289 return Ok(answer.is_some());
6290 }
6291 Ok(has_own(object, key))
6292 }
6293
6294 /// `CreateListFromArrayLike`, optionally restricted to property keys.
6295 ///
6296 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
6297 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
6298 /// `TypeError` instead of a property named `"1.5"`.
6299 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
6300 let object = self.object_from(value)?;
6301 let length = self
6302 .get_property(&object, "length")?
6303 .map(|value| value.to_number())
6304 .unwrap_or(0.0);
6305 if !length.is_finite() || length < 0.0 {
6306 return Err(self.type_error("invalid array-like length"));
6307 }
6308 let length = length as usize;
6309 let mut items = Vec::with_capacity(length.min(1024));
6310 for index in 0..length {
6311 let item = self
6312 .get_property(&object, &index.to_string())?
6313 .unwrap_or(Value::Undefined);
6314 if keys_only && matches!(&item, Value::Symbol(_)) {
6315 items.push(item);
6316 continue;
6317 }
6318 if keys_only && !matches!(&item, Value::String(_)) {
6319 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
6320 }
6321 items.push(item);
6322 }
6323 Ok(items)
6324 }
6325
6326 /// A `Property` from the descriptor object a trap returned.
6327 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
6328 let object = self.object_from(value)?;
6329 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
6330 interp.get_property(&object, name)
6331 };
6332 let getter = field(self, "get")?;
6333 let setter = field(self, "set")?;
6334 let accessor = getter.is_some() || setter.is_some();
6335 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
6336 Ok(interp
6337 .get_property(&object, name)?
6338 .is_some_and(|value| value.to_boolean()))
6339 };
6340 let enumerable = boolean(self, "enumerable")?;
6341 let configurable = boolean(self, "configurable")?;
6342 if accessor {
6343 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
6344 return Err(
6345 self.type_error("a descriptor cannot be both a data property and an accessor")
6346 );
6347 }
6348 Ok(Property {
6349 getter: getter.or(Some(Value::Undefined)),
6350 setter: setter.or(Some(Value::Undefined)),
6351 enumerable,
6352 configurable,
6353 writable: false,
6354 value: None,
6355 })
6356 } else {
6357 Ok(Property {
6358 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
6359 writable: boolean(self, "writable")?,
6360 enumerable,
6361 configurable,
6362 getter: None,
6363 setter: None,
6364 })
6365 }
6366 }
6367
6368 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
6369 fn descriptor_from_property(&mut self, property: &Property) -> Value {
6370 let object = self.new_object(None);
6371 if property.is_accessor() {
6372 let getter = property.getter.clone().unwrap_or(Value::Undefined);
6373 let setter = property.setter.clone().unwrap_or(Value::Undefined);
6374 object.define_data("get", getter);
6375 object.define_data("set", setter);
6376 } else {
6377 let value = property.value.clone().unwrap_or(Value::Undefined);
6378 object.define_data("value", value);
6379 object.define_data("writable", Value::Bool(property.writable));
6380 }
6381 object.define_data("enumerable", Value::Bool(property.enumerable));
6382 object.define_data("configurable", Value::Bool(property.configurable));
6383 Value::Object(object)
6384 }
6385
6386 // -- calling ------------------------------------------------------------
6387
6388 /// Call `callee` with `this` and `args`.
6389 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
6390 let Value::Object(function) = &callee else {
6391 // `typeof x === "function"` is not enough to make `x()` legal: only a
6392 // callable object is. `null` and `undefined` need no special wording
6393 // here — their `ToString` already reads the way the reference's does.
6394 let what = format!("{} is not a function", callee.to_js_string());
6395 return Err(Signal::Throw(self.make_error("TypeError", &what)));
6396 };
6397 // A proxy of a function is called through its `apply` trap. It has no
6398 // `ObjectKind::Function` of its own, so this has to come before the dispatch
6399 // below, and a proxy of a non-function has nothing to forward to.
6400 if function.proxy_state().is_some() {
6401 return match self.proxy_apply(function, this, args)? {
6402 Some(result) => Ok(result),
6403 None => Err(Signal::Throw(
6404 self.make_error("TypeError", "proxy target is not callable"),
6405 )),
6406 };
6407 }
6408 let callable = function.with(|data| match &data.kind {
6409 ObjectKind::Function(callable) => match callable {
6410 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
6411 // The `Rc` is cloned out so the borrow of this object's data is released
6412 // before the closure runs: the closure may touch the same object.
6413 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
6414 Callable::Bound {
6415 target,
6416 this,
6417 args: leading,
6418 } => Some(NativeCall::Bound {
6419 target: target.clone(),
6420 this: this.clone(),
6421 leading: leading.clone(),
6422 }),
6423 Callable::Bytecode { code, env } => {
6424 Some(NativeCall::Bytecode(code.clone(), env.clone()))
6425 }
6426 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
6427 Callable::PromiseResolve(promise) => {
6428 Some(NativeCall::PromiseResolve(promise.clone()))
6429 }
6430 Callable::PromiseReject(promise) => {
6431 Some(NativeCall::PromiseReject(promise.clone()))
6432 }
6433 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
6434 state: state.clone(),
6435 }),
6436 Callable::ThenShim {
6437 handler,
6438 resolve,
6439 reject,
6440 fulfilled,
6441 } => Some(NativeCall::ThenShim {
6442 handler: handler.clone(),
6443 resolve: resolve.clone(),
6444 reject: reject.clone(),
6445 fulfilled: *fulfilled,
6446 }),
6447 Callable::AwaitResume {
6448 coroutine,
6449 promise,
6450 kind,
6451 } => Some(NativeCall::AwaitResume {
6452 coroutine: coroutine.clone(),
6453 promise: promise.clone(),
6454 kind: *kind,
6455 }),
6456 Callable::CombinatorSettle {
6457 state,
6458 index,
6459 fulfilled,
6460 } => Some(NativeCall::CombinatorSettle {
6461 state: state.clone(),
6462 index: *index,
6463 fulfilled: *fulfilled,
6464 }),
6465 Callable::FinallyShim {
6466 callback,
6467 fulfilled,
6468 constructor,
6469 } => Some(NativeCall::FinallyShim {
6470 callback: callback.clone(),
6471 fulfilled: *fulfilled,
6472 constructor: constructor.clone(),
6473 }),
6474 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
6475 Callable::CompletedReturn {
6476 generator,
6477 promise,
6478 rejected,
6479 } => Some(NativeCall::CompletedReturn {
6480 generator: generator.clone(),
6481 promise: promise.clone(),
6482 rejected: *rejected,
6483 }),
6484 Callable::YieldResult {
6485 generator,
6486 promise,
6487 done,
6488 } => Some(NativeCall::YieldResult {
6489 generator: generator.clone(),
6490 promise: promise.clone(),
6491 done: *done,
6492 }),
6493 Callable::DisposeStep {
6494 remaining,
6495 promise,
6496 error,
6497 rejected,
6498 } => Some(NativeCall::DisposeStep {
6499 remaining: remaining.clone(),
6500 promise: promise.clone(),
6501 error: error.clone(),
6502 rejected: *rejected,
6503 }),
6504 Callable::GeneratorResume {
6505 generator,
6506 promise,
6507 kind,
6508 } => Some(NativeCall::GeneratorResume {
6509 generator: generator.clone(),
6510 promise: promise.clone(),
6511 kind: *kind,
6512 }),
6513 Callable::SettlePromise {
6514 promise,
6515 value,
6516 rejected,
6517 } => Some(NativeCall::SettlePromise {
6518 promise: promise.clone(),
6519 value: value.clone(),
6520 rejected: *rejected,
6521 }),
6522 },
6523 _ => None,
6524 });
6525 match callable {
6526 Some(NativeCall::Host(func)) => {
6527 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
6528 // function by name rather than stopping at the caller.
6529 let frame_less = function
6530 .own_property("_frame_less")
6531 .and_then(|property| property.value)
6532 .is_some_and(|value| value.to_boolean());
6533 let outer = if frame_less {
6534 None
6535 } else {
6536 self.native_frames
6537 .push((function.clone(), self.frames.len()));
6538 Some(self.current_native.replace(function.clone()))
6539 };
6540 let result = {
6541 let mut body = func.borrow_mut();
6542 body(self, this, &args)
6543 };
6544 if !frame_less {
6545 self.native_frames.pop();
6546 self.current_native = outer.flatten();
6547 }
6548 result
6549 }
6550 Some(NativeCall::Native(func)) => {
6551 // A function marked `_frame_less` is one the reference implements
6552 // without a call frame — `eval` is the only one so far.
6553 let frame_less = function
6554 .own_property("_frame_less")
6555 .and_then(|property| property.value)
6556 .is_some_and(|value| value.to_boolean());
6557 let outer = if frame_less {
6558 None
6559 } else {
6560 self.native_frames
6561 .push((function.clone(), self.frames.len()));
6562 Some(self.current_native.replace(function.clone()))
6563 };
6564 let result = func(self, this, &args);
6565 if !frame_less {
6566 self.native_frames.pop();
6567 self.current_native = outer.flatten();
6568 }
6569 result
6570 }
6571 Some(NativeCall::Revoker(slots)) => {
6572 // Idempotent: revoking twice answers `undefined` again rather than
6573 // complaining, which is what the spec says and what a `finally` block
6574 // relies on.
6575 let mut state = slots.borrow_mut();
6576 state.target = None;
6577 state.handler = None;
6578 Ok(Value::Undefined)
6579 }
6580 Some(NativeCall::PromiseResolve(promise)) => {
6581 // One-shot: a second call is silently ignored, which
6582 // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
6583 let value = args.first().cloned().unwrap_or(Value::Undefined);
6584 self.resolve_promise_with(&promise, value)?;
6585 Ok(Value::Undefined)
6586 }
6587 Some(NativeCall::PromiseReject(promise)) => {
6588 let reason = args.first().cloned().unwrap_or(Value::Undefined);
6589 self.reject_promise(&promise, reason);
6590 Ok(Value::Undefined)
6591 }
6592 Some(NativeCall::ThenShim {
6593 handler,
6594 resolve,
6595 reject,
6596 fulfilled,
6597 }) => {
6598 // `PerformPromiseThen` with a capability: run the handler, then settle
6599 // through the capability's own pair. A throw from the handler is the
6600 // rejection, and a throw from the capability's `resolve` is not caught —
6601 // exactly the spec's `?`.
6602 let value = args.first().cloned().unwrap_or(Value::Undefined);
6603 match handler {
6604 Some(handler) => {
6605 match self.call_value(handler, Value::Undefined, vec![value]) {
6606 Ok(result) => {
6607 self.call_value(resolve, Value::Undefined, vec![result])?;
6608 }
6609 Err(Signal::Throw(reason)) => {
6610 self.call_value(reject, Value::Undefined, vec![reason])?;
6611 }
6612 Err(signal) => return Err(signal),
6613 }
6614 }
6615 None => {
6616 let handler = if fulfilled { resolve } else { reject };
6617 self.call_value(handler, Value::Undefined, vec![value])?;
6618 }
6619 }
6620 Ok(Value::Undefined)
6621 }
6622 Some(NativeCall::CapabilityExecutor { state }) => {
6623 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
6624 // slot holds a value yet. The test is on the *values*, not on a call count —
6625 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
6626 // called-twice`'s first case does exactly that), while a second call after a
6627 // real pair is the `TypeError`.
6628 let defined = |name: &str| {
6629 state
6630 .own_property(name)
6631 .and_then(|property| property.value)
6632 .is_some_and(|value| !matches!(value, Value::Undefined))
6633 };
6634 if defined("resolve") || defined("reject") {
6635 return Err(self.type_error("promise capability executor called twice"));
6636 }
6637 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
6638 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
6639 state.define_data("resolve", resolve);
6640 state.define_data("reject", reject);
6641 Ok(Value::Undefined)
6642 }
6643 Some(NativeCall::CombinatorSettle {
6644 state,
6645 index,
6646 fulfilled,
6647 }) => {
6648 let value = args.first().cloned().unwrap_or(Value::Undefined);
6649 self.settle_combinator(&state, index, fulfilled, value)?;
6650 Ok(Value::Undefined)
6651 }
6652 Some(NativeCall::AwaitResume {
6653 coroutine,
6654 promise,
6655 kind,
6656 }) => {
6657 // Resume *inline*, in the reaction that delivered the value. Deferring it
6658 // by another job inserts a tick between every `await` and its
6659 // continuation, which reorders `await` against unrelated `then` chains —
6660 // `f().then(g)` then runs before `f`'s own next statement.
6661 self.drive_async(
6662 &coroutine,
6663 &promise,
6664 kind,
6665 args.first().cloned().unwrap_or(Value::Undefined),
6666 )
6667 .map(|()| Value::Undefined)
6668 }
6669 Some(NativeCall::FinallyShim {
6670 callback,
6671 fulfilled,
6672 constructor,
6673 }) => {
6674 // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
6675 // that settles with the *original* outcome once the callback's result has
6676 // settled. The callback's own value is discarded — that is the whole
6677 // difference between `finally` and `then`.
6678 let original = args.first().cloned().unwrap_or(Value::Undefined);
6679 let result = match &callback {
6680 Some(callback) => {
6681 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
6682 }
6683 None => Value::Undefined,
6684 };
6685 // `PromiseResolve(C, result)`, not the intrinsic: a `result` that is
6686 // already a promise of this constructor is reused rather than rewrapped.
6687 let resolved = self.promise_resolve_for(&constructor, result)?;
6688 let Value::Object(resolved) = resolved else {
6689 return Ok(original);
6690 };
6691 // The wait is a chained promise rather than a bare return, so a callback
6692 // that returns a slow promise really does delay the continuation.
6693 let waiting = self.new_promise();
6694 let pass = JsObject::function(
6695 self.heap,
6696 Some(self.realm.function_proto.clone()),
6697 Callable::SettlePromise {
6698 promise: waiting.clone(),
6699 value: original,
6700 rejected: !fulfilled,
6701 },
6702 );
6703 let pass = Value::Object(pass);
6704 // Whichever way the callback's promise settles, the original outcome wins.
6705 self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
6706 Ok(Value::Object(waiting))
6707 }
6708 Some(NativeCall::DisposeStep {
6709 remaining,
6710 promise,
6711 error,
6712 rejected,
6713 }) => {
6714 let error = if rejected {
6715 let reason = args.first().cloned().unwrap_or(Value::Undefined);
6716 self.merge_dispose_error(reason, error)
6717 } else {
6718 error
6719 };
6720 self.dispose_step(&remaining, &promise, error)?;
6721 Ok(Value::Undefined)
6722 }
6723 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
6724 Some(NativeCall::CompletedReturn {
6725 generator,
6726 promise,
6727 rejected,
6728 }) => {
6729 let value = args.first().cloned().unwrap_or(Value::Undefined);
6730 let outcome = if rejected {
6731 AsyncOutcome::Error(value)
6732 } else {
6733 AsyncOutcome::Value(self.iterator_result(value, true)?)
6734 };
6735 self.settle_async_request(&generator, &promise, outcome)?;
6736 Ok(Value::Undefined)
6737 }
6738 Some(NativeCall::YieldResult {
6739 generator,
6740 promise,
6741 done,
6742 }) => {
6743 let value = args.first().cloned().unwrap_or(Value::Undefined);
6744 let result = self.iterator_result(value, done)?;
6745 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
6746 Ok(Value::Undefined)
6747 }
6748 Some(NativeCall::GeneratorResume {
6749 generator,
6750 promise,
6751 kind,
6752 }) => {
6753 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
6754 // tick and reorders the generator against other chains.
6755 self.step_async_generator(
6756 &generator,
6757 &promise,
6758 kind,
6759 args.first().cloned().unwrap_or(Value::Undefined),
6760 )
6761 .map(|()| Value::Undefined)
6762 }
6763 Some(NativeCall::SettlePromise {
6764 promise,
6765 value,
6766 rejected,
6767 }) => {
6768 if rejected {
6769 self.reject_promise(&promise, value);
6770 } else {
6771 self.fulfill_promise(&promise, value);
6772 }
6773 Ok(Value::Undefined)
6774 }
6775 Some(NativeCall::Bound {
6776 target,
6777 this: bound_this,
6778 leading,
6779 }) => {
6780 let mut all = leading;
6781 all.extend(args);
6782 self.call_value(target, bound_this, all)
6783 }
6784 Some(NativeCall::Bytecode(code, env)) => {
6785 if code.code.kind.is_generator() {
6786 return self.new_generator(callee, this, args);
6787 }
6788 if code.code.kind.is_async() {
6789 // Same coroutine machinery as a generator; the difference is only in
6790 // what the completion does — see `new_async_function`.
6791 return self.new_async_function(callee, this, args);
6792 }
6793 self.execute(code, env, this, args, callee)
6794 }
6795 None => Err(Signal::Throw(
6796 self.make_error("TypeError", "not a function"),
6797 )),
6798 }
6799 }
6800
6801 /// Give a freshly built function its own `prototype` object.
6802 ///
6803 /// Every function that can be used with `new` carries one, and its
6804 /// `constructor` points back at the function — a reference cycle, which is
6805 /// exactly what the collector's cycle pass exists to reclaim.
6806 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
6807 let prototype = self.new_object(Some(self.realm.object_proto.clone()));
6808 let constructor = Value::Object(function.clone());
6809 prototype.define(
6810 "constructor",
6811 Property::with_attributes(constructor, true, false),
6812 );
6813 let value = Value::Object(prototype);
6814 function.define("prototype", Property::prototype_of(value, true));
6815 }
6816
6817 /// A getter or setter that reads or writes the reference cell behind a mapped
6818 /// `arguments` index.
6819 ///
6820 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
6821 /// count — which is what the collector treats as "a reference from outside the
6822 /// heap". The closure therefore keeps the cell alive for exactly as long as the
6823 /// accessor is reachable, which is the same lifetime the arguments object has.
6824 ///
6825 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
6826 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
6827 /// parameter value and the arguments object reaches the closure, never the other
6828 /// way round. Nothing the collector has to see is hidden.
6829 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
6830 let name = if is_setter { "set" } else { "get" };
6831 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
6832 if is_setter {
6833 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
6834 Ok(Value::Undefined)
6835 } else {
6836 Ok(cell.get())
6837 }
6838 };
6839 self.new_host_function(name, 1, Box::new(func))
6840 }
6841
6842 /// The object `special_object` builds.
6843 ///
6844 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
6845 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
6846 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
6847 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
6848 /// write through `arguments` does not reach the parameter.
6849 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
6850 match magic {
6851 0 | 1 => {
6852 let args = self.frame().passed().to_vec();
6853 let proto = self.realm.object_proto.clone();
6854 let object = self.new_object(Some(proto));
6855 // The marker `Object.prototype.toString` needs: an arguments object is an
6856 // ordinary object apart from reporting `[object Arguments]`, and that has
6857 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
6858 // show up ahead of them in a key listing anyway — it is non-enumerable.
6859 self.internal_set(&object, "_class", self.string("Arguments"));
6860 // `length` is writable and configurable but neither enumerable nor a
6861 // plain data property: `Object.keys(arguments)` lists the indices only,
6862 // which is how `{...arguments}` copies them without the length.
6863 object.define(
6864 "length",
6865 Property::with_attributes(Value::Int(args.len() as i32), true, false),
6866 );
6867 // `magic == 1` is sloppy mode, where each index is *mapped* to the
6868 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
6869 // change `a`, and assigning `a` has to change `arguments[0]`.
6870 //
6871 // The shared storage is the parameter's reference cell. The compiler
6872 // gives every parameter of such a function one (see
6873 // `provide_body_arguments`), and the cell outlives the frame, so this
6874 // keeps working after the arguments object escapes.
6875 //
6876 // The index becomes an accessor rather than a data property. A mapped
6877 // index reports as a plain writable/enumerable data property through
6878 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
6879 // the getter/setter pair is only the plumbing underneath.
6880 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
6881 let frame = self.frame();
6882 frame
6883 .code
6884 .arg_cell
6885 .iter()
6886 .map(|cell| {
6887 (*cell >= 0)
6888 .then(|| frame.cells.get(*cell as usize).cloned())
6889 .flatten()
6890 })
6891 .collect()
6892 } else {
6893 Vec::new()
6894 };
6895 // Tell the object which indices are mapped, so
6896 // `Object.getOwnPropertyDescriptor` can report them as the data
6897 // properties the spec describes instead of the accessors that
6898 // implement the aliasing.
6899 if magic == 1 {
6900 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
6901 for cell in &mapped_cells {
6902 table.push(cell.clone());
6903 }
6904 object.set_mapped_arguments(table);
6905 }
6906 for (index, value) in args.into_iter().enumerate() {
6907 match mapped_cells.get(index).cloned().flatten() {
6908 Some(cell) => {
6909 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
6910 let setter = self.new_mapped_arguments_accessor(cell, true);
6911 object.define(
6912 &index.to_string(),
6913 Property::accessor_with(
6914 Some(Value::Object(getter)),
6915 Some(Value::Object(setter)),
6916 true,
6917 ),
6918 );
6919 }
6920 None => object.define_data(&index.to_string(), value),
6921 }
6922 }
6923 // §10.4.4: a *mapped* arguments object carries `callee` as a writable,
6924 // non-enumerable, configurable data property holding the function being
6925 // called. A strict (unmapped) one gets no such property at all; the
6926 // spec's poison-pill accessor for it is unreachable in this engine
6927 // because a strict `arguments.callee` is already a compile-time error.
6928 //
6929 // The legacy `S10.6_*` tests predate that restriction and ask only that
6930 // `arguments.hasOwnProperty("callee")` be true in sloppy mode.
6931 if magic == 1 {
6932 let callee = self.frame().callee.clone();
6933 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
6934 object.define("callee", Property::with_attributes(callee, true, false));
6935 }
6936 // An arguments object is iterable: `[...arguments]` and
6937 // `for (const a of arguments)` both work, through the *array* iterator
6938 // because the object is array-like. Without this the whole spread form
6939 // reported "not iterable".
6940 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
6941 let values = self
6942 .realm
6943 .array_proto
6944 .own_property("values")
6945 .and_then(|property| property.value);
6946 if let Some(values) = values {
6947 object.define_key(
6948 &iterator_key,
6949 Property::with_attributes(values, true, false),
6950 );
6951 }
6952 Ok(Value::Object(object))
6953 }
6954 // `this.active_func`: the constructor `super()` resolves against.
6955 //
6956 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
6957 // own, so it inherits this from the function it was written in along with `this`
6958 // — and that is a lexical relationship, not a stack one: an arrow that escaped
6959 // the constructor and is called back later (`iter.return = () => super()`) has
6960 // the constructor nowhere on the stack. The compiler therefore reads it out of
6961 // a closure variable of the enclosing function, exactly as the reference does
6962 // with its `this_active_func` local.
6963 2 => Ok(self
6964 .current_callee()
6965 .map_or(Value::Undefined, Value::Object)),
6966 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
6967 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
6968 // its own either, so the lookup walks out to the nearest non-arrow frame for
6969 // the same reason as `this.active_func` above — without that, `super()` inside
6970 // an arrow passed `undefined` as the new target and the parent constructor was
6971 // then rejected for being invoked without `new`.
6972 3 => Ok(self
6973 .eval_new_target
6974 .clone()
6975 .unwrap_or_else(|| self.frame().new_target.clone())),
6976 // `[[HomeObject]]` of the function being run: what `super` is relative to.
6977 // An arrow has none of its own, so the lookup walks out to the enclosing
6978 // method — which is why `super` works inside an arrow inside a method.
6979 4 => Ok(self
6980 .frames
6981 .iter()
6982 .rev()
6983 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
6984 .map_or(Value::Undefined, Value::Object)),
6985 // `import.meta`: the innermost module body's meta object. Outside a module
6986 // the compiler never emits this, so an empty fallback is unreachable rather
6987 // than permissive.
6988 6 => {
6989 let name = self.module_stack.last().cloned();
6990 let meta = name
6991 .and_then(|name| self.modules.get(&name).cloned())
6992 .and_then(|module| module.with(|r| r.import_meta.clone()));
6993 Ok(meta.map_or(Value::Undefined, Value::Object))
6994 }
6995 other => Err(Signal::Throw(self.make_error(
6996 "InternalError",
6997 &format!("special_object {other} is not implemented yet"),
6998 ))),
6999 }
7000 }
7001
7002 /// `[[HomeObject]]` of the innermost function that has one, if any.
7003 ///
7004 /// An arrow has none, so the search walks out to the enclosing method — the same
7005 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
7006 /// inside a method.
7007 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
7008 self.frames
7009 .iter()
7010 .rev()
7011 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
7012 }
7013
7014 /// The dispose method a `using` declaration should snapshot, or an error.
7015 ///
7016 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
7017 /// is what makes a resource that only knows the synchronous protocol usable in both
7018 /// forms.
7019 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
7020 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
7021 if value.is_nullish() {
7022 return Ok(Value::Undefined);
7023 }
7024 let Some(object) = value.as_object() else {
7025 return Err(self.type_error("not an object"));
7026 };
7027 let mut method = if await_form {
7028 let found = self.get_property_key(
7029 object,
7030 &self.realm.well_known_key(WellKnown::AsyncDisposable),
7031 )?;
7032 match found {
7033 Some(found) if !found.is_nullish() => Some(found),
7034 _ => self
7035 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
7036 }
7037 } else {
7038 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
7039 };
7040 let Some(found) = method.take() else {
7041 return Err(self.type_error("value is not disposable"));
7042 };
7043 if found.is_nullish() {
7044 return Err(self.type_error("value is not disposable"));
7045 }
7046 let callable = found.as_object().is_some_and(|object| object.is_callable());
7047 if !callable {
7048 return Err(self.type_error("dispose method is not a function"));
7049 }
7050 Ok(found)
7051 }
7052
7053 /// Call one resource's disposer, folding a failure into `error_state`.
7054 ///
7055 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
7056 /// because a captured `using` binding lives in its reference cell and the local slot is
7057 /// stale — a closure over the resource is legal and must not change what is disposed.
7058 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
7059 let value = self.get_loc(slot);
7060 let method = self.get_loc(slot + 1);
7061 // A resource that was never initialised — its declaration threw — or that is
7062 // `null`/`undefined` has nothing to dispose.
7063 if value.is_nullish() || matches!(value, Value::Uninitialized) {
7064 return Ok(error_state);
7065 }
7066 if matches!(method, Value::Undefined | Value::Uninitialized) {
7067 return Ok(error_state);
7068 }
7069 match self.call_value(method, value, Vec::new()) {
7070 Ok(_) => Ok(error_state),
7071 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
7072 Err(other) => Err(other),
7073 }
7074 }
7075
7076 /// Combine a disposal failure with whatever was already going wrong.
7077 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
7078 if matches!(error_state, Value::Uninitialized) {
7079 return new_error;
7080 }
7081 self.new_suppressed_error(new_error, error_state)
7082 }
7083
7084 /// A `SuppressedError` instance built straight from its prototype.
7085 ///
7086 /// Not through the constructor: a script that rewrites
7087 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
7088 /// error wrapping.
7089 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
7090 let proto = self
7091 .realm
7092 .suppressed_error_proto
7093 .clone()
7094 .unwrap_or_else(|| self.realm.error_proto.clone());
7095 let object = self.new_object(Some(proto));
7096 object.define("error", Property::with_attributes(error, true, true));
7097 object.define(
7098 "suppressed",
7099 Property::with_attributes(suppressed, true, true),
7100 );
7101 object.define(
7102 "message",
7103 Property::with_attributes(self.string("SuppressedError"), true, true),
7104 );
7105 self.internal_set(&object, "_class", self.string("Error"));
7106 self.add_stack(&object);
7107 Value::Object(object)
7108 }
7109
7110 /// Call `callee`, or push its frame and let the main loop run it.
7111 ///
7112 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
7113 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
7114 /// continues, so `function f(){ return f() }` costs heap and stops at
7115 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
7116 /// is entered directly, and natives do not re-enter JavaScript in this
7117 /// milestone.
7118 ///
7119 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
7120 /// because the returning frame will.
7121 /// The elements of an array-like value, as a call argument list.
7122 ///
7123 /// `apply` accepts any array-like, not only a real array: the reference reads
7124 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
7125 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
7126 let Some(object) = value.as_object().cloned() else {
7127 if value.is_nullish() {
7128 // `f.apply(this, null)` passes no arguments at all.
7129 return Ok(Vec::new());
7130 }
7131 return Err(self.type_error("createListFromArrayLike called on non-object"));
7132 };
7133 let length = match self.get_property(&object, "length")? {
7134 Some(length) => length.to_number(),
7135 None => 0.0,
7136 };
7137 if !length.is_finite() || length <= 0.0 {
7138 return Ok(Vec::new());
7139 }
7140 let length = (length as usize).min(1_000_000);
7141 let mut args = Vec::with_capacity(length);
7142 for index in 0..length {
7143 let element = self.get_property(&object, &index.to_string())?;
7144 args.push(element.unwrap_or(Value::Undefined));
7145 }
7146 Ok(args)
7147 }
7148
7149 /// Turn a call to a generator function into a generator object.
7150 ///
7151 /// The frame is built exactly as an ordinary call would build it, then detached and
7152 /// stored in the generator before any body instruction runs — which is what makes
7153 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
7154 /// is `initial_yield`, the first instruction of every suspending body.
7155 pub fn new_generator(
7156 &mut self,
7157 function: Value,
7158 this: Value,
7159 args: Vec<Value>,
7160 ) -> JsResult<Value> {
7161 let Some(object) = function.as_object().cloned() else {
7162 return Err(self.type_error("not a generator function"));
7163 };
7164 let Some((code, env)) = bytecode_of(&object) else {
7165 return Err(self.type_error("not a generator function"));
7166 };
7167 let is_async = code.code.kind.is_async();
7168 self.push_frame(code, env, this, args, function)?;
7169 let frame = self.frames.pop().expect("push_frame just pushed it");
7170 // A fresh generator is *suspended at start*: the body has not run, so a
7171 // `return`/`throw` on it finishes without executing anything.
7172 let mut state = GeneratorState {
7173 frame: Some(frame),
7174 phase: GeneratorPhase::SuspendedStart,
7175 parked_on_await: false,
7176 parked_on_yield_star: false,
7177 requests: std::collections::VecDeque::new(),
7178 async_busy: false,
7179 };
7180 // Run to the first suspension. For a generator that is `initial_yield`, so no
7181 // body code runs; for a malformed body it would be the first `yield`.
7182 // An `async function*` answers an async generator: same coroutine, but its
7183 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
7184 let proto = if is_async {
7185 self.realm
7186 .async_generator_proto
7187 .clone()
7188 .unwrap_or_else(|| self.realm.generator_proto.clone())
7189 } else {
7190 self.realm.generator_proto.clone()
7191 };
7192 let generator = self.new_object(Some(proto));
7193 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
7194 Ok(_) => {}
7195 Err(error) => return Err(error),
7196 }
7197 generator.with_mut(|data| {
7198 data.kind = ObjectKind::Generator(Box::new(state));
7199 });
7200 Ok(Value::Object(generator))
7201 }
7202
7203 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7204 ///
7205 /// Returns the `{value, done}` object itself rather than the pair, because a
7206 /// `yield*` suspension already has one — the inner iterator's own result — and the
7207 /// protocol says to hand that straight through rather than nest it.
7208 /// Advance a generator and report *why* it parked.
7209 ///
7210 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
7211 /// "hand this value to the caller" — but an async generator does: an `await` has to
7212 /// settle before it can answer, while a `yield` is the answer.
7213 fn resume_generator_detailed(
7214 &mut self,
7215 generator: &Gc<JsObject>,
7216 kind: ResumeKind,
7217 value: Value,
7218 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7219 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
7220 ObjectKind::Generator(state) => Some(std::mem::replace(
7221 state.as_mut(),
7222 GeneratorState {
7223 frame: None,
7224 phase: GeneratorPhase::Executing,
7225 parked_on_await: false,
7226 parked_on_yield_star: false,
7227 requests: std::collections::VecDeque::new(),
7228 async_busy: false,
7229 },
7230 )),
7231 _ => None,
7232 }) else {
7233 return Err(self.type_error("not a generator"));
7234 };
7235 let result = self.step_generator(&mut state, kind, value);
7236 generator.with_mut(|data| {
7237 data.kind = ObjectKind::Generator(Box::new(state));
7238 });
7239 result
7240 }
7241
7242 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7243 ///
7244 /// Returns the `{value, done}` object itself rather than the pair, because a
7245 /// `yield*` suspension already has one — the inner iterator's own result — and the
7246 /// protocol says to hand that straight through rather than nest it.
7247 pub fn resume_generator(
7248 &mut self,
7249 generator: &Gc<JsObject>,
7250 kind: ResumeKind,
7251 value: Value,
7252 ) -> JsResult<Value> {
7253 let (value, done, ready, _reason) =
7254 self.resume_generator_detailed(generator, kind, value)?;
7255 if ready {
7256 return Ok(value);
7257 }
7258 self.iterator_result(value, done)
7259 }
7260
7261 /// `next`/`return`/`throw` on an async generator, which answer a promise.
7262 ///
7263 /// The body is the same coroutine a sync generator runs; what changes is that an
7264 /// `await` inside it has to settle before the method can answer, so the step is
7265 /// driven off the job queue rather than returning inline.
7266 pub fn resume_async_generator(
7267 &mut self,
7268 generator: &Gc<JsObject>,
7269 kind: ResumeKind,
7270 value: Value,
7271 ) -> JsResult<Value> {
7272 let promise = self.new_promise();
7273 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
7274 // that order, and the second value must reach the *second* `yield`.
7275 let idle = generator.with_mut(|data| match &mut data.kind {
7276 ObjectKind::Generator(state) => {
7277 state.requests.push_back(AsyncRequest {
7278 kind,
7279 value,
7280 promise: promise.clone(),
7281 });
7282 !state.async_busy
7283 }
7284 _ => false,
7285 });
7286 if idle {
7287 self.next_async_request(generator)?;
7288 }
7289 Ok(Value::Object(promise))
7290 }
7291
7292 /// Serve the front queued request, if the generator is free to run one.
7293 ///
7294 /// A finished generator answers from the queue without running anything:
7295 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
7296 /// first, and `throw(e)` rejects.
7297 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
7298 enum Front {
7299 Idle,
7300 Run(ResumeKind, Value, Gc<JsObject>),
7301 Finished(ResumeKind, Value, Gc<JsObject>),
7302 }
7303 let front = generator.with_mut(|data| match &mut data.kind {
7304 ObjectKind::Generator(state) => {
7305 let Some(request) = state.requests.front() else {
7306 return Front::Idle;
7307 };
7308 // Busy means a request is still in flight — awaiting inside the body, not
7309 // finished. Serving another now would interleave two requests.
7310 if state.async_busy && state.phase != GeneratorPhase::Completed {
7311 return Front::Idle;
7312 }
7313 let kind = request.kind;
7314 let value = request.value.clone();
7315 let promise = request.promise.clone();
7316 state.async_busy = true;
7317 if state.phase == GeneratorPhase::Completed {
7318 Front::Finished(kind, value, promise)
7319 } else {
7320 Front::Run(kind, value, promise)
7321 }
7322 }
7323 _ => Front::Idle,
7324 });
7325 match front {
7326 Front::Idle => Ok(()),
7327 Front::Run(kind, value, promise) => {
7328 self.step_async_generator(generator, &promise, kind, value)
7329 }
7330 Front::Finished(kind, value, promise) => match kind {
7331 ResumeKind::Throw => {
7332 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
7333 }
7334 ResumeKind::Next | ResumeKind::Start => {
7335 let result = self.iterator_result(Value::Undefined, true)?;
7336 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
7337 }
7338 ResumeKind::Return => {
7339 // `js_async_generator_completed_return`: the value is awaited before it
7340 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
7341 // finished generator answers `1`, not a promise.
7342 let resolved = match self.promise_resolve_value(value) {
7343 Ok(resolved) => resolved,
7344 Err(Signal::Throw(reason)) => {
7345 return self.settle_async_request(
7346 generator,
7347 &promise,
7348 AsyncOutcome::Error(reason),
7349 );
7350 }
7351 Err(other) => return Err(other),
7352 };
7353 let done = JsObject::function(
7354 self.heap,
7355 Some(self.realm.function_proto.clone()),
7356 Callable::CompletedReturn {
7357 generator: generator.clone(),
7358 promise: promise.clone(),
7359 rejected: false,
7360 },
7361 );
7362 let failed = JsObject::function(
7363 self.heap,
7364 Some(self.realm.function_proto.clone()),
7365 Callable::CompletedReturn {
7366 generator: generator.clone(),
7367 promise: promise.clone(),
7368 rejected: true,
7369 },
7370 );
7371 let Value::Object(resolved) = resolved else {
7372 return self.settle_async_request(
7373 generator,
7374 &promise,
7375 AsyncOutcome::Error(Value::Undefined),
7376 );
7377 };
7378 self.perform_then(
7379 &resolved,
7380 Some(Value::Object(done)),
7381 Some(Value::Object(failed)),
7382 )?;
7383 Ok(())
7384 }
7385 },
7386 }
7387 }
7388
7389 /// Settle the front request and start the next one.
7390 ///
7391 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
7392 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
7393 /// generator would strand every later request.
7394 fn settle_async_request(
7395 &mut self,
7396 generator: &Gc<JsObject>,
7397 promise: &Gc<JsObject>,
7398 outcome: AsyncOutcome,
7399 ) -> JsResult<()> {
7400 let settled = generator.with_mut(|data| match &mut data.kind {
7401 ObjectKind::Generator(state) => {
7402 let front = state.requests.front();
7403 debug_assert!(
7404 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
7405 "a request settled outside its turn"
7406 );
7407 state.requests.pop_front();
7408 state.async_busy = false;
7409 true
7410 }
7411 _ => false,
7412 });
7413 if settled {
7414 match outcome {
7415 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
7416 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
7417 }
7418 }
7419 self.next_async_request(generator)
7420 }
7421
7422 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
7423 ///
7424 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
7425 /// disposer runs **synchronously** — the reference starts it before returning, which
7426 /// a test can observe by logging after the call — and the rest follow once their
7427 /// predecessor settles.
7428 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
7429 let promise = self.new_promise();
7430 let mut pairs = Vec::with_capacity(resources.len());
7431 for (value, method) in resources {
7432 let pair = self.new_array(vec![value, method]);
7433 pairs.push(Value::Object(pair));
7434 }
7435 let remaining = self.new_array(pairs);
7436 self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
7437 Ok(Value::Object(promise))
7438 }
7439
7440 /// One link of the `disposeAsync` chain.
7441 ///
7442 /// Loops while the disposers finish synchronously, and parks on the first thenable it
7443 /// meets — pushing itself back in as the continuation, with the accumulated error
7444 /// carried along so a later failure can still be folded into the `SuppressedError`.
7445 fn dispose_step(
7446 &mut self,
7447 remaining: &Gc<JsObject>,
7448 promise: &Gc<JsObject>,
7449 mut error: Value,
7450 ) -> JsResult<()> {
7451 loop {
7452 let length = remaining.array_length().unwrap_or(0);
7453 if length == 0 {
7454 if matches!(error, Value::Uninitialized) {
7455 self.fulfill_promise(promise, Value::Undefined);
7456 } else {
7457 self.reject_promise(promise, error);
7458 }
7459 return Ok(());
7460 }
7461 let Some(Value::Object(pair)) = remaining
7462 .array_get(length - 1)
7463 .filter(|v| !matches!(v, Value::Hole))
7464 else {
7465 remaining.array_truncate(self.heap, length - 1);
7466 continue;
7467 };
7468 remaining.array_truncate(self.heap, length - 1);
7469 let value = pair.array_get(0).unwrap_or(Value::Undefined);
7470 let Some(Value::Object(method)) = pair.array_get(1) else {
7471 continue;
7472 };
7473 if !method.is_callable() {
7474 continue;
7475 }
7476 match self.call_value(Value::Object(method), value, Vec::new()) {
7477 Ok(result) => {
7478 if !self.is_thenable(&result)? {
7479 // Finished synchronously; the next disposer is the next iteration.
7480 continue;
7481 }
7482 let awaited = match self.promise_resolve_value(result) {
7483 Ok(awaited) => awaited,
7484 Err(Signal::Throw(reason)) => {
7485 self.reject_promise(promise, reason);
7486 return Ok(());
7487 }
7488 Err(other) => return Err(other),
7489 };
7490 let Value::Object(awaited) = awaited else {
7491 continue;
7492 };
7493 let ok = JsObject::function(
7494 self.heap,
7495 Some(self.realm.function_proto.clone()),
7496 Callable::DisposeStep {
7497 remaining: remaining.clone(),
7498 promise: promise.clone(),
7499 error: error.clone(),
7500 rejected: false,
7501 },
7502 );
7503 let failed = JsObject::function(
7504 self.heap,
7505 Some(self.realm.function_proto.clone()),
7506 Callable::DisposeStep {
7507 remaining: remaining.clone(),
7508 promise: promise.clone(),
7509 error,
7510 rejected: true,
7511 },
7512 );
7513 self.perform_then(
7514 &awaited,
7515 Some(Value::Object(ok)),
7516 Some(Value::Object(failed)),
7517 )?;
7518 return Ok(());
7519 }
7520 Err(Signal::Throw(thrown)) => {
7521 error = self.merge_dispose_error(thrown, error);
7522 }
7523 Err(other) => return Err(other),
7524 }
7525 }
7526 }
7527
7528 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
7529 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
7530 let Value::Object(object) = value else {
7531 return Ok(false);
7532 };
7533 Ok(matches!(
7534 self.get_property(object, "then")?,
7535 Some(Value::Object(then)) if then.is_callable()
7536 ))
7537 }
7538
7539 /// One step of an async generator, settling `promise` with an `{value, done}` result.
7540 fn step_async_generator(
7541 &mut self,
7542 generator: &Gc<JsObject>,
7543 promise: &Gc<JsObject>,
7544 kind: ResumeKind,
7545 value: Value,
7546 ) -> JsResult<()> {
7547 let stepped = self.resume_generator_detailed(generator, kind, value);
7548 let (value, done, ready, reason) = match stepped {
7549 Ok(stepped) => stepped,
7550 Err(Signal::Throw(reason)) => {
7551 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
7552 }
7553 Err(other) => return Err(other),
7554 };
7555 // Only an `await` has to wait before the method can answer.
7556 if !done && reason == Some(SuspendKind::Await) {
7557 let awaited = match self.promise_resolve_value(value) {
7558 Ok(awaited) => awaited,
7559 Err(Signal::Throw(reason)) => {
7560 return self.settle_async_request(
7561 generator,
7562 promise,
7563 AsyncOutcome::Error(reason),
7564 );
7565 }
7566 Err(other) => return Err(other),
7567 };
7568 let Value::Object(awaited) = awaited else {
7569 return Ok(());
7570 };
7571 let resumed = JsObject::function(
7572 self.heap,
7573 Some(self.realm.function_proto.clone()),
7574 Callable::GeneratorResume {
7575 generator: generator.clone(),
7576 promise: promise.clone(),
7577 kind: ResumeKind::Next,
7578 },
7579 );
7580 let raised = JsObject::function(
7581 self.heap,
7582 Some(self.realm.function_proto.clone()),
7583 Callable::GeneratorResume {
7584 generator: generator.clone(),
7585 promise: promise.clone(),
7586 kind: ResumeKind::Throw,
7587 },
7588 );
7589 self.perform_then(
7590 &awaited,
7591 Some(Value::Object(resumed)),
7592 Some(Value::Object(raised)),
7593 )?;
7594 return Ok(());
7595 }
7596 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
7597 // completes it — both arrive as the settled value rather than as the promise
7598 // object. A plain value skips the round trip, which is also what keeps `yield 1`
7599 // from costing an extra tick.
7600 let awaits_value = self.is_thenable(&value)?;
7601 if awaits_value {
7602 let awaited = match self.promise_resolve_value(value) {
7603 Ok(awaited) => awaited,
7604 Err(Signal::Throw(reason)) => {
7605 return self.settle_async_request(
7606 generator,
7607 promise,
7608 AsyncOutcome::Error(reason),
7609 );
7610 }
7611 Err(other) => return Err(other),
7612 };
7613 let Value::Object(awaited) = awaited else {
7614 return Ok(());
7615 };
7616 // A rejected yield throws *at the yield* inside the body, so the rejection
7617 // resumes the generator rather than the method's promise.
7618 let answer = JsObject::function(
7619 self.heap,
7620 Some(self.realm.function_proto.clone()),
7621 Callable::YieldResult {
7622 generator: generator.clone(),
7623 promise: promise.clone(),
7624 done,
7625 },
7626 );
7627 let raise = JsObject::function(
7628 self.heap,
7629 Some(self.realm.function_proto.clone()),
7630 Callable::GeneratorResume {
7631 generator: generator.clone(),
7632 promise: promise.clone(),
7633 kind: ResumeKind::Throw,
7634 },
7635 );
7636 self.perform_then(
7637 &awaited,
7638 Some(Value::Object(answer)),
7639 Some(Value::Object(raise)),
7640 )?;
7641 return Ok(());
7642 }
7643 let result = if ready {
7644 // `yield*` handed back the inner iterator's own result object.
7645 value
7646 } else {
7647 self.iterator_result(value, done)?
7648 };
7649 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
7650 }
7651
7652 /// The `{value, done}` object an iterator method answers with.
7653 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
7654 let result = self.new_object(Some(self.realm.object_proto.clone()));
7655 result.define_data("value", value);
7656 result.define_data("done", Value::Bool(done));
7657 Ok(Value::Object(result))
7658 }
7659
7660 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
7661 fn step_generator(
7662 &mut self,
7663 state: &mut GeneratorState,
7664 kind: ResumeKind,
7665 value: Value,
7666 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7667 match state.phase {
7668 GeneratorPhase::Executing => {
7669 return Err(self.type_error("cannot invoke a running generator"));
7670 }
7671 GeneratorPhase::Completed => {
7672 // A finished generator answers every resumption without running.
7673 return Ok(match kind {
7674 ResumeKind::Throw => return Err(Signal::Throw(value)),
7675 ResumeKind::Return => (value, true, false, None),
7676 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
7677 });
7678 }
7679 GeneratorPhase::SuspendedStart => {
7680 if kind != ResumeKind::Next && kind != ResumeKind::Start {
7681 // The body never started, so there is nothing to unwind or return
7682 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
7683 state.frame = None;
7684 state.phase = GeneratorPhase::Completed;
7685 return Ok(match kind {
7686 ResumeKind::Throw => return Err(Signal::Throw(value)),
7687 _ => (value, true, false, None),
7688 });
7689 }
7690 }
7691 GeneratorPhase::SuspendedYield => {}
7692 }
7693
7694 let Some(mut frame) = state.frame.take() else {
7695 return Ok((Value::Undefined, true, false, None));
7696 };
7697 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
7698 // number that says which method resumed it; the emitted `if_false` branches on
7699 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
7700 let mut raised = None;
7701 match kind {
7702 ResumeKind::Next | ResumeKind::Start => {
7703 if state.phase == GeneratorPhase::SuspendedYield {
7704 frame.stack.push(value);
7705 // An `await` resumes with its value alone; only a `yield` gets the
7706 // magic number that says which of `next`/`return` resumed it.
7707 if !state.parked_on_await {
7708 frame.stack.push(Value::Int(RESUME_NEXT));
7709 }
7710 }
7711 }
7712 ResumeKind::Return => {
7713 // A `return` on a not-yet-started generator is handled above, so this is
7714 // always a real resumption.
7715 frame.stack.push(value);
7716 frame.stack.push(Value::Int(RESUME_RETURN));
7717 }
7718 ResumeKind::Throw => {
7719 // At a `yield*` the exception is *data* for the delegation: the compiled
7720 // code resumes with the value and magic `2` and calls the inner iterator's
7721 // `throw`. Everywhere else it is raised at the suspension point, so the
7722 // body's own handler sees it.
7723 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
7724 frame.stack.push(value);
7725 frame.stack.push(Value::Int(RESUME_THROW));
7726 } else {
7727 raised = Some(value);
7728 }
7729 }
7730 }
7731 state.phase = GeneratorPhase::Executing;
7732
7733 let depth = self.frames.len();
7734 self.frames.push(frame);
7735 // A `throw` unwinds from where the frame parked, exactly as if the exception had
7736 // happened at the `yield`.
7737 if let Some(exception) = raised {
7738 if self.catch_here(exception.clone()).is_none() {
7739 self.pop_frame();
7740 state.phase = GeneratorPhase::Completed;
7741 return Err(Signal::Throw(exception));
7742 }
7743 }
7744
7745 // Only the generator's *own* frame ends the generator. The body may call ordinary
7746 // functions, and those push frames of their own: a `Step::Return` from one of them
7747 // is a nested call finishing, not the generator completing. Miscounting that is
7748 // silent — the generator reports the callee's value as its own result and marks
7749 // itself done — so the depth comparison is load-bearing, not defensive.
7750 let own_frame = depth + 1;
7751 loop {
7752 match self.step() {
7753 Ok(Step::Continue) => {}
7754 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
7755 let mut frame = self.frames.pop().expect("a frame is live");
7756 // `yield` left the value on the stack; `initial_yield` left nothing.
7757 let yielded = if reason == SuspendKind::Initial {
7758 Value::Undefined
7759 } else {
7760 frame.stack.pop().unwrap_or(Value::Undefined)
7761 };
7762 state.frame = Some(frame);
7763 state.parked_on_await = reason == SuspendKind::Await;
7764 state.parked_on_yield_star =
7765 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
7766 state.phase = if reason == SuspendKind::Initial {
7767 GeneratorPhase::SuspendedStart
7768 } else {
7769 GeneratorPhase::SuspendedYield
7770 };
7771 // `yield*` hands the inner iterator's own result object straight
7772 // back, so the caller sees one `{value, done}` rather than a nested
7773 // one — which is why the third field says "already a result".
7774 return Ok((
7775 yielded,
7776 false,
7777 reason == SuspendKind::YieldStar,
7778 Some(reason),
7779 ));
7780 }
7781 Ok(Step::Suspend(_)) => {
7782 // A `yield` in a frame other than the generator's would mean a
7783 // generator body entered as an ordinary call, which
7784 // `call_or_push` prevents.
7785 self.unwind_to(depth);
7786 state.phase = GeneratorPhase::Completed;
7787 return Err(Signal::Throw(self.make_error(
7788 "InternalError",
7789 "a generator body ran as an ordinary call",
7790 )));
7791 }
7792 Ok(Step::Return(value)) => {
7793 self.pop_frame();
7794 if self.frames.len() > depth {
7795 // A nested call finished: hand the value back to its caller and
7796 // keep running the generator body.
7797 self.frames
7798 .last_mut()
7799 .expect("a caller is live")
7800 .stack
7801 .push(value);
7802 continue;
7803 }
7804 state.phase = GeneratorPhase::Completed;
7805 // The reference closes the generator's closure variables here; ours
7806 // live in cells the frame owned, which the drop below releases.
7807 return Ok((value, true, false, None));
7808 }
7809 Err(Signal::Throw(exception)) => {
7810 // The frame that threw gets the first chance to catch, exactly as in
7811 // the ordinary call loop; a frame above the generator's is popped and
7812 // the exception carries on down.
7813 let exception = exception;
7814 loop {
7815 if self.frames.len() <= depth {
7816 // The generator's own frame is gone, so nothing here caught it.
7817 state.phase = GeneratorPhase::Completed;
7818 return Err(Signal::Throw(exception));
7819 }
7820 if self.catch_here(exception.clone()).is_some() {
7821 break;
7822 }
7823 self.pop_frame();
7824 }
7825 }
7826 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
7827 }
7828 }
7829 }
7830
7831 /// Pop frames until `depth` are left, keeping their buffers.
7832 fn unwind_to(&mut self, depth: usize) {
7833 while self.frames.len() > depth {
7834 self.pop_frame();
7835 }
7836 }
7837 fn call_or_push(
7838 &mut self,
7839 callee: Value,
7840 this: Value,
7841 args: Vec<Value>,
7842 ) -> JsResult<Option<Value>> {
7843 if let Value::Object(function) = &callee
7844 && let Some((code, env)) = bytecode_of(function)
7845 {
7846 // Calling a generator function does not run anything: it captures the
7847 // arguments in a frame and hands back the generator object.
7848 if code.code.kind.is_generator() {
7849 return self.new_generator(callee, this, args).map(Some);
7850 }
7851 // An async function answers a promise and runs its body as a coroutine, so it
7852 // takes the same path as a plain call into it.
7853 if code.code.kind.is_async() {
7854 return self.new_async_function(callee, this, args).map(Some);
7855 }
7856 self.push_frame(code, env, this, args, callee)?;
7857 return Ok(None);
7858 }
7859 self.call_value(callee, this, args).map(Some)
7860 }
7861
7862 /// `new callee(args)`.
7863 ///
7864 /// A constructor differs from a plain call in three ways: it gets a fresh object
7865 /// as `this` whose prototype is the constructor's `prototype` property, its
7866 /// return value is *replaced* by that object unless it returns an object itself,
7867 /// and a native constructor is expected to initialise the object it is given
7868 /// rather than build one.
7869 pub fn construct(
7870 &mut self,
7871 callee: Value,
7872 new_target: Value,
7873 args: Vec<Value>,
7874 ) -> JsResult<Value> {
7875 // `new` on a bound function constructs its *target*, prepending the arguments
7876 // the bind fixed and ignoring the bound `this` — a bound function is a
7877 // constructor only when its target is one, and `new` always makes a fresh
7878 // object of the target's prototype rather than reusing the bound receiver.
7879 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
7880 // ran the body with `this === null` and threw on `this.x = a`.
7881 let mut callee = callee;
7882 let mut new_target = new_target;
7883 let mut args = args;
7884 loop {
7885 let Some(object) = callee.as_object().cloned() else {
7886 return Err(Signal::Throw(
7887 self.make_error("TypeError", "not a constructor"),
7888 ));
7889 };
7890 // A proxy of a function constructs through its `construct` trap, and the
7891 // trap's answer is the result directly — no fresh object is made here.
7892 if object.proxy_state().is_some() {
7893 return match self.proxy_construct(&object, args, &new_target)? {
7894 Some(result) => Ok(result),
7895 None => Err(Signal::Throw(
7896 self.make_error("TypeError", "proxy target is not a constructor"),
7897 )),
7898 };
7899 }
7900 // A generator function has no `[[Construct]]`, and the reference names it in
7901 // the message: `new (function* G(){})()` reports "G is not a constructor".
7902 if object.with(|data| match &data.kind {
7903 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
7904 code.code.kind.is_generator()
7905 }
7906 _ => false,
7907 }) {
7908 let name = object
7909 .own_property("name")
7910 .and_then(|property| property.value)
7911 .map(|value| value.to_js_string())
7912 .unwrap_or_default();
7913 return Err(Signal::Throw(
7914 self.make_error("TypeError", &format!("{name} is not a constructor")),
7915 ));
7916 }
7917 let bound = object.with(|data| match &data.kind {
7918 ObjectKind::Function(Callable::Bound {
7919 target,
7920 args: leading,
7921 ..
7922 }) => Some((target.clone(), leading.clone())),
7923 _ => None,
7924 });
7925 let Some((target, leading)) = bound else {
7926 // Not a bound function, so this object is the callee. §7.2.4
7927 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
7928 // refusals above cover only the built-ins the reference also refuses by
7929 // name. Everything else — a method, an arrow, an async function — has no
7930 // `[[Construct]]` either, and answering "yes" here made
7931 // `new (Array.prototype.map)` build an object instead of throwing.
7932 if !object.is_constructor() {
7933 let name = object
7934 .own_property("name")
7935 .and_then(|property| property.value)
7936 .map(|value| value.to_js_string())
7937 .unwrap_or_default();
7938 return Err(Signal::Throw(
7939 self.make_error("TypeError", &format!("{name} is not a constructor")),
7940 ));
7941 }
7942 break;
7943 };
7944 let mut all = leading;
7945 all.extend(args);
7946 args = all;
7947 // A bound function that is its own `new.target` stands in for its target:
7948 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
7949 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
7950 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
7951 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
7952 _ => false,
7953 };
7954 if same_wrapper {
7955 new_target = target.clone();
7956 }
7957 callee = target;
7958 }
7959 let Value::Object(function) = &callee else {
7960 unreachable!("the loop above only breaks on an object");
7961 };
7962 // The fresh object's prototype comes from `new.target`, not from the callee: a
7963 // derived constructor reaches here through `super()`, and the instance must be a
7964 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
7965 // an object inheriting `D.prototype` rather than `C.prototype`.
7966 let prototype_source = match new_target.as_object() {
7967 Some(target) => target.clone(),
7968 None => function.clone(),
7969 };
7970 // A native constructor builds its own instance, through `new_ctor_instance`, once it
7971 // has validated its arguments. Pre-building one here would read
7972 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
7973 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
7974 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
7975 let is_native = function.native_creates_own_instance();
7976 let this = if is_native {
7977 Value::Undefined
7978 } else {
7979 let prototype = self.get_property(&prototype_source, "prototype")?;
7980 let prototype = match prototype {
7981 Some(Value::Object(proto)) => Some(proto),
7982 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
7983 // object, the answer is the realm's *intrinsic* prototype for this
7984 // constructor, not `%Object.prototype%`.
7985 _ => {
7986 let fallback = self.get_property(function, "prototype")?;
7987 match fallback {
7988 Some(Value::Object(proto)) => Some(proto),
7989 _ => Some(self.realm.object_proto.clone()),
7990 }
7991 }
7992 };
7993 Value::Object(self.new_object(prototype))
7994 };
7995 // `new.target` inside the body is the constructor that was written, so a bound
7996 // function's target sees itself rather than the bound wrapper.
7997 //
7998 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
7999 // `?`, so assigning `None` after the call would be skipped and the failed
8000 // `new.target` would stay visible to every later native call. The symptom was a
8001 // native constructor refusing a plain call — `var s = Symbol(); new
8002 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
8003 // "FinalizationRegistry is not a constructor".
8004 let outer_new_target = self.pending_new_target.replace(new_target);
8005 let result = self.call_value(callee, this.clone(), args);
8006 self.pending_new_target = outer_new_target;
8007 let result = result?;
8008 // A constructor that returns an object overrides `this`; any other return
8009 // value (including `undefined`) is ignored.
8010 Ok(match result {
8011 Value::Object(_) => result,
8012 _ => this,
8013 })
8014 }
8015
8016 /// `new.target` for the call currently being made.
8017 ///
8018 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
8019 /// it as `this`), but a *host* constructor that builds its own instance is handed
8020 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
8021 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
8022 /// it here.
8023 ///
8024 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
8025 /// receives for a plain call.
8026 pub fn current_new_target(&self) -> Value {
8027 self.pending_new_target.clone().unwrap_or(Value::Undefined)
8028 }
8029
8030 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
8031 ///
8032 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
8033 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
8034 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
8035 let constructor = self.realm.errors.get("AggregateError").cloned();
8036 let Some(constructor) = constructor else {
8037 return self.make_error("AggregateError", message);
8038 };
8039 let list = self.new_array(errors);
8040 match self.construct(
8041 Value::Object(constructor.clone()),
8042 Value::Object(constructor),
8043 vec![Value::Object(list), self.string(message)],
8044 ) {
8045 Ok(value) => value,
8046 // A user could have replaced `AggregateError` with something that throws; the
8047 // engine still owes the caller a rejection, so it falls back rather than
8048 // turning `Promise.any`'s rejection into a throw.
8049 Err(_) => self.make_error("AggregateError", message),
8050 }
8051 }
8052
8053 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
8054 ///
8055 /// The error classes themselves arrive with the builtins milestone; what
8056 /// matters here is that the thrown value stringifies the way a script printing
8057 /// the caught value expects.
8058 ///
8059 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
8060 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
8061 /// rely on when they print a caught value.
8062 pub fn make_error(&self, name: &str, message: &str) -> Value {
8063 let proto = self
8064 .realm
8065 .errors
8066 .get(name)
8067 .map(|constructor| self.prototype_of(constructor))
8068 .unwrap_or_else(|| self.realm.error_proto.clone());
8069 let error = self.new_object(Some(proto));
8070 // `name` and `message` are own properties of the instance, which is what
8071 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
8072 // `Error`.
8073 error.define(
8074 "name",
8075 Property::with_attributes(self.string(name), true, false),
8076 );
8077 error.define(
8078 "message",
8079 Property::with_attributes(self.string(message), true, false),
8080 );
8081 // The internal class, which is what tells a printer this is an error rather than a
8082 // plain object with `name` and `message` properties. The constructor path sets it
8083 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
8084 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
8085 // literally `"Error"` in both places — the *name* is read from `name`, which is why
8086 // a `RangeError` still prints as `RangeError`.
8087 self.internal_set(&error, "_class", self.string("Error"));
8088 // The trace is captured where the error is *made*, which is where the reference
8089 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
8090 // way out, so a caught engine error already has its stack even if the handler
8091 // never rethrows it.
8092 self.add_stack(&error);
8093 Value::Object(error)
8094 }
8095
8096 /// Give an error object its `stack` property, from the current frame stack.
8097 ///
8098 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
8099 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
8100 /// `stack` a script set, is not rewritten.
8101 pub fn add_stack(&self, object: &Gc<JsObject>) {
8102 self.add_stack_skipping(object, 0);
8103 }
8104
8105 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
8106 ///
8107 /// An `Error` constructor passes 1: the reference builds those traces with
8108 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
8109 /// constructor itself, while a `RangeError` raised inside `toISOString` does
8110 /// report `at toISOString (native)`.
8111 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
8112 if object.has_own("stack") {
8113 return;
8114 }
8115 let trace = self.stack_trace_skipping(skip);
8116 let text = self.string(trace);
8117 object.define("stack", Property::with_attributes(text, true, false));
8118 }
8119
8120 /// The function object currently being called, if any.
8121 ///
8122 /// A native function is a bare `fn` pointer, so it cannot capture which class
8123 /// it belongs to; it reads that from the callee instead. This is also what a
8124 /// stack trace would use.
8125 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
8126 match &self.frames.last()?.callee {
8127 Value::Object(object) => Some(object.clone()),
8128 _ => None,
8129 }
8130 }
8131
8132 /// The `prototype` property of a constructor, falling back to
8133 /// `Object.prototype` for anything that is not shaped like one.
8134 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
8135 constructor
8136 .own_property("prototype")
8137 .and_then(|property| property.value)
8138 .and_then(|value| value.as_object().cloned())
8139 .unwrap_or_else(|| self.realm.object_proto.clone())
8140 }
8141
8142 /// Throw a `TypeError` carrying `message`.
8143 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
8144 Signal::Throw(self.make_error("TypeError", message.as_ref()))
8145 }
8146
8147 /// Throw a `RangeError` carrying `message`.
8148 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
8149 Signal::Throw(self.make_error("RangeError", message.as_ref()))
8150 }
8151
8152 /// The `ReferenceError` a read of an uninitialised binding raises.
8153 /// The name of the binding `slot` refers to, for an error message.
8154 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
8155 match kind {
8156 VarSlot::Loc => self
8157 .frame()
8158 .code
8159 .code
8160 .vars
8161 .get(slot)
8162 .map(|v| v.name.clone()),
8163 VarSlot::Closure => self
8164 .frame()
8165 .code
8166 .code
8167 .closure_vars
8168 .get(slot)
8169 .map(|c| c.name.clone()),
8170 }
8171 .unwrap_or_default()
8172 }
8173
8174 /// Whether `slot` names a `const` binding, which rejects every store after its
8175 /// initialiser.
8176 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
8177 match kind {
8178 VarSlot::Loc => self
8179 .frame()
8180 .code
8181 .code
8182 .vars
8183 .get(slot)
8184 .is_some_and(|v| v.is_const),
8185 VarSlot::Closure => self
8186 .frame()
8187 .code
8188 .code
8189 .closure_vars
8190 .get(slot)
8191 .is_some_and(|c| c.is_const),
8192 }
8193 }
8194
8195 /// The `TypeError` a store to a `const` binding raises.
8196 ///
8197 /// `const` is enforced here rather than at compile time because the binding can be
8198 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
8199 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
8200 /// both halves of what "checked store" means: the dead zone is over, and the
8201 /// binding is writable.
8202 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
8203 let name = self.binding_name(slot, kind);
8204 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
8205 }
8206
8207 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
8208 let name = match kind {
8209 VarSlot::Loc => self
8210 .frame()
8211 .code
8212 .code
8213 .vars
8214 .get(slot)
8215 .map(|v| v.name.clone()),
8216 VarSlot::Closure => self
8217 .frame()
8218 .code
8219 .code
8220 .closure_vars
8221 .get(slot)
8222 .map(|c| c.name.clone()),
8223 }
8224 .unwrap_or_default();
8225 Signal::Throw(self.make_error(
8226 "ReferenceError",
8227 &format!("cannot access '{name}' before initialization"),
8228 ))
8229 }
8230
8231 fn throw_reference(&self, name: &str) -> Signal {
8232 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
8233 }
8234
8235 // -- the instruction loop -----------------------------------------------
8236
8237 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
8238 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
8239 // measured at 16% of a tight arithmetic loop's total time.
8240 #[inline(always)]
8241 fn step(&mut self) -> JsResult<Step> {
8242 // The instruction is already decoded (see [`crate::insn`]), so this is an index
8243 // and a `Copy` read rather than a table lookup plus a width switch. Only the
8244 // borrow lives across the boundary; nothing is cloned.
8245 // **One** borrow of the frame: fetch the record, then advance in the same scope.
8246 // The obvious version borrowed it three times (`last` to read, `last_mut` to
8247 // write, and once more inside the handler), and each is a bounds check plus an
8248 // `Option` unwrap — on the one path every instruction takes.
8249 let Some((insn, next)) = ({
8250 let frame = self
8251 .frames
8252 .last_mut()
8253 .expect("step() is only called with a live frame");
8254 // Past the last instruction is a normal return: the compiler ends a function
8255 // with `return`, and a jump to the end of a block lands here.
8256 let insn = frame.insns().get(frame.pc).copied();
8257 match insn {
8258 None => None,
8259 Some(insn) => {
8260 // A fused record stands for the next few instructions, so the next
8261 // `pc` is its width ahead — the instructions it replaces are never
8262 // dispatched. `at` is the byte offset a stack trace reports; it stays
8263 // an offset because the line table is keyed by bytes.
8264 frame.at = insn.offset as usize;
8265 frame.pc += insn.width();
8266 Some((insn, frame.pc))
8267 }
8268 }
8269 }) else {
8270 return Ok(Step::Return(Value::Undefined));
8271 };
8272 self.check_memory()?;
8273 self.check_interrupt()?;
8274 if insn.fused == crate::insn::Fused::None {
8275 self.execute_instruction(insn.op, insn.a, insn.b, next)
8276 } else {
8277 self.execute_fused(insn)
8278 }
8279 }
8280
8281 /// Run a fused instruction: several bytecode instructions in one dispatch.
8282 ///
8283 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
8284 /// it cannot throw and cannot allocate — and anything else falls back to the real
8285 /// instructions, in their real order, so an exception leaves the operand stack
8286 /// exactly as it would have been.
8287 #[inline]
8288 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
8289 use crate::insn::Fused;
8290 let slot = insn.a as usize;
8291 match insn.fused {
8292 // `x = k`: `push k; put_loc x`.
8293 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
8294 // `x += k`: `get_loc x; push k; add; put_loc x`.
8295 Fused::AddImmLoc => {
8296 let delta = insn.b as i32;
8297 match self.get_loc(slot) {
8298 Value::Int(left) => {
8299 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
8300 // that built two `Value`s, called a function, and matched on them
8301 // again to reach this same `checked_add`. It is the innermost
8302 // operation of every accumulator in every program.
8303 let answer = match left.checked_add(delta) {
8304 Some(sum) => Value::Int(sum),
8305 None => Value::Float(left as f64 + delta as f64),
8306 };
8307 self.put_loc(slot, answer);
8308 }
8309 other => {
8310 self.push(other);
8311 self.push(Value::Int(delta));
8312 self.binary_add()?;
8313 let value = self.pop();
8314 self.put_loc(slot, value);
8315 }
8316 }
8317 }
8318 // `x += "literal"` and `x += y`: the two shapes that can append in place.
8319 Fused::AddAtomLoc => {
8320 let text = self.atom_wtf8(insn.b as usize);
8321 let right = self.string_wtf8(text);
8322 self.add_into_loc(slot, right)?;
8323 }
8324 Fused::AddLocLoc => {
8325 let source = (insn.a & 0xFFFF) as usize;
8326 let target = (insn.a >> 16) as usize;
8327 let right = self.get_loc(source);
8328 self.add_into_loc(target, right)?;
8329 }
8330 Fused::AddArgLoc => {
8331 let source = (insn.a & 0xFFFF) as usize;
8332 let target = (insn.a >> 16) as usize;
8333 let right = self.get_arg(source);
8334 self.add_into_loc(target, right)?;
8335 }
8336 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
8337 Fused::PostIncLoc => match self.get_loc(slot) {
8338 Value::Int(left) => {
8339 let answer = match left.checked_add(1) {
8340 Some(sum) => Value::Int(sum),
8341 None => Value::Float(left as f64 + 1.0),
8342 };
8343 self.put_loc(slot, answer);
8344 }
8345 other => {
8346 self.push(other);
8347 let raw = self.pop();
8348 let (old, updated) = self.advance_numeric(raw, true)?;
8349 self.push(old);
8350 self.push(updated);
8351 let value = self.pop();
8352 self.put_loc(slot, value);
8353 self.pop();
8354 }
8355 },
8356 // `if (!(x < arg)) goto target`: a loop header.
8357 //
8358 // The comparison is computed rather than replayed on the operand stack. That
8359 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
8360 // that throws: the effects happen in the same order, and a handler truncates
8361 // the stack down to its marker, so the intermediate values are unobservable.
8362 Fused::LtLocArgJump => {
8363 let loc = (insn.a >> 16) as usize;
8364 let arg = (insn.a & 0xFFFF) as usize;
8365 let left = self.get_loc(loc);
8366 let right = self.get_arg(arg);
8367 let taken = match (&left, &right) {
8368 (Value::Int(left), Value::Int(right)) => !(left < right),
8369 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8370 };
8371 if taken {
8372 self.frame_mut().pc = insn.b as usize;
8373 }
8374 }
8375 // `i < k` in a loop header, where `k` is an integer literal.
8376 Fused::LtLocImmJump => {
8377 let left = self.get_loc(insn.a as usize);
8378 let right = Value::Int(insn.imm as i32);
8379 let taken = match &left {
8380 Value::Int(left) => !(*left < insn.imm as i32),
8381 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8382 };
8383 if taken {
8384 self.frame_mut().pc = insn.b as usize;
8385 }
8386 }
8387 Fused::None => unreachable!("only called for a fused record"),
8388 }
8389 Ok(Step::Continue)
8390 }
8391
8392 /// Run records that cannot call script, cannot throw and cannot change frames.
8393 ///
8394 /// Returns `Some(value)` when the function ran off the end of its instructions (a
8395 /// normal return), and `None` when it stopped in front of an instruction the slow path
8396 /// has to handle — `pc` is written back either way, so `step` resumes at the right
8397 /// place.
8398 ///
8399 /// **The invariant is the whole point.** Every arm here is restricted to work that
8400 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
8401 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
8402 /// that the memory limit has to see. An opcode whose operands turn out to need any of
8403 /// that **stops the loop** instead of trying, so the slow path gets the instruction
8404 /// untouched and with its operands still on the stack. That is why the fallback is a
8405 /// `break` and not a duplicated slow arm: a second implementation of the same
8406 /// semantics is how a wrong answer gets in with no test noticing.
8407 ///
8408 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
8409 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
8410 fn run_fast(&mut self) -> JsResult<Option<Value>> {
8411 use crate::insn::Fused;
8412 // The outer loop exists only so a `Call` can come back through here: once a
8413 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
8414 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
8415 // frame. Re-entering re-reads both from whichever frame is now on top. Every
8416 // other exit from the inner loop returns, so this costs one loop per call.
8417 'outer: loop {
8418 // One reference-count bump per *slow* instruction (a call, an allocation, a
8419 // property access), never one per instruction — that distinction is worth
8420 // two orders of magnitude and was measured as such.
8421 let (code, mut pc) = {
8422 let frame = self.frame();
8423 (frame.code.clone(), frame.pc)
8424 };
8425 let insns = &code.insns;
8426 loop {
8427 let Some(insn) = insns.get(pc).copied() else {
8428 self.frame_mut().pc = pc;
8429 return Ok(Some(Value::Undefined));
8430 };
8431 match insn.fused {
8432 // `x = k`
8433 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
8434 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
8435 // object — stops the loop so `binary_add` can decide.
8436 Fused::AddImmLoc => {
8437 let slot = insn.a as usize;
8438 let delta = insn.b as i32;
8439 let Value::Int(left) = self.get_loc(slot) else {
8440 return Ok(self.stop(pc));
8441 };
8442 let sum = match left.checked_add(delta) {
8443 Some(sum) => Value::Int(sum),
8444 None => Value::Float(left as f64 + delta as f64),
8445 };
8446 self.put_loc(slot, sum);
8447 }
8448 // `x += "literal"` / `x += y`: the operand is a string, so the append
8449 // either allocates one or grows one. Both are the slow path's business;
8450 // the fusion's job is only to make the *slot* the sole owner, which is what
8451 // `execute_fused` needs and what `get_loc` alone destroys.
8452 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
8453 return Ok(self.stop(pc));
8454 }
8455 // `x++` on an integer, old value dropped.
8456 Fused::PostIncLoc => {
8457 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
8458 // value is read in place and overwritten in place, so the reference
8459 // count it held is released by the same assignment that stores the
8460 // new one. `get_loc` plus `put_loc` did two borrows, two table
8461 // lookups and a clone, and this arm is the whole body of a counting
8462 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
8463 let slot = insn.a as usize;
8464 let frame = self.frames.last_mut().expect("a frame is live");
8465 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
8466 let target = if cell < 0 {
8467 frame.locals.get_mut(slot)
8468 } else {
8469 None
8470 };
8471 let Some(target) = target else {
8472 return Ok(self.stop(pc));
8473 };
8474 let Value::Int(left) = *target else {
8475 return Ok(self.stop(pc));
8476 };
8477 *target = match left.checked_add(1) {
8478 Some(sum) => Value::Int(sum),
8479 None => Value::Float(left as f64 + 1.0),
8480 };
8481 }
8482 // A loop header, `if (!(x < arg)) goto target`, with both sides already
8483 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
8484 // bound stayed small integers.
8485 Fused::LtLocArgJump => {
8486 let loc = (insn.a >> 16) as usize;
8487 let arg = (insn.a & 0xFFFF) as usize;
8488 // One borrow for both slots: this arm *is* the whole loop of a
8489 // `for (i = 0; i < n; i++)` with an argument bound, so a second
8490 // `frames.last()` here is paid on every iteration. Measured 7.5% on
8491 // `dispatch:empty-loop`.
8492 let (left, right) = {
8493 let frame = self.frame();
8494 (frame.read_loc(loc), frame.read_arg(arg))
8495 };
8496 // Heavily measured: the bound is very often a `Float` even when the
8497 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
8498 // `JSON.parse` or a division is one — so requiring both sides to be
8499 // `Int` sent every iteration of those loops down the slow path. The
8500 // comparison below is the same one `relational` makes for two numbers.
8501 if !is_number(&left) || !is_number(&right) {
8502 return Ok(self.stop(pc));
8503 }
8504 // `if_false` branches on the comparison being false, which is **not**
8505 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
8506 // `>=` is also false and would keep it running forever. Clippy wants the
8507 // negation folded; that would be a wrong answer.
8508 let ordered = left.to_number() < right.to_number();
8509 let take_branch = !ordered;
8510 if take_branch {
8511 pc = insn.b as usize;
8512 continue;
8513 }
8514 }
8515 // The same header with a literal bound: `if (!(x < k)) goto target`.
8516 // The bound is an immediate, so only the counter needs a type test.
8517 #[allow(clippy::neg_cmp_op_on_partial_ord)]
8518 Fused::LtLocImmJump => {
8519 let left = self.get_loc(insn.a as usize);
8520 if !is_number(&left) {
8521 return Ok(self.stop(pc));
8522 }
8523 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
8524 if take_branch {
8525 pc = insn.b as usize;
8526 continue;
8527 }
8528 }
8529 Fused::None => match insn.op {
8530 // -- branches ---------------------------------------------------
8531 // A jump is an assignment now, because the target is an instruction
8532 // index. No arithmetic, no resolution table.
8533 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
8534 let target = insn.a as usize;
8535 // A **back-edge** is a loop, and it is the only place an
8536 // instruction-level checkpoint can stop one: `for(;;){}` compiles
8537 // to a jump to itself and never leaves this loop, so the
8538 // per-instruction checks in `step` never run. That is exactly the
8539 // hole this arm closes — a host's `JS_SetInterruptHandler` did
8540 // nothing to a `for(;;){}` until it did, which is what
8541 // `tests/c/embed.c` is for.
8542 //
8543 // Polling here rather than on every instruction in this loop is
8544 // also the reference's choice (`OP_goto` calls
8545 // `js_poll_interrupts`), and it costs one compare per branch
8546 // instead of one decrement per instruction.
8547 if target <= pc {
8548 self.frame_mut().pc = target;
8549 self.check_memory()?;
8550 self.check_interrupt()?;
8551 }
8552 pc = target;
8553 continue;
8554 }
8555 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
8556 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
8557 let taken = self.pop().to_boolean();
8558 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
8559 if taken == want {
8560 pc = insn.a as usize;
8561 continue;
8562 }
8563 }
8564 // -- slot access -------------------------------------------------
8565 // A load's slot is already an operand (see `insn::implicit_operand`);
8566 // a captured one goes through its cell, which runs no script.
8567 Opcode::GetLoc
8568 | Opcode::GetLoc8
8569 | Opcode::GetLoc0
8570 | Opcode::GetLoc1
8571 | Opcode::GetLoc2
8572 | Opcode::GetLoc3 => {
8573 let value = self.get_loc(insn.a as usize);
8574 self.push(value);
8575 }
8576 Opcode::PutLoc
8577 | Opcode::PutLoc8
8578 | Opcode::PutLoc0
8579 | Opcode::PutLoc1
8580 | Opcode::PutLoc2
8581 | Opcode::PutLoc3 => {
8582 let value = self.pop();
8583 self.put_loc(insn.a as usize, value);
8584 }
8585 Opcode::GetArg
8586 | Opcode::GetArg0
8587 | Opcode::GetArg1
8588 | Opcode::GetArg2
8589 | Opcode::GetArg3 => {
8590 let value = self.get_arg(insn.a as usize);
8591 self.push(value);
8592 }
8593 Opcode::PutArg
8594 | Opcode::PutArg0
8595 | Opcode::PutArg1
8596 | Opcode::PutArg2
8597 | Opcode::PutArg3 => {
8598 let value = self.pop();
8599 self.put_arg(insn.a as usize, value);
8600 }
8601 // `a[i]` with an integer index on a dense array: see `fast_array_get`
8602 // for why a non-hole own element is exactly the slow path's answer.
8603 // The two operands are *peeked*, so a miss leaves the stack as the
8604 // slow path expects to find it.
8605 Opcode::GetArrayEl => {
8606 // One lookup, not two. The guard used `if …is_some()` and the arm
8607 // then called it again to get the value — two `peek`s, two
8608 // `array_get`s and two `Value` clones for one element.
8609 // `fast_array_get` was 13.1% of `array:indexed`, and the same
8610 // double call was the first version of the `get_field` fast path.
8611 let Some(value) = self.fast_array_get() else {
8612 return Ok(self.stop(pc));
8613 };
8614 // `a[i]` consumes both operands and leaves the element in their
8615 // place: one `truncate` and one write, no `pop`/`push` pair.
8616 let frame = self.frame_mut();
8617 frame.stack.truncate(frame.stack.len() - 2);
8618 frame.stack.push(value);
8619 }
8620 // `a[i] = v` on a dense array with an integer index: see
8621 // `fast_array_set` for why the whole store is one step.
8622 Opcode::PutArrayEl if self.fast_array_set() => {}
8623 // `o.x` resolved from the inline cache without leaving the loop.
8624 //
8625 // The cache is keyed by `(receiver identity, atom, site)` and a
8626 // monomorphic read re-validates the same chain every iteration, so
8627 // each one used to cost a `stop(pc)` — a write of `pc` into the
8628 // frame, a return out of this loop, a re-dispatch through `step` and
8629 // a re-entry. `property:monomorphic` spent 18% in
8630 // `read_field_cached` and 21% in `push`, both across that boundary.
8631 //
8632 // The site is `pc + width`, which is exactly the `next` the slow arm
8633 // passes — the two must agree or every fast lookup misses and
8634 // re-records the same entry forever.
8635 //
8636 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
8637 // slow arm finds the receiver where it expects it.
8638 // `name` resolved from the global-variable cache inside the loop.
8639 //
8640 // Same shape as `get_field` above and for the same reason: `get_var`
8641 // was not in the fast loop, so reading a global — which `fib` does
8642 // once per recursive call, for its own name — cost a `stop(pc)`, a
8643 // return out of the loop, a `step` re-dispatch and a re-entry, before
8644 // `get_global` even started its `scopes_are_plain` checks.
8645 //
8646 // Everything here is exactly `get_global`'s first branch: not lexical,
8647 // no `eval` scope, cache hit. Anything else leaves the stack untouched
8648 // and lets the slow arm decide.
8649 Opcode::GetVar => {
8650 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
8651 return Ok(self.stop(pc));
8652 };
8653 self.push(value);
8654 }
8655 Opcode::GetField | Opcode::GetField2 => {
8656 let Some(value) =
8657 self.fast_field_get(insn.a as usize, pc + insn.width())
8658 else {
8659 return Ok(self.stop(pc));
8660 };
8661 if insn.op == Opcode::GetField2 {
8662 // `get_field2` keeps the receiver for the `call_method` that
8663 // follows.
8664 self.push(value);
8665 } else {
8666 // `get_field` replaces the receiver, so this is one store over
8667 // the top slot rather than a `pop` and a `push`: the length
8668 // never changes, so neither `Vec` arm has a capacity check or a
8669 // drop to run beyond the one the overwrite itself does.
8670 let frame = self.frame_mut();
8671 match frame.stack.last_mut() {
8672 Some(slot) => *slot = value,
8673 None => return Ok(self.stop(pc)),
8674 }
8675 }
8676 }
8677 // -- constants ---------------------------------------------------
8678 Opcode::PushMinus1
8679 | Opcode::Push0
8680 | Opcode::Push1
8681 | Opcode::Push2
8682 | Opcode::Push3
8683 | Opcode::Push4
8684 | Opcode::Push5
8685 | Opcode::Push6
8686 | Opcode::Push7
8687 | Opcode::PushI8
8688 | Opcode::PushI16
8689 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
8690 // -- stack shuffling ---------------------------------------------
8691 Opcode::Drop => {
8692 self.pop();
8693 }
8694 // -- arithmetic on two integers ----------------------------------
8695 //
8696 // The operands are *looked at* before they are popped, so a non-integer
8697 // pair leaves the stack exactly as the slow path expects to find it.
8698 Opcode::Add if self.numeric_pair() => {
8699 let right = self.pop();
8700 let left = self.pop();
8701 // Exactly [`add_numbers`], which is what the slow arm reaches.
8702 let answer = match (&left, &right) {
8703 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
8704 Some(sum) => Value::Int(sum),
8705 None => Value::Float(*a as f64 + *b as f64),
8706 },
8707 _ => Value::Float(left.to_number() + right.to_number()),
8708 };
8709 self.push(answer);
8710 }
8711 Opcode::Sub
8712 | Opcode::And
8713 | Opcode::Or
8714 | Opcode::Xor
8715 | Opcode::Shl
8716 | Opcode::Sar
8717 | Opcode::Shr
8718 if self.numeric_pair() =>
8719 {
8720 let right = self.pop();
8721 let left = self.pop();
8722 let answer =
8723 arithmetic(insn.op, left, right).expect("numbers cannot throw");
8724 self.push(answer);
8725 }
8726 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
8727 if self.numeric_pair() =>
8728 {
8729 let right = self.pop();
8730 let left = self.pop();
8731 let answer = self
8732 .relational(insn.op, left, right)
8733 .expect("numbers cannot throw");
8734 self.push(answer);
8735 }
8736 // -- calls -------------------------------------------------------
8737 //
8738 // A plain call: `callee(arg0, …, argN) -> result`.
8739 //
8740 // This arm exists because of one measurement. `call:recursion` had
8741 // **20.4% of its profile in `execute_instruction`** — the *slow*
8742 // executor — and `fib`'s recursive call is the only thing in that
8743 // function which is not a fast arm. Every call therefore left this
8744 // loop via `stop()`, went through `step()`'s dispatch and
8745 // `execute_instruction`'s match over every opcode, and came back here
8746 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
8747 //
8748 // Two things make it safe to do here rather than only in the slow path:
8749 //
8750 // * the caller's `pc` is stored *before* the call, which is what
8751 // `step` does too — so when the callee returns, the caller resumes
8752 // after the call and not at it;
8753 // * `check_memory` runs, because `step` calls it once per instruction
8754 // and a call allocates a frame, its locals and its cells. Skipping
8755 // the checkpoint here would let a `--memory-limit` script overshoot
8756 // by one call per instruction.
8757 Opcode::Call
8758 | Opcode::Call0
8759 | Opcode::Call1
8760 | Opcode::Call2
8761 | Opcode::Call3 => {
8762 let argc = self.argc_operand(insn.op, insn.a);
8763 let next = pc + insn.width();
8764 {
8765 let frame = self
8766 .frames
8767 .last_mut()
8768 .expect("run_fast() is only called with a live frame");
8769 // `at` is what a stack trace reports for this frame, so a throw
8770 // inside the callee has to see the call site and not whatever
8771 // the last `stop()` left there.
8772 frame.at = insn.offset as usize;
8773 frame.pc = next;
8774 }
8775 self.check_memory()?;
8776 self.check_interrupt()?;
8777 let args = self.pop_n(argc);
8778 let callee = self.pop();
8779 // A plain call has no receiver; the callee decides what to do with
8780 // `undefined` (a sloppy function substitutes the global object).
8781 if let Some(result) =
8782 self.call_or_push(callee, Value::Undefined, args)?
8783 {
8784 // Native, host, generator, async, bound — no frame was pushed,
8785 // so this loop is still describing the right function. `pc`
8786 // is advanced by the loop tail like every other arm; only the
8787 // frame's copy had to be written here, and it already was.
8788 self.push(result);
8789 } else {
8790 // A bytecode callee: its frame is on top now, and `insns` and
8791 // `pc` both belong to the caller. Start over on the new frame.
8792 continue 'outer;
8793 }
8794 }
8795 // -- return ------------------------------------------------------
8796 Opcode::Return => {
8797 let value = self.pop();
8798 self.frame_mut().pc = pc + insn.width();
8799 return Ok(Some(value));
8800 }
8801 Opcode::ReturnUndef => {
8802 self.frame_mut().pc = pc + insn.width();
8803 return Ok(Some(Value::Undefined));
8804 }
8805 // Everything else needs the slow path.
8806 _ => return Ok(self.stop(pc)),
8807 },
8808 }
8809 pc += insn.width();
8810 }
8811 }
8812 }
8813
8814 /// Whether the top two operand-stack values are both numbers.
8815 ///
8816 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
8817 /// cannot run script, so the arm may not throw and may not change frames.
8818 fn numeric_pair(&self) -> bool {
8819 is_number(&self.peek(0)) && is_number(&self.peek(1))
8820 }
8821
8822 /// `a[i]` for a dense array and an integer index, without the string round trip.
8823 ///
8824 /// The slow path answers this by turning `i` into a string (`propkey` →
8825 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
8826 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
8827 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
8828 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
8829 /// without even the cheap `Int` formatting.
8830 ///
8831 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
8832 /// unambiguously the one the slow path would give:
8833 ///
8834 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
8835 /// `2^32-1` is the length, not an index),
8836 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
8837 /// typed array or an ordinary object, all of which have their own rules),
8838 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
8839 /// starts walking the prototype chain, and `a[i]` on a hole must find
8840 /// `Array.prototype[i]` if it exists rather than `undefined`.
8841 ///
8842 /// The last condition is the one that makes this safe rather than merely fast: an own
8843 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
8844 /// `get_var` answered from the global-variable cache, or `None`.
8845 ///
8846 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
8847 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
8848 /// records nothing — the slow arm is about to walk the chain and record it.
8849 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
8850 let frame = self.frame();
8851 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
8852 // "Lexical" is presence in the realm's table, not the closure var's flag: a
8853 // `GlobalRef` forwarded through a nested function has its flags cleared.
8854 if self.realm.globals.contains_key(name) {
8855 return None;
8856 }
8857 if !self.scopes_are_plain() {
8858 return None;
8859 }
8860 let object = &self.realm.global;
8861 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
8862 let cached = self.global_cache[site].as_ref()?;
8863 if !object.upgrades_to(&cached.object) {
8864 return None;
8865 }
8866 object.data_property_at(cached.index, name)
8867 }
8868
8869 /// `o.x` answered entirely from the inline cache, or `None`.
8870 ///
8871 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
8872 /// about to do exactly that and recording it twice would rebuild the chain for every
8873 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
8874 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
8875 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
8876 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
8877 // an object receiver is a reference-count bump that the answer never needs.
8878 let frame = self.frame();
8879 let object = frame.stack.last()?;
8880 let Value::Object(target) = object else {
8881 return None;
8882 };
8883 // A proxy traps the lookup, so no cache entry ever describes it.
8884 if target.proxy_state().is_some() {
8885 return None;
8886 }
8887 let key = frame.code.atom_keys.get(atom)?;
8888 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
8889 if cached.key != *key {
8890 return None;
8891 }
8892 Self::cached_hit(target, cached)
8893 }
8894
8895 fn fast_array_get(&self) -> Option<Value> {
8896 let Value::Int(index) = self.peek(0) else {
8897 return None;
8898 };
8899 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
8900 // set for an `i32`.
8901 if index < 0 {
8902 return None;
8903 }
8904 let Value::Object(object) = self.peek(1) else {
8905 return None;
8906 };
8907 match object.array_get(index as usize) {
8908 Some(value) if !matches!(value, Value::Hole) => Some(value),
8909 _ => None,
8910 }
8911 }
8912
8913 /// `a[i] = v` on a dense array with an integer index, as one store.
8914 ///
8915 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
8916 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
8917 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
8918 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
8919 /// reference at the time it was measured (14.7x).
8920 ///
8921 /// Every condition here is one the slow path would also have to satisfy before
8922 /// storing into the element vector:
8923 ///
8924 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
8925 /// accepts as an index;
8926 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
8927 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
8928 /// one inside a recorded descriptor, reports `false` and the caller stops.
8929 ///
8930 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
8931 /// writes the own element too once `array_set` says it did.
8932 fn fast_array_set(&mut self) -> bool {
8933 // Every test runs *before* anything is popped: a refusal has to leave the stack
8934 // exactly as the slow path expects to find it. Popping first and reporting the
8935 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
8936 // then ran the slow path with nothing to write.
8937 let Value::Int(index) = self.peek(1) else {
8938 return false;
8939 };
8940 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
8941 if index < 0 {
8942 return false;
8943 }
8944 // Only a real array: a typed array's elements live in its buffer, a string-like
8945 // object has no element vector, and `array_set` on either does nothing.
8946 let Value::Object(object) = self.peek(2) else {
8947 return false;
8948 };
8949 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
8950 return false;
8951 }
8952 // A non-extensible array reports `false` here, but the *slow* path has to decide
8953 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
8954 // that with the key and the stack still intact.
8955 if !object.is_extensible() {
8956 return false;
8957 }
8958 // Inside the logical length, so the store cannot change `length`. Combined with
8959 // extensibility above, the only growth left for `array_set` is filling a hole in
8960 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
8961 // shape this fast path exists for. A store past the length would grow the array,
8962 // and whether that is allowed is the slow path's question.
8963 if index as usize >= object.array_length().unwrap_or(0) {
8964 return false;
8965 }
8966 // The bound `array_set` refuses past. Checking it here keeps that arm from having
8967 // to report a failure after the operands are gone.
8968 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
8969 return false;
8970 }
8971 let value = self.pop();
8972 self.pop();
8973 self.pop();
8974 object.array_store(self.heap, index as usize, value)
8975 }
8976
8977 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
8978 fn stop(&mut self, pc: usize) -> Option<Value> {
8979 self.frame_mut().pc = pc;
8980 None
8981 }
8982
8983 fn push(&mut self, value: Value) {
8984 self.frame_mut().stack.push(value);
8985 }
8986
8987 fn pop(&mut self) -> Value {
8988 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
8989 }
8990
8991 fn pop_n(&mut self, count: usize) -> Vec<Value> {
8992 let frame = self.frame_mut();
8993 let start = frame.stack.len().saturating_sub(count);
8994 frame.stack.split_off(start)
8995 }
8996
8997 fn peek(&self, back: usize) -> Value {
8998 let frame = self.frame();
8999 frame
9000 .stack
9001 .get(frame.stack.len().wrapping_sub(1 + back))
9002 .cloned()
9003 .unwrap_or(Value::Undefined)
9004 }
9005
9006 #[allow(clippy::too_many_lines)]
9007 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
9008 use Opcode::*;
9009 match op {
9010 // -- constants and stack shuffling -----------------------------
9011 Nop => {}
9012 PushMinus1 => self.push(Value::Int(-1)),
9013 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
9014 let value = match op {
9015 Push0 => 0,
9016 Push1 => 1,
9017 Push2 => 2,
9018 Push3 => 3,
9019 Push4 => 4,
9020 Push5 => 5,
9021 Push6 => 6,
9022 _ => 7,
9023 };
9024 self.push(Value::Int(value));
9025 }
9026 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
9027 PushBigintI32 => {
9028 // The immediate form of a `BigInt` literal; the reference has the same
9029 // split between this and a constant-pool entry.
9030 let value = crate::bigint::BigInt::from_i64(a as i64);
9031 self.push(self.bigint(value));
9032 }
9033 PushTrue => self.push(Value::Bool(true)),
9034 PushFalse => self.push(Value::Bool(false)),
9035 PushEmptyString => self.push(self.string("")),
9036 Undefined => self.push(Value::Undefined),
9037 Null => self.push(Value::Null),
9038 Object => {
9039 let proto = self.realm.object_proto.clone();
9040 self.push(Value::Object(self.new_object(Some(proto))));
9041 }
9042 PushThis => {
9043 let this = self.frame().this.clone();
9044 self.push(this);
9045 }
9046 PushConst | PushConst8 => {
9047 let value = self.constant(a as usize)?;
9048 self.push(value);
9049 }
9050 PushAtomValue => {
9051 let text = self.atom_wtf8(a as usize);
9052 self.push(self.string_wtf8(text));
9053 }
9054 Dup => {
9055 let value = self.peek(0);
9056 self.push(value);
9057 }
9058 Dup2 => {
9059 // `a b -> a b a b`
9060 let b = self.peek(0);
9061 let a = self.peek(1);
9062 self.push(a);
9063 self.push(b);
9064 }
9065 Dup3 => {
9066 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
9067 // prototype and key while reading the current value through them.
9068 let c = self.peek(0);
9069 let b = self.peek(1);
9070 let a = self.peek(2);
9071 self.push(a);
9072 self.push(b);
9073 self.push(c);
9074 }
9075 Swap => {
9076 // `a b -> b a`
9077 let bottom = self.pop();
9078 let top = self.pop();
9079 self.push(bottom);
9080 self.push(top);
9081 }
9082 Perm3 => {
9083 // `a b c -> b a c`, the reference's reordering for a spread method
9084 // call: `obj func array` becomes the `func this array` that `apply`
9085 // takes.
9086 let c = self.pop();
9087 let b = self.pop();
9088 let a = self.pop();
9089 self.push(b);
9090 self.push(a);
9091 self.push(c);
9092 }
9093 Dup1 => {
9094 let value = self.peek(1);
9095 self.push(value);
9096 }
9097 Drop => {
9098 self.pop();
9099 }
9100 Nip => {
9101 // `a b -> b`
9102 let top = self.pop();
9103 self.pop();
9104 self.push(top);
9105 }
9106 Perm4 => {
9107 // `obj prop a b -> a obj prop b`, the reference's reordering for a
9108 // postfix update of a computed element: it puts the *old* value
9109 // underneath the receiver and key so `put_array_el` can consume them
9110 // and leave the old value as the expression's result.
9111 let d = self.pop();
9112 let c = self.pop();
9113 let b = self.pop();
9114 let a = self.pop();
9115 self.push(c);
9116 self.push(a);
9117 self.push(b);
9118 self.push(d);
9119 }
9120 Insert2 => {
9121 // `obj a -> a obj a`
9122 let value = self.pop();
9123 let object = self.pop();
9124 self.push(value.clone());
9125 self.push(object);
9126 self.push(value);
9127 }
9128 Insert3 => {
9129 // `obj prop a -> a obj prop a`
9130 let value = self.pop();
9131 let key = self.pop();
9132 let object = self.pop();
9133 self.push(value.clone());
9134 self.push(object);
9135 self.push(key);
9136 self.push(value);
9137 }
9138 Insert4 => {
9139 // `this obj prop a -> a this obj prop a`
9140 //
9141 // `put_super_value` consumes all four and yields nothing, so the copy
9142 // underneath is what leaves the assignment an expression value.
9143 let value = self.pop();
9144 let key = self.pop();
9145 let object = self.pop();
9146 let receiver = self.pop();
9147 self.push(value.clone());
9148 self.push(receiver);
9149 self.push(object);
9150 self.push(key);
9151 self.push(value);
9152 }
9153 Swap2 => {
9154 // `a b c d -> c d a b`
9155 let d = self.pop();
9156 let c = self.pop();
9157 let b = self.pop();
9158 let a = self.pop();
9159 self.push(c);
9160 self.push(d);
9161 self.push(a);
9162 self.push(b);
9163 }
9164 Rot3l => {
9165 // `x a b -> a b x`
9166 let b = self.pop();
9167 let a = self.pop();
9168 let x = self.pop();
9169 self.push(a);
9170 self.push(b);
9171 self.push(x);
9172 }
9173 Rot3r => {
9174 // `a b c -> c a b`
9175 let c = self.pop();
9176 let b = self.pop();
9177 let a_value = self.pop();
9178 self.push(c);
9179 self.push(a_value);
9180 self.push(b);
9181 }
9182
9183 Rest => {
9184 // `...rest` in a parameter list: the arguments from index `a` on, as a
9185 // real array. It takes nothing off the stack — the arguments are in the
9186 // frame, not on it.
9187 let frame = self.frame();
9188 let from = a as usize;
9189 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
9190 let array = self.new_array(collected);
9191 self.push(Value::Object(array));
9192 }
9193
9194 // -- slots ------------------------------------------------------
9195 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
9196 let slot = self.slot_operand(op, a);
9197 let value = self.get_loc(slot);
9198 self.push(value);
9199 }
9200 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
9201 let slot = self.slot_operand(op, a);
9202 let value = self.pop();
9203 self.put_loc(slot, value);
9204 }
9205 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
9206 let slot = self.slot_operand(op, a);
9207 let value = self.pop();
9208 self.put_loc(slot, value.clone());
9209 self.push(value);
9210 }
9211 // The `_check` forms are the temporal dead zone: they throw when the
9212 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
9213 // *reads*, so only the two writes may pop — mishandling that quietly
9214 // consumes the value the caller pushed just before.
9215 GetLocCheck => {
9216 let slot = self.slot_operand(op, a);
9217 let value = self.get_loc(slot);
9218 if matches!(value, Value::Uninitialized) {
9219 return Err(self.dead_zone(slot, VarSlot::Loc));
9220 }
9221 self.push(value);
9222 }
9223 PutLocCheck | SetLocCheck => {
9224 let slot = self.slot_operand(op, a);
9225 let value = self.pop();
9226 if matches!(value, Value::Uninitialized) {
9227 return Err(self.dead_zone(slot, VarSlot::Loc));
9228 }
9229 // The initialiser goes through `put_loc`, not this, so any store that
9230 // reaches here is a later assignment — which a `const` refuses.
9231 if self.is_read_only(slot, VarSlot::Loc) {
9232 return Err(self.read_only(slot, VarSlot::Loc));
9233 }
9234 if op == SetLocCheck {
9235 self.put_loc(slot, value.clone());
9236 self.push(value);
9237 } else {
9238 self.put_loc(slot, value);
9239 }
9240 }
9241 PutLocCheckInit => {
9242 // The one store that *initialises* a lexical slot: `this` in a derived
9243 // constructor, which only exists after `super()` has run. A second
9244 // initialisation is the error the reference reports as
9245 // "'this' can be initialized only once".
9246 let slot = self.slot_operand(op, a);
9247 let value = self.pop();
9248 if !matches!(self.get_loc(slot), Value::Uninitialized) {
9249 return Err(Signal::Throw(self.make_error(
9250 "ReferenceError",
9251 "'this' can be initialized only once",
9252 )));
9253 }
9254 self.put_loc(slot, value);
9255 }
9256 CheckCtor => {
9257 // A class constructor may only run under `new`, which is what makes
9258 // `class A {}; A()` a TypeError.
9259 if matches!(self.frame().new_target, Value::Undefined) {
9260 return Err(Signal::Throw(self.make_error(
9261 "TypeError",
9262 "class constructors must be invoked with 'new'",
9263 )));
9264 }
9265 }
9266 InitCtor => {
9267 // The body a derived class gets when it declares no constructor:
9268 // forward every argument to the parent constructor, keeping `new.target`.
9269 if matches!(self.frame().new_target, Value::Undefined) {
9270 return Err(Signal::Throw(self.make_error(
9271 "TypeError",
9272 "class constructors must be invoked with 'new'",
9273 )));
9274 }
9275 let Some(callee) = self.current_callee() else {
9276 return Err(Signal::Throw(
9277 self.make_error("TypeError", "no constructor to inherit from"),
9278 ));
9279 };
9280 let parent = callee.proto().map_or(Value::Null, Value::Object);
9281 let new_target = self.frame().new_target.clone();
9282 let args = self.frame().passed().to_vec();
9283 let result = self.construct(parent, new_target, args)?;
9284 self.push(result);
9285 }
9286 SetLocUninitialized => {
9287 let slot = self.slot_operand(op, a);
9288 self.put_loc(slot, Value::Uninitialized);
9289 }
9290 CloseLoc => {
9291 // "Close" a binding: give it a *fresh* cell holding the current
9292 // value. Closures created before this point keep the old cell and the
9293 // ones created after see the new one, which is what makes every
9294 // iteration of `for (let i ...)` capture its own `i`, and what freezes
9295 // a block-scoped binding when the block ends.
9296 //
9297 // Clearing the slot instead (which this used to do) broke both: a
9298 // closure over a captured block variable read `undefined`, and a loop
9299 // terminated after one iteration.
9300 let slot = self.slot_operand(op, a);
9301 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
9302 if index >= 0 {
9303 let current = self.frame().cells[index as usize].get();
9304 let fresh = self.new_cell(current);
9305 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
9306 *cell = fresh;
9307 }
9308 }
9309 }
9310 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
9311 let slot = self.slot_operand(op, a);
9312 let value = self.get_arg(slot);
9313 self.push(value);
9314 }
9315 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
9316 let slot = self.slot_operand(op, a);
9317 let value = self.pop();
9318 self.put_arg(slot, value);
9319 }
9320 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
9321 let slot = self.slot_operand(op, a);
9322 let value = self.pop();
9323 self.put_arg(slot, value.clone());
9324 self.push(value);
9325 }
9326
9327 // -- closure variables ------------------------------------------
9328 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
9329 let slot = self.slot_operand(op, a);
9330 // A name a direct `eval` created shadows the binding the compiler chose.
9331 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
9332 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
9333 // and only a runtime lookup can know that.
9334 if let Some(cell) = self.eval_created_local(slot) {
9335 self.push(cell.get());
9336 return self.step();
9337 }
9338 let value = self.cell_value(slot)?;
9339 self.push(value);
9340 }
9341 GetVarRefCheck => {
9342 let slot = self.slot_operand(op, a);
9343 let value = self.cell_value(slot)?;
9344 if matches!(value, Value::Uninitialized) {
9345 return Err(self.dead_zone(slot, VarSlot::Closure));
9346 }
9347 self.push(value);
9348 }
9349 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
9350 let slot = self.slot_operand(op, a);
9351 let value = self.pop();
9352 if let Some(cell) = self.eval_created_local(slot) {
9353 cell.set(value);
9354 return self.step();
9355 }
9356 // Same rule as `PutLocCheck`: a checked store to a captured binding
9357 // refuses a `const` once its initialiser has run.
9358 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
9359 return Err(self.read_only(slot, VarSlot::Closure));
9360 }
9361 self.set_cell(slot, value)?;
9362 }
9363 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
9364 let slot = self.slot_operand(op, a);
9365 let value = self.pop();
9366 if let Some(cell) = self.eval_created_local(slot) {
9367 cell.set(value.clone());
9368 self.push(value);
9369 return self.step();
9370 }
9371 self.set_cell(slot, value.clone())?;
9372 self.push(value);
9373 }
9374
9375 // -- globals ----------------------------------------------------
9376 GetVar => {
9377 let value = self.get_global(a as usize)?;
9378 self.push(value);
9379 }
9380 GetVarUndef => {
9381 let value = self
9382 .get_global(a as usize)
9383 .or_else(|_| Ok(Value::Undefined))?;
9384 self.push(value);
9385 }
9386 DeleteVar => {
9387 // `delete name` for a name that is not a declared binding. A lexical
9388 // global lives in the reference table and cannot be deleted; anything
9389 // reachable only as a property of the global object is *implicit* —
9390 // `x = 1` with no declaration — and goes away if it is configurable,
9391 // which is what `delete` on an implicit global answers.
9392 let name = self.atom_text(a as usize);
9393 let global = self.realm.global.clone();
9394 let deleted = if self.realm.globals.contains_key(&name) {
9395 false
9396 } else if global.own_property(&name).is_some() {
9397 self.delete_property(&global, &name)?
9398 } else {
9399 true
9400 };
9401 self.push(Value::Bool(deleted));
9402 }
9403 PutVar => {
9404 let value = self.pop();
9405 self.put_global(a as usize, value)?;
9406 }
9407 PutVarInit => {
9408 let slot = a as usize;
9409 let value = self.pop();
9410 self.init_global(slot, value)?;
9411 }
9412
9413 // -- arithmetic -------------------------------------------------
9414 Add => self.binary_add()?,
9415 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
9416 let raw_right = self.pop();
9417 let raw_left = self.pop();
9418 // BigInt arithmetic is a separate path, and not only for the type of the
9419 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
9420 // rather than a silent conversion.
9421 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
9422 let left = self.primitive_of(raw_left)?;
9423 let right = self.primitive_of(raw_right)?;
9424 let value = self.bigint_arithmetic(op, left, right)?;
9425 self.push(value);
9426 } else {
9427 let right = self.numeric(raw_right)?;
9428 let left = self.numeric(raw_left)?;
9429 self.push(arithmetic(op, left, right)?);
9430 }
9431 }
9432 Neg => {
9433 let raw = self.pop();
9434 match raw {
9435 // A bigint negates exactly, however wide it is.
9436 Value::BigInt(big) => {
9437 let negated = big.negate();
9438 self.push(self.bigint(negated));
9439 }
9440 other => {
9441 let value = self.numeric(other)?;
9442 self.push(negate(value));
9443 }
9444 }
9445 }
9446 Plus => {
9447 let value = self.pop();
9448 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
9449 // unary plus is defined to produce a *number*, which a bigint cannot
9450 // become without loss. It used to fall through to `NaN`.
9451 if matches!(value, Value::BigInt(_)) {
9452 return Err(self.type_error("cannot convert bigint to number"));
9453 }
9454 let numeric = self.numeric_of(value)?;
9455 self.push(numeric);
9456 }
9457 Inc => {
9458 let raw = self.pop();
9459 let (_, updated) = self.advance_numeric(raw, true)?;
9460 self.push(updated);
9461 }
9462 Dec => {
9463 let raw = self.pop();
9464 let (_, updated) = self.advance_numeric(raw, false)?;
9465 self.push(updated);
9466 }
9467 PostInc | PostDec => {
9468 // `x -> x x+1`: the *new* value ends up on top, so the store the
9469 // compiler emits right after (`put_var`) writes the incremented
9470 // one, while the old value stays underneath for the expression's
9471 // own result. Getting this backwards makes `i++` a no-op, which
9472 // turns `while (i < 3)` into an infinite loop.
9473 let raw = self.pop();
9474 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
9475 self.push(old);
9476 self.push(updated);
9477 }
9478 Not => {
9479 let raw = self.pop();
9480 match raw {
9481 // `~x` on a bigint is `-x - 1`, exact at any width.
9482 Value::BigInt(big) => {
9483 let inverted = big.bitnot();
9484 self.push(self.bigint(inverted));
9485 }
9486 other => {
9487 let value = self.numeric(other)?;
9488 self.push(Value::Int(!value.to_int32()));
9489 }
9490 }
9491 }
9492 Lnot => {
9493 let value = self.pop();
9494 self.push(Value::Bool(!value.to_boolean()));
9495 }
9496
9497 // -- comparison -------------------------------------------------
9498 Lt | Lte | Gt | Gte => {
9499 let right = self.pop();
9500 let left = self.pop();
9501 let answer = self.relational(op, left, right)?;
9502 self.push(answer);
9503 }
9504 Eq | Neq => {
9505 let right = self.pop();
9506 let left = self.pop();
9507 let equal = self.abstract_equals(left, right)?;
9508 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
9509 }
9510 StrictEq => {
9511 let right = self.pop();
9512 let left = self.pop();
9513 self.push(Value::Bool(left.strict_equals(&right)));
9514 }
9515 StrictNeq => {
9516 let right = self.pop();
9517 let left = self.pop();
9518 self.push(Value::Bool(!left.strict_equals(&right)));
9519 }
9520 IsUndefined => {
9521 // `=== undefined`, which is what a destructuring default tests. It is
9522 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
9523 let value = self.pop();
9524 self.push(Value::Bool(matches!(value, Value::Undefined)));
9525 }
9526 IsUndefinedOrNull => {
9527 let value = self.pop();
9528 self.push(Value::Bool(value.is_nullish()));
9529 }
9530 Typeof => {
9531 let value = self.pop();
9532 self.push(self.string(value.type_of()));
9533 }
9534 ToObject => {
9535 // A destructuring *object* pattern starts here, which is why
9536 // `var {} = null` throws. Only `undefined` and `null` are refused; a
9537 // primitive is boxed.
9538 let value = self.pop();
9539 let object = self.object_from(&value)?;
9540 self.push(Value::Object(object));
9541 }
9542 Instanceof => {
9543 let constructor = self.pop();
9544 let object = self.pop();
9545 let answer = self.instance_of(&object, &constructor)?;
9546 self.push(Value::Bool(answer));
9547 }
9548 In => {
9549 let object = self.pop();
9550 let key = self.pop();
9551 let answer = self.has_property(&key, &object)?;
9552 self.push(Value::Bool(answer));
9553 }
9554
9555 // -- control flow -----------------------------------------------
9556 Goto | Goto8 | Goto16 => {
9557 self.frame_mut().pc = a as usize;
9558 }
9559 IfTrue | IfTrue8 => {
9560 let value = self.pop();
9561 if value.to_boolean() {
9562 self.frame_mut().pc = a as usize;
9563 }
9564 }
9565 IfFalse | IfFalse8 => {
9566 let value = self.pop();
9567 if !value.to_boolean() {
9568 self.frame_mut().pc = a as usize;
9569 }
9570 }
9571 Catch => {
9572 // Pushes the handler target onto the value stack; `unwind` finds it.
9573 self.push(Value::CatchOffset(a));
9574 }
9575 Gosub => {
9576 self.push(Value::ReturnAddress(next as u32));
9577 self.frame_mut().pc = a as usize;
9578 }
9579 Ret => {
9580 let value = self.pop();
9581 match value {
9582 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
9583 _ => {
9584 return Err(Signal::Throw(
9585 self.make_error("InternalError", "invalid return address"),
9586 ));
9587 }
9588 }
9589 }
9590 NipCatch => {
9591 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
9592 // including the marker, keeping the top value.
9593 let top = self.pop();
9594 loop {
9595 match self.pop() {
9596 Value::CatchOffset(_) | Value::Undefined => break,
9597 _ => {}
9598 }
9599 if self.frame().stack.is_empty() {
9600 break;
9601 }
9602 }
9603 self.push(top);
9604 }
9605 Throw => {
9606 let value = self.pop();
9607 return Err(Signal::Throw(value));
9608 }
9609 ThrowError => {
9610 let name = self.atom_text(a as usize);
9611 let (class, message) = match b {
9612 0 => ("TypeError", format!("'{name}' is read-only")),
9613 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
9614 2 => ("ReferenceError", format!("'{name}' is not initialized")),
9615 // `delete super.x` is a syntax-level mistake the reference reports
9616 // with this wording, not a property-access failure.
9617 3 => (
9618 "ReferenceError",
9619 "unsupported reference to 'super'".to_string(),
9620 ),
9621 4 => (
9622 "TypeError",
9623 "iterator does not have a throw method".to_string(),
9624 ),
9625 5 => (
9626 "ReferenceError",
9627 "invalid assignment left-hand side".to_string(),
9628 ),
9629 _ => ("TypeError", format!("invalid operation on '{name}'")),
9630 };
9631 return Err(Signal::Throw(self.make_error(class, &message)));
9632 }
9633 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
9634 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
9635 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
9636 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
9637 Await => return Ok(Step::Suspend(SuspendKind::Await)),
9638 ReturnAsync => {
9639 // The reference's `return_async` returns `undefined` and lets the resume
9640 // machinery pick the real value off `sp[-1]`, which is how it tells a
9641 // completion from a suspension. Carrying the value explicitly says the
9642 // same thing without the implicit stack slot.
9643 let value = self.pop();
9644 return Ok(Step::Return(value));
9645 }
9646 Return => {
9647 let value = self.pop();
9648 return Ok(Step::Return(value));
9649 }
9650 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
9651
9652 // -- calls ------------------------------------------------------
9653 Call | Call0 | Call1 | Call2 | Call3 => {
9654 let argc = self.argc_operand(op, a);
9655 let args = self.pop_n(argc);
9656 let callee = self.pop();
9657 // A plain call has no receiver; the callee decides what to do with
9658 // `undefined` (a sloppy function substitutes the global object).
9659 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
9660 self.push(result);
9661 }
9662 }
9663 CallConstructor => {
9664 // `constructor this_obj args… -> object`. The duplicated
9665 // constructor is `new.target`; this milestone does not expose it,
9666 // so the extra copy is simply consumed here.
9667 let argc = a as usize;
9668 let args = self.pop_n(argc);
9669 let new_target = self.pop();
9670 let callee = self.pop();
9671 let result = self.construct(callee, new_target, args)?;
9672 self.push(result);
9673 }
9674 CallMethod => {
9675 let argc = a as usize;
9676 let args = self.pop_n(argc);
9677 let callee = self.pop();
9678 let this = self.pop();
9679 if let Some(result) = self.call_or_push(callee, this, args)? {
9680 self.push(result);
9681 }
9682 }
9683 Apply => {
9684 // `func this array -> result`, the spread-call form: the compiler
9685 // builds one array of arguments, and all that is left here is to
9686 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
9687 let array = self.pop();
9688 let this = self.pop();
9689 let callee = self.pop();
9690 let args = self.array_like_to_args(&array)?;
9691 if a & 1 != 0 {
9692 let result = self.construct(callee, this, args)?;
9693 self.push(result);
9694 } else if let Some(result) = self.call_or_push(callee, this, args)? {
9695 self.push(result);
9696 }
9697 }
9698 TailCall | TailCallMethod => {
9699 // `tail_call` is `call` whose result is returned immediately — the
9700 // reference jumps straight to `done` instead of storing the value and
9701 // running on. The callee still gets its own frame, so deep tail
9702 // recursion hits the stack limit exactly like plain recursion does;
9703 // marking this frame lets the return path unwind without needing
9704 // instructions after the call.
9705 let argc = if op == TailCallMethod {
9706 a as usize
9707 } else {
9708 self.argc_operand(op, a)
9709 };
9710 let args = self.pop_n(argc);
9711 let callee = self.pop();
9712 let this = if op == TailCallMethod {
9713 self.pop()
9714 } else {
9715 Value::Undefined
9716 };
9717 if let Value::Object(function) = &callee
9718 && let Some((code, env)) = bytecode_of(function)
9719 {
9720 // A generator or async body is not run here at all: calling it only
9721 // *creates* the generator/coroutine, so it must not inherit this
9722 // frame. Doing so made `function f(){ return g() }` push `g`'s body
9723 // onto `f`'s frame, and the first `yield`/`await` then reported
9724 // "a generator body ran as an ordinary call".
9725 if code.code.kind.is_generator() || code.code.kind.is_async() {
9726 let value = self.call_value(callee, this, args)?;
9727 return Ok(Step::Return(value));
9728 }
9729 self.frame_mut().tail = true;
9730 self.push_frame(code, env, this, args, callee)?;
9731 return Ok(Step::Continue);
9732 }
9733 // A native callee has no frame to reuse, so its value is simply
9734 // returned.
9735 let value = self.call_value(callee, this, args)?;
9736 return Ok(Step::Return(value));
9737 }
9738
9739 // -- objects ----------------------------------------------------
9740 SpecialObject => {
9741 let value = self.special_object(a)?;
9742 self.push(value);
9743 }
9744 PrivateSymbol => {
9745 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
9746 // symbol each time it is evaluated, which is why the compiler evaluates it
9747 // once (at class definition) and stores it in a class-scope binding.
9748 let name = self.atom_text(a as usize);
9749 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
9750 self.push(Value::Symbol(symbol));
9751 }
9752 GetPrivateField => {
9753 // `obj symbol -> value`. A missing private field is a TypeError, which is what
9754 // makes `#x` inaccessible on any object not built by this class.
9755 let symbol = self.pop();
9756 let object = self.pop();
9757 let value = self.read_private_field(&object, &symbol)?;
9758 self.push(value);
9759 }
9760 PutPrivateField => {
9761 // `obj value symbol ->`, and the store is a plain assignment to a property the
9762 // class already created, so there is no setter to consult.
9763 let symbol = self.pop();
9764 let value = self.pop();
9765 let object = self.pop();
9766 self.write_private_field(&object, &symbol, value)?;
9767 }
9768 DefinePrivateField => {
9769 // `obj symbol value -> obj`: a field initialiser creates the property, and
9770 // redefining one is a TypeError ("already exists").
9771 let value = self.pop();
9772 let symbol = self.pop();
9773 let object = self.pop();
9774 self.define_private_field(&object, &symbol, value)?;
9775 self.push(object);
9776 }
9777 PrivateIn => {
9778 // `obj key -> bool`: `#x in o`. The second operand decides which question is
9779 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
9780 // is a field, so this is an own-property test; a *function* is a method or
9781 // accessor, so this is a brand check.
9782 let key = self.pop();
9783 let object = self.pop();
9784 let Some(target) = object.as_object() else {
9785 return Err(Signal::Throw(
9786 self.make_error("TypeError", "invalid 'in' operand"),
9787 ));
9788 };
9789 let present = match &key {
9790 Value::Object(_) => self.check_brand(target, &key)?,
9791 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
9792 };
9793 self.push(Value::Bool(present));
9794 }
9795 AddBrand => {
9796 // `obj home ->`: create the class brand on `home` if it has none, then give
9797 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
9798 // class definition: only the prototype's copy of the symbol is wanted.
9799 let home = self.pop();
9800 let object = self.pop();
9801 self.add_brand(&object, &home)?;
9802 }
9803 CheckBrand => {
9804 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
9805 // Both stay, because the caller needs them — `nip` halves a read into its
9806 // value and `call_method` uses the pair as receiver and callee.
9807 let function = self.peek(0);
9808 let object = self.peek(1);
9809 let Some(target) = object.as_object() else {
9810 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9811 };
9812 if !self.check_brand(target, &function)? {
9813 return Err(Signal::Throw(
9814 self.make_error("TypeError", "invalid brand on object"),
9815 ));
9816 }
9817 }
9818 GetLength => {
9819 // `get_length` is the `.length` read; an array and a string answer
9820 // from their own length, anything else from the property.
9821 let target = self.pop();
9822 let value = match &target {
9823 Value::Object(object) => match object.array_length() {
9824 Some(length) => crate::object::length_value(length),
9825 None => self.read_field(&target, "length")?,
9826 },
9827 Value::String(text) => Value::Int(text.utf16_len() as i32),
9828 _ => self.read_field(&target, "length")?,
9829 };
9830 self.push(value);
9831 }
9832 GetField | GetField2 => {
9833 let object = self.pop();
9834 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
9835 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
9836 // just below is what lets the borrow outlive the `&mut self` the lookup
9837 // needs — one refcount bump instead of a key clone plus its drop, on the
9838 // hottest property path there is: every `o.x` and every `o.m()` receiver.
9839 let code = self.frame().code.clone();
9840 let key = &code.atom_keys[a as usize];
9841 let value = self.read_field_cached(&object, key, next)?;
9842 if op == GetField2 {
9843 self.push(object);
9844 }
9845 self.push(value);
9846 }
9847 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
9848 let key = self.pop();
9849 let object = self.pop();
9850 let key = self.propkey(&key)?;
9851 let value = self.read_field_key(&object, &key)?;
9852 if matches!(op, GetArrayEl2 | GetArrayEl3) {
9853 self.push(object);
9854 }
9855 if op == GetArrayEl3 {
9856 // The key goes back in its *value* form, which the compiler stores
9857 // into the target of a destructuring assignment.
9858 self.push(match &key {
9859 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
9860 PropertyKey::String(text) => self.string_wtf8(text.clone()),
9861 });
9862 }
9863 self.push(value);
9864 }
9865 PutField => {
9866 let value = self.pop();
9867 let object = self.pop();
9868 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
9869 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
9870 // only reads. `this.value = …` is the write half of the hottest loop in
9871 // `property:method-call`, and `own_property_key` was 4.8% of the case.
9872 let code = self.frame().code.clone();
9873 let key = &code.atom_keys[a as usize];
9874 self.write_field_key(&object, key, value)?;
9875 }
9876 PutArrayEl => {
9877 let value = self.pop();
9878 let key = self.pop();
9879 let object = self.pop();
9880 let key = self.propkey(&key)?;
9881 self.write_field_key(&object, &key, value)?;
9882 }
9883 DefineField => {
9884 let value = self.pop();
9885 let object = self.pop();
9886 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
9887 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
9888 // three U+FFFD — a property under a different name from the one
9889 // `o["\uD800"]` reads.
9890 let code = self.frame().code.clone();
9891 let key = code.atom_keys[a as usize].clone();
9892 // No naming here. `{m: function(){}}` is named by the *compiler*, which
9893 // emits `set_name` — and only where `NamedEvaluation` applies, so
9894 // `{m: (0, function(){})}` stays anonymous. Naming every function that
9895 // reaches a property definition got that case wrong, and the compiler is
9896 // the only place that can tell the two apart.
9897 if let Some(target) = object.as_object() {
9898 // Only an *array* stores into the element vector. A numeric key
9899 // on an ordinary object is an ordinary property, which is what
9900 // makes `{1: 'a'}` iterate as a key rather than disappear.
9901 let stored = target.is_array()
9902 && key.as_str().and_then(array_index).is_some_and(|index| {
9903 target.array_set(self.heap, index as usize, value.clone())
9904 });
9905 if !stored {
9906 target.define_data_key(&key, value);
9907 }
9908 }
9909 self.push(object);
9910 }
9911 DefineArrayEl => {
9912 // `obj key value -> obj key`. The *value* form of the key is what goes
9913 // back on the stack — the compiler stores it into the pattern's binding —
9914 // so the symbol is not stringified on the way through.
9915 let value = self.pop();
9916 let key_value = self.pop();
9917 let object = self.peek(0);
9918 let key = self.propkey(&key_value)?;
9919 self.write_field_key(&object, &key, value)?;
9920 self.push(key_value);
9921 }
9922 SetHomeObject => {
9923 // `obj func -> obj func`: records the object a method was defined on so
9924 // `super` inside it resolves against that object's prototype.
9925 let function = self.peek(0);
9926 let home = self.peek(1);
9927 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
9928 function.set_home_object(Some(home.clone()));
9929 }
9930 }
9931 Regexp => {
9932 // `pattern flags -> regexp`. A literal compiles here rather than through the
9933 // constructor, which is both what the reference's dedicated opcode is for
9934 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
9935 let flags = self.pop();
9936 let pattern = self.pop();
9937 let pattern = self.to_js_string(&pattern)?;
9938 let flags = self.to_js_string(&flags)?;
9939 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
9940 self.push(Value::Object(object));
9941 }
9942 UsingDisposeInit => {
9943 // The error state a disposal accumulates into. Uninitialised means "no
9944 // failure yet"; anything else is the exception being propagated.
9945 self.push(Value::Uninitialized);
9946 }
9947 UsingCheck => {
9948 // `value -> value, method`: validate and snapshot the disposer now, so a
9949 // later change to `Symbol.dispose` cannot change what gets called, and so a
9950 // value that is not disposable fails before the body runs.
9951 let value = self.pop();
9952 let method = self.using_method_for(&value, a as u8 == 1)?;
9953 self.push(value);
9954 self.push(method);
9955 }
9956 UsingDispose => {
9957 // `error_state -> error_state'`: dispose the variable at `slot` — its value
9958 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
9959 // the pending error.
9960 let slot = self.slot_operand(op, a);
9961 let error_state = self.pop();
9962 let merged = self.using_dispose_once(slot, error_state)?;
9963 self.push(merged);
9964 }
9965 UsingDisposeMerge => {
9966 let new_error = self.pop();
9967 let error_state = self.pop();
9968 let merged = self.merge_dispose_error(new_error, error_state);
9969 self.push(merged);
9970 }
9971 UsingDisposeEnd => {
9972 // A disposal that failed replaces the block's normal completion, so the
9973 // error state becomes a real throw here rather than at the call site.
9974 let error_state = self.pop();
9975 if !matches!(error_state, Value::Uninitialized) {
9976 return Err(Signal::Throw(error_state));
9977 }
9978 }
9979 UsingDisposeAsync => {
9980 // `await using` needs a promise to await and this runtime has no
9981 // `Promise` builtin, so the disposer is called synchronously and its result
9982 // discarded. That is correct for a disposer that returns nothing and is
9983 // reported as a gap rather than silently skipped.
9984 let slot = self.slot_operand(op, a);
9985 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
9986 self.push(error_state);
9987 }
9988 GetSuper => {
9989 // `obj -> obj's prototype`: the starting point of a `super` lookup.
9990 let object = self.pop();
9991 let proto = match &object {
9992 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
9993 _ => Value::Null,
9994 };
9995 self.push(proto);
9996 }
9997 GetSuperValue => {
9998 // `receiver proto key -> value`, searching from `proto` but reporting to
9999 // `receiver`, which is what `super.g` must do for a getter to see `this`.
10000 //
10001 // Three values in, one out: the receiver is *consumed*, not left under the
10002 // result. Leaving it there was invisible for `super.x` in `return` or
10003 // statement position (the result is what gets popped) and corrupted the
10004 // frame everywhere else — `print(super.x)` left the class where the call
10005 // opcode looks for the receiver and called the class itself.
10006 let key = self.pop();
10007 let proto = self.pop();
10008 let receiver = self.pop();
10009 let value = self.super_read(&receiver, &proto, &key)?;
10010 self.push(value);
10011 }
10012 PutSuperValue => {
10013 // `receiver proto key value ->`: a store that starts at `proto` but
10014 // assigns to `receiver`.
10015 let value = self.pop();
10016 let key = self.pop();
10017 let proto = self.pop();
10018 let receiver = self.pop();
10019 self.super_write(&receiver, &proto, &key, value)?;
10020 }
10021 DefineClass => {
10022 // `parent ctor -> ctor proto`: the constructor becomes the class and a
10023 // fresh prototype object lands on top for the methods to go on.
10024 let name = self.atom_text(a as usize);
10025 let (ctor, proto) = self.define_class(&name, b)?;
10026 self.push(ctor);
10027 self.push(Value::Object(proto));
10028 }
10029 DefineClassComputed => {
10030 // `parent ctor key -> ctor proto key`: the computed name stays put so
10031 // `define_field`-style consumers can still read it.
10032 let key = self.pop();
10033 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
10034 let (ctor, proto) = self.define_class(&name, b)?;
10035 self.push(ctor);
10036 self.push(Value::Object(proto));
10037 self.push(key);
10038 }
10039 DefineMethod => {
10040 let function = self.pop();
10041 let object = self.pop();
10042 // The exact key, like `define_field`: a quoted method key may hold an
10043 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
10044 // that `o["\uD800"]` finds.
10045 let code = self.frame().code.clone();
10046 let key = code.atom_keys[a as usize].clone();
10047 // A method's `[[HomeObject]]` is the object it was defined on, which is
10048 // what `super` inside it resolves against.
10049 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
10050 function.set_home_object(Some(object.clone()));
10051 }
10052 if let Some(text) = key.as_wtf8() {
10053 self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
10054 } else {
10055 self.set_function_name(
10056 &function,
10057 &key_with_accessor_prefix(&key.to_string(), b),
10058 );
10059 }
10060 if let Some(array) = object.as_object() {
10061 define_function_property(array, &key, function, b);
10062 }
10063 self.push(object);
10064 }
10065 DefineMethodComputed => {
10066 let function = self.pop();
10067 let key = self.pop();
10068 let object = self.pop();
10069 let key = self.propkey(&key)?;
10070 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
10071 // the name: `super` inside a computed method resolves through it. Without
10072 // this, `class B extends A { [k]() { return super.m() } }` read the
10073 // home object as null and threw.
10074 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
10075 function.set_home_object(Some(object.clone()));
10076 }
10077 match key.as_wtf8() {
10078 Some(text) => {
10079 let name = accessor_prefixed(text, a);
10080 self.set_function_name_wtf8(&function, &name);
10081 }
10082 None => self.set_function_name(
10083 &function,
10084 &key_with_accessor_prefix(&key.to_string(), a),
10085 ),
10086 }
10087 if let Some(array) = object.as_object() {
10088 define_function_property(array, &key, function, a);
10089 }
10090 self.push(object);
10091 }
10092 SetProto => {
10093 let proto = self.pop();
10094 let object = self.pop();
10095 if let Some(target) = object.as_object() {
10096 target.set_proto(proto.as_object().cloned());
10097 }
10098 self.push(object);
10099 }
10100 CopyDataProperties => {
10101 let exclusion = self.pop();
10102 let source = self.pop();
10103 let target = self.peek(0);
10104 self.copy_properties(&target, &source, &exclusion)?;
10105 self.push(source);
10106 self.push(exclusion);
10107 }
10108 ToPropkey => {
10109 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
10110 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
10111 // ordinary `"Symbol(b)"` property.
10112 let value = self.pop();
10113 let key = match self.propkey(&value)? {
10114 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
10115 PropertyKey::String(text) => self.string_wtf8(text),
10116 };
10117 self.push(key);
10118 }
10119 SetName => {
10120 let function = self.peek(0);
10121 let name = self.atom_wtf8(a as usize);
10122 self.set_function_name_wtf8(&function, &name);
10123 }
10124 SetNameComputed => {
10125 let key = self.peek(1);
10126 let function = self.peek(0);
10127 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
10128 self.set_function_name(&function, &name);
10129 }
10130
10131 // -- arrays -----------------------------------------------------
10132 ArrayFrom => {
10133 let count = a as usize;
10134 let elements = self.pop_n(count);
10135 let array = self.new_array(elements);
10136 self.push(Value::Object(array));
10137 }
10138 Append => {
10139 // `array index iterable -> array new_index`
10140 let iterable = self.pop();
10141 self.pop();
10142 let array = self.peek(0);
10143 let added = self.append_enumerate(&array, &iterable)?;
10144 self.push(Value::Int(added));
10145 }
10146
10147 // -- iteration --------------------------------------------------
10148 ForInStart => {
10149 let value = self.pop();
10150 let record = self.for_in_record(&value)?;
10151 self.push(Value::Object(record));
10152 }
10153 ForInNext => {
10154 // `record -> record key done`. The flag is *done*, not "found":
10155 // the compiler tests it with `if_false` to jump back into the body,
10156 // so reporting `true` while keys remain would end the loop at once.
10157 let record = self.peek(0);
10158 match self.for_in_advance(&record)? {
10159 Some(key) => {
10160 let text = self.string(key);
10161 self.push(text);
10162 self.push(Value::Bool(false));
10163 }
10164 None => {
10165 self.push(Value::Undefined);
10166 self.push(Value::Bool(true));
10167 }
10168 }
10169 }
10170 ForOfStart => {
10171 let value = self.pop();
10172 let iterator = self.get_iterator(&value)?;
10173 self.push(iterator.object);
10174 self.push(iterator.next);
10175 self.push(Value::CatchOffset(0));
10176 }
10177 ForOfNext => {
10178 // `iter next catch_offset -> iter next catch_offset value done`.
10179 //
10180 // The operand is how many values sit *above* the iterator triple: a
10181 // destructuring rest element keeps its target array and running index
10182 // there while draining the iterator, so the triple is not at the top.
10183 let extra = a as usize;
10184 let iterator_slot = 2 + extra;
10185 // An exhausted iterator is replaced by `undefined` (see below), so a
10186 // second step must not call `next` again — `Array.from` and a
10187 // destructuring pattern both keep stepping past the end.
10188 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
10189 (Value::Undefined, true)
10190 } else {
10191 let iterator = Iterator {
10192 object: self.peek(iterator_slot),
10193 next: self.peek(1 + extra),
10194 };
10195 self.iterator_step(&iterator)?
10196 };
10197 if done {
10198 // The result's `value` is meaningless once the iterator is done:
10199 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
10200 // rather than binding the generator's return value.
10201 let top = self.frame().stack.len() - 1 - iterator_slot;
10202 self.frame_mut().stack[top] = Value::Undefined;
10203 self.push(Value::Undefined);
10204 self.push(Value::Bool(true));
10205 } else {
10206 self.push(value);
10207 self.push(Value::Bool(false));
10208 }
10209 }
10210 IteratorNext => {
10211 // `iter next catch val -> iter next catch val'`: replace the argument with
10212 // the result of `next(val)`. The triple below stays put, which is why the
10213 // three instructions of the `yield*` loop all address the stack the same way.
10214 let value = self.pop();
10215 let object = self.peek(2);
10216 let next = self.peek(1);
10217 let result = self.call_value(next, object, vec![value])?;
10218 self.push(result);
10219 }
10220 IteratorCall => {
10221 // `iter next catch val -> iter next catch val' flag`.
10222 //
10223 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
10224 // The flag is `true` when the method was missing, which is how the
10225 // caller learns that the inner iterator cannot take part in the
10226 // unwinding.
10227 let value = self.pop();
10228 let object = self.peek(2);
10229 let key = if a & 1 != 0 { "throw" } else { "return" };
10230 let method = self.read_field(&object, key)?;
10231 if matches!(method, Value::Undefined | Value::Null) {
10232 self.push(value);
10233 self.push(Value::Bool(true));
10234 } else {
10235 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
10236 let result = self.call_value(method, object, argument)?;
10237 self.push(result);
10238 self.push(Value::Bool(false));
10239 }
10240 }
10241 IteratorCheckObject => {
10242 if !matches!(self.peek(0), Value::Object(_)) {
10243 return Err(Signal::Throw(
10244 self.make_error("TypeError", "iterator must return an object"),
10245 ));
10246 }
10247 }
10248 IteratorClose => {
10249 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
10250 // calling the iterator's `return` so it can release whatever it holds.
10251 //
10252 // The catch offset goes first, so an exception from `return` is not caught
10253 // by the loop being abandoned. This used to pop the three operands and call
10254 // nothing at all, which made `break` out of a `for of` invisible to an
10255 // iterator with a `return` method.
10256 self.pop();
10257 self.pop();
10258 let iterator = self.pop();
10259 if !matches!(iterator, Value::Undefined) {
10260 let method = self.read_field(&iterator, "return")?;
10261 if !matches!(method, Value::Undefined | Value::Null) {
10262 let result = self.call_value(method, iterator.clone(), Vec::new())?;
10263 // §7.4.6: a `return` that answers a non-object is a TypeError.
10264 if !matches!(result, Value::Object(_)) {
10265 return Err(Signal::Throw(
10266 self.make_error("TypeError", "iterator must return an object"),
10267 ));
10268 }
10269 }
10270 }
10271 }
10272 Import => {
10273 // `import(specifier)`: the options slot is on top and is not read yet.
10274 let _options = self.pop();
10275 let specifier = self.pop();
10276 let promise = self.dynamic_import(specifier)?;
10277 self.push(promise);
10278 }
10279 ForAwaitOfStart => {
10280 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
10281 // `Symbol.iterator` fallback.
10282 let value = self.pop();
10283 let iterator = self.get_async_iterator(&value)?;
10284 self.push(iterator.object);
10285 self.push(iterator.next);
10286 self.push(Value::CatchOffset(0));
10287 }
10288 ForAwaitOfNext => {
10289 // `for await` steps the iterator and leaves the *result* wrapped in a
10290 // promise, so the `await` the compiler emits right after this can suspend
10291 // on it. Unwrapping happens in `iterator_get_value_done`.
10292 let extra = a as usize;
10293 let iterator_slot = 2 + extra;
10294 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
10295 Value::Undefined
10296 } else {
10297 let iterator = Iterator {
10298 object: self.peek(iterator_slot),
10299 next: self.peek(1 + extra),
10300 };
10301 let next = iterator.next.clone();
10302 self.call_value(next, iterator.object, Vec::new())?
10303 };
10304 let promise = self.promise_resolve_value(result)?;
10305 self.push(promise);
10306 }
10307 IteratorGetValueDone => {
10308 // `result -> value done`. A missing result object means the iterator was
10309 // already exhausted, which the loop treats as `done`.
10310 let result = self.pop();
10311 let done = match &result {
10312 Value::Object(object) => self
10313 .get_property(object, "done")?
10314 .is_some_and(|value| value.to_boolean()),
10315 _ => true,
10316 };
10317 if done {
10318 // Clear the iterator object so the `iterator_close` the loop emits on
10319 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
10320 // on normal completion, and this is where a normal completion is
10321 // recognised — the same trick `for_of_next` uses, which also replaces
10322 // the slot with `undefined`.
10323 //
10324 // The layout is fixed because only `for await` emits this opcode:
10325 // `iter next catch [result]`, so the iterator is three below the top.
10326 let depth = self.frame().stack.len();
10327 if depth >= 3 {
10328 self.frame_mut().stack[depth - 3] = Value::Undefined;
10329 }
10330 self.push(Value::Undefined);
10331 self.push(Value::Bool(true));
10332 } else {
10333 let Value::Object(object) = &result else {
10334 self.push(Value::Undefined);
10335 self.push(Value::Bool(true));
10336 return Ok(Step::Continue);
10337 };
10338 let value = self
10339 .get_property(object, "value")?
10340 .unwrap_or(Value::Undefined);
10341 self.push(value);
10342 self.push(Value::Bool(false));
10343 }
10344 }
10345
10346 Delete => {
10347 // `delete obj[key]`, where the key was just pushed. Deleting an array
10348 // index leaves a *hole* rather than closing the gap, and a
10349 // non-configurable property answers `false` and stays.
10350 let key = self.pop();
10351 let target = self.pop();
10352 let key = self.propkey(&key)?;
10353 let text_label = key.as_str().unwrap_or("").to_string();
10354 let deleted = match &target {
10355 Value::Object(object) => {
10356 let object = object.clone();
10357 self.delete_property_key(&object, &key)?
10358 }
10359 // A string's `length` and its index properties are
10360 // non-configurable, so deleting one answers `false`.
10361 Value::String(text) => {
10362 !(text_label == "length"
10363 || array_index(&text_label)
10364 .is_some_and(|index| (index as usize) < text.utf16_len()))
10365 }
10366 // "delete null.a" is a TypeError, not a no-op: the operator needs an
10367 // object to delete from, and only a *boxable* primitive has one.
10368 Value::Undefined | Value::Null => {
10369 return Err(Signal::Throw(
10370 self.make_error("TypeError", "cannot convert to object"),
10371 ));
10372 }
10373 // Any other primitive has no own properties; deleting nothing
10374 // succeeds.
10375 _ => true,
10376 };
10377 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
10378 // `TypeError` rather than a `false` result. Sloppy mode silently reports
10379 // the refusal, which is why the same statement throws here but not there.
10380 if !deleted && self.current_strict() {
10381 return Err(Signal::Throw(
10382 self.make_error("TypeError", "cannot delete property"),
10383 ));
10384 }
10385 self.push(Value::Bool(deleted));
10386 }
10387
10388 // -- exceptions and bookkeeping ---------------------------------
10389 Fclosure | Fclosure8 => {
10390 let value = self.closure(a as usize)?;
10391 self.push(value);
10392 }
10393
10394 other => {
10395 let name = other.info().name;
10396 return Err(Signal::Throw(self.make_error(
10397 "InternalError",
10398 &format!("{name} is not implemented yet"),
10399 )));
10400 }
10401 }
10402 Ok(Step::Continue)
10403 }
10404
10405 // -- operand helpers ----------------------------------------------------
10406
10407 /// The slot index an operand names, taking short forms into account.
10408 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
10409 use Opcode::*;
10410 match op {
10411 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
10412 | SetVarRef0 => 0,
10413 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
10414 | SetVarRef1 => 1,
10415 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
10416 | SetVarRef2 => 2,
10417 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
10418 | SetVarRef3 => 3,
10419 _ => a as usize,
10420 }
10421 }
10422
10423 /// The argument count of a call, taking `call0`…`call3` into account.
10424 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
10425 use Opcode::*;
10426 match op {
10427 Call0 => 0,
10428 Call1 => 1,
10429 Call2 => 2,
10430 Call3 => 3,
10431 _ => a as usize,
10432 }
10433 }
10434
10435 /// The atom's name as a property key.
10436 ///
10437 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
10438 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
10439 /// `String::clone` was a heap allocation and a copy — per property access.
10440 /// The atom at `index`, as a property key.
10441 ///
10442 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
10443 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
10444 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
10445 /// 5.3% of `property:monomorphic`.
10446 /// The atom's text, exactly — including an unpaired surrogate.
10447 ///
10448 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
10449 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
10450 /// `atom_text` below is for the other kind of use, where the atom is a key in the
10451 /// engine's own tables.
10452 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
10453 self.frame()
10454 .code
10455 .code
10456 .atoms
10457 .get(index)
10458 .map(|atom| match atom {
10459 Atom::Str(text) => text.clone(),
10460 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
10461 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
10462 Atom::Null => crate::value::Wtf8::new(String::new()),
10463 })
10464 .unwrap_or_default()
10465 }
10466
10467 fn atom_text(&self, index: usize) -> String {
10468 self.frame()
10469 .code
10470 .code
10471 .atoms
10472 .get(index)
10473 .map(|atom| match atom {
10474 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
10475 // compare it to an identifier, and a surrogate-bearing name is reachable
10476 // through `atom_wtf8` where it matters.
10477 Atom::Str(text) => text.to_string_lossy().into_owned(),
10478 Atom::Index(value) => value.to_string(),
10479 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
10480 // `throw_error`, `delete super.x`) never read it.
10481 Atom::Null => String::new(),
10482 })
10483 .unwrap_or_default()
10484 }
10485
10486 fn constant(&mut self, index: usize) -> JsResult<Value> {
10487 let constant = self.frame().code.code.cpool.get(index).cloned();
10488 Ok(match &constant {
10489 Some(Constant::Number(number)) => Value::Float(*number),
10490 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
10491 Some(Constant::BigInt { digits, radix }) => {
10492 match crate::bigint::BigInt::from_radix(digits, *radix) {
10493 Some(big) => self.bigint(big),
10494 // A literal the parser accepted is always parseable; a failure here
10495 // would be a compiler bug, so it reads as an `InternalError`.
10496 None => {
10497 return Err(Signal::Throw(
10498 self.make_error("InternalError", "unparseable bigint literal"),
10499 ));
10500 }
10501 }
10502 }
10503 Some(Constant::Function(_)) => {
10504 return Err(Signal::Throw(
10505 self.make_error("InternalError", "a bare function constant"),
10506 ));
10507 }
10508 // A tagged template's call site: a frozen array of the cooked chunks with a
10509 // frozen `raw` array beside it, which is what `String.raw` reads back.
10510 Some(Constant::Template { cooked, raw }) => {
10511 let cooked_values: Vec<Value> = cooked
10512 .iter()
10513 .map(|chunk| match chunk {
10514 Some(text) => self.string_wtf8(text.clone()),
10515 None => Value::Undefined,
10516 })
10517 .collect();
10518 let raw_values: Vec<Value> =
10519 raw.iter().map(|text| self.string(text.clone())).collect();
10520 let raw_array = self.new_array(raw_values);
10521 raw_array.set_extensible(false);
10522 let template = self.new_array(cooked_values);
10523 template.define(
10524 "raw",
10525 Property::with_attributes(Value::Object(raw_array), false, false),
10526 );
10527 template.set_extensible(false);
10528 Value::Object(template)
10529 }
10530 _ => Value::Undefined,
10531 })
10532 }
10533
10534 /// The reference cell a closure-variable slot names.
10535 ///
10536 /// Two kinds of binding share this addressing: a genuine closure variable
10537 /// (captured from an enclosing function) lives in this frame's environment,
10538 /// while a *declared global* lives in the realm so that a script, a function
10539 /// declaration and their uses all see one binding. A plain `Global` — an
10540 /// undeclared name that may be satisfied by the global object — has no cell at
10541 /// all, which is how `typeof x` still works for a name that does not exist.
10542 /// The reference cell a closure-variable slot names.
10543 ///
10544 /// The environment is resolved once, when the closure is built, and this is
10545 /// just the lookup afterwards. A *declared global* is in there too, pointing at
10546 /// the realm's cell, so a script, a hoisted function declaration and their uses
10547 /// all share one binding. A plain `Global` — a name the script never declared —
10548 /// is read and written through `get_var`/`put_var` by name instead, which is
10549 /// what lets the global object satisfy it.
10550 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
10551 self.frame().env.cells.get(slot).cloned()
10552 }
10553
10554 /// Whether `slot` refers to a global binding through the reference table.
10555 ///
10556 /// A global's cell in the closure environment only exists so the slot has
10557 /// something to point at; the binding itself lives on the global object (a `var`)
10558 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
10559 /// be routed, not performed on the placeholder.
10560 fn is_global_slot(&self, slot: usize) -> bool {
10561 self.frame()
10562 .code
10563 .code
10564 .closure_vars
10565 .get(slot)
10566 .is_some_and(|c| {
10567 // A module's declarations and imports are *not* globals: their cells are
10568 // the module environment's, filled by the host, so the placeholder routing
10569 // must not apply to them.
10570 matches!(
10571 c.closure_type,
10572 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
10573 )
10574 })
10575 }
10576
10577 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
10578 if self.is_global_slot(slot) {
10579 return self.get_global(slot);
10580 }
10581 Ok(self
10582 .var_ref_cell(slot)
10583 .map(|cell| cell.get())
10584 .unwrap_or(Value::Undefined))
10585 }
10586
10587 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
10588 // A function declaration is hoisted by storing into a global reference before
10589 // the body runs, so this path is also what puts it on the global object.
10590 if self.is_global_slot(slot) {
10591 return self.put_global(slot, value);
10592 }
10593 if let Some(cell) = self.var_ref_cell(slot) {
10594 cell.set(value);
10595 }
10596 Ok(())
10597 }
10598
10599 // -- closures -----------------------------------------------------------
10600
10601 /// Build the closure for the function constant `index`.
10602 ///
10603 /// Every entry in the child's closure table names where its binding lives in
10604 /// *this* frame: a local or argument slot that was marked captured, or a cell
10605 /// this frame is itself holding. That is how a variable three functions deep
10606 /// stays one binding.
10607 fn closure(&mut self, index: usize) -> JsResult<Value> {
10608 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
10609 else {
10610 return Err(Signal::Throw(
10611 self.make_error("InternalError", "fclosure of a non-function"),
10612 ));
10613 };
10614 let mut cells = Vec::with_capacity(function.closure_vars.len());
10615 for closure_var in &function.closure_vars {
10616 let cell = match closure_var.closure_type {
10617 ClosureType::Arg => {
10618 let slot = closure_var.var_idx as usize;
10619 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
10620 }
10621 ClosureType::Local => {
10622 let slot = closure_var.var_idx as usize;
10623 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
10624 }
10625 ClosureType::Ref | ClosureType::GlobalRef => {
10626 // A `Ref` names a cell in this frame's own closure table; a
10627 // `GlobalRef` also starts there, then resolves by name below.
10628 let slot = closure_var.var_idx as usize;
10629 if let Some(cell) = self.frame().env.cells.get(slot) {
10630 cells.push(cell.clone());
10631 continue;
10632 }
10633 -1
10634 }
10635 _ => -1,
10636 };
10637 if cell >= 0 {
10638 let cell = self.frame().cells[cell as usize].clone();
10639 cells.push(cell);
10640 continue;
10641 }
10642 // A global: the cell is created on demand and shared through the realm,
10643 // so every function sees one binding.
10644 let name = closure_var.name.clone();
10645 let cell = match self.realm.globals.get(&name) {
10646 Some(cell) => cell.clone(),
10647 None => {
10648 let cell = self.new_cell(Value::Undefined);
10649 self.realm.globals.insert(name.clone(), cell.clone());
10650 cell
10651 }
10652 };
10653 cells.push(cell);
10654 }
10655 let name = function.name.clone();
10656 // `.length` is the arity before any default or rest parameter, not the number
10657 // of slots a pattern parameter needs.
10658 let length = function.defined_args;
10659 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
10660 // function and an arrow function do not. A *method* also does not, but that is not
10661 // known here — the method is marked when the `[[HomeObject]]` is attached (see
10662 // `set_home_object`), which is the moment it becomes a method.
10663 let function_kind = function.kind;
10664 let constructible =
10665 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
10666 let code = Gc::new(self.heap, CompiledCode::new(*function));
10667 // A closure built inside an `eval` inherits the eval's view of the enclosing
10668 // bindings, so it can still read them once the eval has returned.
10669 let eval_scope = self
10670 .active_eval_scope
10671 .clone()
10672 .or_else(|| self.frame().env.eval_scope.clone());
10673 // A closure sees the variables a direct `eval` declared in the frame it was
10674 // created in — the ones declared before *and after* it, so the same object is
10675 // shared; only the phase bounds which of them are visible.
10676 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
10677 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
10678 let env = Gc::new(
10679 self.heap,
10680 ClosureEnv {
10681 cells,
10682 eval_scope,
10683 local_vars,
10684 local_phase,
10685 },
10686 );
10687 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
10688 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
10689 // the only thing that carries `Symbol.toStringTag`, so without it
10690 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
10691 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
10692 let proto = match function_kind {
10693 js_compile::bytecode::FunctionKind::AsyncGenerator => self
10694 .realm
10695 .async_generator_function_proto
10696 .clone()
10697 .or_else(|| self.realm.function_proto.clone().into()),
10698 js_compile::bytecode::FunctionKind::Generator => self
10699 .realm
10700 .generator_function_proto
10701 .clone()
10702 .or_else(|| self.realm.function_proto.clone().into()),
10703 js_compile::bytecode::FunctionKind::Async => self
10704 .realm
10705 .async_function_proto
10706 .clone()
10707 .or_else(|| self.realm.function_proto.clone().into()),
10708 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
10709 };
10710 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
10711 object.set_constructible(constructible);
10712 object.define(
10713 "length",
10714 Property::name_or_length(Value::Int(length as i32)),
10715 );
10716 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
10717 // that checks the own-property descriptor fails if the property is missing.
10718 object.define("name", Property::name_or_length(self.string(name)));
10719 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
10720 // when `[[Construct]]` is created, so a generator, an async function and an arrow
10721 // function have none of their own. Installing it unconditionally gave
10722 // `Array.fromAsync` (an async function) an own `prototype` property, which
10723 // `builtin.js` checks for absence.
10724 if constructible {
10725 self.install_function_prototype(&object);
10726 }
10727 Ok(Value::Object(object))
10728 }
10729
10730 // -- conversions used by the operators ----------------------------------
10731
10732 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
10733 // `+x` is `ToNumber`, which for a string parses it and for an object runs
10734 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
10735 // string, which then behaves differently in every later comparison.
10736 match value {
10737 Value::Int(_) | Value::Float(_) => Ok(value),
10738 other => Ok(Value::Float(self.to_js_number(&other)?)),
10739 }
10740 }
10741
10742 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
10743 ///
10744 /// Returns the *converted* old value and the new one, because the two callers need
10745 /// different halves: `++x` yields the new value, while `x++` yields the old one and
10746 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
10747 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
10748 /// boolean.
10749 ///
10750 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
10751 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
10752 /// a bigint algorithm then ran exactly once.
10753 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
10754 if let Value::BigInt(big) = &value {
10755 let one = crate::bigint::BigInt::from_i64(1);
10756 let next = if up { big.add(&one) } else { big.sub(&one) };
10757 return Ok((value, self.bigint(next)));
10758 }
10759 let old = self.numeric(value)?;
10760 let new = if up {
10761 increment(old.clone())
10762 } else {
10763 decrement(old.clone())
10764 };
10765 Ok((old, new))
10766 }
10767
10768 fn numeric(&mut self, value: Value) -> JsResult<Value> {
10769 // `ToNumber` on an object runs `ToPrimitive` first, which is how
10770 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
10771 // heard at all. Reading the object's own tag instead (`other.to_number()`)
10772 // turned the whole operand into `NaN` and swallowed the exception.
10773 match value {
10774 Value::Int(_) | Value::Float(_) => Ok(value),
10775 other => Ok(Value::Float(self.to_js_number(&other)?)),
10776 }
10777 }
10778
10779 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
10780 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
10781 match value {
10782 Value::BigInt(big) => Ok((**big).clone()),
10783 // The reference words this the same way for every operator, so a failing
10784 // script reads identically; the operator itself adds nothing a caller can use.
10785 _ => Err(Signal::Throw(
10786 self.make_error("TypeError", "cannot convert bigint to number"),
10787 )),
10788 }
10789 }
10790
10791 /// Arithmetic where at least one operand is a `BigInt`.
10792 ///
10793 /// The two numeric types never mix, so a bigint paired with anything else is an error
10794 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
10795 /// that the relational operators handle it separately.
10796 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10797 use Opcode::*;
10798 let a = self.bigint_operand(&left)?;
10799 let b = self.bigint_operand(&right)?;
10800 let result = match op {
10801 Add => a.add(&b),
10802 Sub => a.sub(&b),
10803 Mul => a.mul(&b),
10804 Div | Mod => {
10805 let Some((quotient, remainder)) = a.div_rem(&b) else {
10806 return Err(Signal::Throw(
10807 self.make_error("RangeError", "division by zero"),
10808 ));
10809 };
10810 if op == Div { quotient } else { remainder }
10811 }
10812 Pow => {
10813 let Some(value) = a.pow(&b) else {
10814 return Err(Signal::Throw(self.make_error(
10815 "RangeError",
10816 "BigInt exponent must be non-negative and not absurdly large",
10817 )));
10818 };
10819 value
10820 }
10821 And => a.bitand(&b),
10822 Or => a.bitor(&b),
10823 Xor => a.bitxor(&b),
10824 Shl | Sar => {
10825 // A shift count is a `BigInt` here, and both directions are exact; a
10826 // negative count would be the other direction, which the spec forbids.
10827 let Some(count) = b.to_i64() else {
10828 return Err(Signal::Throw(
10829 self.make_error("RangeError", "BigInt shift count is too large"),
10830 ));
10831 };
10832 if count < 0 {
10833 return Err(Signal::Throw(self.make_error(
10834 "RangeError",
10835 "BigInt shift count must be non-negative",
10836 )));
10837 }
10838 if op == Shl {
10839 a.shl(count as u64)
10840 } else {
10841 a.shr(count as u64)
10842 }
10843 }
10844 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
10845 _ => {
10846 return Err(Signal::Throw(self.make_error(
10847 "TypeError",
10848 "BigInts have no unsigned right shift, use >> instead",
10849 )));
10850 }
10851 };
10852 Ok(self.bigint(result))
10853 }
10854
10855 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
10856 ///
10857 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
10858 /// is on the mathematical values, and nothing is rounded first.
10859 /// `<`, `<=`, `>`, `>=`.
10860 ///
10861 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
10862 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
10863 /// It is a `?`-returning function for exactly that reason: an object operand can run
10864 /// script, and script can throw. The old version compared `to_number` of the raw
10865 /// values, which answered `false` for every object instead of calling `valueOf` —
10866 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
10867 /// never ran.
10868 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10869 // The hot arm first: `i < n` with both sides already integers. No conversion, no
10870 // call, nothing that can throw.
10871 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10872 let ordering = Some(left.cmp(right));
10873 return Ok(ordering_answer(op, ordering));
10874 }
10875 // Anything that can run script has to be converted first, in this order.
10876 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
10877 {
10878 (
10879 self.to_primitive(left, Hint::Number)?,
10880 self.to_primitive(right, Hint::Number)?,
10881 )
10882 } else {
10883 (left, right)
10884 };
10885 let ordering = match (&left, &right) {
10886 // The loop condition `i < n` is integer against integer, and it runs once
10887 // per iteration of every loop in every program. Without this arm it took the
10888 // `to_number` path twice, which is a `match` plus a conversion each.
10889 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
10890 (Value::String(a), Value::String(b)) => {
10891 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
10892 }
10893 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
10894 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
10895 // is true even though `2.5` has no bigint form.
10896 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
10897 let b = other.to_number();
10898 if b.is_nan() {
10899 None
10900 } else {
10901 compare_bigint_and_f64(a, b)
10902 }
10903 }
10904 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
10905 let a = other.to_number();
10906 if a.is_nan() {
10907 None
10908 } else {
10909 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
10910 }
10911 }
10912 _ => left.to_number().partial_cmp(&right.to_number()),
10913 };
10914 Ok(ordering_answer(op, ordering))
10915 }
10916
10917 fn binary_add(&mut self) -> JsResult<()> {
10918 let right = self.pop();
10919 let left = self.pop();
10920 // Two integers add without any of the machinery below: no `ToPrimitive` (an
10921 // `Int` is already primitive), no string check, no bigint check, no allocation.
10922 // `x += 1` in a loop is the single most common instruction sequence in real
10923 // script, and it used to walk every one of those checks before reaching the
10924 // same `checked_add`.
10925 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10926 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
10927 return Ok(());
10928 }
10929 let left = self.primitive_of(left)?;
10930 let right = self.primitive_of(right)?;
10931 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
10932 // that check comes before the bigint one: `"" + 1n` is a string, not a
10933 // mixed-type error.
10934 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
10935 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
10936 // `TypeError`, the one place a symbol and a string do not mix.
10937 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
10938 // between a copy and a rope from their lengths, and a rope is what turns
10939 // `text += "abc"` in a loop from quadratic into linear.
10940 if let (Value::String(left), Value::String(right)) = (&left, &right) {
10941 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
10942 // reports as `InternalError: string too long`.
10943 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
10944 return Err(Signal::Throw(
10945 self.make_error("InternalError", "string too long"),
10946 ));
10947 };
10948 self.push(Value::String(Gc::new(self.heap, joined)));
10949 return Ok(());
10950 }
10951 // At least one operand was not a string, so `ToString` it. This rejects a
10952 // symbol, which is the one place a symbol and a string do not mix.
10953 let left = self.checked_to_wtf8(&left)?;
10954 let right = self.checked_to_wtf8(&right)?;
10955 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
10956 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
10957 let text = left.concat(&right);
10958 self.push(self.string_wtf8(text));
10959 return Ok(());
10960 }
10961 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
10962 // not a conversion.
10963 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
10964 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
10965 self.push(value);
10966 return Ok(());
10967 }
10968 let left = self.numeric(left)?;
10969 let right = self.numeric(right)?;
10970 self.push(add_numbers(left, right));
10971 Ok(())
10972 }
10973
10974 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
10975 self.to_primitive(value, Hint::Default)
10976 }
10977
10978 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
10979 ///
10980 /// The order depends on the hint: the "number" order tries `valueOf` first and
10981 /// `toString` second, the "string" order the other way round, and the default
10982 /// hint uses the number order. A result that is still an object is a `TypeError`,
10983 /// because no built-in `valueOf`/`toString` returns one.
10984 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
10985 let Value::Object(object) = &value else {
10986 return Ok(value);
10987 };
10988 // A Date overrides the default hint to mean "string", which is what
10989 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
10990 // this, `"" + new Date()` would print the milliseconds, not the date.
10991 let hint = if hint == Hint::Default && is_date_object(self, object) {
10992 Hint::String
10993 } else {
10994 hint
10995 };
10996 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
10997 // handed the hint as a string. This is the hook a Date uses for its default hint
10998 // and a script uses to take over conversion entirely.
10999 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
11000 if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
11001 if !function.is_callable() {
11002 return Err(self.type_error("Symbol.toPrimitive is not a function"));
11003 }
11004 let hint = match hint {
11005 Hint::String => "string",
11006 Hint::Number => "number",
11007 Hint::Default => "default",
11008 };
11009 let hint = self.string(hint);
11010 let result = self.call_value(
11011 Value::Object(function),
11012 Value::Object(object.clone()),
11013 vec![hint],
11014 )?;
11015 if matches!(result, Value::Object(_)) {
11016 return Err(self.type_error("cannot convert object to primitive value"));
11017 }
11018 return Ok(result);
11019 }
11020 let order: [&str; 2] = match hint {
11021 Hint::String => ["toString", "valueOf"],
11022 Hint::Number | Hint::Default => ["valueOf", "toString"],
11023 };
11024 let receiver = object.clone();
11025 for method in order {
11026 if let Some(function) = self.get_property(&receiver, method)?
11027 && matches!(&function, Value::Object(object) if object.is_callable())
11028 {
11029 let result =
11030 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
11031 if !matches!(result, Value::Object(_)) {
11032 return Ok(result);
11033 }
11034 }
11035 }
11036 Err(self.type_error("cannot convert object to primitive value"))
11037 }
11038
11039 /// `ToString` with the object case going through `ToPrimitive`.
11040 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
11041 if matches!(value, Value::Object(_)) {
11042 let primitive = self.to_primitive(value.clone(), Hint::String)?;
11043 return Ok(primitive.to_js_string());
11044 }
11045 Ok(value.to_js_string())
11046 }
11047
11048 /// `ToString` that keeps the string's code units instead of flattening them.
11049 ///
11050 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
11051 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
11052 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
11053 if matches!(value, Value::Symbol(_)) {
11054 return Err(Signal::Throw(
11055 self.make_error("TypeError", "cannot convert symbol to string"),
11056 ));
11057 }
11058 // An object runs `ToPrimitive` first, which may itself produce a symbol.
11059 let value = self.to_primitive(value.clone(), Hint::String)?;
11060 match value {
11061 Value::Symbol(_) => Err(Signal::Throw(
11062 self.make_error("TypeError", "cannot convert symbol to string"),
11063 )),
11064 Value::String(text) => Ok(text.wtf8().clone()),
11065 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
11066 }
11067 }
11068
11069 /// `ToNumber` with the object case going through `ToPrimitive`.
11070 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
11071 let value = if matches!(value, Value::Object(_)) {
11072 self.to_primitive(value.clone(), Hint::Number)?
11073 } else {
11074 value.clone()
11075 };
11076 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
11077 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
11078 // `NaN` to stay total, and the operators check for the bigint themselves — but
11079 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
11080 // refuse, and answering `NaN` made them silently wrong instead.
11081 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
11082 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
11083 match value {
11084 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
11085 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
11086 other => Ok(other.to_number()),
11087 }
11088 }
11089
11090 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
11091 /// [`ElementType::write`].
11092 ///
11093 /// This is separated from the write because both conversions are observable script —
11094 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
11095 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
11096 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
11097 /// setters, and a plain `a[i] = v`.
11098 pub(crate) fn element_value(
11099 &mut self,
11100 element: crate::builtins::typedarray::ElementType,
11101 value: Value,
11102 ) -> JsResult<Value> {
11103 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
11104 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
11105 let primitive = match &value {
11106 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
11107 _ => value,
11108 };
11109 if element.is_bigint() {
11110 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
11111 Ok(Value::BigInt(Gc::new(self.heap, big)))
11112 } else {
11113 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
11114 Ok(Value::Float(self.to_js_number(&primitive)?))
11115 }
11116 }
11117
11118 /// `ToPropertyKey`: what a computed member access uses as its key.
11119 ///
11120 /// A symbol is returned as itself, never stringified — that is what keeps
11121 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
11122 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
11123 match value {
11124 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
11125 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
11126 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
11127 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
11128 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
11129 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
11130 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
11131 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
11132 other.to_js_string(),
11133 ))),
11134 },
11135 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
11136 }
11137 }
11138
11139 /// `ToPropertyKey` for the callers that can only use a string key.
11140 ///
11141 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
11142 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
11143 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
11144 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
11145 /// program continues with a value nobody asked for.
11146 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
11147 use crate::value::Wtf8;
11148 Ok(match value {
11149 // A string key keeps its code units. Going through a lossy `String` would make
11150 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
11151 Value::String(text) => text.wtf8().clone(),
11152 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
11153 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
11154 // falling back to its `ToString` would print `[object Object]`.
11155 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
11156 Value::String(text) => text.wtf8().clone(),
11157 other => Wtf8::new(other.to_js_string()),
11158 },
11159 other => Wtf8::new(other.to_js_string()),
11160 })
11161 }
11162
11163 // -- object operations used by instructions -----------------------------
11164
11165 /// Read `object[key]`, returning `undefined` when the property is missing.
11166 ///
11167 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
11168 /// primitive (looking through its prototype) as well as an object — which is what
11169 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
11170 /// argument needs too.
11171 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
11172 self.read_field_key(object, &PropertyKey::from(key))
11173 }
11174
11175 /// [`Interp::read_field`] with a key that may be a symbol.
11176 ///
11177 /// A symbol key never reaches the string shortcuts: a string's `length` and its
11178 /// indices are string properties, and a symbol named `length` is a different
11179 /// property that a string primitive cannot have.
11180 /// [`Interp::read_field_key`], with an inline cache in front of it.
11181 ///
11182 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
11183 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
11184 /// without this the engine walked the chain and compared ~40 property names on each
11185 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
11186 ///
11187 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
11188 /// missing property. Those answers depend on running code or on state the guard below
11189 /// does not cover, and a wrong answer here is far more expensive than a lookup.
11190 ///
11191 /// A hit is re-validated against the *whole* walked chain, not just the level that
11192 /// answered: the receiver and every prototype down to that level must still be the same
11193 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
11194 /// property-table *lengths* — which is what catches a property appearing on an
11195 /// intermediate prototype and shadowing the cached one.
11196 pub fn read_field_cached(
11197 &mut self,
11198 object: &Value,
11199 key: &PropertyKey,
11200 slot: usize,
11201 ) -> JsResult<Value> {
11202 let index = Self::field_cache_slot(object, key, slot);
11203 let Value::Object(target) = object else {
11204 return self.read_field_key(object, key);
11205 };
11206 if target.proxy_state().is_some() {
11207 return self.read_field_key(object, key);
11208 }
11209 if let Some(cached) = &self.field_cache[index]
11210 && cached.key == *key
11211 && let Some(value) = Self::cached_hit(target, cached)
11212 {
11213 return Ok(value);
11214 }
11215 let value = self.read_field_key(object, key)?;
11216 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
11217 Ok(value)
11218 }
11219
11220 /// Whether a cache entry still describes this lookup, and if so the value.
11221 ///
11222 /// The guard is the whole point of the entry: identity plus property-table length for
11223 /// every level walked. Re-checked per level rather than once at the receiving end,
11224 /// because a shadowing property can appear anywhere along the chain.
11225 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
11226 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
11227 // starts with: a clone is a reference-count bump and a drop, and for
11228 // `property:monomorphic` every single hit takes only this arm.
11229 let (weak, len) = cached.chain[0].as_ref()?;
11230 if !target.upgrades_to(weak) {
11231 return None;
11232 }
11233 if cached.level == 0 {
11234 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
11235 return target.cached_property_at(cached.index, &cached.key, *len);
11236 }
11237 if target.props_len() != *len {
11238 return None;
11239 }
11240 let mut level = 1;
11241 let mut current = target.proto()?;
11242 loop {
11243 let (weak, len) = cached.chain[level].as_ref()?;
11244 if !current.upgrades_to(weak) || current.props_len() != *len {
11245 return None;
11246 }
11247 if level == cached.level as usize {
11248 // The level that answered: the value is only reusable while the key is
11249 // still there and still a plain data property.
11250 return current.cached_data_property(cached.index, &cached.key);
11251 }
11252 current = current.proto()?;
11253 level += 1;
11254 }
11255 }
11256
11257 /// Build a cache entry for a lookup that just went through the slow path.
11258 ///
11259 /// Records the chain only when the answer came from a plain data property at a level
11260 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
11261 /// costs the next lookup the walk it would have cost anyway.
11262 fn record_field_lookup(
11263 target: &Gc<JsObject>,
11264 key: &PropertyKey,
11265 _value: Value,
11266 ) -> Option<FieldCache> {
11267 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
11268 [None, None, None];
11269 let mut current = target.clone();
11270 for level in 0..MAX_CACHED_CHAIN {
11271 chain[level] = Some((current.downgrade(), current.props_len()));
11272 if let Some((found, _)) = current.own_property_index(key) {
11273 // `own_property_index` declines an accessor and a hole, which is exactly
11274 // the set that must not be cached.
11275 return Some(FieldCache {
11276 key: key.clone(),
11277 index: found,
11278 level: level as u8,
11279 chain,
11280 });
11281 }
11282 current = current.proto()?;
11283 }
11284 None
11285 }
11286
11287 /// Which cache slot a lookup uses.
11288 ///
11289 /// Mixes the object's address, the name and the site, so that two properties of one
11290 /// object, and one property of two objects, land in different slots — which is what lets
11291 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
11292 /// other iteration.
11293 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
11294 let mut hash = match object {
11295 Value::Object(object) => object.address(),
11296 _ => 0,
11297 };
11298 hash = hash
11299 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
11300 .rotate_left(17)
11301 .wrapping_add(key.hash_code());
11302 hash = hash.wrapping_add(site.wrapping_mul(31));
11303 // The table is a power of two, so the low bits are the slot.
11304 hash & (FIELD_CACHE_SLOTS - 1)
11305 }
11306
11307 /// Read `key` from `object`, without the inline cache.
11308 ///
11309 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
11310 /// prototype chain, while the cached form answers an own data property from memory.
11311 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
11312 let text = key.as_str().unwrap_or("");
11313 let Value::Object(object) = object else {
11314 // Reading a property of `undefined`/`null` is the classic TypeError.
11315 if object.is_nullish() {
11316 return Err(Signal::Throw(self.make_error(
11317 "TypeError",
11318 &format!("cannot read property '{key}' of {}", object.to_js_string()),
11319 )));
11320 }
11321 // A string has `length` and index access without being boxed.
11322 if let Value::String(value) = object {
11323 if text == "length" {
11324 return Ok(Value::Int(value.utf16_len() as i32));
11325 }
11326 if let Some(index) = array_index(text) {
11327 return Ok(match value.wtf8().unit_at(index as usize) {
11328 Some(unit) => self.string_wtf8(unit),
11329 None => Value::Undefined,
11330 });
11331 }
11332 }
11333 // A property of a primitive is looked up on its prototype: this is what
11334 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
11335 let prototype = match object {
11336 Value::String(_) => self.realm.string_proto.clone(),
11337 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11338 Value::Bool(_) => self.realm.boolean_proto.clone(),
11339 // A symbol's methods live on `Symbol.prototype`, reached the same way —
11340 // `sym.description` reads through the prototype, not off the symbol.
11341 Value::Symbol(_) => self.realm.symbol_proto.clone(),
11342 // …and a bigint's on `BigInt.prototype`, which is how
11343 // `(255n).toString(16)` reaches its method.
11344 Value::BigInt(_) => self.realm.bigint_proto.clone(),
11345 _ => None,
11346 };
11347 if let Some(prototype) = prototype
11348 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
11349 {
11350 return Ok(value);
11351 }
11352 return Ok(Value::Undefined);
11353 };
11354 Ok(self
11355 .get_property_key(object, key)?
11356 .unwrap_or(Value::Undefined))
11357 }
11358
11359 /// The `#name` a private symbol stands for, for error messages.
11360 ///
11361 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
11362 /// was made from.
11363 fn private_name(symbol: &Value) -> Option<String> {
11364 match symbol {
11365 Value::Symbol(symbol) if symbol.is_private() => Some(
11366 symbol
11367 .description()
11368 .map(|text| text.to_string())
11369 .unwrap_or_default(),
11370 ),
11371 _ => None,
11372 }
11373 }
11374
11375 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
11376 ///
11377 /// Every private-field opcode takes the symbol the class stored in its own scope; a
11378 /// non-symbol here would be a compiler bug, and the reference guards it with
11379 /// `JS_ThrowTypeErrorNotASymbol`.
11380 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
11381 match symbol {
11382 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
11383 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
11384 }
11385 }
11386
11387 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
11388 ///
11389 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
11390 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
11391 /// would hit if the parser did not reject it first.
11392 fn define_private_field(
11393 &mut self,
11394 object: &Value,
11395 symbol: &Value,
11396 value: Value,
11397 ) -> JsResult<()> {
11398 let key = self.private_key(symbol)?;
11399 let Some(target) = object.as_object() else {
11400 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11401 };
11402 if !target.is_extensible() {
11403 return Err(Signal::Throw(
11404 self.make_error("TypeError", "object is not extensible"),
11405 ));
11406 }
11407 if target.own_property_key(&key).is_some() {
11408 let name = Self::private_name(symbol).unwrap_or_default();
11409 return Err(Signal::Throw(self.make_error(
11410 "TypeError",
11411 &format!("private class field '{name}' already exists"),
11412 )));
11413 }
11414 target.define_data_key(&key, value);
11415 Ok(())
11416 }
11417
11418 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
11419 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
11420 let key = self.private_key(symbol)?;
11421 let Some(target) = object.as_object() else {
11422 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11423 };
11424 match target.own_property_key(&key) {
11425 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
11426 None => {
11427 let name = Self::private_name(symbol).unwrap_or_default();
11428 Err(Signal::Throw(self.make_error(
11429 "TypeError",
11430 &format!("private class field '{name}' does not exist"),
11431 )))
11432 }
11433 }
11434 }
11435
11436 /// `JS_SetPrivateField`: the store half of the same rule.
11437 fn write_private_field(
11438 &mut self,
11439 object: &Value,
11440 symbol: &Value,
11441 value: Value,
11442 ) -> JsResult<()> {
11443 let key = self.private_key(symbol)?;
11444 let Some(target) = object.as_object() else {
11445 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11446 };
11447 if target.write_value_key(&key, value) {
11448 return Ok(());
11449 }
11450 let name = Self::private_name(symbol).unwrap_or_default();
11451 Err(Signal::Throw(self.make_error(
11452 "TypeError",
11453 &format!("private class field '{name}' does not exist"),
11454 )))
11455 }
11456
11457 /// The `in` half: does `object` have this private field?
11458 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
11459 ///
11460 /// The symbol is created once per class — the first `add_brand` on a given home object
11461 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
11462 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
11463 /// emit for the *instance* brand passes null because all it wants is the symbol.
11464 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
11465 let Some(home_object) = home.as_object() else {
11466 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11467 };
11468 let symbol = match home_object.private_brand() {
11469 Some(symbol) => symbol,
11470 None => {
11471 let symbol = Gc::new(
11472 self.heap,
11473 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
11474 );
11475 home_object.set_private_brand(symbol.clone());
11476 symbol
11477 }
11478 };
11479 let Some(target) = object.as_object() else {
11480 // Not an object: nothing to brand. The reference does the same, and `undefined`
11481 // here would otherwise turn a field initialiser into a TypeError.
11482 return Ok(());
11483 };
11484 if !target.is_extensible() {
11485 return Err(Signal::Throw(
11486 self.make_error("TypeError", "object is not extensible"),
11487 ));
11488 }
11489 if target.carries_brand(&symbol) {
11490 return Err(Signal::Throw(
11491 self.make_error("TypeError", "private method is already present"),
11492 ));
11493 }
11494 target.add_brand(symbol);
11495 Ok(())
11496 }
11497
11498 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
11499 ///
11500 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
11501 /// decides whether to throw.
11502 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
11503 let Some(function) = function.as_object() else {
11504 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11505 };
11506 let Some(home) = function.home_object() else {
11507 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11508 };
11509 let Some(brand) = home.private_brand() else {
11510 return Err(Signal::Throw(
11511 self.make_error("TypeError", "expecting <brand> private field"),
11512 ));
11513 };
11514 Ok(object.carries_brand(&brand))
11515 }
11516
11517 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
11518 let Value::Object(object) = object else {
11519 return Err(Signal::Throw(self.make_error(
11520 "TypeError",
11521 &format!("cannot set property '{key}' of {}", object.to_js_string()),
11522 )));
11523 };
11524 // The write half of the property inline cache, in effect: an own, writable,
11525 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
11526 // decide — no prototype walk (an own property shadows the chain before a setter
11527 // there could matter), no extensibility check (the object already has the key),
11528 // and no `[[DefineOwnProperty]]`.
11529 //
11530 // `this.value = …` inside a method is the whole write side of
11531 // `property:method-call`, and it was reaching `set_property_with_key` with its
11532 // proxy test, its typed-array test, its array-index test and finally a linear
11533 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
11534 //
11535 // Every disqualifier is checked here: a proxy traps the set, an array index and
11536 // `length` live outside the property table, and a typed array's element is stored
11537 // through its view's element type.
11538 if object.proxy_state().is_none()
11539 && !object.is_array()
11540 && object.typed_array_element_type().is_none()
11541 && object.write_value_key(key, value.clone())
11542 {
11543 return Ok(());
11544 }
11545 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
11546 let on_failure = if self.frame().code.code.strict {
11547 DeleteFailure::Throw
11548 } else {
11549 DeleteFailure::Ignore
11550 };
11551 self.set_property_with_key(object, key, value, on_failure)
11552 }
11553
11554 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
11555 ///
11556 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
11557 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
11558 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
11559 /// `Number.parseInt(sym)` — so those callers use this instead.
11560 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
11561 if matches!(value, Value::Symbol(_)) {
11562 return Err(Signal::Throw(
11563 self.make_error("TypeError", "cannot convert symbol to string"),
11564 ));
11565 }
11566 // An object runs `ToPrimitive` first, which may itself produce a symbol —
11567 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
11568 let value = self.to_primitive(value.clone(), Hint::String)?;
11569 if matches!(value, Value::Symbol(_)) {
11570 return Err(Signal::Throw(
11571 self.make_error("TypeError", "cannot convert symbol to string"),
11572 ));
11573 }
11574 Ok(value.to_js_string())
11575 }
11576
11577 /// `ToPropertyKey` for a builtin that takes a key argument.
11578 ///
11579 /// Fallible: a key whose `toString` throws has to propagate that error, both for
11580 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
11581 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
11582 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
11583 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
11584 self.propkey(value)
11585 }
11586
11587 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
11588 ///
11589 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
11590 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
11591 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
11592 /// `RangeError` — and why this cannot be a plain `ToNumber`.
11593 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
11594 let number = match value {
11595 Value::Int(number) => *number as f64,
11596 Value::Float(number) => *number,
11597 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
11598 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
11599 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
11600 // reference answers 0.
11601 Value::Null | Value::Bool(_) => value.to_number(),
11602 _ => {
11603 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
11604 match primitive {
11605 Value::Int(number) => number as f64,
11606 Value::Float(number) => number,
11607 other => {
11608 // `ToString` then `ToNumber`, so a string length goes through the
11609 // full numeric-literal grammar: `"0x00B"` is 11 and `" 5 "` is 5.
11610 // `Value::to_number` on the string already implements exactly that.
11611 let text = self.to_js_string(&other)?;
11612 crate::value::string_to_number(&text)
11613 }
11614 }
11615 }
11616 };
11617 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
11618 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
11619 // is a `RangeError`, not `0`.
11620 if !number.is_finite()
11621 || number.fract() != 0.0
11622 || !(0.0..=u32::MAX as f64).contains(&number)
11623 {
11624 return Err(self.range_error("invalid array length"));
11625 }
11626 Ok(number as u32)
11627 }
11628
11629 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
11630 /// `Object.getOwnPropertySymbols` put in their result array.
11631 pub fn key_value(&self, key: &PropertyKey) -> Value {
11632 match key {
11633 PropertyKey::String(text) => self.string_wtf8(text.clone()),
11634 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11635 }
11636 }
11637
11638 /// Fill in a String exotic object: `_value`, `length` and the index properties.
11639 ///
11640 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
11641 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
11642 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
11643 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
11644 /// the two paths had drifted; this is the one both now use.
11645 ///
11646 /// The indices are *code units*, so an astral character occupies two of them — the
11647 /// same rule `s.length` and `s[i]` follow.
11648 /// Give an already-created object the internal slot that makes it a wrapper of
11649 /// `value`, so the primitive's prototype methods work on it.
11650 ///
11651 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
11652 /// which are wrappers of their own type holding the empty value.
11653 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
11654 self.internal_set(object, "_value", value);
11655 }
11656
11657 pub(crate) fn init_string_wrapper(
11658 &mut self,
11659 object: &Gc<JsObject>,
11660 text: &Gc<crate::value::JsString>,
11661 ) {
11662 object.define(
11663 "length",
11664 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
11665 );
11666 for index in 0..text.utf16_len() {
11667 if let Some(unit) = text.wtf8().unit_at(index) {
11668 object.define(
11669 &index.to_string(),
11670 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
11671 Property::with_attributes(self.string_wtf8(unit), false, true),
11672 );
11673 }
11674 }
11675 object.define_key(
11676 &self.internal_slot("_value"),
11677 Property::with_attributes(Value::String(text.clone()), false, false),
11678 );
11679 }
11680
11681 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
11682 ///
11683 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
11684 /// throws. The wrapper carries its primitive in `_value` — the same slot
11685 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
11686 /// on a boxed value no constructor ever built.
11687 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
11688 let (prototype, primitive) = match value {
11689 Value::Object(object) => return Ok(object.clone()),
11690 Value::String(text) => {
11691 let object = self.new_object(self.realm.string_proto.clone());
11692 self.init_string_wrapper(&object, text);
11693 return Ok(object);
11694 }
11695 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
11696 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
11697 // A symbol and a bigint box into wrappers whose methods live on
11698 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
11699 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
11700 // branch below instead produced an object with *no* prototype, so those
11701 // methods were unreachable on a box.
11702 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
11703 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
11704 Value::Undefined | Value::Null => {
11705 return Err(Signal::Throw(self.make_error(
11706 "TypeError",
11707 &format!("cannot convert {} to object", value.to_js_string()),
11708 )));
11709 }
11710 _ => (None, value.clone()),
11711 };
11712 let object = self.new_object(prototype);
11713 self.internal_set(&object, "_value", primitive);
11714 Ok(object)
11715 }
11716
11717 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
11718 ///
11719 /// Split out for a reader that has to create the object *before* it knows what it wraps:
11720 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
11721 /// written before its primitive, so the placeholder has to exist first and be filled in
11722 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
11723 /// than a second in the deserialiser.
11724 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
11725 let prototype = match value {
11726 Value::String(_) => self.realm.string_proto.clone(),
11727 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11728 Value::Bool(_) => self.realm.boolean_proto.clone(),
11729 Value::Symbol(_) => self.realm.symbol_proto.clone(),
11730 Value::BigInt(_) => self.realm.bigint_proto.clone(),
11731 _ => {
11732 return Err(Signal::Throw(self.make_error(
11733 "TypeError",
11734 &format!("cannot box {}", value.to_js_string()),
11735 )));
11736 }
11737 };
11738 object.set_proto(prototype);
11739 if let Value::String(text) = value {
11740 self.init_string_wrapper(object, text);
11741 return Ok(());
11742 }
11743 self.internal_set(object, "_value", value.clone());
11744 Ok(())
11745 }
11746
11747 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
11748 ///
11749 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
11750 /// through the `Symbol` function object, so the registry is reachable as a method rather
11751 /// than only from `builtins::symbol`.
11752 pub fn symbol_for(&mut self, key: &str) -> Value {
11753 if let Some(existing) = self.realm.symbol_registry.get(key) {
11754 return existing.clone();
11755 }
11756 let symbol = crate::builtins::symbol::symbol_value(
11757 self,
11758 crate::value::JsSymbol::registered(key.to_string()),
11759 );
11760 self.realm
11761 .symbol_registry
11762 .insert(key.to_string(), symbol.clone());
11763 symbol
11764 }
11765
11766 /// `a == b`, the coercing comparison.
11767 ///
11768 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
11769 /// which is what makes `[] == ""` true: `[]` becomes `""` via
11770 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
11771 /// because the conversion is allowed to call script code, so the two primitive
11772 /// operands are handed back to it.
11773 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
11774 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
11775 return Ok(left.loose_equals(&right));
11776 }
11777 // `null == undefined` holds even though neither is an object.
11778 if matches!(left, Value::Undefined | Value::Null)
11779 && matches!(right, Value::Undefined | Value::Null)
11780 {
11781 return Ok(true);
11782 }
11783 if matches!(left, Value::Undefined | Value::Null)
11784 || matches!(right, Value::Undefined | Value::Null)
11785 {
11786 return Ok(false);
11787 }
11788 // Two objects compare by identity. Only an object *against a primitive* is
11789 // converted, which is why `{} == {}` is false while `[] == ""` is true.
11790 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
11791 return Ok(a.ptr_eq(b));
11792 }
11793 let left = self.to_primitive(left, Hint::Default)?;
11794 let right = self.to_primitive(right, Hint::Default)?;
11795 Ok(left.loose_equals(&right))
11796 }
11797
11798 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
11799 let Value::Object(object) = object else {
11800 return Err(Signal::Throw(
11801 self.make_error("TypeError", "cannot use 'in' on a non-object"),
11802 ));
11803 };
11804 let key = self.propkey(key)?;
11805 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
11806 // trap. One implementation, so an array's derived `length` and its inherited holes
11807 // cannot be right in one caller and wrong in another.
11808 self.has_own_or_inherited(object, &key)
11809 }
11810
11811 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
11812 ///
11813 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
11814 /// whole reason the operator is a hook rather than a prototype walk.
11815 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11816 if let Value::Object(function) = constructor {
11817 let key = self.realm.well_known_key(WellKnown::HasInstance);
11818 let method = self.get_property_key(function, &key)?;
11819 if let Some(method) = method
11820 && !matches!(method, Value::Undefined)
11821 {
11822 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
11823 return Ok(answer.to_boolean());
11824 }
11825 }
11826 self.instance_of(object, constructor)
11827 }
11828
11829 /// `OrdinaryHasInstance`: the prototype walk on its own.
11830 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11831 self.instance_of(object, constructor)
11832 }
11833
11834 /// `IsArray`: an array, or a proxy whose target is one.
11835 ///
11836 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
11837 /// makes `Array.isArray(new Proxy([], {}))` true.
11838 pub fn is_array_value(&self, value: &Value) -> bool {
11839 match value {
11840 Value::Object(object) => {
11841 if let Some(state) = object.proxy_state() {
11842 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
11843 }
11844 object.is_array()
11845 }
11846 _ => false,
11847 }
11848 }
11849
11850 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
11851 ///
11852 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
11853 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
11854 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
11855 /// see [`Interp::enqueue_job_function`].
11856 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
11857 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
11858 // the handler is reported rather than lost — the same reason a `then` reaction needs a
11859 // promise to settle.
11860 let promise = self.new_promise();
11861 self.fulfill_promise(&promise, Value::Undefined);
11862 self.jobs.push_back(Job::Reaction {
11863 handler: Some(function),
11864 argument: Value::Undefined,
11865 rejected: false,
11866 promise,
11867 });
11868 Ok(())
11869 }
11870
11871 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11872 let Value::Object(target) = object else {
11873 return Ok(false);
11874 };
11875 let Value::Object(function) = constructor else {
11876 return Err(Signal::Throw(self.make_error(
11877 "TypeError",
11878 "right-hand side of 'instanceof' is not callable",
11879 )));
11880 };
11881 let prototype = self.get_property(function, "prototype")?;
11882 let Some(Value::Object(prototype)) = prototype else {
11883 return Ok(false);
11884 };
11885 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
11886 // which is also what makes `proxyOfInstance instanceof C` work.
11887 let mut current = Some(target.clone());
11888 while let Some(object) = current {
11889 if object.ptr_eq(&prototype) {
11890 return Ok(true);
11891 }
11892 current = self.object_prototype_of(&object)?;
11893 }
11894 Ok(false)
11895 }
11896
11897 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
11898 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
11899 if let Some(proto) = self.proxy_get_prototype_of(object)? {
11900 return Ok(proto);
11901 }
11902 if let Some(exotic) = object.exotic()
11903 && let Some(proto) = exotic.get_prototype(self, object)?
11904 {
11905 return Ok(proto);
11906 }
11907 Ok(object.proto())
11908 }
11909
11910 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
11911 pub fn object_set_prototype_of(
11912 &mut self,
11913 object: &Gc<JsObject>,
11914 proto: Option<Gc<JsObject>>,
11915 ) -> JsResult<bool> {
11916 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
11917 return Ok(answer);
11918 }
11919 if let Some(exotic) = object.exotic()
11920 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
11921 {
11922 return Ok(answer);
11923 }
11924 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
11925 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
11926 // inheriting from itself, which every later prototype walk then had to defend
11927 // against — and `Reflect.setPrototypeOf` reported success for an operation the
11928 // language says is impossible.
11929 if let Some(proto) = &proto {
11930 let mut current = Some(proto.clone());
11931 let mut guard = 0;
11932 while let Some(node) = current {
11933 if node.ptr_eq(object) {
11934 return Err(Signal::Throw(
11935 self.make_error("TypeError", "circular prototype chain"),
11936 ));
11937 }
11938 guard += 1;
11939 if guard > 1000 {
11940 break;
11941 }
11942 current = node.proto();
11943 }
11944 }
11945 object.set_proto(proto);
11946 Ok(true)
11947 }
11948
11949 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
11950 ///
11951 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
11952 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
11953 /// already one.
11954 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
11955 // An integer-indexed exotic object answers from `IsValidIntegerIndex` alone
11956 // (§10.4.5.4 step 1.b.i) — the prototype chain is *not* consulted for a canonical
11957 // numeric index. That is observable: a view that has been resized out of bounds
11958 // has no indices, and `2 in view` must then be `false` even when
11959 // `Object.getPrototypeOf(view)[2]` exists. Falling through to the chain answered
11960 // `true`, which is what `TypedArray/out-of-bounds-behaves-like-detached` catches.
11961 // A proxy is excluded because it has no `[[ViewedArrayBuffer]]` slot of its own.
11962 if object.typed_array_parts().is_some()
11963 && object.proxy_state().is_none()
11964 && let Some(index) = key.as_str().and_then(array_index)
11965 {
11966 return Ok(object
11967 .typed_array_length()
11968 .is_some_and(|length| (index as usize) < length));
11969 }
11970 let mut current = Some(object.clone());
11971 // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
11972 let mut guard = 0;
11973 while let Some(node) = current {
11974 guard += 1;
11975 if guard > 1000 {
11976 return Ok(false);
11977 }
11978 let own = self.object_get_own_property(&node, key)?;
11979 if own.is_some() {
11980 return Ok(true);
11981 }
11982 current = self.object_prototype_of(&node)?;
11983 }
11984 Ok(false)
11985 }
11986
11987 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
11988 ///
11989 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
11990 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
11991 /// boolean as well, and it needs the receiver to be the one the caller named.
11992 pub fn set_property_with_key_receiver(
11993 &mut self,
11994 object: &Gc<JsObject>,
11995 key: &PropertyKey,
11996 value: Value,
11997 receiver: Option<&Value>,
11998 on_failure: DeleteFailure,
11999 ) -> JsResult<bool> {
12000 let receiver = receiver
12001 .cloned()
12002 .unwrap_or_else(|| Value::Object(object.clone()));
12003 if object.proxy_state().is_some() {
12004 return match self.proxy_set(object, key, value, &receiver)? {
12005 Some(accepted) => Ok(accepted),
12006 None => Ok(true),
12007 };
12008 }
12009 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
12010 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
12011 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
12012 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
12013 if object.typed_array_element_type().is_some()
12014 && key.as_str().and_then(array_index).is_some()
12015 {
12016 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
12017 self.set_property_with_key_receiver_aware(object, key, value, on_failure, same)?;
12018 return Ok(true);
12019 }
12020 // An own accessor, or one found up the chain, receives the call with `receiver` as
12021 // `this` — which is the whole reason this variant exists.
12022 if let Some(setter) = self.lookup_setter(object, key)? {
12023 self.call_value(setter, receiver, vec![value])?;
12024 return Ok(true);
12025 }
12026 // Otherwise it is an ordinary create-or-write, which the plain path already does —
12027 // carrying the receiver comparison, which a typed array's element store can see.
12028 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
12029 self.set_property_with_key_receiver_aware(object, key, value, on_failure, same)?;
12030 Ok(true)
12031 }
12032
12033 /// The setter `key` resolves to, if it resolves to an accessor.
12034 fn lookup_setter(
12035 &mut self,
12036 object: &Gc<JsObject>,
12037 key: &PropertyKey,
12038 ) -> JsResult<Option<Value>> {
12039 let mut current = Some(object.clone());
12040 let mut guard = 0;
12041 while let Some(node) = current {
12042 guard += 1;
12043 if guard > 1000 {
12044 return Ok(None);
12045 }
12046 if let Some(property) = self.object_get_own_property(&node, key)? {
12047 if property.is_accessor() {
12048 return Ok(property.setter);
12049 }
12050 // A data property stops the walk: the store writes here, not further up.
12051 return Ok(None);
12052 }
12053 current = self.object_prototype_of(&node)?;
12054 }
12055 Ok(None)
12056 }
12057
12058 /// `[[IsExtensible]]`, with the proxy trap when there is one.
12059 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
12060 if let Some(answer) = self.proxy_is_extensible(object)? {
12061 return Ok(answer);
12062 }
12063 if let Some(exotic) = object.exotic()
12064 && let Some(answer) = exotic.is_extensible(self, object)?
12065 {
12066 return Ok(answer);
12067 }
12068 Ok(object.is_extensible())
12069 }
12070
12071 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
12072 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
12073 if let Some(answer) = self.proxy_prevent_extensions(object)? {
12074 return Ok(answer);
12075 }
12076 if let Some(exotic) = object.exotic()
12077 && let Some(answer) = exotic.prevent_extensions(self, object)?
12078 {
12079 return Ok(answer);
12080 }
12081 object.set_extensible(false);
12082 Ok(true)
12083 }
12084
12085 fn copy_properties(
12086 &mut self,
12087 target: &Value,
12088 source: &Value,
12089 exclusion: &Value,
12090 ) -> JsResult<()> {
12091 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
12092 // does contribute: its index properties are own, enumerable and writable, which
12093 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
12094 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
12095 // is a no-op.
12096 let Some(target) = target.as_object() else {
12097 return Ok(());
12098 };
12099 let source_object = match source {
12100 Value::Object(object) => object.clone(),
12101 Value::String(text) => {
12102 // Untaken keys are the string's indices, which are code units.
12103 for index in 0..text.utf16_len() {
12104 if let Some(unit) = text.wtf8().unit_at(index) {
12105 target.define_data(&index.to_string(), self.string_wtf8(unit));
12106 }
12107 }
12108 return Ok(());
12109 }
12110 _ => return Ok(()),
12111 };
12112 // An object *rest* element passes the keys already taken by the literal part as
12113 // an array of strings; a spread passes `null`, which excludes nothing. Only the
12114 // string keys of the exclusion array are meaningful, so an array is read by its
12115 // elements rather than by its own property names.
12116 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
12117 if let Value::Object(list) = exclusion
12118 && let Some(length) = list.array_length()
12119 {
12120 for index in 0..length {
12121 if let Some(value) = list.array_get(index) {
12122 excluded.push(self.propkey_of(&value)?);
12123 }
12124 }
12125 }
12126 let source = &source_object;
12127 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
12128 // Reading the property table directly made every spread of a proxy empty.
12129 let keys = self.object_own_property_keys(source)?;
12130 for as_key in keys {
12131 if as_key.is_symbol() {
12132 // A spread copies string-keyed properties only.
12133 continue;
12134 }
12135 if excluded.contains(&crate::value::Wtf8::new(
12136 as_key.as_str().unwrap_or_default(),
12137 )) {
12138 continue;
12139 }
12140 let enumerable = self
12141 .object_get_own_property(source, &as_key)?
12142 .is_some_and(|property| property.enumerable);
12143 if !enumerable {
12144 continue;
12145 }
12146 let value = self
12147 .get_property_key(source, &as_key)?
12148 .unwrap_or(Value::Undefined);
12149 target.define_data_key(&as_key, value);
12150 }
12151 Ok(())
12152 }
12153
12154 // -- iteration ---------------------------------------------------------
12155
12156 /// One object's own keys in enumeration order: array indices ascending, then the
12157 /// rest in insertion order.
12158 ///
12159 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
12160 /// whether the key is enumerable, which the caller resolves per key because an
12161 /// array's elements are not in the same store as its named properties.
12162 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
12163 // An index can arrive twice, once from the array's element store and once from
12164 // its property map, so the numeric keys go through a map that keeps the
12165 // enumerable answer if either source gave one.
12166 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
12167 for (key, enumerable) in &own {
12168 if let Some(index) = key.as_str().and_then(array_index) {
12169 let entry = numeric.entry(index).or_insert(false);
12170 *entry = *entry || *enumerable;
12171 }
12172 }
12173 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
12174 .into_iter()
12175 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
12176 .collect();
12177 ordered.extend(
12178 own.into_iter()
12179 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
12180 );
12181 ordered
12182 }
12183
12184 /// Build the key list a `for-in` loop walks.
12185 ///
12186 /// The order is the specification's: own properties before inherited ones, and
12187 /// within one object the integer-like keys in ascending numeric order ahead of the
12188 /// string keys in insertion order. A shadowed key only appears once, and a key that
12189 /// is a non-enumerable own property anywhere nearer is skipped entirely.
12190 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12191 let record = self.new_object(None);
12192 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
12193 // A proxy supplies its own key list, and — the reason this is not just another
12194 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
12195 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
12196 // descriptor there.
12197 if let Value::Object(object) = value
12198 && object.proxy_state().is_some()
12199 {
12200 let own = self
12201 .proxy_own_keys(object)?
12202 .unwrap_or_else(|| object.own_property_keys());
12203 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
12204 let mut numeric: Vec<u32> = Vec::new();
12205 let mut rest: Vec<PropertyKey> = Vec::new();
12206 for key in own {
12207 match key.as_str().and_then(array_index) {
12208 Some(index) => numeric.push(index),
12209 None => rest.push(key),
12210 }
12211 }
12212 numeric.sort_unstable();
12213 ordered.extend(
12214 numeric
12215 .into_iter()
12216 .map(|index| PropertyKey::from(index.to_string())),
12217 );
12218 ordered.extend(rest);
12219 for (index, key) in ordered.into_iter().enumerate() {
12220 record.define_data(&index.to_string(), self.key_value(&key));
12221 }
12222 record.define_data("__index", Value::Int(0));
12223 // The mark that makes `for_in_advance` re-ask the proxy per key.
12224 record.define_data("__proxy", Value::Object(object.clone()));
12225 return Ok(record);
12226 }
12227 if let Value::Object(object) = value {
12228 let mut chain = vec![object.clone()];
12229 chain.extend(object.chain());
12230 // Every own string key the walk has seen, enumerable or not. A
12231 // non-enumerable own property still hides a same-named enumerable one
12232 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
12233 // keeps `x` out of the loop even when the prototype has one.
12234 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
12235 for object in chain {
12236 let mut own: Vec<(crate::value::Wtf8, bool)> = object
12237 .own_property_keys()
12238 .iter()
12239 .filter_map(|key| key.as_wtf8().cloned())
12240 .map(|key| {
12241 let enumerable = object
12242 .own_property(&key.to_string_lossy())
12243 .map(|property| property.enumerable)
12244 .unwrap_or(false);
12245 (key, enumerable)
12246 })
12247 .collect();
12248 if let Some(length) = object.array_length() {
12249 own.retain(|(key, _)| key.as_str() != Some("length"));
12250 for index in 0..length {
12251 if object.array_get(index).is_some() {
12252 own.push((crate::value::Wtf8::new(index.to_string()), true));
12253 }
12254 }
12255 }
12256 // Integer-like keys come first in ascending order, then the rest in
12257 // insertion order — and the ordering is *per object*, not for the chain
12258 // as a whole: one pass over every collected key lifted a prototype's
12259 // `"4"` above the target's own `x`/`y`, which is not the order
12260 // `for…in` reports.
12261 for (key, enumerable) in Self::order_own_keys(own) {
12262 if visited.contains(&key) {
12263 continue;
12264 }
12265 visited.push(key.clone());
12266 if enumerable {
12267 keys.push(key);
12268 }
12269 }
12270 }
12271 }
12272 for (index, key) in keys.into_iter().enumerate() {
12273 record.define_data(&index.to_string(), self.string_wtf8(key));
12274 }
12275 record.define_data("__index", Value::Int(0));
12276 Ok(record)
12277 }
12278
12279 /// The next key of a `for…in` record, `None` when the loop is done.
12280 ///
12281 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
12282 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
12283 /// the loop reaches it, so a handler that stops reporting a key partway through drops
12284 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
12285 /// key the handler had already withdrawn.
12286 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
12287 let Value::Object(record) = record else {
12288 return Ok(None);
12289 };
12290 let proxy = record
12291 .own_property("__proxy")
12292 .and_then(|property| property.value);
12293 loop {
12294 let index = record
12295 .own_property("__index")
12296 .and_then(|property| property.value)
12297 .map(|value| value.to_int32())
12298 .unwrap_or(0);
12299 let Some(candidate) = record
12300 .own_property(&index.to_string())
12301 .and_then(|property| property.value)
12302 else {
12303 return Ok(None);
12304 };
12305 record.define_data("__index", Value::Int(index + 1));
12306 let text = candidate.to_js_string();
12307 let Some(Value::Object(proxy)) = &proxy else {
12308 return Ok(Some(text));
12309 };
12310 // The candidate is already a key string here, so the lookup does not need a
12311 // second `ToPropertyKey` conversion.
12312 let key = PropertyKey::from(text.as_str());
12313 let live = match self.proxy_get_own_property(proxy, &key)? {
12314 Some(descriptor) => descriptor,
12315 // Not a proxy after all, or it lost its state: fall back to the target.
12316 None => proxy.own_property_key(&key),
12317 };
12318 if live.is_some_and(|property| property.enumerable) {
12319 return Ok(Some(text));
12320 }
12321 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
12322 // next one.
12323 }
12324 }
12325
12326 /// The iterator for `for-of`: the object and its `next` method.
12327 ///
12328 /// An object that already carries a `next` method is used as it is — that is what
12329 /// `arr.values()` returns — and only arrays and strings get the built-in
12330 /// sequence iterator.
12331 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
12332 ///
12333 /// Callers that must choose between the iterable and the array-like protocol — the
12334 /// typed-array constructor is the main one — need to ask *before* committing to one.
12335 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
12336 let key = self.realm.well_known_key(WellKnown::Iterator);
12337 let method = self.read_field_key(value, &key)?;
12338 if matches!(method, Value::Undefined | Value::Null) {
12339 return Ok(false);
12340 }
12341 if !matches!(&method, Value::Object(object) if object.is_callable()) {
12342 return Err(Signal::Throw(
12343 self.make_error("TypeError", "Symbol.iterator is not callable"),
12344 ));
12345 }
12346 Ok(true)
12347 }
12348
12349 /// Collect everything an iterable yields.
12350 ///
12351 /// The cap is a guard against a generator that never ends: an unbounded collect would
12352 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
12353 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
12354 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
12355 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
12356 const MAX_ITEMS: usize = 1 << 24;
12357 let iterator = self.get_iterator(value)?;
12358 let mut out = Vec::new();
12359 loop {
12360 let (element, done) = self.iterator_step(&iterator)?;
12361 if done {
12362 return Ok(out);
12363 }
12364 out.push(element);
12365 if out.len() > MAX_ITEMS {
12366 // Close before refusing: the walk is being abandoned, so the iterator's
12367 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
12368 // unrun and a locked resource unreleased.
12369 self.close_iterator_after_throw(&iterator)?;
12370 return Err(self.range_error("iterable is too long to collect"));
12371 }
12372 }
12373 }
12374
12375 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
12376 ///
12377 /// A native constructor calls this once it has validated its arguments, which is the
12378 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
12379 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
12380 /// never reached. The prototype comes from `new.target` when it is an object, and from
12381 /// `default_proto` otherwise.
12382 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12383 let proto = self.ctor_prototype(default_proto)?;
12384 Ok(self.new_object(Some(proto)))
12385 }
12386
12387 /// An **array** whose prototype comes from `new.target`.
12388 ///
12389 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
12390 /// instance from `new.target.prototype`, and building a plain array instead made every
12391 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
12392 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
12393 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
12394 Ok(JsObject::array(self.heap, Some(proto), 0))
12395 }
12396
12397 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
12398 ///
12399 /// The `Option` form is for the constructors that build their instance in a helper which
12400 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
12401 /// from `await`'s internal promise, and only the first has a `new.target`.
12402 fn ctor_prototype_opt(
12403 &mut self,
12404 default_proto: Option<Gc<JsObject>>,
12405 ) -> JsResult<Option<Gc<JsObject>>> {
12406 let Some(target) = self.pending_new_target.clone() else {
12407 return Ok(default_proto);
12408 };
12409 let Some(target) = target.as_object().cloned() else {
12410 return Ok(default_proto);
12411 };
12412 match self.get_property(&target, "prototype")? {
12413 Some(Value::Object(proto)) => Ok(Some(proto)),
12414 _ => Ok(default_proto),
12415 }
12416 }
12417
12418 /// `new.target.prototype`, or `default_proto` when this is a plain call.
12419 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12420 let Some(target) = self.pending_new_target.clone() else {
12421 return Ok(default_proto);
12422 };
12423 let Some(target) = target.as_object().cloned() else {
12424 return Ok(default_proto);
12425 };
12426 match self.get_property(&target, "prototype")? {
12427 Some(Value::Object(proto)) => Ok(proto),
12428 _ => Ok(default_proto),
12429 }
12430 }
12431
12432 /// `CreateDataPropertyOrThrow(O, key, value)`.
12433 ///
12434 /// A *definition*, not an assignment. The difference is visible the moment the target
12435 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
12436 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
12437 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
12438 /// refused (`configurable: false`).
12439 ///
12440 /// The fast path exists because this is called once per element by `map`, `filter`,
12441 /// `slice` and friends: a plain array with no custom element descriptors and a writable
12442 /// `length` can store straight into its element vector.
12443 pub fn create_data_property_or_throw(
12444 &mut self,
12445 object: &Gc<JsObject>,
12446 index: usize,
12447 value: Value,
12448 ) -> JsResult<()> {
12449 if object.is_array()
12450 && object.elements_writable()
12451 && !object.has_element_descriptors()
12452 && object.is_extensible()
12453 && object.array_set(self.heap, index, value.clone())
12454 {
12455 return Ok(());
12456 }
12457 let key = PropertyKey::from(index.to_string());
12458 let property = Property {
12459 value: Some(value),
12460 writable: true,
12461 enumerable: true,
12462 configurable: true,
12463 ..Property::default()
12464 };
12465 // `CreateDataProperty` always asks for the default attributes, so it can only ever
12466 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
12467 // the rest. Checking here rather than inside `object_define_own_property` is
12468 // deliberate: that function receives a fully-populated `Property` and cannot tell
12469 // an omitted attribute from an explicit `false`, so the generic check it would need
12470 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
12471 // writable property (that cost eight `Object/defineProperty` tests).
12472 if let Some(existing) = self.object_get_own_property(object, &key)?
12473 && !existing.configurable
12474 {
12475 return Err(self.type_error("cannot create the property"));
12476 }
12477 if self.object_define_own_property(object, &key, property)? {
12478 return Ok(());
12479 }
12480 Err(self.type_error("cannot create the property"))
12481 }
12482
12483 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
12484 ///
12485 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
12486 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
12487 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
12488 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
12489 /// run user code and both can throw.
12490 pub fn species_constructor(
12491 &mut self,
12492 object: &Gc<JsObject>,
12493 default: Value,
12494 ) -> JsResult<Value> {
12495 let Some(constructor) = self.get_property(object, "constructor")? else {
12496 return Ok(default);
12497 };
12498 let constructor = match constructor {
12499 Value::Undefined => return Ok(default),
12500 Value::Object(constructor) => constructor,
12501 _ => return Err(self.type_error("constructor is not an object")),
12502 };
12503 let key = self.realm.well_known_key(WellKnown::Species);
12504 let species = self.get_property_key(&constructor, &key)?;
12505 match species {
12506 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
12507 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
12508 Some(_) => Err(self.type_error("species is not a constructor")),
12509 }
12510 }
12511
12512 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
12513 ///
12514 /// The result is an array of `length` holes whose prototype comes from
12515 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
12516 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
12517 /// is why the `IsArray` check is the first step and not an optimisation.
12518 pub fn array_species_create(
12519 &mut self,
12520 original: &Value,
12521 length: usize,
12522 ) -> JsResult<Gc<JsObject>> {
12523 let Some(object) = original.as_object().cloned() else {
12524 return Ok(self.new_array_of_length(length));
12525 };
12526 if !object.is_array() {
12527 return Ok(self.new_array_of_length(length));
12528 }
12529 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
12530 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
12531 let Some(constructor) = self.get_property(&object, "constructor")? else {
12532 return Ok(self.new_array_of_length(length));
12533 };
12534 let species = match constructor {
12535 Value::Undefined => return Ok(self.new_array_of_length(length)),
12536 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
12537 return Ok(self.new_array_of_length(length));
12538 }
12539 Value::Object(constructor) => {
12540 let key = self.realm.well_known_key(WellKnown::Species);
12541 match self.get_property_key(&constructor, &key)? {
12542 None | Some(Value::Undefined) | Some(Value::Null) => {
12543 return Ok(self.new_array_of_length(length));
12544 }
12545 Some(species) => species,
12546 }
12547 }
12548 _ => return Ok(self.new_array_of_length(length)),
12549 };
12550 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
12551 // that is merely callable is the `create-species-non-ctor` case.
12552 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
12553 return Err(self.type_error("species is not a constructor"));
12554 }
12555 let created = self.construct(species.clone(), species, vec![Value::Int(length as i32)])?;
12556 let Some(created) = created.as_object().cloned() else {
12557 return Err(self.type_error("species constructor did not answer an object"));
12558 };
12559 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
12560 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
12561 // object, and `create-species-with-non-writable-property` asserts exactly that.
12562 // The length is set for the array case; the generic case is the caller's
12563 // `Set(A, "length", …)`.
12564 if created.is_array() {
12565 created.array_set_length(self.heap, length);
12566 }
12567 Ok(created)
12568 }
12569
12570 /// Whether `object` is this realm's `%Array%`.
12571 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
12572 self.realm
12573 .array_constructor
12574 .as_ref()
12575 .is_some_and(|array| array.ptr_eq(object))
12576 }
12577
12578 /// A fresh `length`-hole array with the intrinsic prototype.
12579 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
12580 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
12581 array.array_set_length(self.heap, length);
12582 array
12583 }
12584
12585 /// Whether this call is a construction, i.e. `new.target` is defined.
12586 ///
12587 /// A native constructor receives `this = undefined` (it builds its own instance), so it
12588 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
12589 /// The native function currently executing, if any.
12590 pub fn current_native(&self) -> Option<Gc<JsObject>> {
12591 self.current_native.clone()
12592 }
12593
12594 /// Whether this call is a construction, i.e. `new.target` is defined.
12595 pub fn is_constructing(&self) -> bool {
12596 self.pending_new_target.is_some()
12597 }
12598
12599 /// The `TypeError` a constructor too primitive to have a wrapper raises.
12600 ///
12601 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
12602 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
12603 /// happens inside the native function, which is why the trace carries an
12604 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
12605 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
12606 /// constructor`, and an unnamed one reports the leading space of `" is not a
12607 /// constructor"` because the reference formats the empty name as it is.
12608 ///
12609 /// It is also the answer for a `new.target` that cannot be named at all — not a
12610 /// function, or a throwing `name` getter — where the reference falls back to the bare
12611 /// `not a constructor`.
12612 pub fn not_a_constructor_error(&mut self) -> Signal {
12613 let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
12614 self.not_a_constructor_error_for(target)
12615 }
12616
12617 /// The same `TypeError` for an explicit target, for the callers that check
12618 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
12619 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
12620 let target = match target {
12621 Value::Object(target) if target.is_callable() => target,
12622 _ => return self.type_error("not a constructor"),
12623 };
12624 let name = match self.get_property(&target, "name") {
12625 Ok(Some(value)) => value.to_js_string(),
12626 _ => return self.type_error("not a constructor"),
12627 };
12628 self.type_error(format!("{name} is not a constructor"))
12629 }
12630
12631 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
12632 ///
12633 /// True whenever `new.target` is not the callee itself, or when it has no usable
12634 /// `prototype` — the cases where reading the property is observable at all.
12635 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
12636 match &self.pending_new_target {
12637 Some(Value::Object(target)) => !target.ptr_eq(callee),
12638 Some(_) => true,
12639 None => false,
12640 }
12641 }
12642
12643 /// The symbol key for one of the engine's own hidden slots.
12644 ///
12645 /// Cached on the realm, so every object of a kind shares one key and a slot can be
12646 /// read back by name.
12647 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
12648 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
12649 return PropertyKey::Symbol(symbol.clone());
12650 }
12651 let symbol = Gc::new(
12652 self.heap,
12653 crate::value::JsSymbol::new(Some(name.to_string())),
12654 );
12655 self.realm
12656 .internal_slots
12657 .borrow_mut()
12658 .insert(name, Value::Symbol(symbol.clone()));
12659 PropertyKey::Symbol(symbol)
12660 }
12661
12662 /// Read a hidden slot, or `None` when the object has none of that name.
12663 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
12664 let slots = self.realm.internal_slots.borrow();
12665 let Value::Symbol(symbol) = slots.get(name)? else {
12666 return None;
12667 };
12668 object
12669 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
12670 .and_then(|property| property.value)
12671 }
12672
12673 /// Define a hidden slot.
12674 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
12675 let key = self.internal_slot(name);
12676 object.define_key(&key, Property::with_attributes(value, false, false));
12677 }
12678
12679 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
12680 ///
12681 /// The method is looked up on the value (through its prototype), called with no
12682 /// arguments, and its result becomes the iterator. A generator gets here through
12683 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
12684 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
12685 ///
12686 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
12687 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
12688 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
12689 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
12690 /// does, and a user-defined iterable works without a special case.
12691 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
12692 /// `Symbol.iterator`.
12693 ///
12694 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
12695 /// iterable is legal there, and each value it produces is simply already settled by
12696 /// the time the `await` around it runs.
12697 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12698 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
12699 let method = self.read_field_key(value, &async_key)?;
12700 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
12701 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
12702 // is *present but not callable* is a TypeError — it does not mean "try the other
12703 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
12704 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
12705 // guard is there to catch.
12706 let absent = matches!(method, Value::Undefined | Value::Null);
12707 if !absent {
12708 let Value::Object(object) = &method else {
12709 return Err(Signal::Throw(
12710 self.make_error("TypeError", "value is not iterable"),
12711 ));
12712 };
12713 if !object.is_callable() {
12714 return Err(Signal::Throw(
12715 self.make_error("TypeError", "value is not iterable"),
12716 ));
12717 }
12718 }
12719 if absent {
12720 return self.get_iterator(value);
12721 }
12722 let iterator = self.call_value(method, value.clone(), Vec::new())?;
12723 if !matches!(iterator, Value::Object(_)) {
12724 return Err(Signal::Throw(
12725 self.make_error("TypeError", "iterator is not an object"),
12726 ));
12727 }
12728 let next = self.read_field(&iterator, "next")?;
12729 Ok(Iterator {
12730 object: iterator,
12731 next,
12732 })
12733 }
12734
12735 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12736 let key = self.realm.well_known_key(WellKnown::Iterator);
12737 let method = self.read_field_key(value, &key)?;
12738 let Value::Object(function) = &method else {
12739 return Err(Signal::Throw(self.make_error(
12740 "TypeError",
12741 &format!("{} is not iterable", value.to_js_string()),
12742 )));
12743 };
12744 if !function.is_callable() {
12745 return Err(Signal::Throw(self.make_error(
12746 "TypeError",
12747 &format!("{} is not iterable", value.to_js_string()),
12748 )));
12749 }
12750 let iterator = self.call_value(method, value.clone(), Vec::new())?;
12751 // The spec requires an object here; a primitive iterator has no `next` to call
12752 // and would fail one step later with a confusing message.
12753 if !matches!(iterator, Value::Object(_)) {
12754 return Err(Signal::Throw(
12755 self.make_error("TypeError", "iterator is not an object"),
12756 ));
12757 }
12758 let next = self.read_field(&iterator, "next")?;
12759 Ok(Iterator {
12760 object: iterator,
12761 next,
12762 })
12763 }
12764
12765 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
12766 /// cannot replace it.
12767 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
12768 let method = self.read_field(&iterator.object, "return")?;
12769 if matches!(method, Value::Undefined | Value::Null) {
12770 return Ok(());
12771 }
12772 if !matches!(&method, Value::Object(object) if object.is_callable()) {
12773 return Err(self.type_error("iterator return is not a function"));
12774 }
12775 self.call_value(method, iterator.object.clone(), Vec::new())?;
12776 Ok(())
12777 }
12778
12779 /// One step of an internal iterator: the value and whether it is exhausted.
12780 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
12781 // A real iterator (`next` is a function) answers with a result object.
12782 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
12783 let result =
12784 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
12785 let Some(result) = result.as_object().cloned() else {
12786 return Err(self.type_error("iterator result is not an object"));
12787 };
12788 let done = self
12789 .get_property(&result, "done")?
12790 .is_some_and(|value| value.to_boolean());
12791 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
12792 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
12793 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
12794 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
12795 // made an unrelated `value` getter observable after the loop was over.
12796 if done {
12797 return Ok((Value::Undefined, true));
12798 }
12799 let value = self
12800 .get_property(&result, "value")?
12801 .unwrap_or(Value::Undefined);
12802 return Ok((value, false));
12803 }
12804 // An iterator whose `next` is not callable is treated as exhausted, which is
12805 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
12806 // that are not iterable at all.
12807 Ok((Value::Undefined, true))
12808 }
12809
12810 /// `[...iterable]`: append everything the iterator yields, and answer the next
12811 /// index.
12812 ///
12813 /// This goes through the same iterator machinery `for-of` uses rather than copying
12814 /// an array's elements, because a spread source is any iterable: a string spreads
12815 /// into its characters and an array iterator spreads into its results. Handling
12816 /// only arrays made `[..."ab"]` come out empty with no error at all.
12817 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
12818 let Some(target) = array.as_object().cloned() else {
12819 return Ok(0);
12820 };
12821 let start = target.array_length().unwrap_or(0);
12822 let mut added = 0;
12823 let iterator = self.get_iterator(iterable)?;
12824 loop {
12825 let (value, done) = self.iterator_step(&iterator)?;
12826 if done {
12827 break;
12828 }
12829 target.array_set(self.heap, start + added, value);
12830 added += 1;
12831 }
12832 Ok((start + added) as i32)
12833 }
12834
12835 /// How an uncaught exception is reported.
12836 ///
12837 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
12838 /// with `ToString` — `js_std_dump_error` is three lines that end in
12839 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
12840 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
12841 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
12842 ///
12843 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
12844 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
12845 /// `toString`"; it does call it, but only for objects of a class it does not know how
12846 /// to walk, and never for errors, arrays or plain objects.
12847 ///
12848 /// A printer that fails must not take the reporter down with it, so that case falls
12849 /// back to the `ToString` rendering.
12850 pub fn describe_exception(&mut self, value: &Value) -> String {
12851 match crate::print::sprint(self, value) {
12852 Ok(text) => text,
12853 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
12854 }
12855 }
12856
12857 /// The file name of whatever is running, innermost frame first.
12858 ///
12859 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
12860 /// innermost frame's file name, without distinguishing a module body from a plain
12861 /// script. `import()` uses it as the base for a relative specifier, which is why
12862 /// `import('./x.js')` inside a script resolves next to the script and not next to the
12863 /// process's working directory.
12864 pub fn script_or_module_name(&self) -> Option<String> {
12865 self.script_or_module_name_at(0)
12866 }
12867
12868 /// [`Interp::script_or_module_name`] `level` frames further out.
12869 ///
12870 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
12871 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
12872 /// frame without a file name is skipped rather than counted, because a native call
12873 /// pushes no frame of its own and so cannot be a level.
12874 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
12875 self.frames
12876 .iter()
12877 .rev()
12878 .filter_map(|frame| frame.code.code.filename.clone())
12879 .nth(level)
12880 }
12881
12882 /// The current call stack, formatted the way `qjs` prints `error.stack`.
12883 ///
12884 /// One ` at name (file:line:col)` line per active frame, innermost first. The
12885 /// position is the one recorded for the instruction each frame is stopped on, which
12886 /// is why the compiler builds a pc-to-position table per function: without it a
12887 /// trace could only name the function, not the line inside it.
12888 ///
12889 /// A frame whose code has no positions prints just `(file)`, matching the
12890 /// reference's output for stripped bytecode.
12891 pub fn stack_trace(&self) -> String {
12892 self.stack_trace_skipping(0)
12893 }
12894
12895 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
12896 fn stack_trace_skipping(&self, skip: usize) -> String {
12897 // One ordered list, innermost first, so `skip` counts the same thing whether the
12898 // frames it leaves out are native or bytecode. Indices rather than references: a
12899 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
12900 let depth = self.frames.len();
12901 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
12902 // A native entered while `at` bytecode frames were live was called *from* the
12903 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
12904 // entered at the current depth are therefore innermost of all.
12905 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
12906 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
12907 if *at == wanted {
12908 order.push((true, index));
12909 }
12910 }
12911 };
12912 push_natives(&mut order, depth);
12913 for index in (0..depth).rev() {
12914 order.push((false, index));
12915 push_natives(&mut order, index);
12916 }
12917 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
12918 // barrier. Natives entered at exactly the barrier depth are the eval entry point
12919 // itself (`evalScript (native)`), and the reference leaves those out too.
12920 if let Some(barrier) = self.trace_barriers.last().copied() {
12921 order.retain(|(is_native, index)| match is_native {
12922 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
12923 false => *index >= barrier,
12924 });
12925 }
12926
12927 let mut out = String::new();
12928 for (is_native, index) in order.into_iter().skip(skip) {
12929 match is_native {
12930 true => {
12931 out.push_str(" at ");
12932 let (native, _) = &self.native_frames[index];
12933 let name = native
12934 .own_property("name")
12935 .and_then(|property| property.value)
12936 .map(|value| value.to_js_string())
12937 .unwrap_or_default();
12938 out.push_str(&name);
12939 out.push_str(" (native)\n");
12940 }
12941 false => {
12942 let frame = &self.frames[index];
12943 let code = &frame.code.code;
12944 let file = code.filename.as_deref().unwrap_or("<input>");
12945 // The name comes from the function *object*, not from the compiled code:
12946 // an anonymous function expression is named by the property it is stored
12947 // in (`{valueOf: function(){}}`), which only the object knows.
12948 let bound_name = match &frame.callee {
12949 Value::Object(object) => {
12950 object
12951 .own_property("name")
12952 .and_then(|property| match property.value {
12953 Some(Value::String(text)) if !text.wtf8().is_empty() => {
12954 Some(text.to_string_lossy().into_owned())
12955 }
12956 _ => None,
12957 })
12958 }
12959 _ => None,
12960 };
12961 // No callee object means the body was entered by the host, so the
12962 // name has to come from the compiled code. Two cases differ:
12963 //
12964 // * an *unnamed* function of any kind — the reference reads the
12965 // `name` property, finds it empty, and prints `<anonymous>`;
12966 // * a *module* body, which has no `name` property at all: the
12967 // reference builds that function object with `js_closure2` and
12968 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
12969 // so a trace reaching it also prints `<anonymous>` — while a
12970 // *script* body prints `<eval>`, its `name`.
12971 let unnamed = code.name.is_empty() || code.module.is_some();
12972 out.push_str(" at ");
12973 match bound_name.as_deref() {
12974 Some(name) => out.push_str(name),
12975 None if unnamed => out.push_str("<anonymous>"),
12976 None => out.push_str(&code.name),
12977 }
12978 match code.position_at(frame.at as u32) {
12979 Some((line, column)) => {
12980 out.push_str(&format!(" ({file}:{line}:{column})\n"));
12981 }
12982 None => out.push_str(&format!(" ({file})\n")),
12983 }
12984 }
12985 }
12986 }
12987 out
12988 }
12989
12990 /// Give an anonymous function the name of the property it is stored in.
12991 ///
12992 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
12993 /// enumerable and not configurable, and a function that already has a real name
12994 /// keeps it.
12995 ///
12996 /// "Already named" means a *non-empty* name: every function object is created with
12997 /// a `name` of `""` so the property exists on all of them, and treating that empty
12998 /// string as a name left every anonymous function nameless — which is how a stack
12999 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
13000 /// `SetFunctionName`, for a name that came from source text.
13001 fn set_function_name(&mut self, function: &Value, name: &str) {
13002 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
13003 }
13004
13005 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
13006 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
13007 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
13008 let Value::Object(object) = function else {
13009 return;
13010 };
13011 // `SetFunctionName` applies to *functions* and classes only, and only when they are
13012 // anonymous. Without the callability guard, `{value: someObject}` renamed
13013 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
13014 // on the right-hand side of a property. That is how a `zipKeyed` result object
13015 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
13016 // has no `NamedEvaluation` at all.
13017 if !object.is_callable() {
13018 return;
13019 }
13020 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
13021 && !existing.wtf8().is_empty()
13022 {
13023 return;
13024 }
13025 let text = self.string_wtf8(name.clone());
13026 object.define("name", Property::name_or_length(text));
13027 }
13028
13029 // -- global declarations -----------------------------------------------
13030
13031 /// Declare a global binding, creating its reference cell.
13032 /// Declare a `var` or function global, whose home is the global object.
13033 ///
13034 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
13035 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
13036 /// such as `print`, or a redeclaration — is left alone.
13037 pub fn declare_var_global(&mut self, name: &str) {
13038 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
13039 // global object is exactly the leak `typeof my_var === "undefined"` after
13040 // `eval("var my_var=2")` rules out.
13041 if let Some(scope) = self.eval_scope.as_mut() {
13042 scope.entry(name.to_string()).or_insert(Value::Undefined);
13043 return;
13044 }
13045 // A sloppy direct eval declares into its *caller's* variable environment. Doing
13046 // this on the global object instead made `eval("var c = 1")` inside a parameter
13047 // list overwrite a global `c`, and made two calls to the same function share one
13048 // binding.
13049 if let Some(cell) = self.declare_eval_local(name) {
13050 cell.set(Value::Undefined);
13051 return;
13052 }
13053 let global = self.realm.global.clone();
13054 if global.own_property(name).is_some() {
13055 return;
13056 }
13057 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
13058 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
13059 // whole point of that trick and what lets `Object.defineProperty` reshape it
13060 // afterwards. `eval_scope` is `Some` while an eval is running.
13061 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
13062 global.define(
13063 name,
13064 Property {
13065 value: Some(Value::Undefined),
13066 writable: true,
13067 enumerable: true,
13068 configurable: from_eval,
13069 ..Property::default()
13070 },
13071 );
13072 }
13073
13074 /// Declare a *lexical* global binding, which starts in its dead zone.
13075 ///
13076 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
13077 /// global object and is created when its initialiser runs.
13078 pub fn declare_global(&mut self, name: &str, is_const: bool) {
13079 if is_const {
13080 self.realm.lexical_consts.insert(name.to_string());
13081 }
13082 if !self.realm.globals.contains_key(name) {
13083 // `Uninitialized` rather than `Undefined`: the binding exists but is not
13084 // readable until its initialiser runs, and that is what `let x` before
13085 // `x = 1` has to observe.
13086 let cell = self.new_cell(Value::Uninitialized);
13087 self.realm.globals.insert(name.to_string(), cell);
13088 self.realm.declared.push(name.to_string());
13089 }
13090 }
13091}
13092
13093/// The bytecode and environment of a function object, if it is a bytecode function.
13094///
13095/// Extracted before a call so no borrow of the object is held across it.
13096fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
13097 function.with(|data| match &data.kind {
13098 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
13099 _ => None,
13100 })
13101}
13102
13103/// A native call target, extracted before the call so no borrow is held.
13104enum NativeCall {
13105 Native(NativeFn),
13106 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
13107 /// not hold that object's `RefCell` borrow.
13108 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
13109 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
13110 Bound {
13111 target: Value,
13112 this: Value,
13113 leading: Vec<Value>,
13114 },
13115 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
13116 Revoker(crate::object::ProxyRef),
13117 /// A promise's `resolve`.
13118 PromiseResolve(Gc<JsObject>),
13119 /// A promise's `reject`.
13120 PromiseReject(Gc<JsObject>),
13121 /// The executor `NewPromiseCapability(C)` hands a user constructor.
13122 CapabilityExecutor {
13123 state: Gc<JsObject>,
13124 },
13125 /// One leg of a `then` that settles through a user capability.
13126 ThenShim {
13127 handler: Option<Value>,
13128 resolve: Value,
13129 reject: Value,
13130 fulfilled: bool,
13131 },
13132 /// One continuation of an `await`.
13133 AwaitResume {
13134 coroutine: Gc<JsObject>,
13135 promise: Gc<JsObject>,
13136 kind: ResumeKind,
13137 },
13138 /// One element of a `Promise` combinator settling.
13139 CombinatorSettle {
13140 state: Gc<JsObject>,
13141 index: usize,
13142 fulfilled: bool,
13143 },
13144 /// One of `Promise.prototype.finally`'s two shims.
13145 FinallyShim {
13146 callback: Option<Value>,
13147 fulfilled: bool,
13148 constructor: Value,
13149 },
13150 /// Settle a promise with a fixed outcome.
13151 SettlePromise {
13152 promise: Gc<JsObject>,
13153 value: Value,
13154 rejected: bool,
13155 },
13156 /// Continue an async generator after its `await` settled.
13157 GeneratorResume {
13158 generator: Gc<JsObject>,
13159 promise: Gc<JsObject>,
13160 kind: ResumeKind,
13161 },
13162 /// Read a module namespace's binding out of its cell.
13163 ModuleBinding(Gc<Cell>),
13164 /// Finish a completed async generator's `return(v)` once `v` has settled.
13165 CompletedReturn {
13166 generator: Gc<JsObject>,
13167 promise: Gc<JsObject>,
13168 rejected: bool,
13169 },
13170 /// Answer a pending async-generator method with `{value, done}`.
13171 YieldResult {
13172 generator: Gc<JsObject>,
13173 promise: Gc<JsObject>,
13174 done: bool,
13175 },
13176 /// One step of `AsyncDisposableStack.disposeAsync`.
13177 DisposeStep {
13178 remaining: Gc<JsObject>,
13179 promise: Gc<JsObject>,
13180 error: Value,
13181 rejected: bool,
13182 },
13183}
13184
13185/// What a store does when the object refuses the write.
13186#[derive(Clone, Copy, PartialEq, Eq)]
13187pub enum DeleteFailure {
13188 /// Raise a `TypeError`, which is what strict mode and every built-in does.
13189 Throw,
13190 /// Ignore the write, which is what a sloppy-mode assignment does.
13191 Ignore,
13192}
13193
13194/// Whether `object` is a `Date` instance, by the class tag it carries.
13195///
13196/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
13197/// builtins module depending on the interpreter's conversion order.
13198fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
13199 interp
13200 .internal_get(object, "_class")
13201 .is_some_and(|value| value.to_js_string() == "Date")
13202}
13203
13204/// Which type `ToPrimitive` prefers when it converts an object.
13205#[derive(Clone, Copy, PartialEq, Eq)]
13206pub enum Hint {
13207 /// The default hint, which behaves like [`Hint::Number`].
13208 Default,
13209 /// `Number(obj)` and the arithmetic operators.
13210 Number,
13211 /// `String(obj)` and `ToPropertyKey`.
13212 String,
13213}
13214
13215/// Which table a binding slot indexes, for the messages that name it.
13216#[derive(Clone, Copy)]
13217enum VarSlot {
13218 Loc,
13219 Closure,
13220}
13221
13222/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
13223fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
13224 Ok(this)
13225}
13226
13227/// An internal iterator: the sequence plus a cursor.
13228pub(crate) struct Iterator {
13229 pub(crate) object: Value,
13230 pub(crate) next: Value,
13231}
13232
13233/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
13234/// and plain `a` for a method.
13235///
13236/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
13237/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
13238/// reads `at get a (file:1:2)`.
13239/// The same prefixing, for a name that may hold an unpaired surrogate.
13240fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
13241 let prefix = match flags & 3 {
13242 1 => "get ",
13243 2 => "set ",
13244 _ => return key.clone(),
13245 };
13246 let mut units: Vec<u16> = prefix.encode_utf16().collect();
13247 units.extend_from_slice(&key.to_units());
13248 crate::value::Wtf8::from_units(&units)
13249}
13250
13251fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
13252 match flags & 3 {
13253 1 => format!("get {key}"),
13254 2 => format!("set {key}"),
13255 _ => key.to_string(),
13256 }
13257}
13258
13259/// Define a method or accessor property, per the `define_method` flag byte.
13260///
13261/// The low two bits pick value/getter/setter and bit 2 marks the property
13262/// enumerable.
13263///
13264/// A getter and a setter arrive as two separate `define_method` instructions, and the
13265/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
13266/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
13267/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
13268/// `JS_DefineProperty`, which leaves the other half alone.
13269fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
13270 let enumerable = flags & 4 != 0;
13271 let kind = flags & 3;
13272 let existing = object.own_property_key(key);
13273 let property = match kind {
13274 1 => Property {
13275 getter: Some(function),
13276 // The setter half, if this literal already defined one.
13277 setter: existing
13278 .filter(Property::is_accessor)
13279 .and_then(|p| p.setter),
13280 enumerable,
13281 configurable: true,
13282 ..Property::default()
13283 },
13284 2 => Property {
13285 getter: existing
13286 .filter(Property::is_accessor)
13287 .and_then(|p| p.getter),
13288 setter: Some(function),
13289 enumerable,
13290 configurable: true,
13291 ..Property::default()
13292 },
13293 _ => Property {
13294 value: Some(function),
13295 writable: true,
13296 enumerable,
13297 configurable: true,
13298 ..Property::default()
13299 },
13300 };
13301 object.define_key(key, property);
13302}
13303
13304// ---------------------------------------------------------------------------
13305// Operand decoding
13306// ---------------------------------------------------------------------------
13307
13308/// How `print` renders a value: the reference's `JS_PrintValue`.
13309///
13310/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
13311/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
13312/// The format is reproduced closely because the test suite compares output text:
13313///
13314/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
13315/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
13316/// * a cycle prints `[circular N]` with `N` the stack index of the object;
13317/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
13318/// end print as `<N empty item(s)>`;
13319/// * a string is quoted inside a container but raw at the top level, which is why
13320/// `print("x")` and `print(["x"])` differ.
13321pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
13322 // A string argument is printed raw: `js_print` converts it with `ToString`
13323 // instead of dumping it, and the quoting only appears inside a container.
13324 if let Value::String(text) = value {
13325 return text.to_string_lossy().into_owned();
13326 }
13327 let mut printer = Printer {
13328 interp,
13329 out: String::new(),
13330 stack: Vec::new(),
13331 };
13332 printer.value(value, 0);
13333 printer.out
13334}
13335
13336/// The internal class name an object carries, when it has one.
13337fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
13338 interp
13339 .internal_get(object, "_class")
13340 .map(|value| value.to_js_string())
13341}
13342
13343/// A string property, looked up the way `GetProperty` does: own first, then the
13344/// prototype chain. Needed because the print formatter holds the interpreter
13345/// immutably and so cannot run getters.
13346fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
13347 let mut current = Some(object.clone());
13348 // Bounded, because a prototype cycle would otherwise loop forever.
13349 for _ in 0..100 {
13350 let node = current?;
13351 if let Some(property) = node.own_property(name)
13352 && let Some(value) = property.value
13353 {
13354 return Some(value.to_js_string());
13355 }
13356 current = node.with(|data| data.proto.clone());
13357 }
13358 None
13359}
13360
13361/// The `JS_PrintValue` state: output, and the objects currently being printed.
13362struct Printer<'a, 'rt> {
13363 /// Kept for the class-name lookups that typed arrays and `Date` will need.
13364 #[allow(dead_code)]
13365 interp: &'a Interp<'rt>,
13366 out: String,
13367 stack: Vec<Gc<JsObject>>,
13368}
13369
13370impl Printer<'_, '_> {
13371 /// Depth past which a container is summarised by its class name.
13372 const MAX_DEPTH: usize = 2;
13373
13374 fn value(&mut self, value: &Value, level: usize) {
13375 match value {
13376 Value::Undefined
13377 | Value::Uninitialized
13378 | Value::Hole
13379 | Value::CatchOffset(_)
13380 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
13381 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
13382 // The printer writes a bigint the way the language spells one, so a dump is
13383 // unambiguous about which kind of number it is showing.
13384 Value::BigInt(big) => {
13385 self.out.push_str(&big.to_decimal_string());
13386 self.out.push('n');
13387 }
13388 Value::Null => self.out.push_str("null"),
13389 Value::Bool(true) => self.out.push_str("true"),
13390 Value::Bool(false) => self.out.push_str("false"),
13391 Value::Int(number) => self.out.push_str(&number.to_string()),
13392 Value::Float(number) => {
13393 self.out
13394 .push_str(&crate::value::number_to_string_for_print(*number));
13395 }
13396 Value::String(text) => self.print_string(&text.to_string_lossy()),
13397 Value::Object(object) => self.object(object, level),
13398 }
13399 }
13400
13401 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
13402 // A cycle is reported rather than followed; the index is where the object
13403 // already sits in the print stack, which is what the reference shows.
13404 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
13405 self.out.push_str(&format!("[circular {index}]"));
13406 return;
13407 }
13408 if object.is_callable() {
13409 let name = object
13410 .own_property("name")
13411 .and_then(|property| property.value)
13412 .map(|value| value.to_js_string())
13413 .unwrap_or_default();
13414 if name.is_empty() {
13415 self.out.push_str("[Function (anonymous)]");
13416 } else {
13417 self.out.push_str(&format!("[Function {name}]"));
13418 }
13419 return;
13420 }
13421 if level >= Self::MAX_DEPTH {
13422 let class = if object.is_array() { "Array" } else { "Object" };
13423 self.out.push_str(&format!("[{class}]"));
13424 return;
13425 }
13426 // `Date` and `Error` print as themselves rather than as bags of properties:
13427 // the ISO string, and `Name: message` followed by the trace.
13428 if let Some(class) = class_of(self.interp, object) {
13429 if class == "Date" {
13430 self.date(object);
13431 return;
13432 }
13433 if class == "Error" {
13434 self.error(object);
13435 return;
13436 }
13437 }
13438 self.stack.push(object.clone());
13439 if object.is_array() {
13440 self.array(object, level);
13441 } else {
13442 self.plain_object(object, level);
13443 }
13444 self.stack.pop();
13445 }
13446
13447 /// A Date prints as its ISO string; an invalid one falls through to the plain
13448 /// object form, the way the reference falls back when `toISOString` throws.
13449 fn date(&mut self, object: &Gc<JsObject>) {
13450 let value = self
13451 .interp
13452 .internal_get(object, "_date_value")
13453 .map(|value| value.to_number());
13454 match value.and_then(crate::builtins::date::iso_string) {
13455 Some(text) => self.out.push_str(&text),
13456 None => self.plain_object(object, 0),
13457 }
13458 }
13459
13460 /// `Name: message`, then the trace with its trailing newline removed.
13461 fn error(&mut self, object: &Gc<JsObject>) {
13462 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
13463 self.out.push_str(&name);
13464 if let Some(message) = inherited(object, "message")
13465 && !message.is_empty()
13466 {
13467 self.out.push_str(": ");
13468 self.out.push_str(&message);
13469 }
13470 if let Some(stack) = inherited(object, "stack") {
13471 self.out.push('\n');
13472 self.out.push_str(stack.trim_end_matches('\n'));
13473 }
13474 }
13475
13476 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
13477 let elements = object.array_elements().unwrap_or_default();
13478 self.out.push_str("[ ");
13479 // An interior hole means the array is "sparse": the reference prints those
13480 // as `index: value` pairs and says nothing about the holes themselves, while
13481 // a hole run at the end becomes a single `<N empty items>` note.
13482 let last_present = elements
13483 .iter()
13484 .rposition(|value| !matches!(value, Value::Hole));
13485 let has_interior_hole = match last_present {
13486 Some(last) => elements[..last]
13487 .iter()
13488 .any(|value| matches!(value, Value::Hole)),
13489 None => false,
13490 };
13491 let mut first = true;
13492 if has_interior_hole {
13493 let mut index = 0;
13494 while index < elements.len() {
13495 let value = &elements[index];
13496 if matches!(value, Value::Hole) {
13497 index += 1;
13498 continue;
13499 }
13500 if !first {
13501 self.out.push_str(", ");
13502 }
13503 first = false;
13504 self.out.push_str(&format!("{index}: "));
13505 self.value(value, level + 1);
13506 index += 1;
13507 }
13508 } else {
13509 for (index, value) in elements.iter().enumerate() {
13510 if matches!(value, Value::Hole) {
13511 continue;
13512 }
13513 if !first {
13514 self.out.push_str(", ");
13515 }
13516 first = false;
13517 let _ = index;
13518 self.value(value, level + 1);
13519 }
13520 if let Some(last) = last_present {
13521 let trailing = elements.len() - last - 1;
13522 if trailing > 0 {
13523 if !first {
13524 self.out.push_str(", ");
13525 }
13526 self.out.push_str(&format!(
13527 "<{trailing} empty item{}>",
13528 if trailing > 1 { "s" } else { "" }
13529 ));
13530 }
13531 } else if !elements.is_empty() {
13532 let count = elements.len();
13533 self.out.push_str(&format!(
13534 "<{count} empty item{}>",
13535 if count > 1 { "s" } else { "" }
13536 ));
13537 }
13538 }
13539 self.out.push_str(" ]");
13540 }
13541
13542 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
13543 self.out.push_str("{ ");
13544 let mut first = true;
13545 for key in object.own_keys() {
13546 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
13547 continue;
13548 };
13549 if !property.enumerable {
13550 continue;
13551 }
13552 if !first {
13553 self.out.push_str(", ");
13554 }
13555 first = false;
13556 self.out
13557 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
13558 &key.to_string_lossy(),
13559 )));
13560 self.out.push_str(": ");
13561 // An accessor has no value to dump; the reference names the half that
13562 // exists instead of calling it.
13563 if property.is_accessor() {
13564 let text = match (property.getter.is_some(), property.setter.is_some()) {
13565 (true, true) => "[Getter/Setter]",
13566 (false, true) => "[Setter]",
13567 _ => "[Getter]",
13568 };
13569 self.out.push_str(text);
13570 } else {
13571 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
13572 }
13573 }
13574 self.out.push_str(" }");
13575 }
13576
13577 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
13578 fn print_string(&mut self, text: &str) {
13579 self.out.push('"');
13580 for character in text.chars() {
13581 match character {
13582 '"' => self.out.push_str("\\\""),
13583 '\\' => self.out.push_str("\\\\"),
13584 '\n' => self.out.push_str("\\n"),
13585 '\r' => self.out.push_str("\\r"),
13586 '\t' => self.out.push_str("\\t"),
13587 c if (c as u32) < 0x20 => {
13588 self.out.push_str(&format!("\\u{:04x}", c as u32));
13589 }
13590 c => self.out.push(c),
13591 }
13592 }
13593 self.out.push('"');
13594 }
13595}
13596
13597/// How `print` renders a value.
13598///
13599/// `ToString`, except that negative zero keeps its sign — the reference's host
13600/// printer does that while `String(-0)` is `"0"`.
13601pub fn display(value: &Value) -> String {
13602 match value {
13603 Value::Float(number) => crate::value::number_to_string_for_print(*number),
13604 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
13605 "undefined".to_string()
13606 }
13607 other => other.to_js_string(),
13608 }
13609}
13610
13611// ---------------------------------------------------------------------------
13612// Numeric operators
13613// ---------------------------------------------------------------------------
13614
13615/// `a + b` keeping the `Int` representation when it fits.
13616fn add_numbers(left: Value, right: Value) -> Value {
13617 match (&left, &right) {
13618 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
13619 Some(sum) => Value::Int(sum),
13620 None => Value::Float(*a as f64 + *b as f64),
13621 },
13622 _ => Value::Float(left.to_number() + right.to_number()),
13623 }
13624}
13625
13626/// The arithmetic operators other than `+`, which needs string concatenation.
13627fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13628 use Opcode::*;
13629 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
13630 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
13631 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
13632 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
13633 return Ok(match op {
13634 And => Value::Int(x & y),
13635 Or => Value::Int(x | y),
13636 Xor => Value::Int(x ^ y),
13637 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
13638 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
13639 Shr => match (*x as u32) >> ((*y as u32) & 31) {
13640 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
13641 shifted => Value::Float(shifted as f64),
13642 },
13643 Sub => match x.checked_sub(*y) {
13644 Some(value) => Value::Int(value),
13645 None => Value::Float(*x as f64 - *y as f64),
13646 },
13647 _ => return arithmetic_slow(op, left, right),
13648 });
13649 }
13650 arithmetic_slow(op, left, right)
13651}
13652
13653/// [`arithmetic`] for everything the integer fast path above does not take.
13654fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13655 use Opcode::*;
13656 let (a, b) = (left.to_number(), right.to_number());
13657 Ok(match op {
13658 Sub => match (&left, &right) {
13659 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
13660 Some(value) => Value::Int(value),
13661 None => Value::Float(a - b),
13662 },
13663 _ => Value::Float(a - b),
13664 },
13665 Mul => Value::Float(a * b),
13666 Div => Value::Float(a / b),
13667 Mod => Value::Float(js_mod(a, b)),
13668 Pow => Value::Float(a.powf(b)),
13669 And => Value::Int(left.to_int32() & right.to_int32()),
13670 Or => Value::Int(left.to_int32() | right.to_int32()),
13671 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
13672 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
13673 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
13674 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
13675 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
13676 // fits the small-integer representation stays an `Int`; the rest become a
13677 // float, which is how the reference keeps `n >>> 0` non-negative.
13678 Shr => {
13679 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
13680 match i32::try_from(shifted) {
13681 Ok(value) => Value::Int(value),
13682 Err(_) => Value::Float(shifted as f64),
13683 }
13684 }
13685 _ => Value::Float(a),
13686 })
13687}
13688
13689/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
13690///
13691/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
13692/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
13693/// slow path where the rules live.
13694fn is_number(value: &Value) -> bool {
13695 matches!(value, Value::Int(_) | Value::Float(_))
13696}
13697
13698/// The `Value::Bool` a comparison operator answers for `ordering`.
13699///
13700/// `None` is the unordered case — a `NaN` on either side — and every operator answers
13701/// false for it, including `<=` and `>=`.
13702fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
13703 use Opcode::*;
13704 let answer = match (op, ordering) {
13705 (_, None) => false,
13706 (Lt, Some(ordering)) => ordering.is_lt(),
13707 (Lte, Some(ordering)) => ordering.is_le(),
13708 (Gt, Some(ordering)) => ordering.is_gt(),
13709 (Gte, Some(ordering)) => ordering.is_ge(),
13710 _ => false,
13711 };
13712 Value::Bool(answer)
13713}
13714
13715/// `%`, which follows the sign of the dividend rather than Rust's.
13716fn js_mod(left: f64, right: f64) -> f64 {
13717 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
13718 return f64::NAN;
13719 }
13720 if right.is_infinite() {
13721 return left;
13722 }
13723 let remainder = left % right;
13724 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
13725 // the spec makes the sign match the dividend.
13726 if remainder == 0.0 {
13727 0.0f64.copysign(left)
13728 } else {
13729 remainder
13730 }
13731}
13732
13733fn negate(value: Value) -> Value {
13734 match value {
13735 Value::Int(0) => Value::Float(-0.0),
13736 Value::Int(i) => Value::Int(-i),
13737 other => Value::Float(-other.to_number()),
13738 }
13739}
13740
13741fn increment(value: Value) -> Value {
13742 match value {
13743 Value::Int(i) => match i.checked_add(1) {
13744 Some(next) => Value::Int(next),
13745 None => Value::Float(i as f64 + 1.0),
13746 },
13747 other => Value::Float(other.to_number() + 1.0),
13748 }
13749}
13750
13751fn decrement(value: Value) -> Value {
13752 match value {
13753 Value::Int(i) => match i.checked_sub(1) {
13754 Some(next) => Value::Int(next),
13755 None => Value::Float(i as f64 - 1.0),
13756 },
13757 other => Value::Float(other.to_number() - 1.0),
13758 }
13759}
13760
13761/// Compare a `BigInt` with an `f64` on their mathematical values.
13762///
13763/// Neither side is rounded to the other's precision: the number is split into its integer
13764/// part (compared as an exact bigint) and its fraction, which is what decides the answer
13765/// when the integer parts are equal. An infinite value is larger than every bigint.
13766fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
13767 use std::cmp::Ordering;
13768 if number.is_nan() {
13769 return None;
13770 }
13771 if number.is_infinite() {
13772 return Some(if number > 0.0 {
13773 Ordering::Less
13774 } else {
13775 Ordering::Greater
13776 });
13777 }
13778 let truncated = number.trunc();
13779 // A number wider than `i128` still has an exact integer part, but no bigint form we can
13780 // build cheaply; the sign of the difference is all that is needed, so compare against
13781 // the bigint's own magnitude instead.
13782 if truncated.abs() >= 1.7e38 {
13783 let big_as_f64 = big.to_f64();
13784 return big_as_f64.partial_cmp(&number);
13785 }
13786 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
13787 match big.cmp(&integer) {
13788 Ordering::Equal => {
13789 // Same integer part: the fraction decides, and a negative number's fraction is
13790 // below the integer (`-1.5` truncates to `-1`).
13791 if number > truncated {
13792 Some(Ordering::Less)
13793 } else if number < truncated {
13794 Some(Ordering::Greater)
13795 } else {
13796 Some(Ordering::Equal)
13797 }
13798 }
13799 other => Some(other),
13800 }
13801}