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 // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1731 // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1732 // which only a *custom* constructor can observe, and none of the combinator tests
1733 // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1734 let executor = self.builtin_function(
1735 "",
1736 2,
1737 Callable::CapabilityExecutor {
1738 state: state.clone(),
1739 },
1740 );
1741 let promise = self.construct(
1742 Value::Object(object.clone()),
1743 Value::Object(object),
1744 vec![Value::Object(executor)],
1745 )?;
1746 // The pair is read *after* the constructor returns, so a constructor that never
1747 // called its executor, or called it with non-callables, is the spec's step 11
1748 // `TypeError` — not something the engine can paper over.
1749 let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1750 return Err(self.type_error("promise executor never ran"));
1751 };
1752 let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1753 return Err(self.type_error("promise executor never ran"));
1754 };
1755 for handler in [&resolve, &reject] {
1756 if !matches!(handler, Value::Object(object) if object.is_callable()) {
1757 return Err(self.type_error("promise capability handler is not callable"));
1758 }
1759 }
1760 Ok((promise, resolve, reject))
1761 }
1762
1763 /// §27.2.3.1 `PromiseResolve(C, x)`.
1764 ///
1765 /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1766 /// an `x` that is already a promise of exactly this constructor is handed back
1767 /// unchanged, and anything else gets a fresh capability from `C`.
1768 pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1769 if let Value::Object(object) = &value
1770 && self.promise_state(object).is_some()
1771 {
1772 // `x.constructor === C` means "already the right kind", so no capability is
1773 // built — which is observable through a `resolve` that counts its calls.
1774 let x_constructor = self.get_property(object, "constructor")?;
1775 let same = match (
1776 x_constructor.as_ref().and_then(Value::as_object),
1777 constructor.as_object(),
1778 ) {
1779 (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1780 _ => false,
1781 };
1782 if same {
1783 return Ok(value);
1784 }
1785 }
1786 let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1787 self.call_value(resolve, Value::Undefined, vec![value])?;
1788 Ok(promise)
1789 }
1790
1791 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1792 /// promise, as `{ value: completion }`.
1793 ///
1794 /// The three cases are the reference's, and they differ on purpose:
1795 ///
1796 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1797 /// exception before any promise exists;
1798 /// * a **runtime** error rejects the returned promise;
1799 /// * success resolves it with `{ value }`, where the value is the script's completion
1800 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1801 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1802 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1803 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1804 ///
1805 /// # What this does not do
1806 ///
1807 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1808 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1809 /// the parser and the suspension machinery to accept a suspended top-level script, and
1810 /// is not implemented — such source is a syntax error here. Everything else about the
1811 /// flag is reproduced.
1812 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1813 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1814 // too, and the reference truncates that one at the same place as a runtime failure.
1815 if barrier {
1816 let depth = self.frames.len();
1817 self.trace_barriers.push(depth);
1818 }
1819 // Compiled before the promise exists, so a parse failure propagates as a throw
1820 // instead of being folded into a rejection.
1821 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1822 Ok(compiled) => compiled,
1823 Err(error) => {
1824 if barrier {
1825 self.trace_barriers.pop();
1826 }
1827 return Err(error);
1828 }
1829 };
1830 // An async body answers its own promise, and that promise is what the reference
1831 // hands back — the same object, not a wrapper around it. Its resolution value is
1832 // the `{value}` object the compiled epilogue built.
1833 if compiled.kind.is_async() {
1834 let strict = compiled.strict;
1835 let promise = self.run_eval_script(compiled, strict)?;
1836 if barrier {
1837 self.trace_barriers.pop();
1838 }
1839 return Ok(promise);
1840 }
1841 let (promise, resolve, reject) = self.new_promise_capability();
1842 let strict = compiled.strict;
1843 match self.run_eval_script(compiled, strict) {
1844 Ok(value) => {
1845 // `{ value }` is a plain object, so resolving with it adopts nothing even
1846 // when the completion value is itself a promise.
1847 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1848 self.set_property(&wrapped, "value", value)?;
1849 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1850 }
1851 Err(Signal::Throw(error)) => {
1852 self.call_value(reject, Value::Undefined, vec![error])?;
1853 }
1854 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1855 }
1856 if barrier {
1857 self.trace_barriers.pop();
1858 }
1859 Ok(Value::Object(promise))
1860 }
1861
1862 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1863 ///
1864 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1865 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1866 /// timer table, where the collector already scans it.
1867 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1868 let (promise, resolve, _reject) = self.new_promise_capability();
1869 let resolve = self.new_host_function(
1870 "resolve",
1871 1,
1872 Box::new(
1873 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1874 let value = args.first().cloned().unwrap_or(Value::Undefined);
1875 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1876 },
1877 ),
1878 );
1879 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1880 // timer table is part of what the collector walks.
1881 self.schedule_timer(Value::Object(resolve), delay_ms);
1882 Ok(Value::Object(promise))
1883 }
1884
1885 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1886 /// new promise resolved with it.
1887 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1888 if let Value::Object(object) = &value
1889 && self.promise_state(object).is_some()
1890 {
1891 return Ok(value);
1892 }
1893 let promise = self.new_promise();
1894 self.resolve_promise_with(&promise, value)?;
1895 Ok(Value::Object(promise))
1896 }
1897
1898 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1899 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1900 // Resolving a promise with itself is a `TypeError`. The check exists because the
1901 // alternative is a chain of self-reactions that never settles.
1902 if let Value::Object(object) = &value
1903 && object.ptr_eq(promise)
1904 {
1905 // The spec rejects *and* throws, so both the promise and the caller see it.
1906 let thrown = self.type_error("cannot resolve a promise with itself");
1907 let Signal::Throw(error) = thrown.clone() else {
1908 unreachable!("type_error always throws")
1909 };
1910 self.reject_promise(promise, error);
1911 return Err(thrown);
1912 }
1913 let then = match &value {
1914 Value::Object(object) => self.get_property(object, "then")?,
1915 _ => None,
1916 };
1917 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
1918 if !callable_then {
1919 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
1920 self.fulfill_promise(promise, value);
1921 return Ok(());
1922 }
1923 // Adopting a thenable is asynchronous — `then` is called from a job, never from
1924 // inside `resolve`, so a script cannot make a promise settle synchronously.
1925 self.jobs.push_back(Job::Thenable {
1926 then: then.expect("checked callable"),
1927 value,
1928 promise: promise.clone(),
1929 });
1930 Ok(())
1931 }
1932
1933 /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
1934 ///
1935 /// `C.resolve` is user code and may answer a plain thenable rather than one of this
1936 /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
1937 ///
1938 /// The property read is **not** short-circuitable even for a real promise: the spec says
1939 /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
1940 /// expects it to run. Skipping the read for promises not only lost the throw, it made
1941 /// the combinator's loop infinite — the test's iterator never sets `done`.
1942 pub fn invoke_then(
1943 &mut self,
1944 thenable: Value,
1945 on_fulfilled: Value,
1946 on_rejected: Value,
1947 ) -> JsResult<()> {
1948 let then = match &thenable {
1949 Value::Object(object) => self.get_property(object, "then")?,
1950 primitive => {
1951 let boxed = self.object_from(primitive)?;
1952 self.get_property(&boxed, "then")?
1953 }
1954 };
1955 let Some(then) = then else {
1956 return Err(self.type_error("thenable has no then method"));
1957 };
1958 if !matches!(&then, Value::Object(object) if object.is_callable()) {
1959 return Err(self.type_error("then is not a function"));
1960 }
1961 self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
1962 Ok(())
1963 }
1964
1965 /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
1966 ///
1967 /// `Promise.prototype.then` in one step: register a reaction and answer the derived
1968 /// promise.
1969 pub fn perform_then(
1970 &mut self,
1971 promise: &Gc<JsObject>,
1972 on_fulfilled: Option<Value>,
1973 on_rejected: Option<Value>,
1974 ) -> JsResult<Value> {
1975 let Some(state) = self.promise_state(promise) else {
1976 return Err(self.type_error("not a promise"));
1977 };
1978 // Whether a rejection handler is being attached decides whether a recorded
1979 // rejection stops being unhandled, so it is read before the values are moved.
1980 let has_rejection_handler = on_rejected.is_some();
1981 let derived = self.new_promise();
1982 let reaction = crate::object::PromiseReaction {
1983 on_fulfilled,
1984 on_rejected,
1985 promise: derived.clone(),
1986 };
1987 let settled = {
1988 let mut state = state.borrow_mut();
1989 // A rejection somebody reacts to is no longer unhandled.
1990 state.handled = true;
1991 match &state.status {
1992 crate::object::PromiseStatus::Pending => {
1993 state.reactions.push(reaction.clone());
1994 None
1995 }
1996 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
1997 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
1998 }
1999 };
2000 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2001 // later, means somebody is listening after all.
2002 if has_rejection_handler {
2003 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2004 }
2005 if let Some((argument, rejected)) = settled {
2006 let handler = if rejected {
2007 reaction.on_rejected
2008 } else {
2009 reaction.on_fulfilled
2010 };
2011 self.jobs.push_back(Job::Reaction {
2012 handler,
2013 argument,
2014 rejected,
2015 promise: reaction.promise,
2016 });
2017 }
2018 Ok(Value::Object(derived))
2019 }
2020
2021 /// The rejections nobody listened to, formatted the way the reference reports them.
2022 ///
2023 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2024 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2025 /// unhandled at the point the queue drains, because a `then` may still be attached
2026 /// before the host acts on it.
2027 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2028 let entries = std::mem::take(&mut self.unhandled);
2029 // Somebody may have attached a handler after the rejection was recorded, so the
2030 // promise is the authority rather than the list.
2031 let still_unhandled: Vec<Value> = entries
2032 .into_iter()
2033 .filter_map(|(promise, reason)| {
2034 let handled = self
2035 .promise_state(&promise)
2036 .map(|state| state.borrow().handled)
2037 .unwrap_or(true);
2038 (!handled).then_some(reason)
2039 })
2040 .collect();
2041 still_unhandled
2042 .into_iter()
2043 .map(|reason| {
2044 let text = self.describe_exception(&reason);
2045 let stack = match &reason {
2046 Value::Object(object) => self
2047 .get_property(object, "stack")
2048 .ok()
2049 .flatten()
2050 .map(|value| value.to_js_string())
2051 // `stack` carries a trailing newline of its own, which would leave
2052 // a blank line between two reported rejections.
2053 .map(|text| text.trim_end().to_string())
2054 .unwrap_or_default(),
2055 _ => String::new(),
2056 };
2057 if stack.is_empty() {
2058 format!("Possibly unhandled promise rejection: {text}")
2059 } else {
2060 format!("Possibly unhandled promise rejection: {text}\n{stack}")
2061 }
2062 })
2063 .collect()
2064 }
2065
2066 /// Run the microtask queue to exhaustion.
2067 ///
2068 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2069 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2070 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2071 ///
2072 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2073 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2074 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2075 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2076 crate::builtins::json::parse_text(self, text, true)
2077 }
2078
2079 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2080 ///
2081 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2082 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2083 /// immediately, and `setTimeout(f, -1)` is ordinary code.
2084 ///
2085 /// The callback is called with **no arguments**. The reference stores only the function
2086 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2087 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2088 /// extra arguments arrive as `undefined`.
2089 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2090 let id = self.next_timer_id;
2091 // Wrap rather than grow: the id reaches the script as an `Int32`.
2092 self.next_timer_id = if self.next_timer_id == i32::MAX {
2093 1
2094 } else {
2095 self.next_timer_id + 1
2096 };
2097 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2098 self.tasks.push(Task::Timer {
2099 id,
2100 callback,
2101 due_at,
2102 });
2103 id
2104 }
2105
2106 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2107 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2108 pub fn cancel_timer(&mut self, id: i32) -> bool {
2109 let before = self.tasks.len();
2110 self.tasks.retain(|task| match task {
2111 Task::Timer { id: task_id, .. } => *task_id != id,
2112 });
2113 self.tasks.len() != before
2114 }
2115
2116 /// How long until the earliest pending timer, or `None` when none is pending.
2117 pub fn next_timeout(&self) -> Option<std::time::Duration> {
2118 let now = std::time::Instant::now();
2119 self.tasks
2120 .iter()
2121 .map(|task| match task {
2122 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2123 })
2124 .min()
2125 }
2126
2127 /// Run one turn of the event loop.
2128 ///
2129 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2130 /// run at most one due timer, then drain again. The blocking belongs to the caller
2131 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2132 /// is how it asks.
2133 ///
2134 /// One timer per turn rather than all of them: a timer callback may schedule another
2135 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2136 /// starve the microtask queue.
2137 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2138 self.drain_jobs()?;
2139 let now = std::time::Instant::now();
2140 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2141 // followed by `setTimeout(g, 1)` must run `g` first.
2142 let due = self
2143 .tasks
2144 .iter()
2145 .enumerate()
2146 .filter(|(_, task)| match task {
2147 Task::Timer { due_at, .. } => *due_at <= now,
2148 })
2149 .min_by_key(|(_, task)| match task {
2150 Task::Timer { due_at, .. } => *due_at,
2151 })
2152 .map(|(index, _)| index);
2153 let Some(index) = due else {
2154 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2155 // descriptor is registered but no timer is closer, so a script that never
2156 // touches the descriptor still gets control back. Without a cap a handler on a
2157 // descriptor that is never ready would block for as long as the host allows.
2158 let timeout = self
2159 .next_timeout()
2160 .unwrap_or(std::time::Duration::from_secs(10))
2161 .min(std::time::Duration::from_secs(10));
2162 if !self.fd_handlers.is_empty() {
2163 // Blocking on a timer while descriptors are registered would starve them,
2164 // and blocking on the descriptors while a timer is due would delay it; the
2165 // host polls with the earlier of the two deadlines, which this timeout is.
2166 return Ok(Turn::Poll(timeout));
2167 }
2168 return Ok(match self.next_timeout() {
2169 Some(wait) => Turn::Wait(wait),
2170 None => Turn::Done,
2171 });
2172 };
2173 let Task::Timer { callback, .. } = self.tasks.remove(index);
2174 let this = Value::Undefined;
2175 // A throwing timer callback must not stop the loop: the reference reports it and
2176 // keeps going, because the alternative is that one bad timer silently stops every
2177 // later one.
2178 // No arguments: see `schedule_timer` — the reference calls the callback bare.
2179 match self.call_value(callback, this, Vec::new()) {
2180 Ok(_) => {}
2181 Err(Signal::Throw(value)) => {
2182 let text = self.describe_exception(&value);
2183 self.timer_errors.push(text);
2184 }
2185 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2186 }
2187 self.drain_jobs()?;
2188 Ok(Turn::Ran)
2189 }
2190
2191 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2192 ///
2193 /// `callback` of `None` unregisters that direction, and an entry with neither direction
2194 /// left is removed — the reference does the same, so a script can rely on
2195 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2196 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2197 let entry = self.fd_handlers.entry(fd).or_default();
2198 if readable {
2199 entry.read = callback;
2200 } else {
2201 entry.write = callback;
2202 }
2203 if entry.read.is_none() && entry.write.is_none() {
2204 self.fd_handlers.remove(&fd);
2205 }
2206 }
2207
2208 /// Register or clear an `os.signal` handler.
2209 ///
2210 /// `None` removes it; the host separately restores the default disposition or sets
2211 /// ignore, because which of those happened is the script's choice (`null` versus
2212 /// `undefined`) and not something this table can express.
2213 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2214 match handler {
2215 Some(handler) => {
2216 self.signal_handlers.insert(signal, handler);
2217 }
2218 None => {
2219 self.signal_handlers.remove(&signal);
2220 }
2221 }
2222 }
2223
2224 /// Run the handler for `signal`, reporting whether one ran.
2225 ///
2226 /// A throwing handler is reported and the loop continues, like a timer's.
2227 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2228 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2229 return Ok(false);
2230 };
2231 match self.call_value(handler, Value::Undefined, Vec::new()) {
2232 Ok(_) => {}
2233 Err(Signal::Throw(value)) => {
2234 let text = self.describe_exception(&value);
2235 self.timer_errors.push(text);
2236 }
2237 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2238 }
2239 self.drain_jobs()?;
2240 Ok(true)
2241 }
2242
2243 /// The descriptors the host has to poll, and in which direction.
2244 ///
2245 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2246 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2247 /// `os_poll` asks for.
2248 pub fn pending_fds(&self) -> Vec<FdInterest> {
2249 self.fd_handlers
2250 .iter()
2251 .map(|(fd, entry)| FdInterest {
2252 fd: *fd,
2253 read: entry.read.is_some(),
2254 write: entry.write.is_some(),
2255 })
2256 .collect()
2257 }
2258
2259 /// Call the handler registered for `fd`, reporting whether one ran.
2260 ///
2261 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2262 /// poll iteration and then restarts the loop, because the handler may have changed the
2263 /// registration list underneath it; doing the same here keeps a handler that
2264 /// unregisters itself from being called with stale state.
2265 ///
2266 /// A throwing handler is reported and the loop continues — a bad handler must not stop
2267 /// every later one, exactly as with timers.
2268 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2269 let Some(entry) = self.fd_handlers.get(&fd) else {
2270 return Ok(false);
2271 };
2272 let callback = if readable {
2273 entry.read.clone()
2274 } else if writable {
2275 entry.write.clone()
2276 } else {
2277 None
2278 };
2279 let Some(callback) = callback else {
2280 return Ok(false);
2281 };
2282 self.drain_jobs()?;
2283 match self.call_value(callback, Value::Undefined, Vec::new()) {
2284 Ok(_) => {}
2285 Err(Signal::Throw(value)) => {
2286 let text = self.describe_exception(&value);
2287 self.timer_errors.push(text);
2288 }
2289 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2290 }
2291 self.drain_jobs()?;
2292 Ok(true)
2293 }
2294
2295 /// Take the errors timer callbacks threw, leaving the list empty.
2296 pub fn take_timer_errors(&mut self) -> Vec<String> {
2297 std::mem::take(&mut self.timer_errors)
2298 }
2299
2300 /// Whether anything is still pending: a microtask or a timer.
2301 pub fn has_pending_work(&self) -> bool {
2302 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2303 }
2304
2305 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2306 pub fn has_pending_timers_or_jobs(&self) -> bool {
2307 !self.jobs.is_empty() || !self.tasks.is_empty()
2308 }
2309
2310 /// Run every queued microtask, including ones queued while draining.
2311 pub fn drain_jobs(&mut self) -> JsResult<()> {
2312 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2313 // would spin forever, so the drain is bounded the way the call stack is.
2314 let mut budget = 1_000_000usize;
2315 while let Some(job) = self.jobs.pop_front() {
2316 if budget == 0 {
2317 return Err(Signal::Throw(
2318 self.make_error("InternalError", "promise job queue did not drain"),
2319 ));
2320 }
2321 budget -= 1;
2322 self.run_job(job)?;
2323 // `FinalizationRegistry` at the job boundary: this is the safe point where the
2324 // engine may run script that the script itself did not ask for. Doing it here
2325 // rather than from a drop hook is what keeps the callback out of arbitrary
2326 // engine bookkeeping — see `builtins::weak`'s header.
2327 crate::builtins::weak::drain_finalizers(self)?;
2328 }
2329 // A script that queued no jobs may still have dropped targets, so the checkpoint
2330 // runs once more after the queue empties.
2331 crate::builtins::weak::drain_finalizers(self)?;
2332 Ok(())
2333 }
2334
2335 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2336 ///
2337 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2338 /// `None` and is swept out here. This is also where the realm learns that a registry
2339 /// died, which is why it is a mutation rather than a read.
2340 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2341 let handles = std::mem::take(&mut self.realm.finalization_registries);
2342 let mut live = Vec::with_capacity(handles.len());
2343 for handle in handles {
2344 let Some(object) = handle.upgrade() else {
2345 continue;
2346 };
2347 let Some(state) = object.finalization_state() else {
2348 continue;
2349 };
2350 live.push((object.clone(), *state));
2351 self.realm.finalization_registries.push(object.downgrade());
2352 }
2353 live
2354 }
2355
2356 /// Run one microtask.
2357 fn run_job(&mut self, job: Job) -> JsResult<()> {
2358 match job {
2359 Job::Reaction {
2360 handler: None,
2361 argument,
2362 rejected,
2363 promise,
2364 } => {
2365 // No handler: the settlement passes straight through to the derived
2366 // promise, which is why `p.catch(f)` ignores fulfilments.
2367 if rejected {
2368 self.reject_promise(&promise, argument);
2369 } else {
2370 self.fulfill_promise(&promise, argument);
2371 }
2372 Ok(())
2373 }
2374 Job::Reaction {
2375 handler: Some(handler),
2376 argument,
2377 promise,
2378 ..
2379 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2380 Ok(answer) => {
2381 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2382 self.reject_promise(&promise, error);
2383 }
2384 Ok(())
2385 }
2386 Err(Signal::Throw(reason)) => {
2387 self.reject_promise(&promise, reason);
2388 Ok(())
2389 }
2390 Err(other) => Err(other),
2391 },
2392 Job::Thenable {
2393 then,
2394 value,
2395 promise,
2396 } => {
2397 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2398 // the value it produces settles `promise`.
2399 // The thenable's `then` gets this promise's own pair, so whatever it
2400 // produces settles `promise`.
2401 let resolve = JsObject::function(
2402 self.heap,
2403 Some(self.realm.function_proto.clone()),
2404 Callable::PromiseResolve(promise.clone()),
2405 );
2406 let reject = JsObject::function(
2407 self.heap,
2408 Some(self.realm.function_proto.clone()),
2409 Callable::PromiseReject(promise.clone()),
2410 );
2411 match self.call_value(
2412 then,
2413 value,
2414 vec![Value::Object(resolve), Value::Object(reject)],
2415 ) {
2416 Ok(_) => Ok(()),
2417 Err(Signal::Throw(reason)) => {
2418 self.reject_promise(&promise, reason);
2419 Ok(())
2420 }
2421 Err(other) => Err(other),
2422 }
2423 }
2424 Job::Resume {
2425 coroutine,
2426 promise,
2427 kind,
2428 value,
2429 } => self.drive_async(&coroutine, &promise, kind, value),
2430 Job::GeneratorResume {
2431 generator,
2432 promise,
2433 kind,
2434 value,
2435 } => self.step_async_generator(&generator, &promise, kind, value),
2436 Job::Import {
2437 specifier,
2438 referrer,
2439 promise,
2440 } => {
2441 self.run_dynamic_import(&specifier, &referrer, &promise);
2442 Ok(())
2443 }
2444 }
2445 }
2446
2447 /// One element of a `Promise` combinator settled.
2448 ///
2449 /// The shared state object holds the result array, the number still outstanding, and
2450 /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2451 /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2452 /// to settle, only whatever `Sub` said a capability is.
2453 ///
2454 /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2455 /// and `any` must ignore every later settlement, and `all` must not report a second
2456 /// rejection after the first.
2457 fn settle_combinator(
2458 &mut self,
2459 state: &Gc<JsObject>,
2460 index: usize,
2461 fulfilled: bool,
2462 value: Value,
2463 ) -> JsResult<()> {
2464 let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2465 // Each element settles at most once: a thenable may call `onFulfilled` twice
2466 // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2467 // call a no-op. Without it the second call decremented `remaining` again and settled
2468 // `all` with a short values array (`call-resolve-element-items`).
2469 let done = field("done");
2470 let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2471 let settled = field("settled").is_some_and(|value| value.to_boolean());
2472 if settled {
2473 return Ok(());
2474 }
2475 if let Some(Value::Object(done)) = &done {
2476 if done
2477 .array_get(index)
2478 .is_some_and(|value| value.to_boolean())
2479 {
2480 return Ok(());
2481 }
2482 done.array_set(self.heap, index, Value::Bool(true));
2483 }
2484 let resolve = field("resolve");
2485 let reject = field("reject");
2486 let keys = field("keys");
2487 let results = field("results").and_then(|value| value.as_object().cloned());
2488 // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2489 // promise: the handler is a plain function the constructor chose.
2490 let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2491 if let Some(handler) = handler {
2492 interp.call_value(handler, Value::Undefined, vec![value])?;
2493 }
2494 Ok(())
2495 };
2496 match kind {
2497 // `race`: the first settlement wins and stops the rest.
2498 3 => {
2499 state.define_data("settled", Value::Bool(true));
2500 let handler = if fulfilled { resolve } else { reject };
2501 settle_with(self, handler, value)?;
2502 return Ok(());
2503 }
2504 // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2505 // the first rejection wins outright.
2506 0 | 4 if !fulfilled => {
2507 state.define_data("settled", Value::Bool(true));
2508 settle_with(self, reject, value)?;
2509 return Ok(());
2510 }
2511 // `any`: the first fulfilment wins.
2512 2 if fulfilled => {
2513 state.define_data("settled", Value::Bool(true));
2514 settle_with(self, resolve, value)?;
2515 return Ok(());
2516 }
2517 _ => {}
2518 }
2519 let Some(results) = &results else {
2520 return Ok(());
2521 };
2522 match kind {
2523 4 => {
2524 results.array_set(self.heap, index, value);
2525 }
2526 0 => {
2527 results.array_set(self.heap, index, value);
2528 }
2529 // `allSettled` (and its keyed twin) never rejects; each slot records what
2530 // happened.
2531 1 | 5 => {
2532 let record = self.new_object(Some(self.realm.object_proto.clone()));
2533 if fulfilled {
2534 record.define_data("status", self.string("fulfilled"));
2535 record.define_data("value", value);
2536 } else {
2537 record.define_data("status", self.string("rejected"));
2538 record.define_data("reason", value);
2539 }
2540 results.array_set(self.heap, index, Value::Object(record));
2541 }
2542 // `any`: a rejection is parked in the errors array and the sweep continues.
2543 2 => {
2544 results.array_set(self.heap, index, value);
2545 }
2546 _ => {}
2547 }
2548 let remaining = field("remaining")
2549 .map(|value| value.to_int32())
2550 .unwrap_or(0);
2551 let left = remaining - 1;
2552 state.define_data("remaining", Value::Int(left));
2553 if left != 0 {
2554 return Ok(());
2555 }
2556 state.define_data("settled", Value::Bool(true));
2557 match kind {
2558 0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2559 // The keyed result: an ordinary object with a **null** prototype, holding the
2560 // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2561 4 | 5 => {
2562 let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2563 settle_with(self, resolve, keyed)?;
2564 }
2565 2 => {
2566 // The rejection is an `AggregateError` whose `errors` is the results array
2567 // itself — the slots are the reasons, in input order.
2568 let errors = results.array_elements().unwrap_or_default();
2569 let error = self.aggregate_error(errors, "all promises were rejected");
2570 settle_with(self, reject, error)?;
2571 }
2572 _ => {}
2573 }
2574 Ok(())
2575 }
2576
2577 /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2578 ///
2579 /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2580 /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2581 /// prototype is load-bearing in both directions: a key called `toString` must not
2582 /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2583 /// (`resolves-empty-object.js`).
2584 pub(crate) fn keyed_result_object(
2585 &mut self,
2586 keys: Option<&Value>,
2587 values: &Gc<JsObject>,
2588 ) -> JsResult<Value> {
2589 let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2590 return Ok(Value::Object(self.new_object(None)));
2591 };
2592 let result = self.new_object(None);
2593 let count = values.array_length().unwrap_or(0);
2594 for index in 0..count {
2595 let Some(key) = keys.array_get(index) else {
2596 continue;
2597 };
2598 let Some(value) = values.array_get(index) else {
2599 continue;
2600 };
2601 let property = Property::with_attributes(value, true, true);
2602 match &key {
2603 Value::Symbol(symbol) => {
2604 result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2605 }
2606 other => {
2607 let text = self.to_js_string(other)?;
2608 result.define_key(&PropertyKey::from(text.as_str()), property);
2609 }
2610 }
2611 }
2612 Ok(Value::Object(result))
2613 }
2614
2615 /// Build an async function's result: a promise whose body runs as a coroutine.
2616 pub fn new_async_function(
2617 &mut self,
2618 function: Value,
2619 this: Value,
2620 args: Vec<Value>,
2621 ) -> JsResult<Value> {
2622 let promise = self.new_promise();
2623 let coroutine = self.new_coroutine(function, this, args)?;
2624 if let Err(Signal::Throw(reason)) =
2625 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2626 {
2627 self.reject_promise(&promise, reason);
2628 }
2629 Ok(Value::Object(promise))
2630 }
2631
2632 /// The coroutine an async body runs in.
2633 ///
2634 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2635 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2636 /// than growing a second state machine. The difference is only in the ending — a
2637 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2638 /// Run `code` as an async function body, answering the promise it settles.
2639 ///
2640 /// Used for a module with top-level `await`: its body is an async function whose
2641 /// caller is the host, so there is no function object to pass through
2642 /// [`Interp::new_async_function`].
2643 pub fn run_async_body(
2644 &mut self,
2645 code: Gc<CompiledCode>,
2646 env: Gc<ClosureEnv>,
2647 this: Value,
2648 ) -> JsResult<Value> {
2649 let promise = self.new_promise();
2650 let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2651 if let Err(Signal::Throw(reason)) =
2652 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2653 {
2654 self.reject_promise(&promise, reason);
2655 }
2656 Ok(Value::Object(promise))
2657 }
2658
2659 fn new_coroutine(
2660 &mut self,
2661 function: Value,
2662 this: Value,
2663 args: Vec<Value>,
2664 ) -> JsResult<Gc<JsObject>> {
2665 let Some(object) = function.as_object().cloned() else {
2666 return Err(self.type_error("not a function"));
2667 };
2668 let Some((code, env)) = bytecode_of(&object) else {
2669 return Err(self.type_error("not a function"));
2670 };
2671 self.new_coroutine_from(code, env, this, args)
2672 }
2673
2674 /// Build a coroutine over an already-resolved body.
2675 fn new_coroutine_from(
2676 &mut self,
2677 code: Gc<CompiledCode>,
2678 env: Gc<ClosureEnv>,
2679 this: Value,
2680 args: Vec<Value>,
2681 ) -> JsResult<Gc<JsObject>> {
2682 let function = Value::Undefined;
2683 self.push_frame(code, env, this, args, function)?;
2684 let frame = self.frames.pop().expect("push_frame just pushed it");
2685 let state = GeneratorState {
2686 frame: Some(frame),
2687 phase: GeneratorPhase::SuspendedStart,
2688 parked_on_await: false,
2689 parked_on_yield_star: false,
2690 requests: std::collections::VecDeque::new(),
2691 async_busy: false,
2692 };
2693 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2694 coroutine.with_mut(|data| {
2695 data.kind = ObjectKind::Generator(Box::new(state));
2696 });
2697 Ok(coroutine)
2698 }
2699
2700 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2701 /// `await` and `value` is what it awaited.
2702 fn resume_coroutine(
2703 &mut self,
2704 coroutine: &Gc<JsObject>,
2705 kind: ResumeKind,
2706 value: Value,
2707 ) -> JsResult<(Value, bool)> {
2708 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2709 ObjectKind::Generator(state) => Some(std::mem::replace(
2710 state.as_mut(),
2711 GeneratorState {
2712 frame: None,
2713 phase: GeneratorPhase::Executing,
2714 parked_on_await: false,
2715 parked_on_yield_star: false,
2716 requests: std::collections::VecDeque::new(),
2717 async_busy: false,
2718 },
2719 )),
2720 _ => None,
2721 }) else {
2722 return Err(self.type_error("not a coroutine"));
2723 };
2724 let result = self.step_generator(&mut state, kind, value);
2725 coroutine.with_mut(|data| {
2726 data.kind = ObjectKind::Generator(Box::new(state));
2727 });
2728 let (value, done, _ready, _reason) = result?;
2729 Ok((value, done))
2730 }
2731
2732 /// Advance an async body and settle its promise with the outcome.
2733 fn drive_async(
2734 &mut self,
2735 coroutine: &Gc<JsObject>,
2736 promise: &Gc<JsObject>,
2737 kind: ResumeKind,
2738 value: Value,
2739 ) -> JsResult<()> {
2740 match self.resume_coroutine(coroutine, kind, value) {
2741 Ok((value, true)) => {
2742 // `Ok` with `done` means the body finished *normally*, even when it was
2743 // resumed by a `throw` — `try { await p } catch {}` completes by
2744 // returning. Only the `Err` arm below is a rejection.
2745 //
2746 // Resolving rather than fulfilling matters: `return promise` in an async
2747 // body adopts the inner promise, so `async function f(){ return
2748 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2749 // promise.
2750 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2751 self.reject_promise(promise, reason);
2752 }
2753 Ok(())
2754 }
2755 Ok((value, false)) => {
2756 // Parked on `await`: follow what it awaited and resume with the outcome.
2757 let awaited = match self.promise_resolve_value(value) {
2758 Ok(awaited) => awaited,
2759 Err(Signal::Throw(error)) => {
2760 self.reject_promise(promise, error);
2761 return Ok(());
2762 }
2763 Err(other) => return Err(other),
2764 };
2765 self.hook_await(awaited, coroutine, promise)
2766 }
2767 Err(Signal::Throw(reason)) => {
2768 self.reject_promise(promise, reason);
2769 Ok(())
2770 }
2771 Err(other) => Err(other),
2772 }
2773 }
2774
2775 /// Arrange for `coroutine` to resume when `awaited` settles.
2776 fn hook_await(
2777 &mut self,
2778 awaited: Value,
2779 coroutine: &Gc<JsObject>,
2780 promise: &Gc<JsObject>,
2781 ) -> JsResult<()> {
2782 let resumed = JsObject::function(
2783 self.heap,
2784 Some(self.realm.function_proto.clone()),
2785 Callable::AwaitResume {
2786 coroutine: coroutine.clone(),
2787 promise: promise.clone(),
2788 kind: ResumeKind::Next,
2789 },
2790 );
2791 let raised = JsObject::function(
2792 self.heap,
2793 Some(self.realm.function_proto.clone()),
2794 Callable::AwaitResume {
2795 coroutine: coroutine.clone(),
2796 promise: promise.clone(),
2797 kind: ResumeKind::Throw,
2798 },
2799 );
2800 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2801 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2802 let Value::Object(awaited) = &awaited else {
2803 self.jobs.push_back(Job::Resume {
2804 coroutine: coroutine.clone(),
2805 promise: promise.clone(),
2806 kind: ResumeKind::Next,
2807 value: awaited,
2808 });
2809 return Ok(());
2810 };
2811 self.perform_then(
2812 awaited,
2813 Some(Value::Object(resumed)),
2814 Some(Value::Object(raised)),
2815 )?;
2816 Ok(())
2817 }
2818
2819 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2820 /// things an engine keeps outside it — array elements and an array's `length`.
2821 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2822 if let Some(property) = object.own_property_key(key) {
2823 return Some(property);
2824 }
2825 // An array's elements live in their own vector rather than the property table, so
2826 // a descriptor for one has to be synthesized — with the attributes an element has.
2827 if let Some(index) = key.as_str().and_then(array_index)
2828 && let Some(value) = object.array_get(index as usize)
2829 && !matches!(value, Value::Hole)
2830 {
2831 return Some(Property::data(value));
2832 }
2833 // `length` is an own property of an array that is not in its property table
2834 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2835 // and non-enumerable.
2836 if key.as_str() == Some("length")
2837 && let Some(length) = object.array_length()
2838 {
2839 return Some(Property {
2840 value: Some(crate::object::length_value(length)),
2841 writable: object.length_writable(),
2842 enumerable: false,
2843 configurable: false,
2844 getter: None,
2845 setter: None,
2846 });
2847 }
2848 None
2849 }
2850
2851 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2852 pub fn object_get_own_property(
2853 &mut self,
2854 object: &Gc<JsObject>,
2855 key: &PropertyKey,
2856 ) -> JsResult<Option<Property>> {
2857 if let Some(answer) = self.proxy_get_own_property(object, key)? {
2858 return Ok(answer);
2859 }
2860 if let Some(exotic) = object.exotic()
2861 && let Some(answer) = exotic.get_own_property(self, object, key)?
2862 {
2863 return Ok(answer);
2864 }
2865 // A mapped `arguments` index is a data property as far as script can see: the
2866 // accessor pair that aliases the parameter is plumbing, and exposing it would
2867 // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
2868 // report a `get` where the spec has a `[[Value]]`.
2869 if let Some(index) = key.as_str().and_then(crate::object::array_index)
2870 && let Some(cell) = object.mapped_argument_cell(index as usize)
2871 {
2872 // Non-configurable is *not* the default: an ordinary mapped index is
2873 // configurable, and only becomes non-configurable once something
2874 // redefines it. Preserve whatever the property table currently says.
2875 // The attributes come from whatever the property table holds, because they
2876 // can be changed independently of the mapping; only the *value* and the
2877 // data-property *kind* are the accessor's secret.
2878 let flags = Self::ordinary_own_property(object, key);
2879 if let Some(existing) = &flags
2880 && !existing.is_accessor()
2881 {
2882 // Already demapped: the table entry is the answer, not the cell.
2883 return Ok(flags);
2884 }
2885 return Ok(Some(Property {
2886 value: Some(cell.get()),
2887 writable: true,
2888 enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
2889 configurable: flags.as_ref().is_some_and(|p| p.configurable),
2890 ..Property::default()
2891 }));
2892 }
2893 Ok(Self::ordinary_own_property(object, key))
2894 }
2895
2896 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
2897 pub fn object_define_own_property(
2898 &mut self,
2899 object: &Gc<JsObject>,
2900 key: &PropertyKey,
2901 property: Property,
2902 ) -> JsResult<bool> {
2903 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
2904 return Ok(accepted);
2905 }
2906 // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
2907 // non-extensible object. The check lives here rather than in the callers because
2908 // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
2909 // `Array.prototype.filter` uses to store its result, and a species object made
2910 // non-extensible by its own constructor must make that a `TypeError`
2911 // (`target-array-non-extensible`).
2912 if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
2913 return Ok(false);
2914 }
2915 // A host class that intercepts definitions owns the attributes of the properties it
2916 // defines: `_class`-style storage on the native side is the usual reason.
2917 if let Some(exotic) = object.exotic()
2918 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
2919 {
2920 return Ok(accepted);
2921 }
2922 // An array index is stored in the element vector, which can hold a plain value and
2923 // nothing else. An accessor — or a data property with non-default attributes —
2924 // therefore has to live in the property table, and the element slot is blanked so
2925 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
2926 // {get})` stored the accessor where no read ever looked, and the array kept
2927 // answering its old value.
2928 // An array's `length` is not stored in the property table, so defining it has to
2929 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
2930 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
2931 // {value: 1})` reported success and changed nothing.
2932 if key.as_str() == Some("length") && object.is_array() {
2933 // `{writable: false}` on `length` does not change the length, but it does make
2934 // it read-only — after which neither a later `{writable: true}` nor a store
2935 // past the end may succeed.
2936 if property.value.is_none() {
2937 if !object.length_writable() && property.writable {
2938 return Ok(false);
2939 }
2940 object.set_length_writable(property.writable);
2941 return Ok(true);
2942 }
2943 if !object.length_writable() {
2944 return Ok(false);
2945 }
2946 }
2947 if key.as_str() == Some("length")
2948 && object.is_array()
2949 && let Some(value) = property.value.clone()
2950 {
2951 let requested = value.to_number();
2952 let valid = requested.is_finite()
2953 && requested >= 0.0
2954 && requested.fract() == 0.0
2955 && requested <= u32::MAX as f64;
2956 if !valid {
2957 return Err(self.range_error("invalid array length"));
2958 }
2959 // Truncating deletes the elements above the new length, and a non-configurable
2960 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
2961 // makes `a.length = 2` fail rather than quietly drop it.
2962 let current = object.array_length().unwrap_or(0);
2963 let requested = requested as usize;
2964 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
2965 return Ok(false);
2966 }
2967 object.array_set_length(self.heap, requested);
2968 return Ok(true);
2969 }
2970 let plain = property.writable
2971 && property.enumerable
2972 && property.configurable
2973 && !property.is_accessor();
2974 if let Some(index) = key.as_str().and_then(array_index)
2975 && object.is_array()
2976 {
2977 // Growing the array needs a writable `length`: after
2978 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
2979 // be added.
2980 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
2981 return Ok(false);
2982 }
2983 if plain && property.value.is_some() {
2984 // An ordinary element: the vector is where a read looks first, so it has
2985 // to be the vector that changes — unless the index is too far out to be
2986 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
2987 // one property, because past its own limit it stores the index as an
2988 // ordinary key. Falling through to `define_key` below is the same choice,
2989 // and the alternative was worse: the store used to be *dropped* and the
2990 // length left at 0, which is a silent wrong answer.
2991 let value = property.value.clone().unwrap_or(Value::Undefined);
2992 object.delete_key(key);
2993 if object.array_set(self.heap, index as usize, value) {
2994 return Ok(true);
2995 }
2996 // Past the dense limit the element lives in the table like any property.
2997 object.note_element_descriptor();
2998 object.define_key(key, property);
2999 // A sparse store past the dense limit still extends `length`, which is what
3000 // `a[a.length] = v` relies on — but only extends: shortening would delete
3001 // the sparse properties above the index, including this one.
3002 if index as usize + 1 > object.array_length().unwrap_or(0) {
3003 object.array_set_length(self.heap, index as usize + 1);
3004 }
3005 return Ok(true);
3006 }
3007 // A non-plain element — an accessor, or an attribute that is not the default —
3008 // lives in the table while the slot becomes a hole. Recording it keeps every
3009 // later `a[i] = v` off the dense path, where the write would have shadowed the
3010 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3011 // replace the accessor with a plain data property.
3012 object.note_element_descriptor();
3013 object.define_key(key, property);
3014 // The slot stays, so `length` does not shrink; a hole is not an element, so
3015 // the table entry is now what a read finds.
3016 object.array_set(self.heap, index as usize, Value::Hole);
3017 return Ok(true);
3018 }
3019 object.define_key(key, property);
3020 Ok(true)
3021 }
3022
3023 /// Build a proxy object over `target`, with its traps read from `handler`.
3024 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3025 JsObject::proxy(self.heap, target, handler)
3026 }
3027
3028 /// The `revoke` function for a proxy's slots.
3029 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3030 JsObject::function(
3031 self.heap,
3032 Some(self.realm.function_proto.clone()),
3033 Callable::Revoker(slots),
3034 )
3035 }
3036
3037 /// A new array.
3038 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3039 let array = JsObject::array(
3040 self.heap,
3041 Some(self.realm.array_proto.clone()),
3042 elements.len(),
3043 );
3044 for (index, element) in elements.into_iter().enumerate() {
3045 array.array_set(self.heap, index, element);
3046 }
3047 array
3048 }
3049
3050 /// A new native function object.
3051 ///
3052 /// The observable `name` and `length` are installed as properties here, which is
3053 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3054 /// so `f.name = "x"` behaves like the writable property it is.
3055 /// A native constructor that builds its own instance after validating its arguments.
3056 ///
3057 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3058 /// check runs before `new.target.prototype` is read.
3059 pub fn new_native_ctor(
3060 &self,
3061 name: impl Into<String>,
3062 length: u32,
3063 func: NativeFn,
3064 ) -> Gc<JsObject> {
3065 let function = JsObject::function(
3066 self.heap,
3067 Some(self.realm.function_proto.clone()),
3068 Callable::Native {
3069 func,
3070 own_instance: true,
3071 },
3072 );
3073 function.set_constructible(true);
3074 function.define(
3075 "length",
3076 Property::name_or_length(Value::Int(length as i32)),
3077 );
3078 function.define("name", Property::name_or_length(self.string(name)));
3079 function
3080 }
3081
3082 /// A native constructor that lets `new` build the instance first.
3083 ///
3084 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3085 /// validation that must precede reading `new.target.prototype`, so the object can be
3086 /// created before the implementation runs. Distinct from [`Interp::new_native`],
3087 /// which makes a *method* and therefore not a constructor at all.
3088 pub fn new_native_constructor(
3089 &self,
3090 name: impl Into<String>,
3091 length: u32,
3092 func: NativeFn,
3093 ) -> Gc<JsObject> {
3094 let function = self.new_native(name, length, func);
3095 function.set_constructible(true);
3096 function
3097 }
3098
3099 /// A new host function object: a native closure that carries its own state.
3100 ///
3101 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3102 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3103 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3104 /// this safe: the closure must not capture a `Gc`.
3105 pub fn new_host_function(
3106 &self,
3107 name: impl Into<String>,
3108 length: u32,
3109 func: crate::object::HostFn,
3110 ) -> Gc<JsObject> {
3111 self.new_host_inner(name.into(), length, func, false)
3112 }
3113
3114 /// A host constructor: `new` hands it `this = undefined`, so it validates its
3115 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3116 pub fn new_host_ctor(
3117 &self,
3118 name: impl Into<String>,
3119 length: u32,
3120 func: crate::object::HostFn,
3121 ) -> Gc<JsObject> {
3122 let function = self.new_host_inner(name.into(), length, func, true);
3123 function.set_constructible(true);
3124 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3125 // installs its own methods on it, so it starts as a plain object.
3126 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3127 function.define(
3128 "prototype",
3129 Property {
3130 value: Some(Value::Object(proto)),
3131 writable: true,
3132 enumerable: false,
3133 configurable: false,
3134 ..Property::default()
3135 },
3136 );
3137 function
3138 }
3139
3140 fn new_host_inner(
3141 &self,
3142 name: String,
3143 length: u32,
3144 func: crate::object::HostFn,
3145 own_instance: bool,
3146 ) -> Gc<JsObject> {
3147 let function = JsObject::function(
3148 self.heap,
3149 Some(self.realm.function_proto.clone()),
3150 Callable::Host {
3151 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3152 own_instance,
3153 },
3154 );
3155 function.define(
3156 "length",
3157 Property::name_or_length(Value::Int(length as i32)),
3158 );
3159 function.define("name", Property::name_or_length(self.string(name)));
3160 function
3161 }
3162
3163 /// A callable object with the `length`/`name` a built-in function has, in that order.
3164 ///
3165 /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3166 /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3167 /// [`JsObject::function`] defines neither, which is why every capability helper built
3168 /// with it reported no own `length` and no own `name` at all.
3169 ///
3170 /// The attributes are the spec's for a built-in: not writable, not enumerable,
3171 /// configurable.
3172 pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3173 let function =
3174 JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3175 function.define(
3176 "length",
3177 Property::name_or_length(Value::Int(length as i32)),
3178 );
3179 function.define("name", Property::name_or_length(self.string(name)));
3180 function
3181 }
3182
3183 /// A new native function object.
3184 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3185 let function = JsObject::function(
3186 self.heap,
3187 Some(self.realm.function_proto.clone()),
3188 Callable::Native {
3189 func,
3190 own_instance: false,
3191 },
3192 );
3193 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3194 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3195 // `length,name` and this listed `name,length`. A bytecode function already gets it
3196 // the right way round; only native ones were built backwards.
3197 function.define(
3198 "length",
3199 Property::name_or_length(Value::Int(length as i32)),
3200 );
3201 function.define("name", Property::name_or_length(self.string(name)));
3202 function
3203 }
3204
3205 /// A new bound function.
3206 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3207 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3208 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3209 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3210 let constructible = target
3211 .as_object()
3212 .is_some_and(|target| target.is_constructor());
3213 let bound = JsObject::function(
3214 self.heap,
3215 Some(self.realm.function_proto.clone()),
3216 Callable::Bound { target, this, args },
3217 );
3218 bound.set_constructible(constructible);
3219 bound
3220 }
3221
3222 /// A new reference cell.
3223 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3224 Gc::new(self.heap, Cell::new(value))
3225 }
3226
3227 // -- running ------------------------------------------------------------
3228
3229 /// Evaluate `code` as a script body and return its completion value.
3230 /// Compile and run `source` for the engine's own use, returning its completion value.
3231 ///
3232 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3233 /// needs to be a real async function, and the engine already runs those as coroutines,
3234 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3235 ///
3236 /// Differences from [`Self::eval_in_global`], both deliberate:
3237 ///
3238 /// * It does **not** drain the microtask queue. Install runs while the realm is still
3239 /// being built, and the source is an IIFE that only constructs a closure, so there
3240 /// is nothing to drain — and draining here would run script-queued jobs in the
3241 /// middle of `install`.
3242 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3243 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3244 /// and it should not look like the user wrote something wrong.
3245 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3246 let program = match js_parse::parse_script(source) {
3247 Ok(program) => program,
3248 Err(error) => {
3249 let message = format!("builtin source does not parse: {error}");
3250 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3251 }
3252 };
3253 let mut code = match js_compile::compile_script_with_source(&program, source) {
3254 Ok(code) => code,
3255 Err(error) => {
3256 let message = format!("builtin source does not compile: {}", error.message);
3257 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3258 }
3259 };
3260 // The frame has to name something, and `<builtin>` is what a stack trace through
3261 // this code should say.
3262 code.set_filename("<builtin>");
3263 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3264 let closure_vars = compiled.code.closure_vars.clone();
3265 let env = self.global_env(&closure_vars);
3266 let this = Value::Object(self.realm.global.clone());
3267 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3268 }
3269
3270 /// Run an already-parsed script and drain the microtasks it queued.
3271 ///
3272 /// The drain is what lets an `async` function's body advance past its first `await`
3273 /// before the host sees the result: nothing else pumps the job queue.
3274 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3275 let this = Value::Object(self.realm.global.clone());
3276 self.run_script_with_this(code, this)
3277 }
3278
3279 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3280 ///
3281 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3282 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3283 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3284 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3285 /// state the next script evaluation tripped over.
3286 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3287 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3288 let closure_vars = compiled.code.closure_vars.clone();
3289 let env = self.global_env(&closure_vars);
3290 let callee = Value::Undefined;
3291 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3292 // The script is done, so the microtasks it queued run before the host sees the
3293 // result. Without this an `async` function's body would never advance past its
3294 // first `await`, because nothing else drains the queue.
3295 self.drain_jobs()?;
3296 Ok(result)
3297 }
3298
3299 /// Compile and run `source` in global scope, returning its completion value.
3300 ///
3301 /// This is what `eval` and `new Function` use. Running it as a script means it
3302 /// sees the global object and nothing else, which is right for `eval("1+1")` and
3303 /// for a `Function` body; a *direct* eval that reads a local variable would need
3304 /// the compiler to hand its variable environment over, which is not implemented.
3305 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3306 self.eval_in_global_named(source, EVAL_FILE, false)
3307 }
3308
3309 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3310 ///
3311 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3312 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3313 /// through the code, so they cannot share one constant.
3314 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3315 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3316 }
3317
3318 /// Evaluate `source` as a global script, reported under `file`.
3319 ///
3320 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3321 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3322 /// from inside a C callback, where the interpreter is the running one rather than a
3323 /// context's own.
3324 pub fn eval_in_global_named(
3325 &mut self,
3326 source: &str,
3327 file: &str,
3328 barrier: bool,
3329 ) -> JsResult<Value> {
3330 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3331 // eval-created global binding — configurable, unlike a script's own `var`.
3332 self.eval_depth += 1;
3333 if barrier {
3334 let depth = self.frames.len();
3335 self.trace_barriers.push(depth);
3336 }
3337 let result = self.eval_in_global_inner(source, file);
3338 if barrier {
3339 self.trace_barriers.pop();
3340 }
3341 self.eval_depth -= 1;
3342 result
3343 }
3344
3345 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3346 let compiled = self.compile_global_script(source, file, false)?;
3347 let strict = compiled.strict;
3348 self.run_eval_script(compiled, strict)
3349 }
3350
3351 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3352 ///
3353 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3354 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3355 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3356 /// direct eval's is.
3357 pub fn eval_script_with_this(
3358 &mut self,
3359 source: &str,
3360 file: &str,
3361 this: Value,
3362 ) -> JsResult<Value> {
3363 let program = match js_parse::parse_script(source) {
3364 Ok(program) => program,
3365 Err(error) => {
3366 return Err(Signal::Throw(self.syntax_error_at(
3367 file,
3368 error.span.start.line,
3369 error.span.start.column,
3370 &error.message,
3371 )));
3372 }
3373 };
3374 let mut compiled = match js_compile::compile_script(&program) {
3375 Ok(compiled) => compiled,
3376 Err(error) => {
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 compiled.set_filename(file);
3386 self.run_script_with_this(compiled, this)
3387 }
3388
3389 /// Parse and compile `source` as a global script, without running it.
3390 ///
3391 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3392 /// before a promise exists to reject — while still evaluating in the same eval context
3393 /// (direct-eval strictness, `new.target`, `super`).
3394 fn compile_global_script(
3395 &mut self,
3396 source: &str,
3397 file: &str,
3398 async_body: bool,
3399 ) -> JsResult<CompiledFunction> {
3400 // A *direct* eval inherits the strictness of the code that called it, which is
3401 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3402 // implicit global. The caller's frame is the innermost one here, because a
3403 // native function does not push a frame of its own.
3404 let strict = self.current_strict();
3405 // `eval` runs in the caller's function context, so `new.target` is legal here
3406 // even though the source is a bare script — and so is `super.x` when the caller
3407 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3408 // caller's, which is what `special_object 4` already does.
3409 let context = js_parse::EvalContext {
3410 in_method: self.enclosing_home_object().is_some(),
3411 // `super()` belongs to a derived constructor, and an eval'd body is not a
3412 // constructor at all: the caller frame's `this` is already built.
3413 in_derived_constructor: false,
3414 };
3415 // A *global* eval is not a function body: `new.target` and `super` are out of
3416 // reach there. Its `{async: true}` form differs in the other direction — the body
3417 // may `await` — so the two flags are independent and the reference sets both from
3418 // the eval type rather than from the caller.
3419 let parsed = if async_body {
3420 js_parse::parse_suspensible_global_eval(source, strict)
3421 } else {
3422 js_parse::parse_eval_script_in(source, strict, context)
3423 };
3424 let program = match parsed {
3425 Ok(program) => program,
3426 Err(error) => {
3427 // The message is bare: the position lives in `fileName`,
3428 // `lineNumber`, `columnNumber` and the stack frame above, which is where
3429 // the reference puts it. An `invalid source: L:C: ` prefix made
3430 // `e.message` differ from the reference while the stack already agreed.
3431 return Err(Signal::Throw(self.syntax_error_at(
3432 file,
3433 error.span.start.line,
3434 error.span.start.column,
3435 &error.message,
3436 )));
3437 }
3438 };
3439 let mut compiled = match if async_body {
3440 js_compile::compile_script_suspensible(&program)
3441 } else {
3442 js_compile::compile_script(&program)
3443 } {
3444 Ok(compiled) => compiled,
3445 // A construct the compiler does not handle yet is reported the same way a
3446 // parse error is: it happens before anything runs, so the trace is the
3447 // position in the source followed by the caller.
3448 Err(error) => {
3449 return Err(Signal::Throw(self.syntax_error_at(
3450 file,
3451 error.span.start.line,
3452 error.span.start.column,
3453 &error.message,
3454 )));
3455 }
3456 };
3457 compiled.set_filename(file);
3458 Ok(compiled)
3459 }
3460
3461 /// Run an `eval`'d script in the caller's scope.
3462 ///
3463 /// Three things have to come from the calling frame, because the eval'd code is a
3464 /// script and would otherwise see only the global object:
3465 ///
3466 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3467 /// * `arguments`, exposed as a binding of the eval's own scope, so
3468 /// `f("arguments.length", 1)` sees the caller's arguments;
3469 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3470 /// `eval("var v = 1")` into the global object.
3471 ///
3472 /// Locals of the calling function are *not* reachable: that needs the compiler to
3473 /// hand its variable environment over, which this milestone does not do.
3474 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3475 // `this` and `arguments` come from the innermost frame only — those are not
3476 // lexical — while the name bindings come from the whole chain of frames, part
3477 // of it being ordinary scope resolution.
3478 // An arrow has no `this` of its own, so an `eval` inside one inherits the
3479 // enclosing function's receiver — the lexical `this` the arrow was compiled to
3480 // read from its closure.
3481 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3482 // variable environment is the innermost frame of all: an arrow's own body is where
3483 // `var`s declared by an `eval` inside it belong.
3484 let caller_index = self
3485 .frames
3486 .iter()
3487 .rposition(|frame| !frame.code.code.is_arrow)
3488 .or_else(|| self.frames.len().checked_sub(1));
3489 let env_index = self.frames.len().checked_sub(1);
3490 let caller = caller_index.and_then(|index| self.frames.get(index));
3491 let (this, passed) = match caller {
3492 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3493 // No frame at all: the eval is running at the top level, so there is
3494 // nothing to inherit and the global receiver is right.
3495 None => (Value::Object(self.realm.global.clone()), Vec::new()),
3496 };
3497 // Innermost frame first, so the first binding found for a name is the one that
3498 // shadows the rest. A script frame (`<eval>`) contributes nothing.
3499 let mut bindings: Vec<EvalBinding> = Vec::new();
3500 // The calling function's own bindings, resolved by the compiler at the call
3501 // site. That table is the only reliable answer when a name is declared twice in
3502 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3503 // body means, and guessing by declaration order picks the wrong one as soon as
3504 // two loops in a row use the same name.
3505 // Only a *direct* eval sees the caller's scope. The compiler records a site for
3506 // every direct call — a bare `eval(...)` callee — so finding one at the current
3507 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3508 // callee to a value first and leave no site behind.
3509 let mut direct = false;
3510 let mut resolved_here = false;
3511 if let Some(frame) = self.frames.last() {
3512 let (line, column) = frame
3513 .code
3514 .code
3515 .position_at(frame.at as u32)
3516 .unwrap_or_default();
3517 // The nearest site at or before the current position, not an exact match:
3518 // the recorded position of the `call` instruction is the callee's, which
3519 // sits a few columns inside the call expression the compiler recorded. A
3520 // site is unique per call, so "the closest one behind us" identifies it.
3521 if let Some(site) = frame
3522 .code
3523 .code
3524 .eval_sites
3525 .iter()
3526 .filter(|site| (site.line, site.column) <= (line, column))
3527 .max_by_key(|site| (site.line, site.column))
3528 {
3529 direct = true;
3530 resolved_here = true;
3531 for binding in &site.bindings {
3532 // An enclosing function's frame sits `owner` levels below the one
3533 // running the call.
3534 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3535 else {
3536 continue;
3537 };
3538 bindings.push(EvalBinding {
3539 name: binding.name.clone(),
3540 frame,
3541 slot: if binding.is_arg {
3542 EvalSlot::Arg
3543 } else {
3544 EvalSlot::Local
3545 },
3546 index: binding.index as usize,
3547 });
3548 }
3549 }
3550 }
3551 for frame_index in (0..self.frames.len()).rev() {
3552 // Skip the innermost frame's flat scan when the compiler already answered
3553 // for it; an enclosing frame still needs one, because the eval resolves
3554 // those names dynamically.
3555 if resolved_here && frame_index == self.frames.len() - 1 {
3556 continue;
3557 }
3558 let frame = &self.frames[frame_index];
3559 for (index, arg) in frame.code.code.args.iter().enumerate() {
3560 bindings.push(EvalBinding {
3561 name: arg.name.clone(),
3562 frame: frame_index,
3563 slot: EvalSlot::Arg,
3564 index,
3565 });
3566 }
3567 for (index, local) in frame.code.code.vars.iter().enumerate() {
3568 bindings.push(EvalBinding {
3569 name: local.name.clone(),
3570 frame: frame_index,
3571 slot: EvalSlot::Local,
3572 index,
3573 });
3574 }
3575 }
3576 let mut seen = BTreeSet::new();
3577 bindings.retain(|binding| seen.insert(binding.name.clone()));
3578
3579 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
3580 // elements is all the spec's ordinary uses need.
3581 //
3582 // Known divergence: this is bound for a *global* eval too, where there is no
3583 // caller and the reference throws `'arguments' is not defined`. Deciding properly
3584 // needs "does the calling frame have an `arguments` of its own", which is not
3585 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
3586 // script or eval body does not, and `eval(b)` passes the callee as a value so even
3587 // the call-site detection does not answer it. Modelled as a binding in the caller's
3588 // variable environment, this would fall out; that is a larger change than the one
3589 // this comment is attached to.
3590 let arguments = Value::Object(self.new_array(passed));
3591
3592 // Only a *strict* eval gets a variable environment of its own. A sloppy one
3593 // declares its `var`s in the caller's — which for a top-level eval is the global
3594 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
3595 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
3596 // vanish into a scope nobody reads back from.
3597 let previous_scope = if code_strict {
3598 self.eval_scope.replace(BTreeMap::new())
3599 } else {
3600 None
3601 };
3602 let previous_arguments = self.eval_arguments.replace(arguments);
3603 let previous_with = self.eval_with.replace(self.with_objects());
3604 let inherited_new_target = self
3605 .frames
3606 .iter()
3607 .rev()
3608 .find(|frame| !frame.code.code.is_arrow)
3609 .map(|frame| frame.new_target.clone());
3610 let previous_new_target = self
3611 .eval_new_target
3612 .replace(inherited_new_target.unwrap_or(Value::Undefined));
3613 let eval_cells = self.eval_cells_for(&bindings);
3614 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
3615 // A sloppy direct eval declares its `var`s in the caller's variable environment;
3616 // `declare_eval_local` needs to know which frame that is.
3617 // An indirect eval gets the global environment, so nothing of the caller's is
3618 // recorded as the place its `var`s belong.
3619 let previous_caller = self
3620 .eval_caller
3621 .replace(if direct { env_index } else { None });
3622 // The cell-based view of the same bindings, which is what a closure created
3623 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
3624 // whose compiler did not put a binding in a cell simply does not appear here —
3625 // reads and writes still work through `eval_bindings`, they just cannot outlive
3626 // the eval.
3627 let previous_eval_scope = self
3628 .active_eval_scope
3629 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
3630 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3631 let closure_vars = compiled.code.closure_vars.clone();
3632 let env = self.global_env(&closure_vars);
3633 let callee = Value::Undefined;
3634 // An async body does not run here: it becomes a coroutine and answers a promise,
3635 // which is what makes `await` legal in it. `this` still has to be the caller's
3636 // (for a global eval, the global object), because `this` is not part of `await`.
3637 let result = if compiled.code.kind.is_async() {
3638 self.run_async_body(compiled, env, this)
3639 } else {
3640 self.execute(compiled, env, this, Vec::new(), callee)
3641 };
3642 self.eval_scope = previous_scope;
3643 self.eval_arguments = previous_arguments;
3644 self.eval_with = previous_with;
3645 self.eval_new_target = previous_new_target;
3646 self.eval_bindings = previous_bindings;
3647 self.eval_caller = previous_caller;
3648 self.active_eval_scope = previous_eval_scope;
3649 result
3650 }
3651
3652 /// The cell-backed subset of `bindings`, in the same priority order.
3653 ///
3654 /// Both lookup routes have to agree — the eval's own reads go through
3655 /// [`Interp::eval_binding_value`] and the closures it builds go through
3656 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
3657 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
3658 /// is not in a cell simply does not appear: reads and writes still work, they just
3659 /// cannot be handed to a closure that outlives the eval.
3660 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
3661 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
3662 for binding in bindings {
3663 let Some(frame) = self.frames.get(binding.frame) else {
3664 continue;
3665 };
3666 let cell = match binding.slot {
3667 EvalSlot::Arg => frame
3668 .code
3669 .arg_cell
3670 .get(binding.index)
3671 .copied()
3672 .unwrap_or(-1),
3673 EvalSlot::Local => frame
3674 .code
3675 .loc_cell
3676 .get(binding.index)
3677 .copied()
3678 .unwrap_or(-1),
3679 };
3680 if cell < 0 {
3681 continue;
3682 }
3683 if let Some(cell) = frame.cells.get(cell as usize) {
3684 names.push((binding.name.clone(), cell.clone()));
3685 }
3686 }
3687 names
3688 }
3689
3690 /// A `SyntaxError` that reports where in the source it happened.
3691 ///
3692 /// Compile-time failures never run, so they have no frame of their own; the
3693 /// reference still puts the position first in the trace, with no function name and
3694 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
3695 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
3696 /// reference borrows), which is how a script reads the position without parsing
3697 /// the trace.
3698 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
3699 ///
3700 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
3701 /// `columnNumber`, which is how the reference prints one. A positionless error
3702 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
3703 /// the reference raises it from `js_resolve_module`, where there is no position.
3704 pub(crate) fn syntax_error_plain(
3705 &mut self,
3706 error: &js_parse::SyntaxError,
3707 file: &str,
3708 ) -> Value {
3709 if error.positionless {
3710 return self.make_error("SyntaxError", &error.message);
3711 }
3712 self.syntax_error_at(
3713 file,
3714 error.span.start.line,
3715 error.span.start.column,
3716 &error.message,
3717 )
3718 }
3719
3720 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
3721 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
3722 let value = self.make_error("SyntaxError", message);
3723 if let Value::Object(object) = &value {
3724 let text = self.string(blamed);
3725 // `stack` is an own data property, and the reference keeps it
3726 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
3727 object.define("stack", Property::with_attributes(text, true, false));
3728 let name = self.string(file);
3729 object.define("fileName", Property::with_attributes(name, true, true));
3730 object.define(
3731 "lineNumber",
3732 Property::with_attributes(Value::Int(line as i32), true, true),
3733 );
3734 object.define(
3735 "columnNumber",
3736 Property::with_attributes(Value::Int(column as i32), true, true),
3737 );
3738 }
3739 value
3740 }
3741
3742 /// Run a compiled script whose completion value is a function, returning it.
3743 ///
3744 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
3745 /// get the closure out, which keeps the constant-pool plumbing in one place.
3746 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
3747 self.run_script(code)
3748 }
3749
3750 /// The environment of a script or of any function compiled at global scope:
3751 /// every entry is a global binding, so each one resolves to the realm's cell.
3752 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
3753 let mut cells = Vec::with_capacity(closure_vars.len());
3754 for closure_var in closure_vars {
3755 let cell = match closure_var.closure_type {
3756 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
3757 if closure_var.is_lexical =>
3758 {
3759 // A lexical declaration: the cell is created here holding the
3760 // dead-zone marker, which is what makes the binding exist and
3761 // unreadable before its initialiser runs.
3762 self.declare_global(&closure_var.name, closure_var.is_const);
3763 self.realm.globals[&closure_var.name].clone()
3764 }
3765 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
3766 // A `var` or function declaration becomes a property of the global
3767 // object, and it exists from here on — which is why
3768 // `print(v); var v = 1` prints `undefined` instead of raising.
3769 // Declaring it at instantiation time (rather than at the
3770 // initialiser) is also what makes it non-configurable: the store
3771 // then lands on an existing property instead of creating one.
3772 self.declare_var_global(&closure_var.name);
3773 // The cell is a placeholder that nothing indexes; it cannot be
3774 // omitted because the slot has to hold something.
3775 self.new_cell(Value::Undefined)
3776 }
3777 _ => {
3778 // An undeclared global is read by name; the cell is a
3779 // placeholder that nothing indexes.
3780 self.new_cell(Value::Undefined)
3781 }
3782 };
3783 cells.push(cell);
3784 }
3785 Gc::new(
3786 self.heap,
3787 ClosureEnv {
3788 cells,
3789 eval_scope: None,
3790 local_vars: None,
3791 local_phase: 1,
3792 },
3793 )
3794 }
3795
3796 /// Push a frame and run until it returns.
3797 pub(crate) fn execute(
3798 &mut self,
3799 code: Gc<CompiledCode>,
3800 env: Gc<ClosureEnv>,
3801 this: Value,
3802 args: Vec<Value>,
3803 callee: Value,
3804 ) -> JsResult<Value> {
3805 let depth = self.frames.len();
3806 if depth == 0 {
3807 // A throw that reached the host ends the *active* mode: the next one is catchable
3808 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
3809 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
3810 // for the throw that evaluation will raise.
3811 self.uncatchable = false;
3812 }
3813 self.push_frame(code, env, this, args, callee)?;
3814 loop {
3815 // The fast loop first: it runs whole runs of records with `pc` in a register.
3816 //
3817 // `step`'s `pc` lives in the frame, so every instruction writes it back and
3818 // reads it again — a store, a load and two bounds checks that a loop body does
3819 // not need, because nothing outside the loop can run in between. This is the
3820 // classic split: advance a register, and only spill it when leaving.
3821 //
3822 // `Some(value)` means the function ended by running off the end of its
3823 // instruction array, which is a normal return.
3824 let step = match self.run_fast() {
3825 Ok(Some(value)) => Ok(Step::Return(value)),
3826 Ok(None) => self.step(),
3827 Err(signal) => Err(signal),
3828 };
3829 match step {
3830 Ok(Step::Continue) => {}
3831 Ok(Step::Return(value)) => {
3832 self.pop_frame();
3833 // A frame that ended in a `tail_call` hands its value straight to
3834 // its caller: nothing after the call can run, so every frame above
3835 // the callee unwinds with the same value. See [`Frame::tail`] —
3836 // the reference does not reuse frames either, so recursion depth
3837 // and the stack-overflow limit behave the same way.
3838 while self.frames.len() > depth && self.frame().tail {
3839 self.pop_frame();
3840 }
3841 if self.frames.len() == depth {
3842 return Ok(value);
3843 }
3844 // The caller resumes with the value on its stack.
3845 self.frames
3846 .last_mut()
3847 .expect("a caller is live")
3848 .stack
3849 .push(value);
3850 }
3851 Err(Signal::Throw(value)) => {
3852 // The host's standing request becomes the active mode for this unwind,
3853 // and is consumed here so it does not leak into the next throw.
3854 if self.uncatchable_next {
3855 self.uncatchable_next = false;
3856 self.uncatchable = true;
3857 }
3858 // An uncatchable throw walks past every `catch` on the way out. The
3859 // frames are still popped, because the values they hold have to be
3860 // dropped — only the search for a handler is skipped.
3861 if self.uncatchable {
3862 while self.frames.len() > depth {
3863 self.frames.pop();
3864 }
3865 return Err(Signal::Throw(value));
3866 }
3867 // A handler lives on the stack of the frame that is throwing —
3868 // `catch` pushed it there — so this frame gets the first chance
3869 // to catch before it is popped.
3870 let value = value;
3871 loop {
3872 if self.frames.len() <= depth {
3873 return Err(Signal::Throw(value));
3874 }
3875 if self.catch_here(value.clone()).is_some() {
3876 break;
3877 }
3878 self.frames.pop();
3879 }
3880 }
3881 // A `yield` in a frame that `execute` is running directly means a
3882 // generator body was entered as an ordinary call, which only happens if
3883 // the generator check in `call_or_push` was bypassed.
3884 Ok(Step::Suspend(_)) => {
3885 return Err(Signal::Throw(self.make_error(
3886 "InternalError",
3887 "a generator body ran as an ordinary call",
3888 )));
3889 }
3890 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
3891 }
3892 }
3893 }
3894
3895 /// Install a handler for `value` if this frame has one, resuming at it.
3896 ///
3897 /// The scan is the reference's: walk the frame's stack downwards looking for the
3898 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
3899 /// `0` is an enumerator marker rather than a handler — it exists so that a
3900 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
3901 /// here and the unwinding continues.
3902 fn catch_here(&mut self, value: Value) -> Option<()> {
3903 let frame = self.frames.last_mut()?;
3904 while let Some(top) = frame.stack.pop() {
3905 if let Value::CatchOffset(offset) = top {
3906 if offset == 0 {
3907 continue;
3908 }
3909 frame.stack.push(value);
3910 frame.pc = offset as usize;
3911 return Some(());
3912 }
3913 }
3914 None
3915 }
3916
3917 fn push_frame(
3918 &mut self,
3919 code: Gc<CompiledCode>,
3920 env: Gc<ClosureEnv>,
3921 this: Value,
3922 mut args: Vec<Value>,
3923 callee: Value,
3924 ) -> JsResult<()> {
3925 // Two bounds, and the byte budget is the one that decides in practice. The
3926 // reference's message is `stack overflow` on an `InternalError`, not V8's
3927 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
3928 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
3929 let frame_cost = Self::frame_cost(&code);
3930 let stack_base = self.stack_used();
3931 if self.frames.len() >= self.max_frames
3932 || stack_base.saturating_add(frame_cost) > self.stack_limit
3933 {
3934 return Err(Signal::Throw(
3935 self.make_error("InternalError", "stack overflow"),
3936 ));
3937 }
3938 let arg_count = code.code.args.len();
3939 // How many were actually passed, which `arguments.length` reports and
3940 // `assert(x)` depends on: a call with one argument must not look like a call
3941 // with one argument and an explicit `undefined`.
3942 let passed = args.len();
3943 // Missing arguments are `undefined` in their slots; extra ones are dropped
3944 // from the slots but still reachable through `arguments`.
3945 //
3946 // A call that passes no more than the declared parameters needs **no** copy:
3947 // after the resize below, `args[..passed]` *is* the passed values. Only the
3948 // extra ones — which `truncate` is about to drop — have to be kept, and they are
3949 // the rare case. This used to copy every call: one `Value` clone per argument
3950 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
3951 let passed_overflow = (passed > arg_count).then(|| {
3952 let mut values = self.take_values(passed, Value::Undefined);
3953 values[..passed].clone_from_slice(&args[..passed]);
3954 values
3955 });
3956 // Only when the counts differ, which for the overwhelmingly common call — as many
3957 // arguments as parameters — is never. `resize` followed by `truncate` on equal
3958 // lengths is two length compares and nothing else, but this is the hottest few
3959 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
3960 if passed != arg_count {
3961 args.resize(arg_count, Value::Undefined);
3962 args.truncate(arg_count);
3963 }
3964 let cell_count = code.code.var_ref_count as usize;
3965 let mut cells = Vec::with_capacity(cell_count);
3966 for _ in 0..cell_count {
3967 cells.push(self.new_cell(Value::Undefined));
3968 }
3969 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
3970 // A captured argument lives in its cell, not in the argument slot, so the
3971 // incoming value has to be moved there before the body runs.
3972 for (slot, cell) in code.arg_cell.iter().enumerate() {
3973 if *cell >= 0
3974 && let Some(value) = args.get(slot).cloned()
3975 {
3976 cells[*cell as usize].set(value);
3977 }
3978 }
3979 // Sloppy mode substitutes the global object for a missing receiver and boxes a
3980 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
3981 // reports `object`. Strict mode passes the value through untouched.
3982 let this = if code.code.strict {
3983 this
3984 } else if this.is_nullish() {
3985 Value::Object(self.realm.global.clone())
3986 } else if matches!(this, Value::Object(_)) {
3987 this
3988 } else {
3989 match crate::builtins::this_object(self, &this) {
3990 Ok(boxed) => Value::Object(boxed),
3991 Err(_) => this,
3992 }
3993 };
3994 let stack_depth = code.code.stack_size as usize + 1;
3995 // Taken before the `push` borrows `self.frames`, because the operand stack comes
3996 // out of the same recycle pool the locals did.
3997 let stack = self.take_values(stack_depth, Value::Undefined);
3998 self.frames.push(Frame {
3999 code,
4000 env,
4001 this,
4002 args,
4003 passed_count: passed,
4004 passed_overflow: passed_overflow.map(Box::new),
4005 locals,
4006 cells,
4007 local_vars: None,
4008 // Exactly the depth the compiler computed, so the operand stack never
4009 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4010 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4011 // the buffer between calls, so "exactly" costs nothing after the first one.
4012 stack,
4013 pc: 0,
4014 at: 0,
4015 callee,
4016 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4017 cost: frame_cost,
4018 stack_base,
4019 tail: false,
4020 });
4021 Ok(())
4022 }
4023
4024 /// A value buffer of `len` slots, from the recycle pool when there is one.
4025 ///
4026 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4027 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4028 // A frame with no locals asks for nothing, and that is most frames: taking a
4029 // buffer out of the pool, clearing it and resizing it to zero is four operations
4030 // and a pool pop for an empty `Vec`, which is free to construct.
4031 if len == 0 {
4032 return Vec::new();
4033 }
4034 let mut buffer = self.free_values.pop().unwrap_or_default();
4035 buffer.clear();
4036 buffer.resize(len, fill);
4037 buffer
4038 }
4039
4040 /// Return a finished frame's value buffers for the next call to reuse.
4041 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4042 for mut buffer in [
4043 std::mem::take(&mut frame.locals),
4044 frame
4045 .passed_overflow
4046 .take()
4047 .map(|buffer| *buffer)
4048 .unwrap_or_default(),
4049 std::mem::take(&mut frame.stack),
4050 ] {
4051 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4052 // GC root: it kept every value the frame held reachable, which is invisible
4053 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4054 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4055 // exactly that within one run — the target `{}` of a finished IIFE was still
4056 // in its operand stack, in the pool.
4057 buffer.clear();
4058 // A buffer with no capacity is what `Vec::new` is; putting it back would just
4059 // fill the pool with nothing to offer.
4060 if free_values.len() < RECYCLE_SLOTS
4061 && buffer.capacity() > 0
4062 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4063 {
4064 free_values.push(buffer);
4065 }
4066 }
4067 }
4068
4069 /// Pop a finished frame and keep its buffers.
4070 ///
4071 /// Every place that drops a frame goes through here: a recycled buffer is also where
4072 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4073 /// nothing but the reuse.
4074 fn pop_frame(&mut self) -> Option<()> {
4075 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4076 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4077 let last = self.frames.len().checked_sub(1)?;
4078 Self::recycle(&mut self.free_values, &mut self.frames[last]);
4079 self.frames.truncate(last);
4080 Some(())
4081 }
4082
4083 /// Poll the host's interrupt handler, if one is installed.
4084 ///
4085 /// The counter is what keeps this off the hot path when nobody asked: the early return is
4086 /// one `Option` test, and with no handler installed the whole function is that test —
4087 /// `check_memory` next door already costs more, so this cannot be what shows up in a
4088 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4089 #[inline]
4090 fn check_interrupt(&mut self) -> JsResult<()> {
4091 if self.interrupt.is_none() {
4092 return Ok(());
4093 }
4094 if self.interrupt_counter > 0 {
4095 self.interrupt_counter -= 1;
4096 return Ok(());
4097 }
4098 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4099 // The closure is taken out for the duration so that a handler which re-enters the
4100 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4101 let mut handler = self.interrupt.take().expect("checked above");
4102 let abort = handler();
4103 self.interrupt = Some(handler);
4104 if abort {
4105 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4106 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4107 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4108 // documentation says.
4109 self.uncatchable = true;
4110 return Err(Signal::Throw(
4111 self.make_error("InternalError", "interrupted"),
4112 ));
4113 }
4114 Ok(())
4115 }
4116
4117 /// A memory checkpoint: does the heap still fit under its limit?
4118 ///
4119 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4120 /// a `Cell` read and a predictable branch, and the point of asking that often is that
4121 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4122 /// only at calls would let it run until the machine died, which is the exact failure
4123 /// `--memory-limit` exists to prevent.
4124 ///
4125 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4126 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4127 /// script that catches it, drops the reference and carries on is legitimate: measured
4128 /// on `qjs --memory-limit 1M`, the engine recovers.
4129 fn check_memory(&mut self) -> JsResult<()> {
4130 // One `Cell` read and a predictable branch when no limit is set, and an integer
4131 // compare when one is. Containers report their own growth as it happens
4132 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4133 // walking it here was the first version and it was O(live) per 256 instructions,
4134 // which turned a 100k-element push loop into a five-minute one.
4135 let Some(limit) = self.heap.memory_limit() else {
4136 return Ok(());
4137 };
4138 let used = self.heap.used_bytes();
4139 if used <= limit {
4140 // Back under the limit — a collection or a dropped reference did it. The next
4141 // time it goes over is a new failure, not a repeat of this one.
4142 self.oom_reported_at = 0;
4143 return Ok(());
4144 }
4145 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4146 // block runs normally after `out of memory` — it allocates nothing, so nothing
4147 // fails. A check that re-fired on every instruction made the handler itself throw,
4148 // which is a dead end: the error became unobservable from script.
4149 //
4150 // Comparing against the total at the last report gives the same behaviour: the
4151 // handler runs while the total is unchanged, and the very next allocation over the
4152 // limit fails.
4153 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4154 {
4155 return Ok(());
4156 }
4157 self.oom_reported_at = used;
4158 Err(Signal::Throw(
4159 self.make_error("InternalError", "out of memory"),
4160 ))
4161 }
4162
4163 /// Fail before allocating `payload` bytes, if they would not fit.
4164 ///
4165 /// For the allocations whose size comes from script data — `new Array(n)`,
4166 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4167 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4168 /// answering NULL for the one big request.
4169 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4170 if self.heap.fits(payload) {
4171 return Ok(());
4172 }
4173 Err(Signal::Throw(
4174 self.make_error("InternalError", "out of memory"),
4175 ))
4176 }
4177
4178 /// Bytes of frame state the live call chain accounts for.
4179 pub fn stack_used(&self) -> usize {
4180 match self.frames.last() {
4181 Some(frame) => frame.stack_base + frame.cost,
4182 None => 0,
4183 }
4184 }
4185
4186 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4187 ///
4188 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4189 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4190 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4191 /// instead. That is the whole difference between the two models: it rations C stack, we
4192 /// ration frame state, and both quantities are dominated by the value slots — which is
4193 /// why the two depths come out comparable rather than merely proportional.
4194 fn frame_cost(code: &CompiledCode) -> usize {
4195 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4196 std::mem::size_of::<Frame>()
4197 + std::mem::size_of::<Value>() * slots
4198 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4199 }
4200
4201 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4202 ///
4203 /// Only names the eval created are here: a name the frame already declared statically
4204 /// is written through to its own slot instead, so this cannot shadow a real local.
4205 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4206 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4207 let (local_vars, phase) = self.visible_local_vars()?;
4208 if !local_vars.contains(name) {
4209 return None;
4210 }
4211 local_vars.get(name, phase)
4212 }
4213
4214 /// The variables a direct `eval` declared, as the code currently running sees them.
4215 ///
4216 /// Inside an eval that is the *caller's* set — the eval's own variable environment
4217 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4218 /// else it is the current frame's, falling back to the frame the closure was created
4219 /// in.
4220 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4221 ///
4222 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4223 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4224 /// refcount operations (the clone out of the frame, the drop at the end of the match)
4225 /// just to be asked `is_none`.
4226 fn has_visible_local_vars(&self) -> bool {
4227 let index = match self.eval_caller.flatten() {
4228 Some(caller) => caller,
4229 None => match self.frames.len().checked_sub(1) {
4230 Some(top) => top,
4231 None => return false,
4232 },
4233 };
4234 match self.frames.get(index) {
4235 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4236 None => false,
4237 }
4238 }
4239
4240 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4241 // While an `eval` runs, its own frame is on top but its variable environment is
4242 // the *caller's* — so the caller is what the lookup has to start from.
4243 let (index, phase) = match self.eval_caller.flatten() {
4244 Some(caller) => (
4245 caller,
4246 if self.in_parameter_list_at(caller) {
4247 0
4248 } else {
4249 1
4250 },
4251 ),
4252 None => (
4253 self.frames.len().checked_sub(1)?,
4254 if self.in_parameter_list() { 0 } else { 1 },
4255 ),
4256 };
4257 let frame = self.frames.get(index)?;
4258 // The frame's own variables, or — for an arrow, which has no variable environment
4259 // of its own — the one it was created in, which `ClosureEnv` carries.
4260 if let Some(local_vars) = frame.local_vars.clone() {
4261 return Some((local_vars, phase));
4262 }
4263 frame
4264 .env
4265 .local_vars
4266 .clone()
4267 .map(|local_vars| (local_vars, frame.env.local_phase))
4268 }
4269
4270 /// Whether the innermost frame is still evaluating its parameter list.
4271 ///
4272 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4273 /// and a closure created there may only see that much of [`LocalVars`].
4274 fn in_parameter_list(&self) -> bool {
4275 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4276 }
4277
4278 /// [`Interp::in_parameter_list`] for a specific frame.
4279 fn in_parameter_list_at(&self, frame: usize) -> bool {
4280 let Some(frame) = self.frames.get(frame) else {
4281 return false;
4282 };
4283 let code = &frame.code.code;
4284 if !code.has_parameter_expressions {
4285 return false;
4286 }
4287 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4288 // function as its body and let a direct `eval` act accordingly.
4289 if code.body_start == (0, 0) {
4290 return false;
4291 }
4292 match code.position_at(frame.at as u32) {
4293 Some(position) => position < code.body_start,
4294 None => false,
4295 }
4296 }
4297
4298 fn frame(&self) -> &Frame {
4299 self.frames.last().expect("a frame is live")
4300 }
4301
4302 fn frame_mut(&mut self) -> &mut Frame {
4303 self.frames.last_mut().expect("a frame is live")
4304 }
4305
4306 // -- slot access --------------------------------------------------------
4307
4308 /// Move a local's value out, leaving `undefined` in the slot.
4309 ///
4310 /// `None` for a captured slot: its value lives in a cell shared with every closure
4311 /// that closed over it, so it can never be exclusively ours and must not be taken.
4312 ///
4313 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4314 /// for every read and fatal for this one — a clone is exactly the second handle that
4315 /// rules out growing the string in place.
4316 fn take_loc(&mut self, slot: usize) -> Option<Value> {
4317 let frame = self.frames.last_mut()?;
4318 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4319 return None;
4320 }
4321 frame
4322 .locals
4323 .get_mut(slot)
4324 .map(|value| std::mem::replace(value, Value::Undefined))
4325 }
4326
4327 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4328 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4329 ///
4330 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4331 /// it** — the value is put back before the general path runs — so a `valueOf` that
4332 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4333 /// error as it would have without the fusion. This is why the in-place attempt is a
4334 /// `take` and not a `get`: an optimisation that changes what an exception observes is
4335 /// a wrong answer with a good excuse.
4336 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4337 // The take is `matches!`-guarded on the *right* operand only, and the taken value
4338 // is put back on every path that does not append. An earlier version wrote the two
4339 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4340 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4341 // through with its value already taken and dropped: the general path below then
4342 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4343 // A wrong answer, from an optimisation, with every test green.
4344 if matches!(right, Value::String(_))
4345 && let Some(taken) = self.take_loc(slot)
4346 {
4347 if let Value::String(mut left) = taken {
4348 let appended = match left.get_mut() {
4349 Some(string) => string.append_in_place(
4350 // The pattern is the one `matches!` just checked.
4351 match &right {
4352 Value::String(text) => text,
4353 _ => unreachable!("guarded above"),
4354 },
4355 ),
4356 None => None,
4357 };
4358 self.put_loc(slot, Value::String(left));
4359 if let Some(added) = appended {
4360 // The buffer grew where it stood, so the heap's running total has to
4361 // be told: `measure_used` would report the new length, and the two must
4362 // agree or the subtraction at free time leaves the counter wrong.
4363 self.heap.adjust_payload(added as isize);
4364 return Ok(());
4365 }
4366 } else {
4367 self.put_loc(slot, taken);
4368 }
4369 }
4370 // The two-number case, without an operand stack round trip. Everything below
4371 // this point is the *general* path: push both, call `binary_add`, pop the answer,
4372 // store it — five operations and two `Value` clones for what is one integer add.
4373 // `AddImmLoc` already answers this shape that way; the fusion above it was written
4374 // for string append and never got the numeric half, so `t += i` — a counting loop
4375 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4376 let left = self.get_loc(slot);
4377 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4378 self.put_loc(
4379 slot,
4380 match a.checked_add(*b) {
4381 Some(sum) => Value::Int(sum),
4382 None => Value::Float(*a as f64 + *b as f64),
4383 },
4384 );
4385 return Ok(());
4386 }
4387 self.push(left);
4388 self.push(right);
4389 self.binary_add()?;
4390 let value = self.pop();
4391 self.put_loc(slot, value);
4392 Ok(())
4393 }
4394
4395 fn get_arg(&self, slot: usize) -> Value {
4396 self.frame().read_arg(slot)
4397 }
4398
4399 fn put_arg(&mut self, slot: usize, value: Value) {
4400 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4401 if cell == -1 {
4402 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4403 *slot = value;
4404 }
4405 } else {
4406 self.frame().cells[cell as usize].set(value);
4407 }
4408 }
4409
4410 fn get_loc(&self, slot: usize) -> Value {
4411 // The cell mapping is `-1` for every slot that was not captured — which is all of
4412 // them in a function that creates no closure. `Frame::read_loc` tests that first,
4413 // so the common case is one array read and a clone: 20% of every loop iteration
4414 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4415 // sample of `dispatch:arith`).
4416 self.frame().read_loc(slot)
4417 }
4418
4419 fn put_loc(&mut self, slot: usize, value: Value) {
4420 // One borrow instead of three, and the cell check on the frame we already hold.
4421 let frame = self.frames.last_mut().expect("a frame is live");
4422 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4423 if cell < 0 {
4424 if let Some(slot) = frame.locals.get_mut(slot) {
4425 *slot = value;
4426 }
4427 } else if let Some(cell) = frame.cells.get(cell as usize) {
4428 cell.set(value);
4429 }
4430 }
4431
4432 // -- globals ------------------------------------------------------------
4433
4434 /// The name a global-slot operand refers to.
4435 fn global_name(&self, slot: usize) -> String {
4436 self.frame()
4437 .code
4438 .code
4439 .closure_vars
4440 .get(slot)
4441 .map(|c| c.name.clone())
4442 .unwrap_or_default()
4443 }
4444
4445 /// The facts about a global binding that decide where it lives.
4446 ///
4447 /// A script's globals split in two, and the split is observable: `var` and
4448 /// function declarations become properties of the global object (`globalThis.v`
4449 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4450 /// declarations live in the global *lexical* environment and are invisible there
4451 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4452 /// `is_lexical` flag means the answer is already in the bytecode.
4453 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4454 let name = self.global_name(slot);
4455 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4456 // while forwarding a reference through a nested function is built with the
4457 // flags cleared, so `const c` would look like an ordinary `var` from inside a
4458 // closure. Presence in the realm's lexical table is the same fact, recorded
4459 // once, and every slot sees it.
4460 let lexical = self.realm.globals.contains_key(&name);
4461 let is_const = self.realm.lexical_consts.contains(&name);
4462 (name, lexical, is_const)
4463 }
4464
4465 /// The value of `name` in the innermost active `with` object, if any.
4466 ///
4467 /// The active objects are the [`VarKind::With`] locals of every frame still running,
4468 /// innermost frame first and innermost block first within one. Walking frames rather
4469 /// than keeping a separate stack is what makes a closure called from inside a `with`
4470 /// see it, and what keeps the object alive only as long as the block is.
4471 /// The innermost active `with` object that has `name`, if any.
4472 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4473 let objects = self.eval_with.clone().unwrap_or_default();
4474 for object in objects {
4475 let key = self.string(name.to_string());
4476 if self
4477 .has_property(&key, &Value::Object(object.clone()))
4478 .ok()?
4479 {
4480 return Some(object);
4481 }
4482 }
4483 None
4484 }
4485
4486 /// Every active `with` object, innermost first.
4487 fn with_objects(&self) -> Vec<Gc<JsObject>> {
4488 let mut objects = Vec::new();
4489 for frame in self.frames.iter().rev() {
4490 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4491 if var.kind != js_compile::VarKind::With {
4492 continue;
4493 }
4494 // A captured binding lives in its cell and not in the slot list, so the
4495 // cell is consulted first — a closure created inside the block is exactly
4496 // what makes the object captured. Before the store runs the slot still
4497 // holds `undefined`, and a `with` object is always boxed, so a non-object
4498 // entry is simply not in scope yet.
4499 let value = frame
4500 .code
4501 .loc_cell
4502 .get(index)
4503 .copied()
4504 .filter(|cell| *cell >= 0)
4505 .and_then(|cell| frame.cells.get(cell as usize))
4506 .map(|cell| cell.get())
4507 .or_else(|| frame.locals.get(index).cloned());
4508 if let Some(Value::Object(object)) = value {
4509 objects.push(object);
4510 }
4511 }
4512 }
4513 objects
4514 }
4515
4516 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4517 for object in self.eval_with.clone().unwrap_or_default() {
4518 let key = self.string(name.to_string());
4519 if self.has_property(&key, &Value::Object(object.clone()))? {
4520 return Ok(Some(self.read_field(&Value::Object(object), name)?));
4521 }
4522 }
4523 Ok(None)
4524 }
4525
4526 /// Whether every scope between here and the global object is an ordinary one.
4527 ///
4528 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4529 /// bytecode resolved; when any is live the general path has to run in full order. When
4530 /// none is — every ordinary program — a global read is a property read and nothing
4531 /// else, and that is worth caching.
4532 fn scopes_are_plain(&self) -> bool {
4533 self.eval_caller.is_none()
4534 && self.eval_with.is_none()
4535 && self.eval_arguments.is_none()
4536 && self.eval_bindings.is_empty()
4537 && self.eval_scope.is_none()
4538 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4539 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4540 // its `ClosureEnv`, so the test has to be the same one the general path makes.
4541 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4542 // upstream corpus caught and no unit test did.
4543 && !self.has_visible_local_vars()
4544 && self.frame().env.eval_scope.is_none()
4545 }
4546
4547 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4548 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4549 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4550 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4551 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4552 // borrow outlive the `&mut self` the lookup needs.
4553 //
4554 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4555 // forwarded through a nested function has its flags cleared, so the flag cannot
4556 // be believed.
4557 let code = self.frame().code.clone();
4558 let name = code
4559 .code
4560 .closure_vars
4561 .get(slot)
4562 .map(|c| c.name.as_str())
4563 .unwrap_or_default();
4564 let lexical = self.realm.globals.contains_key(name);
4565 // The common case, first: an ordinary global `var`, with a cache in front of the
4566 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4567 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4568 // cache hit and return without touching any of it.
4569 if !lexical && self.scopes_are_plain() {
4570 return self.get_plain_global(name, slot);
4571 }
4572 if name == "arguments"
4573 && let Some(arguments) = &self.eval_arguments
4574 {
4575 return Ok(arguments.clone());
4576 }
4577 // A `with` block around the *call site* is part of the scope an `eval` sees, so
4578 // the objects live when the eval started are consulted before anything else. The
4579 // snapshot is taken at entry rather than scanning the frames on every read: a
4580 // block that has already finished still leaves its object in the slot, and a
4581 // bytecode read outside the block must not see it.
4582 if let Some(value) = self.with_lookup(name)? {
4583 return Ok(value);
4584 }
4585 // A variable a direct `eval` declared shadows everything the compiler resolved,
4586 // including an enclosing function's binding: the eval put it in the caller's own
4587 // variable environment, which is nearer than any captured scope.
4588 if let Some((local_vars, phase)) = self.visible_local_vars()
4589 && let Some(cell) = local_vars.get(name, phase)
4590 {
4591 return Ok(cell.get());
4592 }
4593 // The frame that called `eval` is the innermost scope the eval'd code sees, so
4594 // its local `a` wins over a global `a`.
4595 if let Some(value) = self.eval_binding_value(name) {
4596 return Ok(value);
4597 }
4598 // A closure created by an `eval` resolves its free names against the bindings
4599 // that eval saw, even after the eval (and its frames) are gone.
4600 if let Some(cell) = self
4601 .frame()
4602 .env
4603 .eval_scope
4604 .as_ref()
4605 .and_then(|scope| scope.get(name))
4606 {
4607 let value = cell.get();
4608 if matches!(value, Value::Uninitialized) {
4609 return Err(self.throw_reference(name));
4610 }
4611 return Ok(value);
4612 }
4613 // A binding declared by the strict `eval` currently running shadows anything
4614 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
4615 if let Some(scope) = &self.eval_scope
4616 && let Some(value) = scope.get(name)
4617 {
4618 return Ok(value.clone());
4619 }
4620 if lexical {
4621 // A lexical global is a binding in a side table, so the dead zone is
4622 // visible and it is nowhere on the global object.
4623 if let Some(cell) = self.realm.globals.get(name) {
4624 let value = cell.get();
4625 if matches!(value, Value::Uninitialized) {
4626 return Err(self.throw_reference(name));
4627 }
4628 return Ok(value);
4629 }
4630 return Err(self.throw_reference(name));
4631 }
4632 // A `var` global is an ordinary property, so the prototype chain and the
4633 // global object's own builtins are all reachable through it.
4634 match self.get_property(&self.realm.global.clone(), name)? {
4635 Some(value) => Ok(value),
4636 None => Err(self.throw_reference(name)),
4637 }
4638 }
4639
4640 /// Read a plain global `var`: a cached own data property, or the full lookup.
4641 ///
4642 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
4643 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
4644 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
4645 let object = self.realm.global.clone();
4646 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4647 if let Some(cached) = &self.global_cache[site]
4648 && object.upgrades_to(&cached.object)
4649 && let Some(value) = object.data_property_at(cached.index, name)
4650 {
4651 return Ok(value);
4652 }
4653 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
4654 // chain exactly as before, then remember the answer if it is worth remembering.
4655 let Some(value) = self.get_property(&object, name)? else {
4656 return Err(self.throw_reference(name));
4657 };
4658 if let Some(index) = object.own_data_index(name) {
4659 self.global_cache[site] = Some(GlobalCache {
4660 object: object.downgrade(),
4661 index,
4662 });
4663 }
4664 Ok(value)
4665 }
4666
4667 /// Store to a global binding.
4668 ///
4669 /// Returns a signal when the store is refused: a `const` global may only be
4670 /// written by its initialiser, and a non-configurable `var` global may not be
4671 /// deleted but is always writable.
4672 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4673 let (name, lexical, is_const) = self.global_binding(slot);
4674
4675 // An assignment inside a `with` writes through to the object that supplies the
4676 // name, which for an `eval` means consulting the same chain `get_global` does.
4677 if let Some(owner) = self.with_owner(&name) {
4678 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
4679 return Ok(());
4680 }
4681 // A variable the running eval *declared* takes the write before any caller
4682 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
4683 // environment even when an enclosing function has a `var c` of its own.
4684 if self.eval_caller.flatten().is_some()
4685 && let Some((local_vars, phase)) = self.visible_local_vars()
4686 && local_vars.contains(&name)
4687 && let Some(cell) = local_vars.get(&name, phase)
4688 {
4689 cell.set(value);
4690 return Ok(());
4691 }
4692 // A binding of the frame that called `eval` takes the write, which is what
4693 // makes `f("a = 3")` change the caller's `a`.
4694 if self.set_eval_binding(&name, &value)? {
4695 return Ok(());
4696 }
4697 // A closure that outlived its `eval` writes through to the same cell it reads.
4698 if let Some(cell) = self
4699 .frame()
4700 .env
4701 .eval_scope
4702 .as_ref()
4703 .and_then(|scope| scope.get(&name))
4704 .cloned()
4705 {
4706 cell.set(value);
4707 return Ok(());
4708 }
4709 // Inside a strict `eval`, a name it declared itself is stored there. An
4710 // *assignment* to a name nobody declared is not a declaration, so it falls
4711 // through: strict mode raises `ReferenceError` for it, which is what
4712 // `eval("1 + (@not_def = 1)")` has to do.
4713 if let Some(scope) = self.eval_scope.as_mut()
4714 && scope.contains_key(&name)
4715 {
4716 scope.insert(name, value);
4717 return Ok(());
4718 }
4719 if lexical {
4720 if let Some(cell) = self.realm.globals.get(&name).cloned() {
4721 if is_const && !matches!(cell.get(), Value::Uninitialized) {
4722 return Err(self.read_only_global(&name));
4723 }
4724 cell.set(value);
4725 return Ok(());
4726 }
4727 // Writing an undeclared lexical global is a `ReferenceError` in strict
4728 // mode and a silent global creation otherwise; creating the cell here
4729 // keeps both paths from losing the value.
4730 let cell = self.new_cell(value);
4731 self.realm.globals.insert(name, cell);
4732 return Ok(());
4733 }
4734 // A variable a direct `eval` declared in this call shadows the global object, even
4735 // when the global already has a property of that name — `var c = "global"` at the
4736 // top level must not capture `eval("var c = 1")` inside a function.
4737 if let Some((local_vars, phase)) = self.visible_local_vars()
4738 && local_vars.contains(&name)
4739 && let Some(cell) = local_vars.get(&name, phase)
4740 {
4741 cell.set(value);
4742 return Ok(());
4743 }
4744 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
4745 // remembered a global's slot index since M12b, but the *store* side never did: it
4746 // converted the name to a `PropertyKey` (two allocations) and then scanned the
4747 // global object's whole table — which holds every builtin — on every assignment to
4748 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
4749 // full global lookup per iteration; measured with a counter, `s` as a global made
4750 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
4751 //
4752 // Re-validated exactly like the read: same object, same index, still the name, and
4753 // — the one extra check a store needs — still writable. A global that is an
4754 // accessor, non-writable, or inherited fails here and falls through to the full
4755 // path below, which reports the failure the way it always did.
4756 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
4757 let global = self.realm.global.clone();
4758 if let Some(cached) = &self.global_cache[site]
4759 && global.upgrades_to(&cached.object)
4760 && global.write_data_at(cached.index, &name, value.clone())
4761 {
4762 return Ok(());
4763 }
4764 match global.own_property(&name) {
4765 // A `var` global is writable, so the store goes straight through — but
4766 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
4767 // store (a non-writable or accessor-without-setter global) is a silent
4768 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
4769 // split every other assignment has.
4770 Some(_) => {
4771 let on_failure = if self.current_strict() {
4772 DeleteFailure::Throw
4773 } else {
4774 DeleteFailure::Ignore
4775 };
4776 let result = self.set_property_with(&global, &name, value, on_failure);
4777 // Teach the cache the slot for a plain writable own data property, which is
4778 // what a declared `var` is. Without this the fast path above could never
4779 // fire for a global that is only ever *written* — its entry would have to
4780 // be put there by a read of the same slot, and a write-only loop has none.
4781 if result.is_ok()
4782 && let Some(index) = global.own_data_index(&name)
4783 {
4784 self.global_cache[site] = Some(GlobalCache {
4785 object: global.downgrade(),
4786 index,
4787 });
4788 }
4789 result
4790 }
4791 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
4792 // declaration creates a *configurable* property, which is what makes it
4793 // deletable and is the one way a global differs from a declared `var`.
4794 // In strict mode the same store is a `ReferenceError` instead: that is the
4795 // whole point of strict mode, and creating the global silently meant
4796 // `"use strict"; x = 1` looked like it worked.
4797 None => {
4798 if self.current_strict() {
4799 return Err(self.throw_reference(&name));
4800 }
4801 // A direct eval declares here rather than on the global object: its
4802 // `var`s belong to the caller's variable environment. `declare_eval_local`
4803 // also covers a plain assignment to a variable an earlier eval made.
4804 if let Some(cell) = self.declare_eval_local(&name) {
4805 cell.set(value);
4806 return Ok(());
4807 }
4808 global.define_data(&name, value);
4809 Ok(())
4810 }
4811 }
4812 }
4813
4814 /// The value of a binding of the frame that called `eval`, if there is one.
4815 fn eval_binding_value(&self, name: &str) -> Option<Value> {
4816 let binding = self
4817 .eval_bindings
4818 .iter()
4819 .find(|binding| binding.name == name)?;
4820 let owner = self.frames.get(binding.frame)?;
4821 let (slot, index) = (binding.slot, binding.index);
4822 Some(match slot {
4823 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4824 cell if cell >= 0 => owner
4825 .cells
4826 .get(cell as usize)
4827 .map(|cell| cell.get())
4828 .unwrap_or(Value::Undefined),
4829 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
4830 },
4831 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4832 cell if cell >= 0 => owner
4833 .cells
4834 .get(cell as usize)
4835 .map(|cell| cell.get())
4836 .unwrap_or(Value::Undefined),
4837 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
4838 },
4839 })
4840 }
4841
4842 /// Write to a binding of the frame that called `eval`.
4843 ///
4844 /// `Ok(false)` means no binding matched and the caller should keep looking. A
4845 /// matched binding can still refuse the store, which is why this is fallible: a
4846 /// `const` is read-only everywhere, and a named function expression's own name is
4847 /// read-only in strict mode.
4848 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
4849 let Some(binding) = self
4850 .eval_bindings
4851 .iter()
4852 .find(|binding| binding.name == name)
4853 else {
4854 return Ok(false);
4855 };
4856 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
4857 let strict = self.current_strict();
4858 let Some(owner) = self.frames.get_mut(frame) else {
4859 return Ok(false);
4860 };
4861 match slot {
4862 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
4863 cell if cell >= 0 => {
4864 if let Some(cell) = owner.cells.get(cell as usize) {
4865 cell.set(value.clone());
4866 }
4867 }
4868 _ => {
4869 if let Some(slot) = owner.args.get_mut(index) {
4870 *slot = value.clone();
4871 }
4872 }
4873 },
4874 EvalSlot::Local => {
4875 let declared = owner.code.code.vars.get(index);
4876 // A `const` is read-only even through `eval`. The realm records this for
4877 // globals (see `lexical_consts`), but a local's `const`-ness is only in
4878 // the bytecode, so this is where it has to be enforced.
4879 if declared.is_some_and(|var| var.is_const) {
4880 return Err(self.read_only_local(name));
4881 }
4882 // The name of a named function expression is read-only too, but only
4883 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
4884 // such a name is ignored, the same as a direct store would be.
4885 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
4886 return if strict {
4887 Err(self.read_only_local(name))
4888 } else {
4889 Ok(true)
4890 };
4891 }
4892 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
4893 cell if cell >= 0 => {
4894 if let Some(cell) = owner.cells.get(cell as usize) {
4895 cell.set(value.clone());
4896 }
4897 }
4898 _ => {
4899 if let Some(slot) = owner.locals.get_mut(index) {
4900 *slot = value.clone();
4901 }
4902 }
4903 }
4904 }
4905 }
4906 Ok(true)
4907 }
4908
4909 /// The `TypeError` an assignment to a read-only binding raises.
4910 fn read_only_local(&self, name: &str) -> Signal {
4911 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
4912 }
4913
4914 /// Declare `name` as a variable of the frame that called the running `eval`.
4915 ///
4916 /// `None` when there is no direct eval in progress, or it was called from the top
4917 /// level — then the caller's variable environment *is* the global one and the
4918 /// existing path is right.
4919 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
4920 let caller = self.eval_caller.flatten()?;
4921 // The bottom frame is the top-level script, whose variable environment *is* the
4922 // global one — so `eval("var x = 1")` at the top level still creates a global.
4923 if caller == 0 {
4924 return None;
4925 }
4926 // A name the eval's *own* variable environment already binds is not a new
4927 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
4928 // `arguments`, and creating a second binding would leave the first — the one
4929 // closures read — untouched. A binding of an *outer* frame does not count: a
4930 // declaration shadows it rather than writing through.
4931 if self
4932 .eval_bindings
4933 .iter()
4934 .any(|binding| binding.name == name && binding.frame == caller)
4935 {
4936 return None;
4937 }
4938 let phase = if self.in_parameter_list_at(caller) {
4939 0
4940 } else {
4941 1
4942 };
4943 self.frame_local_vars(caller)?;
4944 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
4945 if let Some(cell) = local_vars.get(name, 1) {
4946 return Some(cell);
4947 }
4948 let cell = self.new_cell(Value::Undefined);
4949 Some(local_vars.declare(name, phase, cell))
4950 }
4951
4952 /// Make sure `frame` has a `LocalVars`, creating it on demand.
4953 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
4954 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
4955 return Some(local_vars.clone());
4956 }
4957 let local_vars = Gc::new(self.heap, LocalVars::new());
4958 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
4959 Some(local_vars)
4960 }
4961
4962 /// Whether the realm already has a binding for `name`, lexically or as an *own*
4963 /// property of the global object. Used to decide whether a store inside an
4964 /// `eval` writes through to the realm or declares a binding of its own.
4965 ///
4966 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
4967 /// write to `Object.prototype.toString`, and must not shadow it either.
4968 fn global_knows(&mut self, name: &str) -> bool {
4969 if self.realm.globals.contains_key(name) {
4970 return true;
4971 }
4972 self.realm.global.own_property(name).is_some()
4973 }
4974
4975 /// Whether the code currently running is strict.
4976 ///
4977 /// Read off the frame's function, which is where the parser's answer ended up; a
4978 /// native function never runs strict-only checks, and there is no frame at all
4979 /// before the first script.
4980 pub fn current_strict(&self) -> bool {
4981 self.frames
4982 .last()
4983 .is_some_and(|frame| frame.code.code.strict)
4984 }
4985
4986 /// Initialise a declared global, which is what ends its dead zone.
4987 ///
4988 /// A `var` global becomes a property of the global object: writable, so a later
4989 /// assignment goes through, and non-configurable, so `delete` refuses.
4990 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
4991 let (name, lexical, _) = self.global_binding(slot);
4992 // A `var` declared by the strict `eval` currently running belongs to the
4993 // eval's scope, not to the global object: `eval("var v = 1")` must not make
4994 // `typeof v` answer `"number"` afterwards. A name the realm already has is
4995 // initialised in place, which is what a re-declaration inside eval does.
4996 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
4997 self.eval_scope
4998 .as_mut()
4999 .expect("checked above")
5000 .insert(name, value);
5001 return Ok(());
5002 }
5003 if let Some(scope) = self.eval_scope.as_mut()
5004 && scope.contains_key(&name)
5005 {
5006 scope.insert(name, value);
5007 return Ok(());
5008 }
5009 if lexical {
5010 // The cell exists (created at declaration time) holding the dead-zone
5011 // marker; storing the value is what makes the binding readable.
5012 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5013 cell.set(value);
5014 return Ok(());
5015 }
5016 let cell = self.new_cell(value);
5017 self.realm.globals.insert(name, cell);
5018 return Ok(());
5019 }
5020 let global = self.realm.global.clone();
5021 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5022 // to answer `false` and leave the binding in place. `with_attributes` ties
5023 // `configurable` to `writable`, so the property is built field by field.
5024 global.define(
5025 &name,
5026 Property {
5027 value: Some(value),
5028 writable: true,
5029 enumerable: true,
5030 configurable: false,
5031 ..Property::default()
5032 },
5033 );
5034 Ok(())
5035 }
5036
5037 /// The `TypeError` a store to a `const` global raises.
5038 fn read_only_global(&self, name: &str) -> Signal {
5039 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5040 }
5041
5042 // -- properties ---------------------------------------------------------
5043
5044 /// Read `object[key]`, following the prototype chain.
5045 ///
5046 /// An inherited accessor runs with the *receiver* as `this`, which is why the
5047 /// lookup returns the owner rather than just the value.
5048 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5049 self.get_property_key(object, &PropertyKey::from(key))
5050 }
5051
5052 /// [`Interp::get_property`] with a key that may be a symbol.
5053 pub fn get_property_key(
5054 &mut self,
5055 object: &Gc<JsObject>,
5056 key: &PropertyKey,
5057 ) -> JsResult<Option<Value>> {
5058 self.get_property_key_for(object, None, key)
5059 }
5060
5061 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5062 ///
5063 /// The receiver matters when the property is found on a *prototype*: a getter has to
5064 /// see the object the read started from. For a primitive that is the primitive
5065 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5066 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5067 /// the owner.
5068 pub fn get_property_key_for(
5069 &mut self,
5070 object: &Gc<JsObject>,
5071 receiver: Option<&Value>,
5072 key: &PropertyKey,
5073 ) -> JsResult<Option<Value>> {
5074 // A proxy answers for itself, before any of the shortcuts below: `new
5075 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5076 // have.
5077 if object.proxy_state().is_some() {
5078 let receiver = receiver
5079 .cloned()
5080 .unwrap_or_else(|| Value::Object(object.clone()));
5081 return self.proxy_get(object, &receiver, key);
5082 }
5083 // A host class's `get_property` trap replaces the whole read, prototype walk
5084 // included — that is what makes a native accessor free rather than a JavaScript
5085 // getter call.
5086 if let Some(exotic) = object.exotic() {
5087 let receiver_value = receiver
5088 .cloned()
5089 .unwrap_or_else(|| Value::Object(object.clone()));
5090 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5091 return Ok(Some(value));
5092 }
5093 // With no `get_property` trap, a `get_own_property` trap still answers for the
5094 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5095 // and the hook lives exactly there. A key the trap reports as absent is still
5096 // looked for on the prototype, which is why the search resumes *above*.
5097 if let Some(property) = exotic.get_own_property(self, object, key)? {
5098 return match property {
5099 Some(property) => self.read_property(property, object, receiver),
5100 None => match lookup_key_above(object, key) {
5101 Some((_, property)) => self.read_property(property, object, receiver),
5102 None => Ok(None),
5103 },
5104 };
5105 }
5106 }
5107 // The element-vector and `length` shortcuts are string-only: an array index
5108 // has no symbol spelling.
5109 if let Some(text) = key.as_str() {
5110 if let Some(value) = self.own_element(object, text) {
5111 return Ok(Some(value));
5112 }
5113 // `length` is not stored as a property: an array's length is its element
5114 // count, and keeping one copy of it is what makes `push`/`pop` and
5115 // `a.length = n` agree.
5116 if let Some(length) = object.array_length()
5117 && text == "length"
5118 {
5119 // Not `Value::Int(length as i32)`: see [`length_value`].
5120 return Ok(Some(crate::object::length_value(length)));
5121 }
5122 }
5123 match lookup_key(object, key) {
5124 Some((_, property)) => self.read_property(property, object, receiver),
5125 None => Ok(None),
5126 }
5127 }
5128
5129 /// The value a property read answers.
5130 ///
5131 /// One place rather than three, because an accessor has to run with the *receiver* as
5132 /// `this` whether the descriptor came from the property table, an exotic
5133 /// `get_own_property` trap, or a prototype above one.
5134 fn read_property(
5135 &mut self,
5136 property: Property,
5137 object: &Gc<JsObject>,
5138 receiver: Option<&Value>,
5139 ) -> JsResult<Option<Value>> {
5140 if property.is_accessor() {
5141 match &property.getter {
5142 Some(getter) if !matches!(getter, Value::Undefined) => {
5143 let receiver = receiver
5144 .cloned()
5145 .unwrap_or_else(|| Value::Object(object.clone()));
5146 self.call_value(getter.clone(), receiver, Vec::new())
5147 .map(Some)
5148 }
5149 // An accessor with no getter reads as `undefined`.
5150 _ => Ok(Some(Value::Undefined)),
5151 }
5152 } else {
5153 Ok(property.value)
5154 }
5155 }
5156
5157 /// `super.key` — start the search at `proto`, but report to `receiver`.
5158 ///
5159 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5160 /// found on the prototype of a class has to see the *instance* as `this`, and a
5161 /// plain property read off `proto` would lose that.
5162 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5163 let start = self.require_object(proto)?;
5164 let key = self.propkey(key)?;
5165 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5166 if matches!(proto, Value::Null) {
5167 return Ok(Value::Undefined);
5168 }
5169 match lookup_key(&start, &key) {
5170 Some((_, property)) if property.is_accessor() => match &property.getter {
5171 Some(getter) if !matches!(getter, Value::Undefined) => {
5172 self.call_value(getter.clone(), receiver.clone(), Vec::new())
5173 }
5174 _ => Ok(Value::Undefined),
5175 },
5176 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5177 None => Ok(Value::Undefined),
5178 }
5179 }
5180
5181 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5182 ///
5183 /// A setter found on the prototype runs with `receiver` as `this`; a data property
5184 /// is shadowed by a new own property on the receiver, the same rule an ordinary
5185 /// assignment follows.
5186 fn super_write(
5187 &mut self,
5188 receiver: &Value,
5189 proto: &Value,
5190 key: &Value,
5191 value: Value,
5192 ) -> JsResult<()> {
5193 let target = self.require_object(receiver)?;
5194 let key = self.propkey(key)?;
5195 if !matches!(proto, Value::Null)
5196 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5197 {
5198 if property.is_accessor() {
5199 if let Some(setter) = &property.setter
5200 && !matches!(setter, Value::Undefined)
5201 {
5202 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5203 }
5204 return Ok(());
5205 }
5206 // A data property on the prototype is writable or not; reading `owner` at
5207 // all is only for the attribute check.
5208 if !property.writable {
5209 return Err(self.type_error(format!("'{key}' is read-only")));
5210 }
5211 let _ = owner;
5212 }
5213 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5214 }
5215
5216 /// The object a `super` operation needs, or the `TypeError` the spec raises.
5217 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5218 match value.as_object() {
5219 Some(object) => Ok(object.clone()),
5220 None => Err(Signal::Throw(
5221 self.make_error("TypeError", "value is not an object"),
5222 )),
5223 }
5224 }
5225
5226 /// Build the class object `define_class` produces.
5227 ///
5228 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5229 /// whose prototype property is a fresh object inheriting from the parent's
5230 /// prototype, and whose own prototype is the parent constructor — which is what makes
5231 /// a static method inherited too.
5232 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5233 let ctor = self.pop();
5234 let parent = self.pop();
5235 let Value::Object(function) = &ctor else {
5236 return Err(Signal::Throw(
5237 self.make_error("TypeError", "class constructor must be a function"),
5238 ));
5239 };
5240 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5241 // but gives the instances no prototype at all.
5242 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5243 match &parent {
5244 Value::Null => (Some(self.realm.function_proto.clone()), None),
5245 Value::Object(parent_class) => {
5246 if !parent_class.is_callable() {
5247 return Err(Signal::Throw(
5248 self.make_error("TypeError", "parent class must be constructor"),
5249 ));
5250 }
5251 let proto = self.get_property(parent_class, "prototype")?;
5252 match proto {
5253 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5254 Some(Value::Null) => (Some(parent_class.clone()), None),
5255 _ => {
5256 return Err(Signal::Throw(self.make_error(
5257 "TypeError",
5258 "parent prototype must be an object or null",
5259 )));
5260 }
5261 }
5262 }
5263 _ => {
5264 return Err(Signal::Throw(
5265 self.make_error("TypeError", "parent class must be constructor"),
5266 ));
5267 }
5268 }
5269 } else {
5270 (
5271 Some(self.realm.function_proto.clone()),
5272 Some(self.realm.object_proto.clone()),
5273 )
5274 };
5275 let proto = self.new_object(parent_proto);
5276 function.set_proto(parent_ctor);
5277 // A class is not callable without `new`, and its `prototype` is not writable —
5278 // both follow from being a class and are what `class A {}; A()` throws on.
5279 function.set_class_constructor(true);
5280 function.set_home_object(None);
5281 self.set_function_name(&ctor, name);
5282 self.define_class_properties(function, &ctor, &proto)?;
5283 Ok((ctor, proto))
5284 }
5285
5286 /// Give the constructor its `prototype` and `length`, and the prototype its
5287 /// `constructor` back-pointer.
5288 fn define_class_properties(
5289 &mut self,
5290 function: &Gc<JsObject>,
5291 ctor: &Value,
5292 proto: &Gc<JsObject>,
5293 ) -> JsResult<()> {
5294 proto.define(
5295 "constructor",
5296 Property::with_attributes(ctor.clone(), true, false),
5297 );
5298 function.define(
5299 "prototype",
5300 Property::prototype_of(Value::Object(proto.clone()), false),
5301 );
5302 if let Some((code, _)) = bytecode_of(function) {
5303 let length = code.code.defined_args;
5304 function.define(
5305 "length",
5306 Property::name_or_length(Value::Int(length as i32)),
5307 );
5308 }
5309 Ok(())
5310 }
5311
5312 /// The own array element `key` names, if this object has one.
5313 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5314 let index = array_index(key)?;
5315 // A typed array's elements live in its buffer, not in a property list: reading one
5316 // goes through the view's element type so a bounds check and a detached buffer are
5317 // both handled there.
5318 if object.typed_array_parts().is_some() {
5319 return object.typed_array_element(index as usize);
5320 }
5321 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5322 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5323 // search early, which is why `Array.prototype[1] = 9` could not be seen through
5324 // `[1,,3][1]`.
5325 match object.array_get(index as usize) {
5326 Some(Value::Hole) | None => None,
5327 other => other,
5328 }
5329 }
5330
5331 /// Store `object[key] = value`, honouring setters and inherited properties.
5332 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5333 self.set_property_with(object, key, value, DeleteFailure::Throw)
5334 }
5335
5336 /// Store a property, choosing what to do when the object refuses.
5337 ///
5338 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5339 /// mode, which is the one place assignment differs by mode. Native code (the array
5340 /// methods, `JSON`) always asks for the throw.
5341 pub fn set_property_with(
5342 &mut self,
5343 object: &Gc<JsObject>,
5344 key: &str,
5345 value: Value,
5346 on_failure: DeleteFailure,
5347 ) -> JsResult<()> {
5348 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5349 }
5350
5351 /// [`Interp::set_property_with`] with a key that may be a symbol.
5352 pub fn set_property_with_key(
5353 &mut self,
5354 object: &Gc<JsObject>,
5355 key: &PropertyKey,
5356 value: Value,
5357 on_failure: DeleteFailure,
5358 ) -> JsResult<()> {
5359 self.set_property_with_key_receiver_aware(object, key, value, on_failure, true)
5360 }
5361
5362 /// As [`Interp::set_property_with_key`], with the receiver explicit.
5363 ///
5364 /// `same_receiver` is `SameValue(O, Receiver)` from §10.4.5.5 step 1.b.i, and the two
5365 /// branches it separates are observable in opposite directions: when the receiver *is*
5366 /// the view the element store converts `V` first and then asks whether the index is
5367 /// valid (`Set/resized-out-of-bounds-to-in-bounds-index`, where a `valueOf` puts the
5368 /// index back in bounds), and when it is not, an invalid index returns `true` without
5369 /// converting anything (`key-is-out-of-bounds-receiver-is-not-object`).
5370 fn set_property_with_key_receiver_aware(
5371 &mut self,
5372 object: &Gc<JsObject>,
5373 key: &PropertyKey,
5374 value: Value,
5375 on_failure: DeleteFailure,
5376 same_receiver: bool,
5377 ) -> JsResult<()> {
5378 // A proxy's `set` trap decides, and its `false` means the same thing an
5379 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5380 if object.proxy_state().is_some() {
5381 let receiver = Value::Object(object.clone());
5382 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5383 return match (accepted, on_failure) {
5384 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5385 (false, DeleteFailure::Throw) => {
5386 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5387 }
5388 };
5389 }
5390 }
5391 // A host class's `set_property` trap decides for itself. `Some(false)` is a
5392 // refusal and means exactly what a proxy's `false` means.
5393 if let Some(exotic) = object.exotic() {
5394 let receiver = Value::Object(object.clone());
5395 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5396 return match (accepted, on_failure) {
5397 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5398 (false, DeleteFailure::Throw) => {
5399 Err(self.type_error(format!("property '{key}' is read-only")))
5400 }
5401 };
5402 }
5403 }
5404 // The element and `length` shortcuts only exist for string keys: an array
5405 // index has no symbol spelling, and a symbol named `length` is an ordinary
5406 // property.
5407 let text = key.as_str();
5408 // A typed array's elements are a window onto its buffer: the store has to go
5409 // through the view's element type so the value is wrapped (or clamped) and so an
5410 // out-of-range or detached write is a silent no-op, as the spec says.
5411 if let Some(text) = text
5412 && let Some(index) = array_index(text)
5413 && let Some(element) = object.typed_array_element_type()
5414 {
5415 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5416 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5417 // in `Interp`, because it is script-observable and the storage borrow inside
5418 // `typed_array_set` must not be held across it.
5419 //
5420 // It runs even for an index that is out of bounds *now*, because `V` itself can
5421 // put it back in bounds: `TypedArraySetElement` converts first and asks
5422 // `IsValidIntegerIndex` afterwards, which is what
5423 // `Set/resized-out-of-bounds-to-in-bounds-index` asserts (a `valueOf` that
5424 // resizes a 0-byte buffer to 1 makes `ta[0] = value` store 100). The write is
5425 // still a no-op when the index stays out of bounds, which is why the extra
5426 // length check that used to guard this has no job left.
5427 if !same_receiver && index as usize >= object.typed_array_length().unwrap_or(0) {
5428 return Ok(());
5429 }
5430 let stored = self.element_value(element, value)?;
5431 if let Some(Err(reason)) = object.typed_array_set(index as usize, stored) {
5432 return Err(self.type_error(reason));
5433 }
5434 return Ok(());
5435 }
5436 if let Some(text) = text
5437 && let Some(index) = array_index(text)
5438 && object.is_array()
5439 {
5440 // An accessor defined on an index lives in the property table while the
5441 // element slot is a hole, so the store has to go through the property first.
5442 // Writing the vector directly skipped the setter entirely.
5443 if let Some(existing) = object.own_property_key(key) {
5444 if existing.is_accessor() {
5445 return match existing.setter.clone() {
5446 Some(setter) if !matches!(setter, Value::Undefined) => {
5447 let receiver = Value::Object(object.clone());
5448 self.call_value(setter, receiver, vec![value]).map(|_| ())
5449 }
5450 _ => match on_failure {
5451 DeleteFailure::Throw => Err(self.type_error(format!(
5452 "cannot set property '{text}', it has only a getter"
5453 ))),
5454 DeleteFailure::Ignore => Ok(()),
5455 },
5456 };
5457 }
5458 if !existing.writable {
5459 return match on_failure {
5460 DeleteFailure::Throw => {
5461 Err(self.type_error(format!("'{text}' is read-only")))
5462 }
5463 DeleteFailure::Ignore => Ok(()),
5464 };
5465 }
5466 }
5467 {
5468 // Growing the array needs a writable `length`.
5469 if (index as usize) >= object.array_length().unwrap_or(0)
5470 && !object.length_writable()
5471 {
5472 return match on_failure {
5473 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5474 DeleteFailure::Ignore => Ok(()),
5475 };
5476 }
5477 // Adding an index past the end makes the array longer, which a
5478 // non-extensible array refuses.
5479 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
5480 return match on_failure {
5481 DeleteFailure::Throw => Err(self.type_error(format!(
5482 "cannot add property '{key}', object is not extensible"
5483 ))),
5484 DeleteFailure::Ignore => Ok(()),
5485 };
5486 }
5487 if object.element_is_locked(index) {
5488 return match on_failure {
5489 DeleteFailure::Throw => {
5490 Err(self.type_error(format!("'{key}' is read-only")))
5491 }
5492 DeleteFailure::Ignore => Ok(()),
5493 };
5494 }
5495 // The element vector is only half of `[[Set]]` for an index: the
5496 // prototype chain is consulted first, and a setter there answers instead
5497 // of the element store. This branch used to write the element directly, so
5498 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
5499 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
5500 // the reference calls the setter and the array keeps no own index.
5501 if let Some((owner, property)) = lookup_key(object, key)
5502 && !owner.ptr_eq(object)
5503 {
5504 match &property {
5505 property if property.is_accessor() => {
5506 match &property.setter {
5507 Some(setter) if !matches!(setter, Value::Undefined) => {
5508 let receiver = Value::Object(object.clone());
5509 self.call_value(setter.clone(), receiver, vec![value])?;
5510 }
5511 _ => {
5512 return match on_failure {
5513 DeleteFailure::Throw => Err(self.type_error(format!(
5514 "cannot set property '{text}', it has only a getter"
5515 ))),
5516 DeleteFailure::Ignore => Ok(()),
5517 };
5518 }
5519 }
5520 return Ok(());
5521 }
5522 property if !property.writable => {
5523 return match on_failure {
5524 DeleteFailure::Throw => {
5525 Err(self.type_error(format!("'{text}' is read-only")))
5526 }
5527 DeleteFailure::Ignore => Ok(()),
5528 };
5529 }
5530 _ => {}
5531 }
5532 }
5533 if object.array_set(self.heap, index as usize, value.clone()) {
5534 return Ok(());
5535 }
5536 // Past the dense limit the slot is too far out to be worth one `Value`
5537 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
5538 // constant time by keeping the index as an ordinary property. The store
5539 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
5540 // to a legal program.
5541 object.define_key(key, Property::with_attributes(value, true, true));
5542 // Extend, never shorten: the index may be *inside* the current length (a
5543 // huge `length` with a sparse store), and shortening would delete the
5544 // sparse properties above it — including the one just stored.
5545 if index as usize + 1 > object.array_length().unwrap_or(0) {
5546 object.array_set_length(self.heap, index as usize + 1);
5547 }
5548 return Ok(());
5549 }
5550 }
5551 if text == Some("length") && object.is_array() {
5552 if !object.length_writable() {
5553 return match on_failure {
5554 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
5555 DeleteFailure::Ignore => Ok(()),
5556 };
5557 }
5558 let length = value.to_number();
5559 if length.is_finite() && length >= 0.0 {
5560 let length = length as usize;
5561 // `a.length = n` with `n` below a non-configurable element cannot
5562 // drop that element, so the whole assignment fails. The spec makes
5563 // this a `TypeError` rather than a silent no-op, in any mode.
5564 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
5565 // Sloppy mode stops the truncation at the blocking element
5566 // instead of failing; strict mode raises.
5567 // Both modes stop at the blocking element; they differ in
5568 // whether that is reported. The reference truncates *then*
5569 // throws, so the array is left in the shortened state.
5570 object.array_truncate(self.heap, blocked + 1);
5571 return match on_failure {
5572 DeleteFailure::Throw => {
5573 Err(self.type_error(format!("cannot delete property '{blocked}'")))
5574 }
5575 DeleteFailure::Ignore => Ok(()),
5576 };
5577 }
5578 object.array_set_length(self.heap, length);
5579 return Ok(());
5580 }
5581 }
5582 if !object.is_extensible() && !object.has_own_key(key) && lookup_key(object, key).is_none()
5583 {
5584 return match on_failure {
5585 DeleteFailure::Throw => Err(self.type_error(format!(
5586 "cannot add property {}, object is not extensible",
5587 key
5588 ))),
5589 DeleteFailure::Ignore => Ok(()),
5590 };
5591 }
5592 if let Some((owner, property)) = self.lookup_for_write(object, key)? {
5593 if property.is_accessor() {
5594 match &property.setter {
5595 Some(setter) if !matches!(setter, Value::Undefined) => {
5596 let receiver = Value::Object(object.clone());
5597 self.call_value(setter.clone(), receiver, vec![value])?;
5598 }
5599 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
5600 // Sloppy code swallows that refusal, strict code raises — the same
5601 // rule the read-only *data* property below follows, and skipping it
5602 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
5603 // return silently. The reference answers `TypeError: 'x' is
5604 // read-only`.
5605 _ => {
5606 return match on_failure {
5607 DeleteFailure::Throw => {
5608 Err(self.type_error(format!("'{key}' is read-only")))
5609 }
5610 DeleteFailure::Ignore => Ok(()),
5611 };
5612 }
5613 }
5614 return Ok(());
5615 }
5616 // A non-writable data property refuses the write, own **or inherited**: an
5617 // own one stops here because nothing may change it, and an inherited one
5618 // because §10.1.9.2 step 4 refuses to create the shadowing own property.
5619 //
5620 // The `ptr_eq` this used to carry meant an inherited read-only property fell
5621 // through to `define_data_key` and *did* create the shadow — `var o =
5622 // Object.create(Object.freeze({x: 1})); o.x = 9` answered `9` and
5623 // `o.hasOwnProperty('x')` answered `true`, where the reference answers `1`
5624 // and `false`.
5625 if !property.writable {
5626 return match on_failure {
5627 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
5628 DeleteFailure::Ignore => Ok(()),
5629 };
5630 }
5631 // An existing writable own property keeps its attributes: only the value
5632 // moves. Redefining instead would reset them, which is how a
5633 // non-configurable global `var` used to become deletable.
5634 if owner.ptr_eq(object) && object.write_value_key(key, value.clone()) {
5635 return Ok(());
5636 }
5637 }
5638 // No own data property: create one, shadowing whatever the prototype holds.
5639 object.define_data_key(key, value);
5640 Ok(())
5641 }
5642
5643 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
5644 ///
5645 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
5646 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
5647 /// a virtual accessor gets its setter run without implementing `set_property` at all.
5648 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
5649 /// the prototype, so the walk resumes above the object.
5650 fn lookup_for_write(
5651 &mut self,
5652 object: &Gc<JsObject>,
5653 key: &PropertyKey,
5654 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
5655 let Some(exotic) = object.exotic() else {
5656 return Ok(lookup_key(object, key));
5657 };
5658 Ok(match exotic.get_own_property(self, object, key)? {
5659 Some(Some(property)) => Some((object.clone(), property)),
5660 Some(None) => lookup_key_above(object, key),
5661 None => lookup_key(object, key),
5662 })
5663 }
5664
5665 /// Delete `object[key]`.
5666 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
5667 self.delete_property_key(object, &PropertyKey::from(key))
5668 }
5669
5670 /// [`Interp::delete_property`] with a key that may be a symbol.
5671 pub fn delete_property_key(
5672 &mut self,
5673 object: &Gc<JsObject>,
5674 key: &PropertyKey,
5675 ) -> JsResult<bool> {
5676 // A proxy decides for itself, and may even throw; the invariant checks live in
5677 // `proxy_delete`.
5678 if let Some(answer) = self.proxy_delete(object, key)? {
5679 return Ok(answer);
5680 }
5681 // A host class's `delete_property` trap decides; `false` is a refusal, which the
5682 // caller reports as a failed delete.
5683 if let Some(exotic) = object.exotic()
5684 && let Some(answer) = exotic.delete_property(self, object, key)?
5685 {
5686 return Ok(answer);
5687 }
5688 let mapped_index = key.as_str().and_then(array_index);
5689 if let Some(index) = mapped_index
5690 && let Some(length) = object.array_length()
5691 && (index as usize) < length
5692 {
5693 // An accessor defined on an index lives in the property table rather than the
5694 // element vector, so both have to be cleared: `delete` after
5695 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
5696 object.delete_key(key);
5697 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
5698 // index stops answering `in`.
5699 if object.element_is_undeletable(index) {
5700 return Ok(false);
5701 }
5702 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
5703 // so a later `defineProperty(arguments, "0", {value})` writes to the object
5704 // and no longer through to the parameter. A refused delete leaves the
5705 // mapping alone.
5706 object.drop_mapped_argument(index as usize);
5707 object.array_set(self.heap, index as usize, Value::Hole);
5708 return Ok(true);
5709 }
5710 // The same for an object that is not an array: only a delete that actually
5711 // removed the property ends the alias.
5712 let deleted = object.delete_key(key);
5713 if deleted && let Some(index) = mapped_index {
5714 object.drop_mapped_argument(index as usize);
5715 }
5716 Ok(deleted)
5717 }
5718
5719 // -- proxy traps --------------------------------------------------------
5720 //
5721 // A proxy's internal methods all look the same: ask the handler for the trap, call it
5722 // with the target and the operation's own arguments, then check the answer against
5723 // the target. The checks are not decoration — they are what stops a proxy from
5724 // reporting a `non-configurable` property as missing, which would let a frozen object
5725 // be rewritten by standing in front of it.
5726
5727 /// The target and handler of `object`, or `None` when it is not a proxy.
5728 ///
5729 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
5730 /// one has to fail: the slots the traps would have been read from are gone.
5731 fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
5732 let Some(state) = object.proxy_state() else {
5733 return Ok(None);
5734 };
5735 let state = state.borrow();
5736 match (&state.target, &state.handler) {
5737 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
5738 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
5739 }
5740 }
5741
5742 /// Call `handler[name]`, or answer `None` when the trap is absent.
5743 ///
5744 /// A trap that is present but not callable is a `TypeError` rather than "no trap":
5745 /// the spec checks `IsCallable` and refuses, so `{ get: 1 }` must not quietly fall
5746 /// back to the target.
5747 fn proxy_trap(
5748 &mut self,
5749 handler: &Value,
5750 name: &str,
5751 args: Vec<Value>,
5752 ) -> JsResult<Option<Value>> {
5753 let Value::Object(table) = handler else {
5754 return Err(self.type_error("proxy handler is not an object"));
5755 };
5756 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
5757 match trap {
5758 Value::Undefined => Ok(None),
5759 Value::Object(function) if function.is_callable() => {
5760 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
5761 Ok(Some(answer))
5762 }
5763 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
5764 }
5765 }
5766
5767 /// Whether `object`'s own property `key` is one the target refuses to lose.
5768 ///
5769 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
5770 /// its value behind the target's back. This goes through
5771 /// [`Self::ordinary_own_property`] rather than the property table so that an array's
5772 /// elements and its `length` — both fixed, both outside the table — are covered.
5773 fn is_fixed_property(target: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
5774 Self::ordinary_own_property(target, key).filter(|property| !property.configurable)
5775 }
5776
5777 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
5778 fn proxy_get(
5779 &mut self,
5780 object: &Gc<JsObject>,
5781 receiver: &Value,
5782 key: &PropertyKey,
5783 ) -> JsResult<Option<Value>> {
5784 let Some((target, handler)) = self.proxy_parts(object)? else {
5785 return Ok(None);
5786 };
5787 let key_value = self.key_value(key);
5788 let Some(result) = self.proxy_trap(
5789 &handler,
5790 "get",
5791 vec![Value::Object(target.clone()), key_value, receiver.clone()],
5792 )?
5793 else {
5794 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
5795 // inherited getter still sees the proxy.
5796 return Ok(Some(
5797 self.get_property_key_for(&target, Some(receiver), key)?
5798 .unwrap_or(Value::Undefined),
5799 ));
5800 };
5801 if let Some(fixed) = Self::is_fixed_property(&target, key) {
5802 if fixed.is_accessor() {
5803 // A fixed accessor with no getter must read as `undefined`.
5804 let has_getter = fixed
5805 .getter
5806 .as_ref()
5807 .is_some_and(|getter| !matches!(getter, Value::Undefined));
5808 if !has_getter && !matches!(result, Value::Undefined) {
5809 return Err(self.type_error(format!(
5810 "proxy 'get' must report undefined for the non-configurable property '{key}'"
5811 )));
5812 }
5813 } else if !fixed.writable {
5814 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5815 if !fixed_value.same_value(&result) {
5816 return Err(self.type_error(format!(
5817 "proxy 'get' disagrees with the non-configurable property '{key}'"
5818 )));
5819 }
5820 }
5821 }
5822 Ok(Some(result))
5823 }
5824
5825 /// `[[Set]]` on a proxy.
5826 ///
5827 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
5828 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
5829 /// read-only store has.
5830 fn proxy_set(
5831 &mut self,
5832 object: &Gc<JsObject>,
5833 key: &PropertyKey,
5834 value: Value,
5835 receiver: &Value,
5836 ) -> JsResult<Option<bool>> {
5837 let Some((target, handler)) = self.proxy_parts(object)? else {
5838 return Ok(None);
5839 };
5840 let key_value = self.key_value(key);
5841 let Some(result) = self.proxy_trap(
5842 &handler,
5843 "set",
5844 vec![
5845 Value::Object(target.clone()),
5846 key_value,
5847 value.clone(),
5848 receiver.clone(),
5849 ],
5850 )?
5851 else {
5852 // No trap: store on the target, which is where an ordinary proxy write lands.
5853 self.set_property_with_key(&target, key, value, DeleteFailure::Ignore)?;
5854 return Ok(Some(true));
5855 };
5856 if !result.to_boolean() {
5857 return Ok(Some(false));
5858 }
5859 if let Some(fixed) = Self::is_fixed_property(&target, key) {
5860 if fixed.is_accessor() {
5861 let has_setter = fixed
5862 .setter
5863 .as_ref()
5864 .is_some_and(|setter| !matches!(setter, Value::Undefined));
5865 if !has_setter {
5866 return Err(self.type_error(format!(
5867 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
5868 )));
5869 }
5870 } else if !fixed.writable {
5871 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
5872 if !fixed_value.same_value(&value) {
5873 return Err(self.type_error(format!(
5874 "proxy 'set' changed the non-configurable property '{key}'"
5875 )));
5876 }
5877 }
5878 }
5879 // A new property cannot appear on a target that refuses new properties.
5880 if Self::ordinary_own_property(&target, key).is_none() && !target.is_extensible() {
5881 return Err(self.type_error(format!(
5882 "proxy 'set' added '{key}' to a non-extensible target"
5883 )));
5884 }
5885 Ok(Some(true))
5886 }
5887
5888 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
5889 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5890 let Some((target, handler)) = self.proxy_parts(object)? else {
5891 return Ok(None);
5892 };
5893 let key_value = self.key_value(key);
5894 let Some(result) = self.proxy_trap(
5895 &handler,
5896 "has",
5897 vec![Value::Object(target.clone()), key_value],
5898 )?
5899 else {
5900 return Ok(Some(self.has_own_or_inherited(&target, key)?));
5901 };
5902 if !result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5903 return Err(self.type_error(format!(
5904 "proxy 'has' denied the non-configurable property '{key}'"
5905 )));
5906 }
5907 // A non-extensible target cannot grow, so every own property it *has* is fixed.
5908 if !result.to_boolean()
5909 && !target.is_extensible()
5910 && Self::ordinary_own_property(&target, key).is_some()
5911 {
5912 return Err(self.type_error(format!(
5913 "proxy 'has' denied the own property '{key}' of a non-extensible target"
5914 )));
5915 }
5916 Ok(Some(result.to_boolean()))
5917 }
5918
5919 /// `[[Delete]]` on a proxy.
5920 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
5921 let Some((target, handler)) = self.proxy_parts(object)? else {
5922 return Ok(None);
5923 };
5924 let key_value = self.key_value(key);
5925 let Some(result) = self.proxy_trap(
5926 &handler,
5927 "deleteProperty",
5928 vec![Value::Object(target.clone()), key_value],
5929 )?
5930 else {
5931 return Ok(Some(self.delete_property_key(&target, key)?));
5932 };
5933 if result.to_boolean() && Self::is_fixed_property(&target, key).is_some() {
5934 return Err(self.type_error(format!(
5935 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
5936 )));
5937 }
5938 if result.to_boolean()
5939 && !target.is_extensible()
5940 && Self::ordinary_own_property(&target, key).is_some()
5941 {
5942 return Err(self.type_error(format!(
5943 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
5944 )));
5945 }
5946 Ok(Some(result.to_boolean()))
5947 }
5948
5949 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
5950 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
5951 let Some((target, handler)) = self.proxy_parts(object)? else {
5952 return Ok(None);
5953 };
5954 let Some(result) =
5955 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
5956 else {
5957 // No trap: the target's own keys, already in the order an object reports.
5958 return Ok(Some(self.object_own_property_keys(&target)?));
5959 };
5960 // `CreateListFromArrayLike` with the string-or-symbol restriction.
5961 let list = self.list_from_array_like(&result, true)?;
5962 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
5963 for value in list {
5964 let key = self.propkey(&value)?;
5965 if keys.contains(&key) {
5966 return Err(self.type_error(format!(
5967 "proxy 'ownKeys' returned the duplicate key '{key}'"
5968 )));
5969 }
5970 keys.push(key);
5971 }
5972 for (key, property) in target.property_entries() {
5973 if !property.configurable && !keys.contains(&key) {
5974 return Err(self.type_error(format!(
5975 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
5976 )));
5977 }
5978 if !target.is_extensible() && !keys.contains(&key) {
5979 return Err(self.type_error(format!(
5980 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
5981 )));
5982 }
5983 }
5984 if !target.is_extensible() {
5985 let own = target.property_entries().len();
5986 if keys.len() != own {
5987 return Err(
5988 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
5989 );
5990 }
5991 }
5992 Ok(Some(keys))
5993 }
5994
5995 /// `[[GetOwnProperty]]` on a proxy.
5996 fn proxy_get_own_property(
5997 &mut self,
5998 object: &Gc<JsObject>,
5999 key: &PropertyKey,
6000 ) -> JsResult<Option<Option<Property>>> {
6001 let Some((target, handler)) = self.proxy_parts(object)? else {
6002 return Ok(None);
6003 };
6004 let key_value = self.key_value(key);
6005 let Some(result) = self.proxy_trap(
6006 &handler,
6007 "getOwnPropertyDescriptor",
6008 vec![Value::Object(target.clone()), key_value],
6009 )?
6010 else {
6011 // No trap: the target's own descriptor is the answer. This has to go through
6012 // the same synthesis an ordinary object gets, because a proxy's own property
6013 // table is empty by design — reading it directly reported `undefined` for
6014 // every key, including an array's indices and `length`.
6015 return Ok(Some(Self::ordinary_own_property(&target, key)));
6016 };
6017 let answer = if matches!(result, Value::Undefined) {
6018 None
6019 } else {
6020 Some(self.property_from_descriptor(&result)?)
6021 };
6022 let fixed = Self::is_fixed_property(&target, key);
6023 match (&answer, &fixed) {
6024 // A non-configurable property cannot be reported as absent.
6025 (None, Some(_)) => {
6026 return Err(self.type_error(format!(
6027 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
6028 )));
6029 }
6030 (Some(descriptor), Some(fixed)) => {
6031 if descriptor.configurable {
6032 return Err(self.type_error(format!(
6033 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
6034 )));
6035 }
6036 if fixed.is_accessor() != descriptor.is_accessor() {
6037 return Err(self.type_error(format!(
6038 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6039 )));
6040 }
6041 if !fixed.is_accessor() && !fixed.writable {
6042 let fixed_value = fixed.value.clone().unwrap_or(Value::Undefined);
6043 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
6044 if !fixed_value.same_value(&reported) {
6045 return Err(self.type_error(format!(
6046 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
6047 )));
6048 }
6049 }
6050 }
6051 _ => {}
6052 }
6053 Ok(Some(answer))
6054 }
6055
6056 /// `[[DefineOwnProperty]]` on a proxy.
6057 fn proxy_define_property(
6058 &mut self,
6059 object: &Gc<JsObject>,
6060 key: &PropertyKey,
6061 property: Property,
6062 ) -> JsResult<Option<bool>> {
6063 let Some((target, handler)) = self.proxy_parts(object)? else {
6064 return Ok(None);
6065 };
6066 let key_value = self.key_value(key);
6067 let descriptor = self.descriptor_from_property(&property);
6068 let Some(result) = self.proxy_trap(
6069 &handler,
6070 "defineProperty",
6071 vec![Value::Object(target.clone()), key_value, descriptor],
6072 )?
6073 else {
6074 return Ok(None);
6075 };
6076 if !result.to_boolean() {
6077 return Ok(Some(false));
6078 }
6079 let fixed = Self::is_fixed_property(&target, key);
6080 let creating = Self::ordinary_own_property(&target, key).is_none();
6081 if creating && !target.is_extensible() {
6082 return Err(self.type_error(format!(
6083 "proxy 'defineProperty' added '{key}' to a non-extensible target"
6084 )));
6085 }
6086 if let Some(fixed) = fixed {
6087 if property.configurable {
6088 return Err(self.type_error(format!(
6089 "proxy 'defineProperty' made the non-configurable '{key}' configurable"
6090 )));
6091 }
6092 if !fixed.writable && property.writable && !fixed.is_accessor() {
6093 return Err(self.type_error(format!(
6094 "proxy 'defineProperty' made the read-only '{key}' writable"
6095 )));
6096 }
6097 }
6098 Ok(Some(true))
6099 }
6100
6101 /// `[[GetPrototypeOf]]` on a proxy.
6102 fn proxy_get_prototype_of(
6103 &mut self,
6104 object: &Gc<JsObject>,
6105 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
6106 let Some((target, handler)) = self.proxy_parts(object)? else {
6107 return Ok(None);
6108 };
6109 let Some(result) = self.proxy_trap(
6110 &handler,
6111 "getPrototypeOf",
6112 vec![Value::Object(target.clone())],
6113 )?
6114 else {
6115 return Ok(Some(target.proto()));
6116 };
6117 let proto = match &result {
6118 Value::Null => None,
6119 Value::Object(proto) => Some(proto.clone()),
6120 _ => {
6121 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
6122 }
6123 };
6124 if !target.is_extensible() && !same_proto(proto.as_ref(), target.proto().as_ref()) {
6125 return Err(self.type_error(
6126 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
6127 ));
6128 }
6129 Ok(Some(proto))
6130 }
6131
6132 /// `[[SetPrototypeOf]]` on a proxy.
6133 fn proxy_set_prototype_of(
6134 &mut self,
6135 object: &Gc<JsObject>,
6136 proto: Option<Gc<JsObject>>,
6137 ) -> JsResult<Option<bool>> {
6138 let Some((target, handler)) = self.proxy_parts(object)? else {
6139 return Ok(None);
6140 };
6141 let proto_value = match &proto {
6142 Some(proto) => Value::Object(proto.clone()),
6143 None => Value::Null,
6144 };
6145 let Some(result) = self.proxy_trap(
6146 &handler,
6147 "setPrototypeOf",
6148 vec![Value::Object(target.clone()), proto_value],
6149 )?
6150 else {
6151 target.set_proto(proto);
6152 return Ok(Some(true));
6153 };
6154 if result.to_boolean()
6155 && !target.is_extensible()
6156 && !same_proto(proto.as_ref(), target.proto().as_ref())
6157 {
6158 return Err(self.type_error(
6159 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
6160 ));
6161 }
6162 Ok(Some(result.to_boolean()))
6163 }
6164
6165 /// `[[IsExtensible]]` on a proxy.
6166 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6167 let Some((target, handler)) = self.proxy_parts(object)? else {
6168 return Ok(None);
6169 };
6170 let Some(result) = self.proxy_trap(
6171 &handler,
6172 "isExtensible",
6173 vec![Value::Object(target.clone())],
6174 )?
6175 else {
6176 return Ok(Some(target.is_extensible()));
6177 };
6178 // The answer is not the proxy's to invent: it must agree with the target, or a
6179 // script could learn `false` while the target keeps accepting new properties.
6180 if result.to_boolean() != target.is_extensible() {
6181 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
6182 }
6183 Ok(Some(result.to_boolean()))
6184 }
6185
6186 /// `[[PreventExtensions]]` on a proxy.
6187 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
6188 let Some((target, handler)) = self.proxy_parts(object)? else {
6189 return Ok(None);
6190 };
6191 let Some(result) = self.proxy_trap(
6192 &handler,
6193 "preventExtensions",
6194 vec![Value::Object(target.clone())],
6195 )?
6196 else {
6197 target.set_extensible(false);
6198 return Ok(Some(true));
6199 };
6200 if result.to_boolean() && target.is_extensible() {
6201 return Err(self.type_error(
6202 "proxy 'preventExtensions' reported success but the target is still extensible",
6203 ));
6204 }
6205 Ok(Some(result.to_boolean()))
6206 }
6207
6208 /// `[[Call]]` on a proxy, through the `apply` trap.
6209 fn proxy_apply(
6210 &mut self,
6211 object: &Gc<JsObject>,
6212 this: Value,
6213 args: Vec<Value>,
6214 ) -> JsResult<Option<Value>> {
6215 let Some((target, handler)) = self.proxy_parts(object)? else {
6216 return Ok(None);
6217 };
6218 // The trap gets the arguments as one array, which is the shape the spec passes
6219 // and the shape `apply` traps are written against (`args[0]` is the first one).
6220 let arguments = self.new_array(args.clone());
6221 let this_for_trap = this.clone();
6222 let Some(result) = self.proxy_trap(
6223 &handler,
6224 "apply",
6225 vec![
6226 Value::Object(target.clone()),
6227 this_for_trap,
6228 Value::Object(arguments),
6229 ],
6230 )?
6231 else {
6232 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
6233 };
6234 Ok(Some(result))
6235 }
6236
6237 /// `[[Construct]]` on a proxy, through the `construct` trap.
6238 fn proxy_construct(
6239 &mut self,
6240 object: &Gc<JsObject>,
6241 args: Vec<Value>,
6242 new_target: &Value,
6243 ) -> JsResult<Option<Value>> {
6244 let Some((target, handler)) = self.proxy_parts(object)? else {
6245 return Ok(None);
6246 };
6247 if !target.is_callable() {
6248 return Err(self.type_error("proxy target is not a constructor"));
6249 }
6250 let arguments = self.new_array(args.clone());
6251 let Some(result) = self.proxy_trap(
6252 &handler,
6253 "construct",
6254 vec![
6255 Value::Object(target.clone()),
6256 Value::Object(arguments),
6257 new_target.clone(),
6258 ],
6259 )?
6260 else {
6261 return Ok(Some(self.construct(
6262 Value::Object(target),
6263 new_target.clone(),
6264 args,
6265 )?));
6266 };
6267 if !matches!(result, Value::Object(_)) {
6268 return Err(self.type_error("proxy 'construct' must return an object"));
6269 }
6270 Ok(Some(result))
6271 }
6272
6273 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
6274 pub(crate) fn has_own_or_inherited(
6275 &mut self,
6276 object: &Gc<JsObject>,
6277 key: &PropertyKey,
6278 ) -> JsResult<bool> {
6279 // The object itself first: it may be a proxy, and then the answer is its trap's.
6280 if let Some(answer) = self.proxy_has(object, key)? {
6281 return Ok(answer);
6282 }
6283 // An integer-indexed exotic object answers a canonical numeric index from
6284 // `IsValidIntegerIndex` alone (§10.4.5.4 step 1.b.i) — **without** walking the
6285 // prototype chain. That is observable: a view the buffer has been resized away from
6286 // has no indices, so `2 in view` is `false` even when
6287 // `Object.getPrototypeOf(view)[2]` exists. Falling through to the chain answered
6288 // `true`, which is what `TypedArray/out-of-bounds-behaves-like-detached` catches.
6289 // The `[[HasProperty]]` that `in` compiles to goes through here, which is why the
6290 // same rule is repeated in `has_property_key` rather than living only there.
6291 if object.typed_array_parts().is_some()
6292 && let Some(index) = key.as_str().and_then(array_index)
6293 {
6294 return Ok(object
6295 .typed_array_length()
6296 .is_some_and(|length| (index as usize) < length));
6297 }
6298 // A host class answers `in` for its own keys, which may live nowhere in a property
6299 // table — `"x" in point` is true because the class says so, not because a property
6300 // exists.
6301 if let Some(exotic) = object.exotic()
6302 && let Some(answer) = exotic.has_property(self, object, key)?
6303 {
6304 return Ok(answer);
6305 }
6306 // `has_own` rather than `own_property_key`: an array's elements and its derived
6307 // `length` are invisible to the property table, and `Array.prototype` is an array.
6308 // A host class's `get_own_property` counts too, because the reference's
6309 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
6310 // lives — a class with only `get_own_property` answers `in` through it.
6311 if self.exotic_has_own(object, key)? {
6312 return Ok(true);
6313 }
6314 // A hole is *not* the end of the search: the chain may still have the key, which
6315 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
6316 for ancestor in object.chain() {
6317 // A proxy further up the chain answers for itself.
6318 if let Some(answer) = self.proxy_has(&ancestor, key)? {
6319 return Ok(answer);
6320 }
6321 // Same for a host class: a prototype may be one, and `in` reaches it.
6322 if let Some(exotic) = ancestor.exotic()
6323 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
6324 {
6325 return Ok(answer);
6326 }
6327 if self.exotic_has_own(&ancestor, key)? {
6328 return Ok(true);
6329 }
6330 }
6331 Ok(false)
6332 }
6333
6334 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
6335 /// trap included.
6336 ///
6337 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
6338 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
6339 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
6340 if let Some(exotic) = object.exotic()
6341 && let Some(answer) = exotic.get_own_property(self, object, key)?
6342 {
6343 return Ok(answer.is_some());
6344 }
6345 Ok(has_own(object, key))
6346 }
6347
6348 /// `CreateListFromArrayLike`, optionally restricted to property keys.
6349 ///
6350 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
6351 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
6352 /// `TypeError` instead of a property named `"1.5"`.
6353 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
6354 let object = self.object_from(value)?;
6355 let length = self
6356 .get_property(&object, "length")?
6357 .map(|value| value.to_number())
6358 .unwrap_or(0.0);
6359 if !length.is_finite() || length < 0.0 {
6360 return Err(self.type_error("invalid array-like length"));
6361 }
6362 let length = length as usize;
6363 let mut items = Vec::with_capacity(length.min(1024));
6364 for index in 0..length {
6365 let item = self
6366 .get_property(&object, &index.to_string())?
6367 .unwrap_or(Value::Undefined);
6368 if keys_only && matches!(&item, Value::Symbol(_)) {
6369 items.push(item);
6370 continue;
6371 }
6372 if keys_only && !matches!(&item, Value::String(_)) {
6373 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
6374 }
6375 items.push(item);
6376 }
6377 Ok(items)
6378 }
6379
6380 /// A `Property` from the descriptor object a trap returned.
6381 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
6382 let object = self.object_from(value)?;
6383 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
6384 interp.get_property(&object, name)
6385 };
6386 let getter = field(self, "get")?;
6387 let setter = field(self, "set")?;
6388 let accessor = getter.is_some() || setter.is_some();
6389 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
6390 Ok(interp
6391 .get_property(&object, name)?
6392 .is_some_and(|value| value.to_boolean()))
6393 };
6394 let enumerable = boolean(self, "enumerable")?;
6395 let configurable = boolean(self, "configurable")?;
6396 if accessor {
6397 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
6398 return Err(
6399 self.type_error("a descriptor cannot be both a data property and an accessor")
6400 );
6401 }
6402 Ok(Property {
6403 getter: getter.or(Some(Value::Undefined)),
6404 setter: setter.or(Some(Value::Undefined)),
6405 enumerable,
6406 configurable,
6407 writable: false,
6408 value: None,
6409 })
6410 } else {
6411 Ok(Property {
6412 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
6413 writable: boolean(self, "writable")?,
6414 enumerable,
6415 configurable,
6416 getter: None,
6417 setter: None,
6418 })
6419 }
6420 }
6421
6422 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
6423 fn descriptor_from_property(&mut self, property: &Property) -> Value {
6424 let object = self.new_object(None);
6425 if property.is_accessor() {
6426 let getter = property.getter.clone().unwrap_or(Value::Undefined);
6427 let setter = property.setter.clone().unwrap_or(Value::Undefined);
6428 object.define_data("get", getter);
6429 object.define_data("set", setter);
6430 } else {
6431 let value = property.value.clone().unwrap_or(Value::Undefined);
6432 object.define_data("value", value);
6433 object.define_data("writable", Value::Bool(property.writable));
6434 }
6435 object.define_data("enumerable", Value::Bool(property.enumerable));
6436 object.define_data("configurable", Value::Bool(property.configurable));
6437 Value::Object(object)
6438 }
6439
6440 // -- calling ------------------------------------------------------------
6441
6442 /// Call `callee` with `this` and `args`.
6443 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
6444 let Value::Object(function) = &callee else {
6445 // `typeof x === "function"` is not enough to make `x()` legal: only a
6446 // callable object is. `null` and `undefined` need no special wording
6447 // here — their `ToString` already reads the way the reference's does.
6448 let what = format!("{} is not a function", callee.to_js_string());
6449 return Err(Signal::Throw(self.make_error("TypeError", &what)));
6450 };
6451 // A proxy of a function is called through its `apply` trap. It has no
6452 // `ObjectKind::Function` of its own, so this has to come before the dispatch
6453 // below, and a proxy of a non-function has nothing to forward to.
6454 if function.proxy_state().is_some() {
6455 return match self.proxy_apply(function, this, args)? {
6456 Some(result) => Ok(result),
6457 None => Err(Signal::Throw(
6458 self.make_error("TypeError", "proxy target is not callable"),
6459 )),
6460 };
6461 }
6462 let callable = function.with(|data| match &data.kind {
6463 ObjectKind::Function(callable) => match callable {
6464 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
6465 // The `Rc` is cloned out so the borrow of this object's data is released
6466 // before the closure runs: the closure may touch the same object.
6467 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
6468 Callable::Bound {
6469 target,
6470 this,
6471 args: leading,
6472 } => Some(NativeCall::Bound {
6473 target: target.clone(),
6474 this: this.clone(),
6475 leading: leading.clone(),
6476 }),
6477 Callable::Bytecode { code, env } => {
6478 Some(NativeCall::Bytecode(code.clone(), env.clone()))
6479 }
6480 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
6481 Callable::PromiseResolve(promise) => {
6482 Some(NativeCall::PromiseResolve(promise.clone()))
6483 }
6484 Callable::PromiseReject(promise) => {
6485 Some(NativeCall::PromiseReject(promise.clone()))
6486 }
6487 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
6488 state: state.clone(),
6489 }),
6490 Callable::ThenShim {
6491 handler,
6492 resolve,
6493 reject,
6494 fulfilled,
6495 } => Some(NativeCall::ThenShim {
6496 handler: handler.clone(),
6497 resolve: resolve.clone(),
6498 reject: reject.clone(),
6499 fulfilled: *fulfilled,
6500 }),
6501 Callable::AwaitResume {
6502 coroutine,
6503 promise,
6504 kind,
6505 } => Some(NativeCall::AwaitResume {
6506 coroutine: coroutine.clone(),
6507 promise: promise.clone(),
6508 kind: *kind,
6509 }),
6510 Callable::CombinatorSettle {
6511 state,
6512 index,
6513 fulfilled,
6514 } => Some(NativeCall::CombinatorSettle {
6515 state: state.clone(),
6516 index: *index,
6517 fulfilled: *fulfilled,
6518 }),
6519 Callable::FinallyShim {
6520 callback,
6521 fulfilled,
6522 constructor,
6523 } => Some(NativeCall::FinallyShim {
6524 callback: callback.clone(),
6525 fulfilled: *fulfilled,
6526 constructor: constructor.clone(),
6527 }),
6528 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
6529 Callable::CompletedReturn {
6530 generator,
6531 promise,
6532 rejected,
6533 } => Some(NativeCall::CompletedReturn {
6534 generator: generator.clone(),
6535 promise: promise.clone(),
6536 rejected: *rejected,
6537 }),
6538 Callable::YieldResult {
6539 generator,
6540 promise,
6541 done,
6542 } => Some(NativeCall::YieldResult {
6543 generator: generator.clone(),
6544 promise: promise.clone(),
6545 done: *done,
6546 }),
6547 Callable::DisposeStep {
6548 remaining,
6549 promise,
6550 error,
6551 rejected,
6552 } => Some(NativeCall::DisposeStep {
6553 remaining: remaining.clone(),
6554 promise: promise.clone(),
6555 error: error.clone(),
6556 rejected: *rejected,
6557 }),
6558 Callable::GeneratorResume {
6559 generator,
6560 promise,
6561 kind,
6562 } => Some(NativeCall::GeneratorResume {
6563 generator: generator.clone(),
6564 promise: promise.clone(),
6565 kind: *kind,
6566 }),
6567 Callable::SettlePromise {
6568 promise,
6569 value,
6570 rejected,
6571 } => Some(NativeCall::SettlePromise {
6572 promise: promise.clone(),
6573 value: value.clone(),
6574 rejected: *rejected,
6575 }),
6576 },
6577 _ => None,
6578 });
6579 match callable {
6580 Some(NativeCall::Host(func)) => {
6581 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
6582 // function by name rather than stopping at the caller.
6583 let frame_less = function
6584 .own_property("_frame_less")
6585 .and_then(|property| property.value)
6586 .is_some_and(|value| value.to_boolean());
6587 let outer = if frame_less {
6588 None
6589 } else {
6590 self.native_frames
6591 .push((function.clone(), self.frames.len()));
6592 Some(self.current_native.replace(function.clone()))
6593 };
6594 let result = {
6595 let mut body = func.borrow_mut();
6596 body(self, this, &args)
6597 };
6598 if !frame_less {
6599 self.native_frames.pop();
6600 self.current_native = outer.flatten();
6601 }
6602 result
6603 }
6604 Some(NativeCall::Native(func)) => {
6605 // A function marked `_frame_less` is one the reference implements
6606 // without a call frame — `eval` is the only one so far.
6607 let frame_less = function
6608 .own_property("_frame_less")
6609 .and_then(|property| property.value)
6610 .is_some_and(|value| value.to_boolean());
6611 let outer = if frame_less {
6612 None
6613 } else {
6614 self.native_frames
6615 .push((function.clone(), self.frames.len()));
6616 Some(self.current_native.replace(function.clone()))
6617 };
6618 let result = func(self, this, &args);
6619 if !frame_less {
6620 self.native_frames.pop();
6621 self.current_native = outer.flatten();
6622 }
6623 result
6624 }
6625 Some(NativeCall::Revoker(slots)) => {
6626 // Idempotent: revoking twice answers `undefined` again rather than
6627 // complaining, which is what the spec says and what a `finally` block
6628 // relies on.
6629 let mut state = slots.borrow_mut();
6630 state.target = None;
6631 state.handler = None;
6632 Ok(Value::Undefined)
6633 }
6634 Some(NativeCall::PromiseResolve(promise)) => {
6635 // One-shot: a second call is silently ignored, which
6636 // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
6637 let value = args.first().cloned().unwrap_or(Value::Undefined);
6638 self.resolve_promise_with(&promise, value)?;
6639 Ok(Value::Undefined)
6640 }
6641 Some(NativeCall::PromiseReject(promise)) => {
6642 let reason = args.first().cloned().unwrap_or(Value::Undefined);
6643 self.reject_promise(&promise, reason);
6644 Ok(Value::Undefined)
6645 }
6646 Some(NativeCall::ThenShim {
6647 handler,
6648 resolve,
6649 reject,
6650 fulfilled,
6651 }) => {
6652 // `PerformPromiseThen` with a capability: run the handler, then settle
6653 // through the capability's own pair. A throw from the handler is the
6654 // rejection, and a throw from the capability's `resolve` is not caught —
6655 // exactly the spec's `?`.
6656 let value = args.first().cloned().unwrap_or(Value::Undefined);
6657 match handler {
6658 Some(handler) => {
6659 match self.call_value(handler, Value::Undefined, vec![value]) {
6660 Ok(result) => {
6661 self.call_value(resolve, Value::Undefined, vec![result])?;
6662 }
6663 Err(Signal::Throw(reason)) => {
6664 self.call_value(reject, Value::Undefined, vec![reason])?;
6665 }
6666 Err(signal) => return Err(signal),
6667 }
6668 }
6669 None => {
6670 let handler = if fulfilled { resolve } else { reject };
6671 self.call_value(handler, Value::Undefined, vec![value])?;
6672 }
6673 }
6674 Ok(Value::Undefined)
6675 }
6676 Some(NativeCall::CapabilityExecutor { state }) => {
6677 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
6678 // slot holds a value yet. The test is on the *values*, not on a call count —
6679 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
6680 // called-twice`'s first case does exactly that), while a second call after a
6681 // real pair is the `TypeError`.
6682 let defined = |name: &str| {
6683 state
6684 .own_property(name)
6685 .and_then(|property| property.value)
6686 .is_some_and(|value| !matches!(value, Value::Undefined))
6687 };
6688 if defined("resolve") || defined("reject") {
6689 return Err(self.type_error("promise capability executor called twice"));
6690 }
6691 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
6692 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
6693 state.define_data("resolve", resolve);
6694 state.define_data("reject", reject);
6695 Ok(Value::Undefined)
6696 }
6697 Some(NativeCall::CombinatorSettle {
6698 state,
6699 index,
6700 fulfilled,
6701 }) => {
6702 let value = args.first().cloned().unwrap_or(Value::Undefined);
6703 self.settle_combinator(&state, index, fulfilled, value)?;
6704 Ok(Value::Undefined)
6705 }
6706 Some(NativeCall::AwaitResume {
6707 coroutine,
6708 promise,
6709 kind,
6710 }) => {
6711 // Resume *inline*, in the reaction that delivered the value. Deferring it
6712 // by another job inserts a tick between every `await` and its
6713 // continuation, which reorders `await` against unrelated `then` chains —
6714 // `f().then(g)` then runs before `f`'s own next statement.
6715 self.drive_async(
6716 &coroutine,
6717 &promise,
6718 kind,
6719 args.first().cloned().unwrap_or(Value::Undefined),
6720 )
6721 .map(|()| Value::Undefined)
6722 }
6723 Some(NativeCall::FinallyShim {
6724 callback,
6725 fulfilled,
6726 constructor,
6727 }) => {
6728 // §27.2.5.4.1: run `onFinally` with no arguments, then hand back a promise
6729 // that settles with the *original* outcome once the callback's result has
6730 // settled. The callback's own value is discarded — that is the whole
6731 // difference between `finally` and `then`.
6732 let original = args.first().cloned().unwrap_or(Value::Undefined);
6733 let result = match &callback {
6734 Some(callback) => {
6735 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
6736 }
6737 None => Value::Undefined,
6738 };
6739 // `PromiseResolve(C, result)`, not the intrinsic: a `result` that is
6740 // already a promise of this constructor is reused rather than rewrapped.
6741 let resolved = self.promise_resolve_for(&constructor, result)?;
6742 let Value::Object(resolved) = resolved else {
6743 return Ok(original);
6744 };
6745 // The wait is a chained promise rather than a bare return, so a callback
6746 // that returns a slow promise really does delay the continuation.
6747 let waiting = self.new_promise();
6748 let pass = JsObject::function(
6749 self.heap,
6750 Some(self.realm.function_proto.clone()),
6751 Callable::SettlePromise {
6752 promise: waiting.clone(),
6753 value: original,
6754 rejected: !fulfilled,
6755 },
6756 );
6757 let pass = Value::Object(pass);
6758 // Whichever way the callback's promise settles, the original outcome wins.
6759 self.perform_then(&resolved, Some(pass.clone()), Some(pass))?;
6760 Ok(Value::Object(waiting))
6761 }
6762 Some(NativeCall::DisposeStep {
6763 remaining,
6764 promise,
6765 error,
6766 rejected,
6767 }) => {
6768 let error = if rejected {
6769 let reason = args.first().cloned().unwrap_or(Value::Undefined);
6770 self.merge_dispose_error(reason, error)
6771 } else {
6772 error
6773 };
6774 self.dispose_step(&remaining, &promise, error)?;
6775 Ok(Value::Undefined)
6776 }
6777 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
6778 Some(NativeCall::CompletedReturn {
6779 generator,
6780 promise,
6781 rejected,
6782 }) => {
6783 let value = args.first().cloned().unwrap_or(Value::Undefined);
6784 let outcome = if rejected {
6785 AsyncOutcome::Error(value)
6786 } else {
6787 AsyncOutcome::Value(self.iterator_result(value, true)?)
6788 };
6789 self.settle_async_request(&generator, &promise, outcome)?;
6790 Ok(Value::Undefined)
6791 }
6792 Some(NativeCall::YieldResult {
6793 generator,
6794 promise,
6795 done,
6796 }) => {
6797 let value = args.first().cloned().unwrap_or(Value::Undefined);
6798 let result = self.iterator_result(value, done)?;
6799 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
6800 Ok(Value::Undefined)
6801 }
6802 Some(NativeCall::GeneratorResume {
6803 generator,
6804 promise,
6805 kind,
6806 }) => {
6807 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
6808 // tick and reorders the generator against other chains.
6809 self.step_async_generator(
6810 &generator,
6811 &promise,
6812 kind,
6813 args.first().cloned().unwrap_or(Value::Undefined),
6814 )
6815 .map(|()| Value::Undefined)
6816 }
6817 Some(NativeCall::SettlePromise {
6818 promise,
6819 value,
6820 rejected,
6821 }) => {
6822 if rejected {
6823 self.reject_promise(&promise, value);
6824 } else {
6825 self.fulfill_promise(&promise, value);
6826 }
6827 Ok(Value::Undefined)
6828 }
6829 Some(NativeCall::Bound {
6830 target,
6831 this: bound_this,
6832 leading,
6833 }) => {
6834 let mut all = leading;
6835 all.extend(args);
6836 self.call_value(target, bound_this, all)
6837 }
6838 Some(NativeCall::Bytecode(code, env)) => {
6839 if code.code.kind.is_generator() {
6840 return self.new_generator(callee, this, args);
6841 }
6842 if code.code.kind.is_async() {
6843 // Same coroutine machinery as a generator; the difference is only in
6844 // what the completion does — see `new_async_function`.
6845 return self.new_async_function(callee, this, args);
6846 }
6847 self.execute(code, env, this, args, callee)
6848 }
6849 None => Err(Signal::Throw(
6850 self.make_error("TypeError", "not a function"),
6851 )),
6852 }
6853 }
6854
6855 /// Give a freshly built function its own `prototype` object.
6856 ///
6857 /// Every function that can be used with `new` carries one, and its
6858 /// `constructor` points back at the function — a reference cycle, which is
6859 /// exactly what the collector's cycle pass exists to reclaim.
6860 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
6861 let prototype = self.new_object(Some(self.realm.object_proto.clone()));
6862 let constructor = Value::Object(function.clone());
6863 prototype.define(
6864 "constructor",
6865 Property::with_attributes(constructor, true, false),
6866 );
6867 let value = Value::Object(prototype);
6868 function.define("prototype", Property::prototype_of(value, true));
6869 }
6870
6871 /// A getter or setter that reads or writes the reference cell behind a mapped
6872 /// `arguments` index.
6873 ///
6874 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
6875 /// count — which is what the collector treats as "a reference from outside the
6876 /// heap". The closure therefore keeps the cell alive for exactly as long as the
6877 /// accessor is reachable, which is the same lifetime the arguments object has.
6878 ///
6879 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
6880 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
6881 /// parameter value and the arguments object reaches the closure, never the other
6882 /// way round. Nothing the collector has to see is hidden.
6883 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
6884 let name = if is_setter { "set" } else { "get" };
6885 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
6886 if is_setter {
6887 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
6888 Ok(Value::Undefined)
6889 } else {
6890 Ok(cell.get())
6891 }
6892 };
6893 self.new_host_function(name, 1, Box::new(func))
6894 }
6895
6896 /// The object `special_object` builds.
6897 ///
6898 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
6899 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
6900 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
6901 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
6902 /// write through `arguments` does not reach the parameter.
6903 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
6904 match magic {
6905 0 | 1 => {
6906 let args = self.frame().passed().to_vec();
6907 let proto = self.realm.object_proto.clone();
6908 let object = self.new_object(Some(proto));
6909 // The marker `Object.prototype.toString` needs: an arguments object is an
6910 // ordinary object apart from reporting `[object Arguments]`, and that has
6911 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
6912 // show up ahead of them in a key listing anyway — it is non-enumerable.
6913 self.internal_set(&object, "_class", self.string("Arguments"));
6914 // `length` is writable and configurable but neither enumerable nor a
6915 // plain data property: `Object.keys(arguments)` lists the indices only,
6916 // which is how `{...arguments}` copies them without the length.
6917 object.define(
6918 "length",
6919 Property::with_attributes(Value::Int(args.len() as i32), true, false),
6920 );
6921 // `magic == 1` is sloppy mode, where each index is *mapped* to the
6922 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
6923 // change `a`, and assigning `a` has to change `arguments[0]`.
6924 //
6925 // The shared storage is the parameter's reference cell. The compiler
6926 // gives every parameter of such a function one (see
6927 // `provide_body_arguments`), and the cell outlives the frame, so this
6928 // keeps working after the arguments object escapes.
6929 //
6930 // The index becomes an accessor rather than a data property. A mapped
6931 // index reports as a plain writable/enumerable data property through
6932 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
6933 // the getter/setter pair is only the plumbing underneath.
6934 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
6935 let frame = self.frame();
6936 frame
6937 .code
6938 .arg_cell
6939 .iter()
6940 .map(|cell| {
6941 (*cell >= 0)
6942 .then(|| frame.cells.get(*cell as usize).cloned())
6943 .flatten()
6944 })
6945 .collect()
6946 } else {
6947 Vec::new()
6948 };
6949 // Tell the object which indices are mapped, so
6950 // `Object.getOwnPropertyDescriptor` can report them as the data
6951 // properties the spec describes instead of the accessors that
6952 // implement the aliasing.
6953 if magic == 1 {
6954 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
6955 for cell in &mapped_cells {
6956 table.push(cell.clone());
6957 }
6958 object.set_mapped_arguments(table);
6959 }
6960 for (index, value) in args.into_iter().enumerate() {
6961 match mapped_cells.get(index).cloned().flatten() {
6962 Some(cell) => {
6963 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
6964 let setter = self.new_mapped_arguments_accessor(cell, true);
6965 object.define(
6966 &index.to_string(),
6967 Property::accessor_with(
6968 Some(Value::Object(getter)),
6969 Some(Value::Object(setter)),
6970 true,
6971 ),
6972 );
6973 }
6974 None => object.define_data(&index.to_string(), value),
6975 }
6976 }
6977 // §10.4.4: a *mapped* arguments object carries `callee` as a writable,
6978 // non-enumerable, configurable data property holding the function being
6979 // called. A strict (unmapped) one gets no such property at all; the
6980 // spec's poison-pill accessor for it is unreachable in this engine
6981 // because a strict `arguments.callee` is already a compile-time error.
6982 //
6983 // The legacy `S10.6_*` tests predate that restriction and ask only that
6984 // `arguments.hasOwnProperty("callee")` be true in sloppy mode.
6985 if magic == 1 {
6986 let callee = self.frame().callee.clone();
6987 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
6988 object.define("callee", Property::with_attributes(callee, true, false));
6989 }
6990 // An arguments object is iterable: `[...arguments]` and
6991 // `for (const a of arguments)` both work, through the *array* iterator
6992 // because the object is array-like. Without this the whole spread form
6993 // reported "not iterable".
6994 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
6995 let values = self
6996 .realm
6997 .array_proto
6998 .own_property("values")
6999 .and_then(|property| property.value);
7000 if let Some(values) = values {
7001 object.define_key(
7002 &iterator_key,
7003 Property::with_attributes(values, true, false),
7004 );
7005 }
7006 Ok(Value::Object(object))
7007 }
7008 // `this.active_func`: the constructor `super()` resolves against.
7009 //
7010 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
7011 // own, so it inherits this from the function it was written in along with `this`
7012 // — and that is a lexical relationship, not a stack one: an arrow that escaped
7013 // the constructor and is called back later (`iter.return = () => super()`) has
7014 // the constructor nowhere on the stack. The compiler therefore reads it out of
7015 // a closure variable of the enclosing function, exactly as the reference does
7016 // with its `this_active_func` local.
7017 2 => Ok(self
7018 .current_callee()
7019 .map_or(Value::Undefined, Value::Object)),
7020 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
7021 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
7022 // its own either, so the lookup walks out to the nearest non-arrow frame for
7023 // the same reason as `this.active_func` above — without that, `super()` inside
7024 // an arrow passed `undefined` as the new target and the parent constructor was
7025 // then rejected for being invoked without `new`.
7026 3 => Ok(self
7027 .eval_new_target
7028 .clone()
7029 .unwrap_or_else(|| self.frame().new_target.clone())),
7030 // `[[HomeObject]]` of the function being run: what `super` is relative to.
7031 // An arrow has none of its own, so the lookup walks out to the enclosing
7032 // method — which is why `super` works inside an arrow inside a method.
7033 4 => Ok(self
7034 .frames
7035 .iter()
7036 .rev()
7037 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
7038 .map_or(Value::Undefined, Value::Object)),
7039 // `import.meta`: the innermost module body's meta object. Outside a module
7040 // the compiler never emits this, so an empty fallback is unreachable rather
7041 // than permissive.
7042 6 => {
7043 let name = self.module_stack.last().cloned();
7044 let meta = name
7045 .and_then(|name| self.modules.get(&name).cloned())
7046 .and_then(|module| module.with(|r| r.import_meta.clone()));
7047 Ok(meta.map_or(Value::Undefined, Value::Object))
7048 }
7049 other => Err(Signal::Throw(self.make_error(
7050 "InternalError",
7051 &format!("special_object {other} is not implemented yet"),
7052 ))),
7053 }
7054 }
7055
7056 /// `[[HomeObject]]` of the innermost function that has one, if any.
7057 ///
7058 /// An arrow has none, so the search walks out to the enclosing method — the same
7059 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
7060 /// inside a method.
7061 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
7062 self.frames
7063 .iter()
7064 .rev()
7065 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
7066 }
7067
7068 /// The dispose method a `using` declaration should snapshot, or an error.
7069 ///
7070 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
7071 /// is what makes a resource that only knows the synchronous protocol usable in both
7072 /// forms.
7073 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
7074 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
7075 if value.is_nullish() {
7076 return Ok(Value::Undefined);
7077 }
7078 let Some(object) = value.as_object() else {
7079 return Err(self.type_error("not an object"));
7080 };
7081 let mut method = if await_form {
7082 let found = self.get_property_key(
7083 object,
7084 &self.realm.well_known_key(WellKnown::AsyncDisposable),
7085 )?;
7086 match found {
7087 Some(found) if !found.is_nullish() => Some(found),
7088 _ => self
7089 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
7090 }
7091 } else {
7092 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
7093 };
7094 let Some(found) = method.take() else {
7095 return Err(self.type_error("value is not disposable"));
7096 };
7097 if found.is_nullish() {
7098 return Err(self.type_error("value is not disposable"));
7099 }
7100 let callable = found.as_object().is_some_and(|object| object.is_callable());
7101 if !callable {
7102 return Err(self.type_error("dispose method is not a function"));
7103 }
7104 Ok(found)
7105 }
7106
7107 /// Call one resource's disposer, folding a failure into `error_state`.
7108 ///
7109 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
7110 /// because a captured `using` binding lives in its reference cell and the local slot is
7111 /// stale — a closure over the resource is legal and must not change what is disposed.
7112 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
7113 let value = self.get_loc(slot);
7114 let method = self.get_loc(slot + 1);
7115 // A resource that was never initialised — its declaration threw — or that is
7116 // `null`/`undefined` has nothing to dispose.
7117 if value.is_nullish() || matches!(value, Value::Uninitialized) {
7118 return Ok(error_state);
7119 }
7120 if matches!(method, Value::Undefined | Value::Uninitialized) {
7121 return Ok(error_state);
7122 }
7123 match self.call_value(method, value, Vec::new()) {
7124 Ok(_) => Ok(error_state),
7125 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
7126 Err(other) => Err(other),
7127 }
7128 }
7129
7130 /// Combine a disposal failure with whatever was already going wrong.
7131 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
7132 if matches!(error_state, Value::Uninitialized) {
7133 return new_error;
7134 }
7135 self.new_suppressed_error(new_error, error_state)
7136 }
7137
7138 /// A `SuppressedError` instance built straight from its prototype.
7139 ///
7140 /// Not through the constructor: a script that rewrites
7141 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
7142 /// error wrapping.
7143 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
7144 let proto = self
7145 .realm
7146 .suppressed_error_proto
7147 .clone()
7148 .unwrap_or_else(|| self.realm.error_proto.clone());
7149 let object = self.new_object(Some(proto));
7150 object.define("error", Property::with_attributes(error, true, true));
7151 object.define(
7152 "suppressed",
7153 Property::with_attributes(suppressed, true, true),
7154 );
7155 object.define(
7156 "message",
7157 Property::with_attributes(self.string("SuppressedError"), true, true),
7158 );
7159 self.internal_set(&object, "_class", self.string("Error"));
7160 self.add_stack(&object);
7161 Value::Object(object)
7162 }
7163
7164 /// Call `callee`, or push its frame and let the main loop run it.
7165 ///
7166 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
7167 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
7168 /// continues, so `function f(){ return f() }` costs heap and stops at
7169 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
7170 /// is entered directly, and natives do not re-enter JavaScript in this
7171 /// milestone.
7172 ///
7173 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
7174 /// because the returning frame will.
7175 /// The elements of an array-like value, as a call argument list.
7176 ///
7177 /// `apply` accepts any array-like, not only a real array: the reference reads
7178 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
7179 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
7180 let Some(object) = value.as_object().cloned() else {
7181 if value.is_nullish() {
7182 // `f.apply(this, null)` passes no arguments at all.
7183 return Ok(Vec::new());
7184 }
7185 return Err(self.type_error("createListFromArrayLike called on non-object"));
7186 };
7187 let length = match self.get_property(&object, "length")? {
7188 Some(length) => length.to_number(),
7189 None => 0.0,
7190 };
7191 if !length.is_finite() || length <= 0.0 {
7192 return Ok(Vec::new());
7193 }
7194 let length = (length as usize).min(1_000_000);
7195 let mut args = Vec::with_capacity(length);
7196 for index in 0..length {
7197 let element = self.get_property(&object, &index.to_string())?;
7198 args.push(element.unwrap_or(Value::Undefined));
7199 }
7200 Ok(args)
7201 }
7202
7203 /// Turn a call to a generator function into a generator object.
7204 ///
7205 /// The frame is built exactly as an ordinary call would build it, then detached and
7206 /// stored in the generator before any body instruction runs — which is what makes
7207 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
7208 /// is `initial_yield`, the first instruction of every suspending body.
7209 pub fn new_generator(
7210 &mut self,
7211 function: Value,
7212 this: Value,
7213 args: Vec<Value>,
7214 ) -> JsResult<Value> {
7215 let Some(object) = function.as_object().cloned() else {
7216 return Err(self.type_error("not a generator function"));
7217 };
7218 let Some((code, env)) = bytecode_of(&object) else {
7219 return Err(self.type_error("not a generator function"));
7220 };
7221 let is_async = code.code.kind.is_async();
7222 self.push_frame(code, env, this, args, function)?;
7223 let frame = self.frames.pop().expect("push_frame just pushed it");
7224 // A fresh generator is *suspended at start*: the body has not run, so a
7225 // `return`/`throw` on it finishes without executing anything.
7226 let mut state = GeneratorState {
7227 frame: Some(frame),
7228 phase: GeneratorPhase::SuspendedStart,
7229 parked_on_await: false,
7230 parked_on_yield_star: false,
7231 requests: std::collections::VecDeque::new(),
7232 async_busy: false,
7233 };
7234 // Run to the first suspension. For a generator that is `initial_yield`, so no
7235 // body code runs; for a malformed body it would be the first `yield`.
7236 // An `async function*` answers an async generator: same coroutine, but its
7237 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
7238 let proto = if is_async {
7239 self.realm
7240 .async_generator_proto
7241 .clone()
7242 .unwrap_or_else(|| self.realm.generator_proto.clone())
7243 } else {
7244 self.realm.generator_proto.clone()
7245 };
7246 let generator = self.new_object(Some(proto));
7247 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
7248 Ok(_) => {}
7249 Err(error) => return Err(error),
7250 }
7251 generator.with_mut(|data| {
7252 data.kind = ObjectKind::Generator(Box::new(state));
7253 });
7254 Ok(Value::Object(generator))
7255 }
7256
7257 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7258 ///
7259 /// Returns the `{value, done}` object itself rather than the pair, because a
7260 /// `yield*` suspension already has one — the inner iterator's own result — and the
7261 /// protocol says to hand that straight through rather than nest it.
7262 /// Advance a generator and report *why* it parked.
7263 ///
7264 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
7265 /// "hand this value to the caller" — but an async generator does: an `await` has to
7266 /// settle before it can answer, while a `yield` is the answer.
7267 fn resume_generator_detailed(
7268 &mut self,
7269 generator: &Gc<JsObject>,
7270 kind: ResumeKind,
7271 value: Value,
7272 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7273 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
7274 ObjectKind::Generator(state) => Some(std::mem::replace(
7275 state.as_mut(),
7276 GeneratorState {
7277 frame: None,
7278 phase: GeneratorPhase::Executing,
7279 parked_on_await: false,
7280 parked_on_yield_star: false,
7281 requests: std::collections::VecDeque::new(),
7282 async_busy: false,
7283 },
7284 )),
7285 _ => None,
7286 }) else {
7287 return Err(self.type_error("not a generator"));
7288 };
7289 let result = self.step_generator(&mut state, kind, value);
7290 generator.with_mut(|data| {
7291 data.kind = ObjectKind::Generator(Box::new(state));
7292 });
7293 result
7294 }
7295
7296 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
7297 ///
7298 /// Returns the `{value, done}` object itself rather than the pair, because a
7299 /// `yield*` suspension already has one — the inner iterator's own result — and the
7300 /// protocol says to hand that straight through rather than nest it.
7301 pub fn resume_generator(
7302 &mut self,
7303 generator: &Gc<JsObject>,
7304 kind: ResumeKind,
7305 value: Value,
7306 ) -> JsResult<Value> {
7307 let (value, done, ready, _reason) =
7308 self.resume_generator_detailed(generator, kind, value)?;
7309 if ready {
7310 return Ok(value);
7311 }
7312 self.iterator_result(value, done)
7313 }
7314
7315 /// `next`/`return`/`throw` on an async generator, which answer a promise.
7316 ///
7317 /// The body is the same coroutine a sync generator runs; what changes is that an
7318 /// `await` inside it has to settle before the method can answer, so the step is
7319 /// driven off the job queue rather than returning inline.
7320 pub fn resume_async_generator(
7321 &mut self,
7322 generator: &Gc<JsObject>,
7323 kind: ResumeKind,
7324 value: Value,
7325 ) -> JsResult<Value> {
7326 let promise = self.new_promise();
7327 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
7328 // that order, and the second value must reach the *second* `yield`.
7329 let idle = generator.with_mut(|data| match &mut data.kind {
7330 ObjectKind::Generator(state) => {
7331 state.requests.push_back(AsyncRequest {
7332 kind,
7333 value,
7334 promise: promise.clone(),
7335 });
7336 !state.async_busy
7337 }
7338 _ => false,
7339 });
7340 if idle {
7341 self.next_async_request(generator)?;
7342 }
7343 Ok(Value::Object(promise))
7344 }
7345
7346 /// Serve the front queued request, if the generator is free to run one.
7347 ///
7348 /// A finished generator answers from the queue without running anything:
7349 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
7350 /// first, and `throw(e)` rejects.
7351 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
7352 enum Front {
7353 Idle,
7354 Run(ResumeKind, Value, Gc<JsObject>),
7355 Finished(ResumeKind, Value, Gc<JsObject>),
7356 }
7357 let front = generator.with_mut(|data| match &mut data.kind {
7358 ObjectKind::Generator(state) => {
7359 let Some(request) = state.requests.front() else {
7360 return Front::Idle;
7361 };
7362 // Busy means a request is still in flight — awaiting inside the body, not
7363 // finished. Serving another now would interleave two requests.
7364 if state.async_busy && state.phase != GeneratorPhase::Completed {
7365 return Front::Idle;
7366 }
7367 let kind = request.kind;
7368 let value = request.value.clone();
7369 let promise = request.promise.clone();
7370 state.async_busy = true;
7371 if state.phase == GeneratorPhase::Completed {
7372 Front::Finished(kind, value, promise)
7373 } else {
7374 Front::Run(kind, value, promise)
7375 }
7376 }
7377 _ => Front::Idle,
7378 });
7379 match front {
7380 Front::Idle => Ok(()),
7381 Front::Run(kind, value, promise) => {
7382 self.step_async_generator(generator, &promise, kind, value)
7383 }
7384 Front::Finished(kind, value, promise) => match kind {
7385 ResumeKind::Throw => {
7386 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
7387 }
7388 ResumeKind::Next | ResumeKind::Start => {
7389 let result = self.iterator_result(Value::Undefined, true)?;
7390 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
7391 }
7392 ResumeKind::Return => {
7393 // `js_async_generator_completed_return`: the value is awaited before it
7394 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
7395 // finished generator answers `1`, not a promise.
7396 let resolved = match self.promise_resolve_value(value) {
7397 Ok(resolved) => resolved,
7398 Err(Signal::Throw(reason)) => {
7399 return self.settle_async_request(
7400 generator,
7401 &promise,
7402 AsyncOutcome::Error(reason),
7403 );
7404 }
7405 Err(other) => return Err(other),
7406 };
7407 let done = JsObject::function(
7408 self.heap,
7409 Some(self.realm.function_proto.clone()),
7410 Callable::CompletedReturn {
7411 generator: generator.clone(),
7412 promise: promise.clone(),
7413 rejected: false,
7414 },
7415 );
7416 let failed = JsObject::function(
7417 self.heap,
7418 Some(self.realm.function_proto.clone()),
7419 Callable::CompletedReturn {
7420 generator: generator.clone(),
7421 promise: promise.clone(),
7422 rejected: true,
7423 },
7424 );
7425 let Value::Object(resolved) = resolved else {
7426 return self.settle_async_request(
7427 generator,
7428 &promise,
7429 AsyncOutcome::Error(Value::Undefined),
7430 );
7431 };
7432 self.perform_then(
7433 &resolved,
7434 Some(Value::Object(done)),
7435 Some(Value::Object(failed)),
7436 )?;
7437 Ok(())
7438 }
7439 },
7440 }
7441 }
7442
7443 /// Settle the front request and start the next one.
7444 ///
7445 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
7446 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
7447 /// generator would strand every later request.
7448 fn settle_async_request(
7449 &mut self,
7450 generator: &Gc<JsObject>,
7451 promise: &Gc<JsObject>,
7452 outcome: AsyncOutcome,
7453 ) -> JsResult<()> {
7454 let settled = generator.with_mut(|data| match &mut data.kind {
7455 ObjectKind::Generator(state) => {
7456 let front = state.requests.front();
7457 debug_assert!(
7458 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
7459 "a request settled outside its turn"
7460 );
7461 state.requests.pop_front();
7462 state.async_busy = false;
7463 true
7464 }
7465 _ => false,
7466 });
7467 if settled {
7468 match outcome {
7469 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
7470 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
7471 }
7472 }
7473 self.next_async_request(generator)
7474 }
7475
7476 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
7477 ///
7478 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
7479 /// disposer runs **synchronously** — the reference starts it before returning, which
7480 /// a test can observe by logging after the call — and the rest follow once their
7481 /// predecessor settles.
7482 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
7483 let promise = self.new_promise();
7484 let mut pairs = Vec::with_capacity(resources.len());
7485 for (value, method) in resources {
7486 let pair = self.new_array(vec![value, method]);
7487 pairs.push(Value::Object(pair));
7488 }
7489 let remaining = self.new_array(pairs);
7490 self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
7491 Ok(Value::Object(promise))
7492 }
7493
7494 /// One link of the `disposeAsync` chain.
7495 ///
7496 /// Loops while the disposers finish synchronously, and parks on the first thenable it
7497 /// meets — pushing itself back in as the continuation, with the accumulated error
7498 /// carried along so a later failure can still be folded into the `SuppressedError`.
7499 fn dispose_step(
7500 &mut self,
7501 remaining: &Gc<JsObject>,
7502 promise: &Gc<JsObject>,
7503 mut error: Value,
7504 ) -> JsResult<()> {
7505 loop {
7506 let length = remaining.array_length().unwrap_or(0);
7507 if length == 0 {
7508 if matches!(error, Value::Uninitialized) {
7509 self.fulfill_promise(promise, Value::Undefined);
7510 } else {
7511 self.reject_promise(promise, error);
7512 }
7513 return Ok(());
7514 }
7515 let Some(Value::Object(pair)) = remaining
7516 .array_get(length - 1)
7517 .filter(|v| !matches!(v, Value::Hole))
7518 else {
7519 remaining.array_truncate(self.heap, length - 1);
7520 continue;
7521 };
7522 remaining.array_truncate(self.heap, length - 1);
7523 let value = pair.array_get(0).unwrap_or(Value::Undefined);
7524 let Some(Value::Object(method)) = pair.array_get(1) else {
7525 continue;
7526 };
7527 if !method.is_callable() {
7528 continue;
7529 }
7530 match self.call_value(Value::Object(method), value, Vec::new()) {
7531 Ok(result) => {
7532 if !self.is_thenable(&result)? {
7533 // Finished synchronously; the next disposer is the next iteration.
7534 continue;
7535 }
7536 let awaited = match self.promise_resolve_value(result) {
7537 Ok(awaited) => awaited,
7538 Err(Signal::Throw(reason)) => {
7539 self.reject_promise(promise, reason);
7540 return Ok(());
7541 }
7542 Err(other) => return Err(other),
7543 };
7544 let Value::Object(awaited) = awaited else {
7545 continue;
7546 };
7547 let ok = JsObject::function(
7548 self.heap,
7549 Some(self.realm.function_proto.clone()),
7550 Callable::DisposeStep {
7551 remaining: remaining.clone(),
7552 promise: promise.clone(),
7553 error: error.clone(),
7554 rejected: false,
7555 },
7556 );
7557 let failed = JsObject::function(
7558 self.heap,
7559 Some(self.realm.function_proto.clone()),
7560 Callable::DisposeStep {
7561 remaining: remaining.clone(),
7562 promise: promise.clone(),
7563 error,
7564 rejected: true,
7565 },
7566 );
7567 self.perform_then(
7568 &awaited,
7569 Some(Value::Object(ok)),
7570 Some(Value::Object(failed)),
7571 )?;
7572 return Ok(());
7573 }
7574 Err(Signal::Throw(thrown)) => {
7575 error = self.merge_dispose_error(thrown, error);
7576 }
7577 Err(other) => return Err(other),
7578 }
7579 }
7580 }
7581
7582 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
7583 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
7584 let Value::Object(object) = value else {
7585 return Ok(false);
7586 };
7587 Ok(matches!(
7588 self.get_property(object, "then")?,
7589 Some(Value::Object(then)) if then.is_callable()
7590 ))
7591 }
7592
7593 /// One step of an async generator, settling `promise` with an `{value, done}` result.
7594 fn step_async_generator(
7595 &mut self,
7596 generator: &Gc<JsObject>,
7597 promise: &Gc<JsObject>,
7598 kind: ResumeKind,
7599 value: Value,
7600 ) -> JsResult<()> {
7601 let stepped = self.resume_generator_detailed(generator, kind, value);
7602 let (value, done, ready, reason) = match stepped {
7603 Ok(stepped) => stepped,
7604 Err(Signal::Throw(reason)) => {
7605 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
7606 }
7607 Err(other) => return Err(other),
7608 };
7609 // Only an `await` has to wait before the method can answer.
7610 if !done && reason == Some(SuspendKind::Await) {
7611 let awaited = match self.promise_resolve_value(value) {
7612 Ok(awaited) => awaited,
7613 Err(Signal::Throw(reason)) => {
7614 return self.settle_async_request(
7615 generator,
7616 promise,
7617 AsyncOutcome::Error(reason),
7618 );
7619 }
7620 Err(other) => return Err(other),
7621 };
7622 let Value::Object(awaited) = awaited else {
7623 return Ok(());
7624 };
7625 let resumed = JsObject::function(
7626 self.heap,
7627 Some(self.realm.function_proto.clone()),
7628 Callable::GeneratorResume {
7629 generator: generator.clone(),
7630 promise: promise.clone(),
7631 kind: ResumeKind::Next,
7632 },
7633 );
7634 let raised = JsObject::function(
7635 self.heap,
7636 Some(self.realm.function_proto.clone()),
7637 Callable::GeneratorResume {
7638 generator: generator.clone(),
7639 promise: promise.clone(),
7640 kind: ResumeKind::Throw,
7641 },
7642 );
7643 self.perform_then(
7644 &awaited,
7645 Some(Value::Object(resumed)),
7646 Some(Value::Object(raised)),
7647 )?;
7648 return Ok(());
7649 }
7650 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
7651 // completes it — both arrive as the settled value rather than as the promise
7652 // object. A plain value skips the round trip, which is also what keeps `yield 1`
7653 // from costing an extra tick.
7654 let awaits_value = self.is_thenable(&value)?;
7655 if awaits_value {
7656 let awaited = match self.promise_resolve_value(value) {
7657 Ok(awaited) => awaited,
7658 Err(Signal::Throw(reason)) => {
7659 return self.settle_async_request(
7660 generator,
7661 promise,
7662 AsyncOutcome::Error(reason),
7663 );
7664 }
7665 Err(other) => return Err(other),
7666 };
7667 let Value::Object(awaited) = awaited else {
7668 return Ok(());
7669 };
7670 // A rejected yield throws *at the yield* inside the body, so the rejection
7671 // resumes the generator rather than the method's promise.
7672 let answer = JsObject::function(
7673 self.heap,
7674 Some(self.realm.function_proto.clone()),
7675 Callable::YieldResult {
7676 generator: generator.clone(),
7677 promise: promise.clone(),
7678 done,
7679 },
7680 );
7681 let raise = JsObject::function(
7682 self.heap,
7683 Some(self.realm.function_proto.clone()),
7684 Callable::GeneratorResume {
7685 generator: generator.clone(),
7686 promise: promise.clone(),
7687 kind: ResumeKind::Throw,
7688 },
7689 );
7690 self.perform_then(
7691 &awaited,
7692 Some(Value::Object(answer)),
7693 Some(Value::Object(raise)),
7694 )?;
7695 return Ok(());
7696 }
7697 let result = if ready {
7698 // `yield*` handed back the inner iterator's own result object.
7699 value
7700 } else {
7701 self.iterator_result(value, done)?
7702 };
7703 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
7704 }
7705
7706 /// The `{value, done}` object an iterator method answers with.
7707 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
7708 let result = self.new_object(Some(self.realm.object_proto.clone()));
7709 result.define_data("value", value);
7710 result.define_data("done", Value::Bool(done));
7711 Ok(Value::Object(result))
7712 }
7713
7714 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
7715 fn step_generator(
7716 &mut self,
7717 state: &mut GeneratorState,
7718 kind: ResumeKind,
7719 value: Value,
7720 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
7721 match state.phase {
7722 GeneratorPhase::Executing => {
7723 return Err(self.type_error("cannot invoke a running generator"));
7724 }
7725 GeneratorPhase::Completed => {
7726 // A finished generator answers every resumption without running.
7727 return Ok(match kind {
7728 ResumeKind::Throw => return Err(Signal::Throw(value)),
7729 ResumeKind::Return => (value, true, false, None),
7730 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
7731 });
7732 }
7733 GeneratorPhase::SuspendedStart => {
7734 if kind != ResumeKind::Next && kind != ResumeKind::Start {
7735 // The body never started, so there is nothing to unwind or return
7736 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
7737 state.frame = None;
7738 state.phase = GeneratorPhase::Completed;
7739 return Ok(match kind {
7740 ResumeKind::Throw => return Err(Signal::Throw(value)),
7741 _ => (value, true, false, None),
7742 });
7743 }
7744 }
7745 GeneratorPhase::SuspendedYield => {}
7746 }
7747
7748 let Some(mut frame) = state.frame.take() else {
7749 return Ok((Value::Undefined, true, false, None));
7750 };
7751 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
7752 // number that says which method resumed it; the emitted `if_false` branches on
7753 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
7754 let mut raised = None;
7755 match kind {
7756 ResumeKind::Next | ResumeKind::Start => {
7757 if state.phase == GeneratorPhase::SuspendedYield {
7758 frame.stack.push(value);
7759 // An `await` resumes with its value alone; only a `yield` gets the
7760 // magic number that says which of `next`/`return` resumed it.
7761 if !state.parked_on_await {
7762 frame.stack.push(Value::Int(RESUME_NEXT));
7763 }
7764 }
7765 }
7766 ResumeKind::Return => {
7767 // A `return` on a not-yet-started generator is handled above, so this is
7768 // always a real resumption.
7769 frame.stack.push(value);
7770 frame.stack.push(Value::Int(RESUME_RETURN));
7771 }
7772 ResumeKind::Throw => {
7773 // At a `yield*` the exception is *data* for the delegation: the compiled
7774 // code resumes with the value and magic `2` and calls the inner iterator's
7775 // `throw`. Everywhere else it is raised at the suspension point, so the
7776 // body's own handler sees it.
7777 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
7778 frame.stack.push(value);
7779 frame.stack.push(Value::Int(RESUME_THROW));
7780 } else {
7781 raised = Some(value);
7782 }
7783 }
7784 }
7785 state.phase = GeneratorPhase::Executing;
7786
7787 let depth = self.frames.len();
7788 self.frames.push(frame);
7789 // A `throw` unwinds from where the frame parked, exactly as if the exception had
7790 // happened at the `yield`.
7791 if let Some(exception) = raised {
7792 if self.catch_here(exception.clone()).is_none() {
7793 self.pop_frame();
7794 state.phase = GeneratorPhase::Completed;
7795 return Err(Signal::Throw(exception));
7796 }
7797 }
7798
7799 // Only the generator's *own* frame ends the generator. The body may call ordinary
7800 // functions, and those push frames of their own: a `Step::Return` from one of them
7801 // is a nested call finishing, not the generator completing. Miscounting that is
7802 // silent — the generator reports the callee's value as its own result and marks
7803 // itself done — so the depth comparison is load-bearing, not defensive.
7804 let own_frame = depth + 1;
7805 loop {
7806 match self.step() {
7807 Ok(Step::Continue) => {}
7808 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
7809 let mut frame = self.frames.pop().expect("a frame is live");
7810 // `yield` left the value on the stack; `initial_yield` left nothing.
7811 let yielded = if reason == SuspendKind::Initial {
7812 Value::Undefined
7813 } else {
7814 frame.stack.pop().unwrap_or(Value::Undefined)
7815 };
7816 state.frame = Some(frame);
7817 state.parked_on_await = reason == SuspendKind::Await;
7818 state.parked_on_yield_star =
7819 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
7820 state.phase = if reason == SuspendKind::Initial {
7821 GeneratorPhase::SuspendedStart
7822 } else {
7823 GeneratorPhase::SuspendedYield
7824 };
7825 // `yield*` hands the inner iterator's own result object straight
7826 // back, so the caller sees one `{value, done}` rather than a nested
7827 // one — which is why the third field says "already a result".
7828 return Ok((
7829 yielded,
7830 false,
7831 reason == SuspendKind::YieldStar,
7832 Some(reason),
7833 ));
7834 }
7835 Ok(Step::Suspend(_)) => {
7836 // A `yield` in a frame other than the generator's would mean a
7837 // generator body entered as an ordinary call, which
7838 // `call_or_push` prevents.
7839 self.unwind_to(depth);
7840 state.phase = GeneratorPhase::Completed;
7841 return Err(Signal::Throw(self.make_error(
7842 "InternalError",
7843 "a generator body ran as an ordinary call",
7844 )));
7845 }
7846 Ok(Step::Return(value)) => {
7847 self.pop_frame();
7848 if self.frames.len() > depth {
7849 // A nested call finished: hand the value back to its caller and
7850 // keep running the generator body.
7851 self.frames
7852 .last_mut()
7853 .expect("a caller is live")
7854 .stack
7855 .push(value);
7856 continue;
7857 }
7858 state.phase = GeneratorPhase::Completed;
7859 // The reference closes the generator's closure variables here; ours
7860 // live in cells the frame owned, which the drop below releases.
7861 return Ok((value, true, false, None));
7862 }
7863 Err(Signal::Throw(exception)) => {
7864 // The frame that threw gets the first chance to catch, exactly as in
7865 // the ordinary call loop; a frame above the generator's is popped and
7866 // the exception carries on down.
7867 let exception = exception;
7868 loop {
7869 if self.frames.len() <= depth {
7870 // The generator's own frame is gone, so nothing here caught it.
7871 state.phase = GeneratorPhase::Completed;
7872 return Err(Signal::Throw(exception));
7873 }
7874 if self.catch_here(exception.clone()).is_some() {
7875 break;
7876 }
7877 self.pop_frame();
7878 }
7879 }
7880 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
7881 }
7882 }
7883 }
7884
7885 /// Pop frames until `depth` are left, keeping their buffers.
7886 fn unwind_to(&mut self, depth: usize) {
7887 while self.frames.len() > depth {
7888 self.pop_frame();
7889 }
7890 }
7891 fn call_or_push(
7892 &mut self,
7893 callee: Value,
7894 this: Value,
7895 args: Vec<Value>,
7896 ) -> JsResult<Option<Value>> {
7897 if let Value::Object(function) = &callee
7898 && let Some((code, env)) = bytecode_of(function)
7899 {
7900 // Calling a generator function does not run anything: it captures the
7901 // arguments in a frame and hands back the generator object.
7902 if code.code.kind.is_generator() {
7903 return self.new_generator(callee, this, args).map(Some);
7904 }
7905 // An async function answers a promise and runs its body as a coroutine, so it
7906 // takes the same path as a plain call into it.
7907 if code.code.kind.is_async() {
7908 return self.new_async_function(callee, this, args).map(Some);
7909 }
7910 self.push_frame(code, env, this, args, callee)?;
7911 return Ok(None);
7912 }
7913 self.call_value(callee, this, args).map(Some)
7914 }
7915
7916 /// `new callee(args)`.
7917 ///
7918 /// A constructor differs from a plain call in three ways: it gets a fresh object
7919 /// as `this` whose prototype is the constructor's `prototype` property, its
7920 /// return value is *replaced* by that object unless it returns an object itself,
7921 /// and a native constructor is expected to initialise the object it is given
7922 /// rather than build one.
7923 pub fn construct(
7924 &mut self,
7925 callee: Value,
7926 new_target: Value,
7927 args: Vec<Value>,
7928 ) -> JsResult<Value> {
7929 // `new` on a bound function constructs its *target*, prepending the arguments
7930 // the bind fixed and ignoring the bound `this` — a bound function is a
7931 // constructor only when its target is one, and `new` always makes a fresh
7932 // object of the target's prototype rather than reusing the bound receiver.
7933 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
7934 // ran the body with `this === null` and threw on `this.x = a`.
7935 let mut callee = callee;
7936 let mut new_target = new_target;
7937 let mut args = args;
7938 loop {
7939 let Some(object) = callee.as_object().cloned() else {
7940 return Err(Signal::Throw(
7941 self.make_error("TypeError", "not a constructor"),
7942 ));
7943 };
7944 // A proxy of a function constructs through its `construct` trap, and the
7945 // trap's answer is the result directly — no fresh object is made here.
7946 if object.proxy_state().is_some() {
7947 return match self.proxy_construct(&object, args, &new_target)? {
7948 Some(result) => Ok(result),
7949 None => Err(Signal::Throw(
7950 self.make_error("TypeError", "proxy target is not a constructor"),
7951 )),
7952 };
7953 }
7954 // A generator function has no `[[Construct]]`, and the reference names it in
7955 // the message: `new (function* G(){})()` reports "G is not a constructor".
7956 if object.with(|data| match &data.kind {
7957 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
7958 code.code.kind.is_generator()
7959 }
7960 _ => false,
7961 }) {
7962 let name = object
7963 .own_property("name")
7964 .and_then(|property| property.value)
7965 .map(|value| value.to_js_string())
7966 .unwrap_or_default();
7967 return Err(Signal::Throw(
7968 self.make_error("TypeError", &format!("{name} is not a constructor")),
7969 ));
7970 }
7971 let bound = object.with(|data| match &data.kind {
7972 ObjectKind::Function(Callable::Bound {
7973 target,
7974 args: leading,
7975 ..
7976 }) => Some((target.clone(), leading.clone())),
7977 _ => None,
7978 });
7979 let Some((target, leading)) = bound else {
7980 // Not a bound function, so this object is the callee. §7.2.4
7981 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
7982 // refusals above cover only the built-ins the reference also refuses by
7983 // name. Everything else — a method, an arrow, an async function — has no
7984 // `[[Construct]]` either, and answering "yes" here made
7985 // `new (Array.prototype.map)` build an object instead of throwing.
7986 if !object.is_constructor() {
7987 let name = object
7988 .own_property("name")
7989 .and_then(|property| property.value)
7990 .map(|value| value.to_js_string())
7991 .unwrap_or_default();
7992 return Err(Signal::Throw(
7993 self.make_error("TypeError", &format!("{name} is not a constructor")),
7994 ));
7995 }
7996 break;
7997 };
7998 let mut all = leading;
7999 all.extend(args);
8000 args = all;
8001 // A bound function that is its own `new.target` stands in for its target:
8002 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
8003 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
8004 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
8005 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
8006 _ => false,
8007 };
8008 if same_wrapper {
8009 new_target = target.clone();
8010 }
8011 callee = target;
8012 }
8013 let Value::Object(function) = &callee else {
8014 unreachable!("the loop above only breaks on an object");
8015 };
8016 // The fresh object's prototype comes from `new.target`, not from the callee: a
8017 // derived constructor reaches here through `super()`, and the instance must be a
8018 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
8019 // an object inheriting `D.prototype` rather than `C.prototype`.
8020 let prototype_source = match new_target.as_object() {
8021 Some(target) => target.clone(),
8022 None => function.clone(),
8023 };
8024 // A native constructor builds its own instance, through `new_ctor_instance`, once it
8025 // has validated its arguments. Pre-building one here would read
8026 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
8027 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
8028 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
8029 let is_native = function.native_creates_own_instance();
8030 let this = if is_native {
8031 Value::Undefined
8032 } else {
8033 let prototype = self.get_property(&prototype_source, "prototype")?;
8034 let prototype = match prototype {
8035 Some(Value::Object(proto)) => Some(proto),
8036 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
8037 // object, the answer is the realm's *intrinsic* prototype for this
8038 // constructor, not `%Object.prototype%`.
8039 _ => {
8040 let fallback = self.get_property(function, "prototype")?;
8041 match fallback {
8042 Some(Value::Object(proto)) => Some(proto),
8043 _ => Some(self.realm.object_proto.clone()),
8044 }
8045 }
8046 };
8047 Value::Object(self.new_object(prototype))
8048 };
8049 // `new.target` inside the body is the constructor that was written, so a bound
8050 // function's target sees itself rather than the bound wrapper.
8051 //
8052 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
8053 // `?`, so assigning `None` after the call would be skipped and the failed
8054 // `new.target` would stay visible to every later native call. The symptom was a
8055 // native constructor refusing a plain call — `var s = Symbol(); new
8056 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
8057 // "FinalizationRegistry is not a constructor".
8058 let outer_new_target = self.pending_new_target.replace(new_target);
8059 let result = self.call_value(callee, this.clone(), args);
8060 self.pending_new_target = outer_new_target;
8061 let result = result?;
8062 // A constructor that returns an object overrides `this`; any other return
8063 // value (including `undefined`) is ignored.
8064 Ok(match result {
8065 Value::Object(_) => result,
8066 _ => this,
8067 })
8068 }
8069
8070 /// `new.target` for the call currently being made.
8071 ///
8072 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
8073 /// it as `this`), but a *host* constructor that builds its own instance is handed
8074 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
8075 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
8076 /// it here.
8077 ///
8078 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
8079 /// receives for a plain call.
8080 pub fn current_new_target(&self) -> Value {
8081 self.pending_new_target.clone().unwrap_or(Value::Undefined)
8082 }
8083
8084 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
8085 ///
8086 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
8087 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
8088 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
8089 let constructor = self.realm.errors.get("AggregateError").cloned();
8090 let Some(constructor) = constructor else {
8091 return self.make_error("AggregateError", message);
8092 };
8093 let list = self.new_array(errors);
8094 match self.construct(
8095 Value::Object(constructor.clone()),
8096 Value::Object(constructor),
8097 vec![Value::Object(list), self.string(message)],
8098 ) {
8099 Ok(value) => value,
8100 // A user could have replaced `AggregateError` with something that throws; the
8101 // engine still owes the caller a rejection, so it falls back rather than
8102 // turning `Promise.any`'s rejection into a throw.
8103 Err(_) => self.make_error("AggregateError", message),
8104 }
8105 }
8106
8107 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
8108 ///
8109 /// The error classes themselves arrive with the builtins milestone; what
8110 /// matters here is that the thrown value stringifies the way a script printing
8111 /// the caught value expects.
8112 ///
8113 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
8114 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
8115 /// rely on when they print a caught value.
8116 pub fn make_error(&self, name: &str, message: &str) -> Value {
8117 let proto = self
8118 .realm
8119 .errors
8120 .get(name)
8121 .map(|constructor| self.prototype_of(constructor))
8122 .unwrap_or_else(|| self.realm.error_proto.clone());
8123 let error = self.new_object(Some(proto));
8124 // `name` and `message` are own properties of the instance, which is what
8125 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
8126 // `Error`.
8127 error.define(
8128 "name",
8129 Property::with_attributes(self.string(name), true, false),
8130 );
8131 error.define(
8132 "message",
8133 Property::with_attributes(self.string(message), true, false),
8134 );
8135 // The internal class, which is what tells a printer this is an error rather than a
8136 // plain object with `name` and `message` properties. The constructor path sets it
8137 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
8138 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
8139 // literally `"Error"` in both places — the *name* is read from `name`, which is why
8140 // a `RangeError` still prints as `RangeError`.
8141 self.internal_set(&error, "_class", self.string("Error"));
8142 // The trace is captured where the error is *made*, which is where the reference
8143 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
8144 // way out, so a caught engine error already has its stack even if the handler
8145 // never rethrows it.
8146 self.add_stack(&error);
8147 Value::Object(error)
8148 }
8149
8150 /// Give an error object its `stack` property, from the current frame stack.
8151 ///
8152 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
8153 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
8154 /// `stack` a script set, is not rewritten.
8155 pub fn add_stack(&self, object: &Gc<JsObject>) {
8156 self.add_stack_skipping(object, 0);
8157 }
8158
8159 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
8160 ///
8161 /// An `Error` constructor passes 1: the reference builds those traces with
8162 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
8163 /// constructor itself, while a `RangeError` raised inside `toISOString` does
8164 /// report `at toISOString (native)`.
8165 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
8166 if object.has_own("stack") {
8167 return;
8168 }
8169 let trace = self.stack_trace_skipping(skip);
8170 let text = self.string(trace);
8171 object.define("stack", Property::with_attributes(text, true, false));
8172 }
8173
8174 /// The function object currently being called, if any.
8175 ///
8176 /// A native function is a bare `fn` pointer, so it cannot capture which class
8177 /// it belongs to; it reads that from the callee instead. This is also what a
8178 /// stack trace would use.
8179 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
8180 match &self.frames.last()?.callee {
8181 Value::Object(object) => Some(object.clone()),
8182 _ => None,
8183 }
8184 }
8185
8186 /// The `prototype` property of a constructor, falling back to
8187 /// `Object.prototype` for anything that is not shaped like one.
8188 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
8189 constructor
8190 .own_property("prototype")
8191 .and_then(|property| property.value)
8192 .and_then(|value| value.as_object().cloned())
8193 .unwrap_or_else(|| self.realm.object_proto.clone())
8194 }
8195
8196 /// Throw a `TypeError` carrying `message`.
8197 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
8198 Signal::Throw(self.make_error("TypeError", message.as_ref()))
8199 }
8200
8201 /// Throw a `RangeError` carrying `message`.
8202 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
8203 Signal::Throw(self.make_error("RangeError", message.as_ref()))
8204 }
8205
8206 /// The `ReferenceError` a read of an uninitialised binding raises.
8207 /// The name of the binding `slot` refers to, for an error message.
8208 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
8209 match kind {
8210 VarSlot::Loc => self
8211 .frame()
8212 .code
8213 .code
8214 .vars
8215 .get(slot)
8216 .map(|v| v.name.clone()),
8217 VarSlot::Closure => self
8218 .frame()
8219 .code
8220 .code
8221 .closure_vars
8222 .get(slot)
8223 .map(|c| c.name.clone()),
8224 }
8225 .unwrap_or_default()
8226 }
8227
8228 /// Whether `slot` names a `const` binding, which rejects every store after its
8229 /// initialiser.
8230 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
8231 match kind {
8232 VarSlot::Loc => self
8233 .frame()
8234 .code
8235 .code
8236 .vars
8237 .get(slot)
8238 .is_some_and(|v| v.is_const),
8239 VarSlot::Closure => self
8240 .frame()
8241 .code
8242 .code
8243 .closure_vars
8244 .get(slot)
8245 .is_some_and(|c| c.is_const),
8246 }
8247 }
8248
8249 /// The `TypeError` a store to a `const` binding raises.
8250 ///
8251 /// `const` is enforced here rather than at compile time because the binding can be
8252 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
8253 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
8254 /// both halves of what "checked store" means: the dead zone is over, and the
8255 /// binding is writable.
8256 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
8257 let name = self.binding_name(slot, kind);
8258 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
8259 }
8260
8261 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
8262 let name = match kind {
8263 VarSlot::Loc => self
8264 .frame()
8265 .code
8266 .code
8267 .vars
8268 .get(slot)
8269 .map(|v| v.name.clone()),
8270 VarSlot::Closure => self
8271 .frame()
8272 .code
8273 .code
8274 .closure_vars
8275 .get(slot)
8276 .map(|c| c.name.clone()),
8277 }
8278 .unwrap_or_default();
8279 Signal::Throw(self.make_error(
8280 "ReferenceError",
8281 &format!("cannot access '{name}' before initialization"),
8282 ))
8283 }
8284
8285 fn throw_reference(&self, name: &str) -> Signal {
8286 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
8287 }
8288
8289 // -- the instruction loop -----------------------------------------------
8290
8291 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
8292 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
8293 // measured at 16% of a tight arithmetic loop's total time.
8294 #[inline(always)]
8295 fn step(&mut self) -> JsResult<Step> {
8296 // The instruction is already decoded (see [`crate::insn`]), so this is an index
8297 // and a `Copy` read rather than a table lookup plus a width switch. Only the
8298 // borrow lives across the boundary; nothing is cloned.
8299 // **One** borrow of the frame: fetch the record, then advance in the same scope.
8300 // The obvious version borrowed it three times (`last` to read, `last_mut` to
8301 // write, and once more inside the handler), and each is a bounds check plus an
8302 // `Option` unwrap — on the one path every instruction takes.
8303 let Some((insn, next)) = ({
8304 let frame = self
8305 .frames
8306 .last_mut()
8307 .expect("step() is only called with a live frame");
8308 // Past the last instruction is a normal return: the compiler ends a function
8309 // with `return`, and a jump to the end of a block lands here.
8310 let insn = frame.insns().get(frame.pc).copied();
8311 match insn {
8312 None => None,
8313 Some(insn) => {
8314 // A fused record stands for the next few instructions, so the next
8315 // `pc` is its width ahead — the instructions it replaces are never
8316 // dispatched. `at` is the byte offset a stack trace reports; it stays
8317 // an offset because the line table is keyed by bytes.
8318 frame.at = insn.offset as usize;
8319 frame.pc += insn.width();
8320 Some((insn, frame.pc))
8321 }
8322 }
8323 }) else {
8324 return Ok(Step::Return(Value::Undefined));
8325 };
8326 self.check_memory()?;
8327 self.check_interrupt()?;
8328 if insn.fused == crate::insn::Fused::None {
8329 self.execute_instruction(insn.op, insn.a, insn.b, next)
8330 } else {
8331 self.execute_fused(insn)
8332 }
8333 }
8334
8335 /// Run a fused instruction: several bytecode instructions in one dispatch.
8336 ///
8337 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
8338 /// it cannot throw and cannot allocate — and anything else falls back to the real
8339 /// instructions, in their real order, so an exception leaves the operand stack
8340 /// exactly as it would have been.
8341 #[inline]
8342 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
8343 use crate::insn::Fused;
8344 let slot = insn.a as usize;
8345 match insn.fused {
8346 // `x = k`: `push k; put_loc x`.
8347 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
8348 // `x += k`: `get_loc x; push k; add; put_loc x`.
8349 Fused::AddImmLoc => {
8350 let delta = insn.b as i32;
8351 match self.get_loc(slot) {
8352 Value::Int(left) => {
8353 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
8354 // that built two `Value`s, called a function, and matched on them
8355 // again to reach this same `checked_add`. It is the innermost
8356 // operation of every accumulator in every program.
8357 let answer = match left.checked_add(delta) {
8358 Some(sum) => Value::Int(sum),
8359 None => Value::Float(left as f64 + delta as f64),
8360 };
8361 self.put_loc(slot, answer);
8362 }
8363 other => {
8364 self.push(other);
8365 self.push(Value::Int(delta));
8366 self.binary_add()?;
8367 let value = self.pop();
8368 self.put_loc(slot, value);
8369 }
8370 }
8371 }
8372 // `x += "literal"` and `x += y`: the two shapes that can append in place.
8373 Fused::AddAtomLoc => {
8374 let text = self.atom_wtf8(insn.b as usize);
8375 let right = self.string_wtf8(text);
8376 self.add_into_loc(slot, right)?;
8377 }
8378 Fused::AddLocLoc => {
8379 let source = (insn.a & 0xFFFF) as usize;
8380 let target = (insn.a >> 16) as usize;
8381 let right = self.get_loc(source);
8382 self.add_into_loc(target, right)?;
8383 }
8384 Fused::AddArgLoc => {
8385 let source = (insn.a & 0xFFFF) as usize;
8386 let target = (insn.a >> 16) as usize;
8387 let right = self.get_arg(source);
8388 self.add_into_loc(target, right)?;
8389 }
8390 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
8391 Fused::PostIncLoc => match self.get_loc(slot) {
8392 Value::Int(left) => {
8393 let answer = match left.checked_add(1) {
8394 Some(sum) => Value::Int(sum),
8395 None => Value::Float(left as f64 + 1.0),
8396 };
8397 self.put_loc(slot, answer);
8398 }
8399 other => {
8400 self.push(other);
8401 let raw = self.pop();
8402 let (old, updated) = self.advance_numeric(raw, true)?;
8403 self.push(old);
8404 self.push(updated);
8405 let value = self.pop();
8406 self.put_loc(slot, value);
8407 self.pop();
8408 }
8409 },
8410 // `if (!(x < arg)) goto target`: a loop header.
8411 //
8412 // The comparison is computed rather than replayed on the operand stack. That
8413 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
8414 // that throws: the effects happen in the same order, and a handler truncates
8415 // the stack down to its marker, so the intermediate values are unobservable.
8416 Fused::LtLocArgJump => {
8417 let loc = (insn.a >> 16) as usize;
8418 let arg = (insn.a & 0xFFFF) as usize;
8419 let left = self.get_loc(loc);
8420 let right = self.get_arg(arg);
8421 let taken = match (&left, &right) {
8422 (Value::Int(left), Value::Int(right)) => !(left < right),
8423 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8424 };
8425 if taken {
8426 self.frame_mut().pc = insn.b as usize;
8427 }
8428 }
8429 // `i < k` in a loop header, where `k` is an integer literal.
8430 Fused::LtLocImmJump => {
8431 let left = self.get_loc(insn.a as usize);
8432 let right = Value::Int(insn.imm as i32);
8433 let taken = match &left {
8434 Value::Int(left) => !(*left < insn.imm as i32),
8435 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
8436 };
8437 if taken {
8438 self.frame_mut().pc = insn.b as usize;
8439 }
8440 }
8441 Fused::None => unreachable!("only called for a fused record"),
8442 }
8443 Ok(Step::Continue)
8444 }
8445
8446 /// Run records that cannot call script, cannot throw and cannot change frames.
8447 ///
8448 /// Returns `Some(value)` when the function ran off the end of its instructions (a
8449 /// normal return), and `None` when it stopped in front of an instruction the slow path
8450 /// has to handle — `pc` is written back either way, so `step` resumes at the right
8451 /// place.
8452 ///
8453 /// **The invariant is the whole point.** Every arm here is restricted to work that
8454 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
8455 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
8456 /// that the memory limit has to see. An opcode whose operands turn out to need any of
8457 /// that **stops the loop** instead of trying, so the slow path gets the instruction
8458 /// untouched and with its operands still on the stack. That is why the fallback is a
8459 /// `break` and not a duplicated slow arm: a second implementation of the same
8460 /// semantics is how a wrong answer gets in with no test noticing.
8461 ///
8462 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
8463 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
8464 fn run_fast(&mut self) -> JsResult<Option<Value>> {
8465 use crate::insn::Fused;
8466 // The outer loop exists only so a `Call` can come back through here: once a
8467 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
8468 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
8469 // frame. Re-entering re-reads both from whichever frame is now on top. Every
8470 // other exit from the inner loop returns, so this costs one loop per call.
8471 'outer: loop {
8472 // One reference-count bump per *slow* instruction (a call, an allocation, a
8473 // property access), never one per instruction — that distinction is worth
8474 // two orders of magnitude and was measured as such.
8475 let (code, mut pc) = {
8476 let frame = self.frame();
8477 (frame.code.clone(), frame.pc)
8478 };
8479 let insns = &code.insns;
8480 loop {
8481 let Some(insn) = insns.get(pc).copied() else {
8482 self.frame_mut().pc = pc;
8483 return Ok(Some(Value::Undefined));
8484 };
8485 match insn.fused {
8486 // `x = k`
8487 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
8488 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
8489 // object — stops the loop so `binary_add` can decide.
8490 Fused::AddImmLoc => {
8491 let slot = insn.a as usize;
8492 let delta = insn.b as i32;
8493 let Value::Int(left) = self.get_loc(slot) else {
8494 return Ok(self.stop(pc));
8495 };
8496 let sum = match left.checked_add(delta) {
8497 Some(sum) => Value::Int(sum),
8498 None => Value::Float(left as f64 + delta as f64),
8499 };
8500 self.put_loc(slot, sum);
8501 }
8502 // `x += "literal"` / `x += y`: the operand is a string, so the append
8503 // either allocates one or grows one. Both are the slow path's business;
8504 // the fusion's job is only to make the *slot* the sole owner, which is what
8505 // `execute_fused` needs and what `get_loc` alone destroys.
8506 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
8507 return Ok(self.stop(pc));
8508 }
8509 // `x++` on an integer, old value dropped.
8510 Fused::PostIncLoc => {
8511 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
8512 // value is read in place and overwritten in place, so the reference
8513 // count it held is released by the same assignment that stores the
8514 // new one. `get_loc` plus `put_loc` did two borrows, two table
8515 // lookups and a clone, and this arm is the whole body of a counting
8516 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
8517 let slot = insn.a as usize;
8518 let frame = self.frames.last_mut().expect("a frame is live");
8519 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
8520 let target = if cell < 0 {
8521 frame.locals.get_mut(slot)
8522 } else {
8523 None
8524 };
8525 let Some(target) = target else {
8526 return Ok(self.stop(pc));
8527 };
8528 let Value::Int(left) = *target else {
8529 return Ok(self.stop(pc));
8530 };
8531 *target = match left.checked_add(1) {
8532 Some(sum) => Value::Int(sum),
8533 None => Value::Float(left as f64 + 1.0),
8534 };
8535 }
8536 // A loop header, `if (!(x < arg)) goto target`, with both sides already
8537 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
8538 // bound stayed small integers.
8539 Fused::LtLocArgJump => {
8540 let loc = (insn.a >> 16) as usize;
8541 let arg = (insn.a & 0xFFFF) as usize;
8542 // One borrow for both slots: this arm *is* the whole loop of a
8543 // `for (i = 0; i < n; i++)` with an argument bound, so a second
8544 // `frames.last()` here is paid on every iteration. Measured 7.5% on
8545 // `dispatch:empty-loop`.
8546 let (left, right) = {
8547 let frame = self.frame();
8548 (frame.read_loc(loc), frame.read_arg(arg))
8549 };
8550 // Heavily measured: the bound is very often a `Float` even when the
8551 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
8552 // `JSON.parse` or a division is one — so requiring both sides to be
8553 // `Int` sent every iteration of those loops down the slow path. The
8554 // comparison below is the same one `relational` makes for two numbers.
8555 if !is_number(&left) || !is_number(&right) {
8556 return Ok(self.stop(pc));
8557 }
8558 // `if_false` branches on the comparison being false, which is **not**
8559 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
8560 // `>=` is also false and would keep it running forever. Clippy wants the
8561 // negation folded; that would be a wrong answer.
8562 let ordered = left.to_number() < right.to_number();
8563 let take_branch = !ordered;
8564 if take_branch {
8565 pc = insn.b as usize;
8566 continue;
8567 }
8568 }
8569 // The same header with a literal bound: `if (!(x < k)) goto target`.
8570 // The bound is an immediate, so only the counter needs a type test.
8571 #[allow(clippy::neg_cmp_op_on_partial_ord)]
8572 Fused::LtLocImmJump => {
8573 let left = self.get_loc(insn.a as usize);
8574 if !is_number(&left) {
8575 return Ok(self.stop(pc));
8576 }
8577 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
8578 if take_branch {
8579 pc = insn.b as usize;
8580 continue;
8581 }
8582 }
8583 Fused::None => match insn.op {
8584 // -- branches ---------------------------------------------------
8585 // A jump is an assignment now, because the target is an instruction
8586 // index. No arithmetic, no resolution table.
8587 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
8588 let target = insn.a as usize;
8589 // A **back-edge** is a loop, and it is the only place an
8590 // instruction-level checkpoint can stop one: `for(;;){}` compiles
8591 // to a jump to itself and never leaves this loop, so the
8592 // per-instruction checks in `step` never run. That is exactly the
8593 // hole this arm closes — a host's `JS_SetInterruptHandler` did
8594 // nothing to a `for(;;){}` until it did, which is what
8595 // `tests/c/embed.c` is for.
8596 //
8597 // Polling here rather than on every instruction in this loop is
8598 // also the reference's choice (`OP_goto` calls
8599 // `js_poll_interrupts`), and it costs one compare per branch
8600 // instead of one decrement per instruction.
8601 if target <= pc {
8602 self.frame_mut().pc = target;
8603 self.check_memory()?;
8604 self.check_interrupt()?;
8605 }
8606 pc = target;
8607 continue;
8608 }
8609 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
8610 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
8611 let taken = self.pop().to_boolean();
8612 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
8613 if taken == want {
8614 pc = insn.a as usize;
8615 continue;
8616 }
8617 }
8618 // -- slot access -------------------------------------------------
8619 // A load's slot is already an operand (see `insn::implicit_operand`);
8620 // a captured one goes through its cell, which runs no script.
8621 Opcode::GetLoc
8622 | Opcode::GetLoc8
8623 | Opcode::GetLoc0
8624 | Opcode::GetLoc1
8625 | Opcode::GetLoc2
8626 | Opcode::GetLoc3 => {
8627 let value = self.get_loc(insn.a as usize);
8628 self.push(value);
8629 }
8630 Opcode::PutLoc
8631 | Opcode::PutLoc8
8632 | Opcode::PutLoc0
8633 | Opcode::PutLoc1
8634 | Opcode::PutLoc2
8635 | Opcode::PutLoc3 => {
8636 let value = self.pop();
8637 self.put_loc(insn.a as usize, value);
8638 }
8639 Opcode::GetArg
8640 | Opcode::GetArg0
8641 | Opcode::GetArg1
8642 | Opcode::GetArg2
8643 | Opcode::GetArg3 => {
8644 let value = self.get_arg(insn.a as usize);
8645 self.push(value);
8646 }
8647 Opcode::PutArg
8648 | Opcode::PutArg0
8649 | Opcode::PutArg1
8650 | Opcode::PutArg2
8651 | Opcode::PutArg3 => {
8652 let value = self.pop();
8653 self.put_arg(insn.a as usize, value);
8654 }
8655 // `a[i]` with an integer index on a dense array: see `fast_array_get`
8656 // for why a non-hole own element is exactly the slow path's answer.
8657 // The two operands are *peeked*, so a miss leaves the stack as the
8658 // slow path expects to find it.
8659 Opcode::GetArrayEl => {
8660 // One lookup, not two. The guard used `if …is_some()` and the arm
8661 // then called it again to get the value — two `peek`s, two
8662 // `array_get`s and two `Value` clones for one element.
8663 // `fast_array_get` was 13.1% of `array:indexed`, and the same
8664 // double call was the first version of the `get_field` fast path.
8665 let Some(value) = self.fast_array_get() else {
8666 return Ok(self.stop(pc));
8667 };
8668 // `a[i]` consumes both operands and leaves the element in their
8669 // place: one `truncate` and one write, no `pop`/`push` pair.
8670 let frame = self.frame_mut();
8671 frame.stack.truncate(frame.stack.len() - 2);
8672 frame.stack.push(value);
8673 }
8674 // `a[i] = v` on a dense array with an integer index: see
8675 // `fast_array_set` for why the whole store is one step.
8676 Opcode::PutArrayEl if self.fast_array_set() => {}
8677 // `o.x` resolved from the inline cache without leaving the loop.
8678 //
8679 // The cache is keyed by `(receiver identity, atom, site)` and a
8680 // monomorphic read re-validates the same chain every iteration, so
8681 // each one used to cost a `stop(pc)` — a write of `pc` into the
8682 // frame, a return out of this loop, a re-dispatch through `step` and
8683 // a re-entry. `property:monomorphic` spent 18% in
8684 // `read_field_cached` and 21% in `push`, both across that boundary.
8685 //
8686 // The site is `pc + width`, which is exactly the `next` the slow arm
8687 // passes — the two must agree or every fast lookup misses and
8688 // re-records the same entry forever.
8689 //
8690 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
8691 // slow arm finds the receiver where it expects it.
8692 // `name` resolved from the global-variable cache inside the loop.
8693 //
8694 // Same shape as `get_field` above and for the same reason: `get_var`
8695 // was not in the fast loop, so reading a global — which `fib` does
8696 // once per recursive call, for its own name — cost a `stop(pc)`, a
8697 // return out of the loop, a `step` re-dispatch and a re-entry, before
8698 // `get_global` even started its `scopes_are_plain` checks.
8699 //
8700 // Everything here is exactly `get_global`'s first branch: not lexical,
8701 // no `eval` scope, cache hit. Anything else leaves the stack untouched
8702 // and lets the slow arm decide.
8703 Opcode::GetVar => {
8704 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
8705 return Ok(self.stop(pc));
8706 };
8707 self.push(value);
8708 }
8709 Opcode::GetField | Opcode::GetField2 => {
8710 let Some(value) =
8711 self.fast_field_get(insn.a as usize, pc + insn.width())
8712 else {
8713 return Ok(self.stop(pc));
8714 };
8715 if insn.op == Opcode::GetField2 {
8716 // `get_field2` keeps the receiver for the `call_method` that
8717 // follows.
8718 self.push(value);
8719 } else {
8720 // `get_field` replaces the receiver, so this is one store over
8721 // the top slot rather than a `pop` and a `push`: the length
8722 // never changes, so neither `Vec` arm has a capacity check or a
8723 // drop to run beyond the one the overwrite itself does.
8724 let frame = self.frame_mut();
8725 match frame.stack.last_mut() {
8726 Some(slot) => *slot = value,
8727 None => return Ok(self.stop(pc)),
8728 }
8729 }
8730 }
8731 // -- constants ---------------------------------------------------
8732 Opcode::PushMinus1
8733 | Opcode::Push0
8734 | Opcode::Push1
8735 | Opcode::Push2
8736 | Opcode::Push3
8737 | Opcode::Push4
8738 | Opcode::Push5
8739 | Opcode::Push6
8740 | Opcode::Push7
8741 | Opcode::PushI8
8742 | Opcode::PushI16
8743 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
8744 // -- stack shuffling ---------------------------------------------
8745 Opcode::Drop => {
8746 self.pop();
8747 }
8748 // -- arithmetic on two integers ----------------------------------
8749 //
8750 // The operands are *looked at* before they are popped, so a non-integer
8751 // pair leaves the stack exactly as the slow path expects to find it.
8752 Opcode::Add if self.numeric_pair() => {
8753 let right = self.pop();
8754 let left = self.pop();
8755 // Exactly [`add_numbers`], which is what the slow arm reaches.
8756 let answer = match (&left, &right) {
8757 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
8758 Some(sum) => Value::Int(sum),
8759 None => Value::Float(*a as f64 + *b as f64),
8760 },
8761 _ => Value::Float(left.to_number() + right.to_number()),
8762 };
8763 self.push(answer);
8764 }
8765 Opcode::Sub
8766 | Opcode::And
8767 | Opcode::Or
8768 | Opcode::Xor
8769 | Opcode::Shl
8770 | Opcode::Sar
8771 | Opcode::Shr
8772 if self.numeric_pair() =>
8773 {
8774 let right = self.pop();
8775 let left = self.pop();
8776 let answer =
8777 arithmetic(insn.op, left, right).expect("numbers cannot throw");
8778 self.push(answer);
8779 }
8780 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
8781 if self.numeric_pair() =>
8782 {
8783 let right = self.pop();
8784 let left = self.pop();
8785 let answer = self
8786 .relational(insn.op, left, right)
8787 .expect("numbers cannot throw");
8788 self.push(answer);
8789 }
8790 // -- calls -------------------------------------------------------
8791 //
8792 // A plain call: `callee(arg0, …, argN) -> result`.
8793 //
8794 // This arm exists because of one measurement. `call:recursion` had
8795 // **20.4% of its profile in `execute_instruction`** — the *slow*
8796 // executor — and `fib`'s recursive call is the only thing in that
8797 // function which is not a fast arm. Every call therefore left this
8798 // loop via `stop()`, went through `step()`'s dispatch and
8799 // `execute_instruction`'s match over every opcode, and came back here
8800 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
8801 //
8802 // Two things make it safe to do here rather than only in the slow path:
8803 //
8804 // * the caller's `pc` is stored *before* the call, which is what
8805 // `step` does too — so when the callee returns, the caller resumes
8806 // after the call and not at it;
8807 // * `check_memory` runs, because `step` calls it once per instruction
8808 // and a call allocates a frame, its locals and its cells. Skipping
8809 // the checkpoint here would let a `--memory-limit` script overshoot
8810 // by one call per instruction.
8811 Opcode::Call
8812 | Opcode::Call0
8813 | Opcode::Call1
8814 | Opcode::Call2
8815 | Opcode::Call3 => {
8816 let argc = self.argc_operand(insn.op, insn.a);
8817 let next = pc + insn.width();
8818 {
8819 let frame = self
8820 .frames
8821 .last_mut()
8822 .expect("run_fast() is only called with a live frame");
8823 // `at` is what a stack trace reports for this frame, so a throw
8824 // inside the callee has to see the call site and not whatever
8825 // the last `stop()` left there.
8826 frame.at = insn.offset as usize;
8827 frame.pc = next;
8828 }
8829 self.check_memory()?;
8830 self.check_interrupt()?;
8831 let args = self.pop_n(argc);
8832 let callee = self.pop();
8833 // A plain call has no receiver; the callee decides what to do with
8834 // `undefined` (a sloppy function substitutes the global object).
8835 if let Some(result) =
8836 self.call_or_push(callee, Value::Undefined, args)?
8837 {
8838 // Native, host, generator, async, bound — no frame was pushed,
8839 // so this loop is still describing the right function. `pc`
8840 // is advanced by the loop tail like every other arm; only the
8841 // frame's copy had to be written here, and it already was.
8842 self.push(result);
8843 } else {
8844 // A bytecode callee: its frame is on top now, and `insns` and
8845 // `pc` both belong to the caller. Start over on the new frame.
8846 continue 'outer;
8847 }
8848 }
8849 // -- return ------------------------------------------------------
8850 Opcode::Return => {
8851 let value = self.pop();
8852 self.frame_mut().pc = pc + insn.width();
8853 return Ok(Some(value));
8854 }
8855 Opcode::ReturnUndef => {
8856 self.frame_mut().pc = pc + insn.width();
8857 return Ok(Some(Value::Undefined));
8858 }
8859 // Everything else needs the slow path.
8860 _ => return Ok(self.stop(pc)),
8861 },
8862 }
8863 pc += insn.width();
8864 }
8865 }
8866 }
8867
8868 /// Whether the top two operand-stack values are both numbers.
8869 ///
8870 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
8871 /// cannot run script, so the arm may not throw and may not change frames.
8872 fn numeric_pair(&self) -> bool {
8873 is_number(&self.peek(0)) && is_number(&self.peek(1))
8874 }
8875
8876 /// `a[i]` for a dense array and an integer index, without the string round trip.
8877 ///
8878 /// The slow path answers this by turning `i` into a string (`propkey` →
8879 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
8880 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
8881 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
8882 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
8883 /// without even the cheap `Int` formatting.
8884 ///
8885 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
8886 /// unambiguously the one the slow path would give:
8887 ///
8888 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
8889 /// `2^32-1` is the length, not an index),
8890 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
8891 /// typed array or an ordinary object, all of which have their own rules),
8892 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
8893 /// starts walking the prototype chain, and `a[i]` on a hole must find
8894 /// `Array.prototype[i]` if it exists rather than `undefined`.
8895 ///
8896 /// The last condition is the one that makes this safe rather than merely fast: an own
8897 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
8898 /// `get_var` answered from the global-variable cache, or `None`.
8899 ///
8900 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
8901 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
8902 /// records nothing — the slow arm is about to walk the chain and record it.
8903 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
8904 let frame = self.frame();
8905 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
8906 // "Lexical" is presence in the realm's table, not the closure var's flag: a
8907 // `GlobalRef` forwarded through a nested function has its flags cleared.
8908 if self.realm.globals.contains_key(name) {
8909 return None;
8910 }
8911 if !self.scopes_are_plain() {
8912 return None;
8913 }
8914 let object = &self.realm.global;
8915 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
8916 let cached = self.global_cache[site].as_ref()?;
8917 if !object.upgrades_to(&cached.object) {
8918 return None;
8919 }
8920 object.data_property_at(cached.index, name)
8921 }
8922
8923 /// `o.x` answered entirely from the inline cache, or `None`.
8924 ///
8925 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
8926 /// about to do exactly that and recording it twice would rebuild the chain for every
8927 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
8928 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
8929 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
8930 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
8931 // an object receiver is a reference-count bump that the answer never needs.
8932 let frame = self.frame();
8933 let object = frame.stack.last()?;
8934 let Value::Object(target) = object else {
8935 return None;
8936 };
8937 // A proxy traps the lookup, so no cache entry ever describes it.
8938 if target.proxy_state().is_some() {
8939 return None;
8940 }
8941 let key = frame.code.atom_keys.get(atom)?;
8942 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
8943 if cached.key != *key {
8944 return None;
8945 }
8946 Self::cached_hit(target, cached)
8947 }
8948
8949 fn fast_array_get(&self) -> Option<Value> {
8950 let Value::Int(index) = self.peek(0) else {
8951 return None;
8952 };
8953 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
8954 // set for an `i32`.
8955 if index < 0 {
8956 return None;
8957 }
8958 let Value::Object(object) = self.peek(1) else {
8959 return None;
8960 };
8961 match object.array_get(index as usize) {
8962 Some(value) if !matches!(value, Value::Hole) => Some(value),
8963 _ => None,
8964 }
8965 }
8966
8967 /// `a[i] = v` on a dense array with an integer index, as one store.
8968 ///
8969 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
8970 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
8971 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
8972 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
8973 /// reference at the time it was measured (14.7x).
8974 ///
8975 /// Every condition here is one the slow path would also have to satisfy before
8976 /// storing into the element vector:
8977 ///
8978 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
8979 /// accepts as an index;
8980 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
8981 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
8982 /// one inside a recorded descriptor, reports `false` and the caller stops.
8983 ///
8984 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
8985 /// writes the own element too once `array_set` says it did.
8986 fn fast_array_set(&mut self) -> bool {
8987 // Every test runs *before* anything is popped: a refusal has to leave the stack
8988 // exactly as the slow path expects to find it. Popping first and reporting the
8989 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
8990 // then ran the slow path with nothing to write.
8991 let Value::Int(index) = self.peek(1) else {
8992 return false;
8993 };
8994 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
8995 if index < 0 {
8996 return false;
8997 }
8998 // Only a real array: a typed array's elements live in its buffer, a string-like
8999 // object has no element vector, and `array_set` on either does nothing.
9000 let Value::Object(object) = self.peek(2) else {
9001 return false;
9002 };
9003 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
9004 return false;
9005 }
9006 // A non-extensible array reports `false` here, but the *slow* path has to decide
9007 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
9008 // that with the key and the stack still intact.
9009 if !object.is_extensible() {
9010 return false;
9011 }
9012 // Inside the logical length, so the store cannot change `length`. Combined with
9013 // extensibility above, the only growth left for `array_set` is filling a hole in
9014 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
9015 // shape this fast path exists for. A store past the length would grow the array,
9016 // and whether that is allowed is the slow path's question.
9017 if index as usize >= object.array_length().unwrap_or(0) {
9018 return false;
9019 }
9020 // The bound `array_set` refuses past. Checking it here keeps that arm from having
9021 // to report a failure after the operands are gone.
9022 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
9023 return false;
9024 }
9025 let value = self.pop();
9026 self.pop();
9027 self.pop();
9028 object.array_store(self.heap, index as usize, value)
9029 }
9030
9031 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
9032 fn stop(&mut self, pc: usize) -> Option<Value> {
9033 self.frame_mut().pc = pc;
9034 None
9035 }
9036
9037 fn push(&mut self, value: Value) {
9038 self.frame_mut().stack.push(value);
9039 }
9040
9041 fn pop(&mut self) -> Value {
9042 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
9043 }
9044
9045 fn pop_n(&mut self, count: usize) -> Vec<Value> {
9046 let frame = self.frame_mut();
9047 let start = frame.stack.len().saturating_sub(count);
9048 frame.stack.split_off(start)
9049 }
9050
9051 fn peek(&self, back: usize) -> Value {
9052 let frame = self.frame();
9053 frame
9054 .stack
9055 .get(frame.stack.len().wrapping_sub(1 + back))
9056 .cloned()
9057 .unwrap_or(Value::Undefined)
9058 }
9059
9060 #[allow(clippy::too_many_lines)]
9061 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
9062 use Opcode::*;
9063 match op {
9064 // -- constants and stack shuffling -----------------------------
9065 Nop => {}
9066 PushMinus1 => self.push(Value::Int(-1)),
9067 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
9068 let value = match op {
9069 Push0 => 0,
9070 Push1 => 1,
9071 Push2 => 2,
9072 Push3 => 3,
9073 Push4 => 4,
9074 Push5 => 5,
9075 Push6 => 6,
9076 _ => 7,
9077 };
9078 self.push(Value::Int(value));
9079 }
9080 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
9081 PushBigintI32 => {
9082 // The immediate form of a `BigInt` literal; the reference has the same
9083 // split between this and a constant-pool entry.
9084 let value = crate::bigint::BigInt::from_i64(a as i64);
9085 self.push(self.bigint(value));
9086 }
9087 PushTrue => self.push(Value::Bool(true)),
9088 PushFalse => self.push(Value::Bool(false)),
9089 PushEmptyString => self.push(self.string("")),
9090 Undefined => self.push(Value::Undefined),
9091 Null => self.push(Value::Null),
9092 Object => {
9093 let proto = self.realm.object_proto.clone();
9094 self.push(Value::Object(self.new_object(Some(proto))));
9095 }
9096 PushThis => {
9097 let this = self.frame().this.clone();
9098 self.push(this);
9099 }
9100 PushConst | PushConst8 => {
9101 let value = self.constant(a as usize)?;
9102 self.push(value);
9103 }
9104 PushAtomValue => {
9105 let text = self.atom_wtf8(a as usize);
9106 self.push(self.string_wtf8(text));
9107 }
9108 Dup => {
9109 let value = self.peek(0);
9110 self.push(value);
9111 }
9112 Dup2 => {
9113 // `a b -> a b a b`
9114 let b = self.peek(0);
9115 let a = self.peek(1);
9116 self.push(a);
9117 self.push(b);
9118 }
9119 Dup3 => {
9120 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
9121 // prototype and key while reading the current value through them.
9122 let c = self.peek(0);
9123 let b = self.peek(1);
9124 let a = self.peek(2);
9125 self.push(a);
9126 self.push(b);
9127 self.push(c);
9128 }
9129 Swap => {
9130 // `a b -> b a`
9131 let bottom = self.pop();
9132 let top = self.pop();
9133 self.push(bottom);
9134 self.push(top);
9135 }
9136 Perm3 => {
9137 // `a b c -> b a c`, the reference's reordering for a spread method
9138 // call: `obj func array` becomes the `func this array` that `apply`
9139 // takes.
9140 let c = self.pop();
9141 let b = self.pop();
9142 let a = self.pop();
9143 self.push(b);
9144 self.push(a);
9145 self.push(c);
9146 }
9147 Dup1 => {
9148 let value = self.peek(1);
9149 self.push(value);
9150 }
9151 Drop => {
9152 self.pop();
9153 }
9154 Nip => {
9155 // `a b -> b`
9156 let top = self.pop();
9157 self.pop();
9158 self.push(top);
9159 }
9160 Perm4 => {
9161 // `obj prop a b -> a obj prop b`, the reference's reordering for a
9162 // postfix update of a computed element: it puts the *old* value
9163 // underneath the receiver and key so `put_array_el` can consume them
9164 // and leave the old value as the expression's result.
9165 let d = self.pop();
9166 let c = self.pop();
9167 let b = self.pop();
9168 let a = self.pop();
9169 self.push(c);
9170 self.push(a);
9171 self.push(b);
9172 self.push(d);
9173 }
9174 Insert2 => {
9175 // `obj a -> a obj a`
9176 let value = self.pop();
9177 let object = self.pop();
9178 self.push(value.clone());
9179 self.push(object);
9180 self.push(value);
9181 }
9182 Insert3 => {
9183 // `obj prop a -> a obj prop a`
9184 let value = self.pop();
9185 let key = self.pop();
9186 let object = self.pop();
9187 self.push(value.clone());
9188 self.push(object);
9189 self.push(key);
9190 self.push(value);
9191 }
9192 Insert4 => {
9193 // `this obj prop a -> a this obj prop a`
9194 //
9195 // `put_super_value` consumes all four and yields nothing, so the copy
9196 // underneath is what leaves the assignment an expression value.
9197 let value = self.pop();
9198 let key = self.pop();
9199 let object = self.pop();
9200 let receiver = self.pop();
9201 self.push(value.clone());
9202 self.push(receiver);
9203 self.push(object);
9204 self.push(key);
9205 self.push(value);
9206 }
9207 Swap2 => {
9208 // `a b c d -> c d a b`
9209 let d = self.pop();
9210 let c = self.pop();
9211 let b = self.pop();
9212 let a = self.pop();
9213 self.push(c);
9214 self.push(d);
9215 self.push(a);
9216 self.push(b);
9217 }
9218 Rot3l => {
9219 // `x a b -> a b x`
9220 let b = self.pop();
9221 let a = self.pop();
9222 let x = self.pop();
9223 self.push(a);
9224 self.push(b);
9225 self.push(x);
9226 }
9227 Rot3r => {
9228 // `a b c -> c a b`
9229 let c = self.pop();
9230 let b = self.pop();
9231 let a_value = self.pop();
9232 self.push(c);
9233 self.push(a_value);
9234 self.push(b);
9235 }
9236
9237 Rest => {
9238 // `...rest` in a parameter list: the arguments from index `a` on, as a
9239 // real array. It takes nothing off the stack — the arguments are in the
9240 // frame, not on it.
9241 let frame = self.frame();
9242 let from = a as usize;
9243 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
9244 let array = self.new_array(collected);
9245 self.push(Value::Object(array));
9246 }
9247
9248 // -- slots ------------------------------------------------------
9249 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
9250 let slot = self.slot_operand(op, a);
9251 let value = self.get_loc(slot);
9252 self.push(value);
9253 }
9254 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
9255 let slot = self.slot_operand(op, a);
9256 let value = self.pop();
9257 self.put_loc(slot, value);
9258 }
9259 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
9260 let slot = self.slot_operand(op, a);
9261 let value = self.pop();
9262 self.put_loc(slot, value.clone());
9263 self.push(value);
9264 }
9265 // The `_check` forms are the temporal dead zone: they throw when the
9266 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
9267 // *reads*, so only the two writes may pop — mishandling that quietly
9268 // consumes the value the caller pushed just before.
9269 GetLocCheck => {
9270 let slot = self.slot_operand(op, a);
9271 let value = self.get_loc(slot);
9272 if matches!(value, Value::Uninitialized) {
9273 return Err(self.dead_zone(slot, VarSlot::Loc));
9274 }
9275 self.push(value);
9276 }
9277 PutLocCheck | SetLocCheck => {
9278 let slot = self.slot_operand(op, a);
9279 let value = self.pop();
9280 if matches!(value, Value::Uninitialized) {
9281 return Err(self.dead_zone(slot, VarSlot::Loc));
9282 }
9283 // The initialiser goes through `put_loc`, not this, so any store that
9284 // reaches here is a later assignment — which a `const` refuses.
9285 if self.is_read_only(slot, VarSlot::Loc) {
9286 return Err(self.read_only(slot, VarSlot::Loc));
9287 }
9288 if op == SetLocCheck {
9289 self.put_loc(slot, value.clone());
9290 self.push(value);
9291 } else {
9292 self.put_loc(slot, value);
9293 }
9294 }
9295 PutLocCheckInit => {
9296 // The one store that *initialises* a lexical slot: `this` in a derived
9297 // constructor, which only exists after `super()` has run. A second
9298 // initialisation is the error the reference reports as
9299 // "'this' can be initialized only once".
9300 let slot = self.slot_operand(op, a);
9301 let value = self.pop();
9302 if !matches!(self.get_loc(slot), Value::Uninitialized) {
9303 return Err(Signal::Throw(self.make_error(
9304 "ReferenceError",
9305 "'this' can be initialized only once",
9306 )));
9307 }
9308 self.put_loc(slot, value);
9309 }
9310 CheckCtor => {
9311 // A class constructor may only run under `new`, which is what makes
9312 // `class A {}; A()` a TypeError.
9313 if matches!(self.frame().new_target, Value::Undefined) {
9314 return Err(Signal::Throw(self.make_error(
9315 "TypeError",
9316 "class constructors must be invoked with 'new'",
9317 )));
9318 }
9319 }
9320 InitCtor => {
9321 // The body a derived class gets when it declares no constructor:
9322 // forward every argument to the parent constructor, keeping `new.target`.
9323 if matches!(self.frame().new_target, Value::Undefined) {
9324 return Err(Signal::Throw(self.make_error(
9325 "TypeError",
9326 "class constructors must be invoked with 'new'",
9327 )));
9328 }
9329 let Some(callee) = self.current_callee() else {
9330 return Err(Signal::Throw(
9331 self.make_error("TypeError", "no constructor to inherit from"),
9332 ));
9333 };
9334 let parent = callee.proto().map_or(Value::Null, Value::Object);
9335 let new_target = self.frame().new_target.clone();
9336 let args = self.frame().passed().to_vec();
9337 let result = self.construct(parent, new_target, args)?;
9338 self.push(result);
9339 }
9340 SetLocUninitialized => {
9341 let slot = self.slot_operand(op, a);
9342 self.put_loc(slot, Value::Uninitialized);
9343 }
9344 CloseLoc => {
9345 // "Close" a binding: give it a *fresh* cell holding the current
9346 // value. Closures created before this point keep the old cell and the
9347 // ones created after see the new one, which is what makes every
9348 // iteration of `for (let i ...)` capture its own `i`, and what freezes
9349 // a block-scoped binding when the block ends.
9350 //
9351 // Clearing the slot instead (which this used to do) broke both: a
9352 // closure over a captured block variable read `undefined`, and a loop
9353 // terminated after one iteration.
9354 let slot = self.slot_operand(op, a);
9355 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
9356 if index >= 0 {
9357 let current = self.frame().cells[index as usize].get();
9358 let fresh = self.new_cell(current);
9359 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
9360 *cell = fresh;
9361 }
9362 }
9363 }
9364 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
9365 let slot = self.slot_operand(op, a);
9366 let value = self.get_arg(slot);
9367 self.push(value);
9368 }
9369 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
9370 let slot = self.slot_operand(op, a);
9371 let value = self.pop();
9372 self.put_arg(slot, value);
9373 }
9374 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
9375 let slot = self.slot_operand(op, a);
9376 let value = self.pop();
9377 self.put_arg(slot, value.clone());
9378 self.push(value);
9379 }
9380
9381 // -- closure variables ------------------------------------------
9382 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
9383 let slot = self.slot_operand(op, a);
9384 // A name a direct `eval` created shadows the binding the compiler chose.
9385 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
9386 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
9387 // and only a runtime lookup can know that.
9388 if let Some(cell) = self.eval_created_local(slot) {
9389 self.push(cell.get());
9390 return self.step();
9391 }
9392 let value = self.cell_value(slot)?;
9393 self.push(value);
9394 }
9395 GetVarRefCheck => {
9396 let slot = self.slot_operand(op, a);
9397 let value = self.cell_value(slot)?;
9398 if matches!(value, Value::Uninitialized) {
9399 return Err(self.dead_zone(slot, VarSlot::Closure));
9400 }
9401 self.push(value);
9402 }
9403 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
9404 let slot = self.slot_operand(op, a);
9405 let value = self.pop();
9406 if let Some(cell) = self.eval_created_local(slot) {
9407 cell.set(value);
9408 return self.step();
9409 }
9410 // Same rule as `PutLocCheck`: a checked store to a captured binding
9411 // refuses a `const` once its initialiser has run.
9412 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
9413 return Err(self.read_only(slot, VarSlot::Closure));
9414 }
9415 self.set_cell(slot, value)?;
9416 }
9417 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
9418 let slot = self.slot_operand(op, a);
9419 let value = self.pop();
9420 if let Some(cell) = self.eval_created_local(slot) {
9421 cell.set(value.clone());
9422 self.push(value);
9423 return self.step();
9424 }
9425 self.set_cell(slot, value.clone())?;
9426 self.push(value);
9427 }
9428
9429 // -- globals ----------------------------------------------------
9430 GetVar => {
9431 let value = self.get_global(a as usize)?;
9432 self.push(value);
9433 }
9434 GetVarUndef => {
9435 let value = self
9436 .get_global(a as usize)
9437 .or_else(|_| Ok(Value::Undefined))?;
9438 self.push(value);
9439 }
9440 DeleteVar => {
9441 // `delete name` for a name that is not a declared binding. A lexical
9442 // global lives in the reference table and cannot be deleted; anything
9443 // reachable only as a property of the global object is *implicit* —
9444 // `x = 1` with no declaration — and goes away if it is configurable,
9445 // which is what `delete` on an implicit global answers.
9446 let name = self.atom_text(a as usize);
9447 let global = self.realm.global.clone();
9448 let deleted = if self.realm.globals.contains_key(&name) {
9449 false
9450 } else if global.own_property(&name).is_some() {
9451 self.delete_property(&global, &name)?
9452 } else {
9453 true
9454 };
9455 self.push(Value::Bool(deleted));
9456 }
9457 PutVar => {
9458 let value = self.pop();
9459 self.put_global(a as usize, value)?;
9460 }
9461 PutVarInit => {
9462 let slot = a as usize;
9463 let value = self.pop();
9464 self.init_global(slot, value)?;
9465 }
9466
9467 // -- arithmetic -------------------------------------------------
9468 Add => self.binary_add()?,
9469 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
9470 let raw_right = self.pop();
9471 let raw_left = self.pop();
9472 // BigInt arithmetic is a separate path, and not only for the type of the
9473 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
9474 // rather than a silent conversion.
9475 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
9476 let left = self.primitive_of(raw_left)?;
9477 let right = self.primitive_of(raw_right)?;
9478 let value = self.bigint_arithmetic(op, left, right)?;
9479 self.push(value);
9480 } else {
9481 let right = self.numeric(raw_right)?;
9482 let left = self.numeric(raw_left)?;
9483 self.push(arithmetic(op, left, right)?);
9484 }
9485 }
9486 Neg => {
9487 let raw = self.pop();
9488 match raw {
9489 // A bigint negates exactly, however wide it is.
9490 Value::BigInt(big) => {
9491 let negated = big.negate();
9492 self.push(self.bigint(negated));
9493 }
9494 other => {
9495 let value = self.numeric(other)?;
9496 self.push(negate(value));
9497 }
9498 }
9499 }
9500 Plus => {
9501 let value = self.pop();
9502 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
9503 // unary plus is defined to produce a *number*, which a bigint cannot
9504 // become without loss. It used to fall through to `NaN`.
9505 if matches!(value, Value::BigInt(_)) {
9506 return Err(self.type_error("cannot convert bigint to number"));
9507 }
9508 let numeric = self.numeric_of(value)?;
9509 self.push(numeric);
9510 }
9511 Inc => {
9512 let raw = self.pop();
9513 let (_, updated) = self.advance_numeric(raw, true)?;
9514 self.push(updated);
9515 }
9516 Dec => {
9517 let raw = self.pop();
9518 let (_, updated) = self.advance_numeric(raw, false)?;
9519 self.push(updated);
9520 }
9521 PostInc | PostDec => {
9522 // `x -> x x+1`: the *new* value ends up on top, so the store the
9523 // compiler emits right after (`put_var`) writes the incremented
9524 // one, while the old value stays underneath for the expression's
9525 // own result. Getting this backwards makes `i++` a no-op, which
9526 // turns `while (i < 3)` into an infinite loop.
9527 let raw = self.pop();
9528 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
9529 self.push(old);
9530 self.push(updated);
9531 }
9532 Not => {
9533 let raw = self.pop();
9534 match raw {
9535 // `~x` on a bigint is `-x - 1`, exact at any width.
9536 Value::BigInt(big) => {
9537 let inverted = big.bitnot();
9538 self.push(self.bigint(inverted));
9539 }
9540 other => {
9541 let value = self.numeric(other)?;
9542 self.push(Value::Int(!value.to_int32()));
9543 }
9544 }
9545 }
9546 Lnot => {
9547 let value = self.pop();
9548 self.push(Value::Bool(!value.to_boolean()));
9549 }
9550
9551 // -- comparison -------------------------------------------------
9552 Lt | Lte | Gt | Gte => {
9553 let right = self.pop();
9554 let left = self.pop();
9555 let answer = self.relational(op, left, right)?;
9556 self.push(answer);
9557 }
9558 Eq | Neq => {
9559 let right = self.pop();
9560 let left = self.pop();
9561 let equal = self.abstract_equals(left, right)?;
9562 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
9563 }
9564 StrictEq => {
9565 let right = self.pop();
9566 let left = self.pop();
9567 self.push(Value::Bool(left.strict_equals(&right)));
9568 }
9569 StrictNeq => {
9570 let right = self.pop();
9571 let left = self.pop();
9572 self.push(Value::Bool(!left.strict_equals(&right)));
9573 }
9574 IsUndefined => {
9575 // `=== undefined`, which is what a destructuring default tests. It is
9576 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
9577 let value = self.pop();
9578 self.push(Value::Bool(matches!(value, Value::Undefined)));
9579 }
9580 IsUndefinedOrNull => {
9581 let value = self.pop();
9582 self.push(Value::Bool(value.is_nullish()));
9583 }
9584 Typeof => {
9585 let value = self.pop();
9586 self.push(self.string(value.type_of()));
9587 }
9588 ToObject => {
9589 // A destructuring *object* pattern starts here, which is why
9590 // `var {} = null` throws. Only `undefined` and `null` are refused; a
9591 // primitive is boxed.
9592 let value = self.pop();
9593 let object = self.object_from(&value)?;
9594 self.push(Value::Object(object));
9595 }
9596 Instanceof => {
9597 let constructor = self.pop();
9598 let object = self.pop();
9599 let answer = self.instance_of(&object, &constructor)?;
9600 self.push(Value::Bool(answer));
9601 }
9602 In => {
9603 let object = self.pop();
9604 let key = self.pop();
9605 let answer = self.has_property(&key, &object)?;
9606 self.push(Value::Bool(answer));
9607 }
9608
9609 // -- control flow -----------------------------------------------
9610 Goto | Goto8 | Goto16 => {
9611 self.frame_mut().pc = a as usize;
9612 }
9613 IfTrue | IfTrue8 => {
9614 let value = self.pop();
9615 if value.to_boolean() {
9616 self.frame_mut().pc = a as usize;
9617 }
9618 }
9619 IfFalse | IfFalse8 => {
9620 let value = self.pop();
9621 if !value.to_boolean() {
9622 self.frame_mut().pc = a as usize;
9623 }
9624 }
9625 Catch => {
9626 // Pushes the handler target onto the value stack; `unwind` finds it.
9627 self.push(Value::CatchOffset(a));
9628 }
9629 Gosub => {
9630 self.push(Value::ReturnAddress(next as u32));
9631 self.frame_mut().pc = a as usize;
9632 }
9633 Ret => {
9634 let value = self.pop();
9635 match value {
9636 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
9637 _ => {
9638 return Err(Signal::Throw(
9639 self.make_error("InternalError", "invalid return address"),
9640 ));
9641 }
9642 }
9643 }
9644 NipCatch => {
9645 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
9646 // including the marker, keeping the top value.
9647 let top = self.pop();
9648 loop {
9649 match self.pop() {
9650 Value::CatchOffset(_) | Value::Undefined => break,
9651 _ => {}
9652 }
9653 if self.frame().stack.is_empty() {
9654 break;
9655 }
9656 }
9657 self.push(top);
9658 }
9659 Throw => {
9660 let value = self.pop();
9661 return Err(Signal::Throw(value));
9662 }
9663 ThrowError => {
9664 let name = self.atom_text(a as usize);
9665 let (class, message) = match b {
9666 0 => ("TypeError", format!("'{name}' is read-only")),
9667 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
9668 2 => ("ReferenceError", format!("'{name}' is not initialized")),
9669 // `delete super.x` is a syntax-level mistake the reference reports
9670 // with this wording, not a property-access failure.
9671 3 => (
9672 "ReferenceError",
9673 "unsupported reference to 'super'".to_string(),
9674 ),
9675 4 => (
9676 "TypeError",
9677 "iterator does not have a throw method".to_string(),
9678 ),
9679 5 => (
9680 "ReferenceError",
9681 "invalid assignment left-hand side".to_string(),
9682 ),
9683 _ => ("TypeError", format!("invalid operation on '{name}'")),
9684 };
9685 return Err(Signal::Throw(self.make_error(class, &message)));
9686 }
9687 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
9688 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
9689 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
9690 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
9691 Await => return Ok(Step::Suspend(SuspendKind::Await)),
9692 ReturnAsync => {
9693 // The reference's `return_async` returns `undefined` and lets the resume
9694 // machinery pick the real value off `sp[-1]`, which is how it tells a
9695 // completion from a suspension. Carrying the value explicitly says the
9696 // same thing without the implicit stack slot.
9697 let value = self.pop();
9698 return Ok(Step::Return(value));
9699 }
9700 Return => {
9701 let value = self.pop();
9702 return Ok(Step::Return(value));
9703 }
9704 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
9705
9706 // -- calls ------------------------------------------------------
9707 Call | Call0 | Call1 | Call2 | Call3 => {
9708 let argc = self.argc_operand(op, a);
9709 let args = self.pop_n(argc);
9710 let callee = self.pop();
9711 // A plain call has no receiver; the callee decides what to do with
9712 // `undefined` (a sloppy function substitutes the global object).
9713 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
9714 self.push(result);
9715 }
9716 }
9717 CallConstructor => {
9718 // `constructor this_obj args… -> object`. The duplicated
9719 // constructor is `new.target`; this milestone does not expose it,
9720 // so the extra copy is simply consumed here.
9721 let argc = a as usize;
9722 let args = self.pop_n(argc);
9723 let new_target = self.pop();
9724 let callee = self.pop();
9725 let result = self.construct(callee, new_target, args)?;
9726 self.push(result);
9727 }
9728 CallMethod => {
9729 let argc = a as usize;
9730 let args = self.pop_n(argc);
9731 let callee = self.pop();
9732 let this = self.pop();
9733 if let Some(result) = self.call_or_push(callee, this, args)? {
9734 self.push(result);
9735 }
9736 }
9737 Apply => {
9738 // `func this array -> result`, the spread-call form: the compiler
9739 // builds one array of arguments, and all that is left here is to
9740 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
9741 let array = self.pop();
9742 let this = self.pop();
9743 let callee = self.pop();
9744 let args = self.array_like_to_args(&array)?;
9745 if a & 1 != 0 {
9746 let result = self.construct(callee, this, args)?;
9747 self.push(result);
9748 } else if let Some(result) = self.call_or_push(callee, this, args)? {
9749 self.push(result);
9750 }
9751 }
9752 TailCall | TailCallMethod => {
9753 // `tail_call` is `call` whose result is returned immediately — the
9754 // reference jumps straight to `done` instead of storing the value and
9755 // running on. The callee still gets its own frame, so deep tail
9756 // recursion hits the stack limit exactly like plain recursion does;
9757 // marking this frame lets the return path unwind without needing
9758 // instructions after the call.
9759 let argc = if op == TailCallMethod {
9760 a as usize
9761 } else {
9762 self.argc_operand(op, a)
9763 };
9764 let args = self.pop_n(argc);
9765 let callee = self.pop();
9766 let this = if op == TailCallMethod {
9767 self.pop()
9768 } else {
9769 Value::Undefined
9770 };
9771 if let Value::Object(function) = &callee
9772 && let Some((code, env)) = bytecode_of(function)
9773 {
9774 // A generator or async body is not run here at all: calling it only
9775 // *creates* the generator/coroutine, so it must not inherit this
9776 // frame. Doing so made `function f(){ return g() }` push `g`'s body
9777 // onto `f`'s frame, and the first `yield`/`await` then reported
9778 // "a generator body ran as an ordinary call".
9779 if code.code.kind.is_generator() || code.code.kind.is_async() {
9780 let value = self.call_value(callee, this, args)?;
9781 return Ok(Step::Return(value));
9782 }
9783 self.frame_mut().tail = true;
9784 self.push_frame(code, env, this, args, callee)?;
9785 return Ok(Step::Continue);
9786 }
9787 // A native callee has no frame to reuse, so its value is simply
9788 // returned.
9789 let value = self.call_value(callee, this, args)?;
9790 return Ok(Step::Return(value));
9791 }
9792
9793 // -- objects ----------------------------------------------------
9794 SpecialObject => {
9795 let value = self.special_object(a)?;
9796 self.push(value);
9797 }
9798 PrivateSymbol => {
9799 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
9800 // symbol each time it is evaluated, which is why the compiler evaluates it
9801 // once (at class definition) and stores it in a class-scope binding.
9802 let name = self.atom_text(a as usize);
9803 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
9804 self.push(Value::Symbol(symbol));
9805 }
9806 GetPrivateField => {
9807 // `obj symbol -> value`. A missing private field is a TypeError, which is what
9808 // makes `#x` inaccessible on any object not built by this class.
9809 let symbol = self.pop();
9810 let object = self.pop();
9811 let value = self.read_private_field(&object, &symbol)?;
9812 self.push(value);
9813 }
9814 PutPrivateField => {
9815 // `obj value symbol ->`, and the store is a plain assignment to a property the
9816 // class already created, so there is no setter to consult.
9817 let symbol = self.pop();
9818 let value = self.pop();
9819 let object = self.pop();
9820 self.write_private_field(&object, &symbol, value)?;
9821 }
9822 DefinePrivateField => {
9823 // `obj symbol value -> obj`: a field initialiser creates the property, and
9824 // redefining one is a TypeError ("already exists").
9825 let value = self.pop();
9826 let symbol = self.pop();
9827 let object = self.pop();
9828 self.define_private_field(&object, &symbol, value)?;
9829 self.push(object);
9830 }
9831 PrivateIn => {
9832 // `obj key -> bool`: `#x in o`. The second operand decides which question is
9833 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
9834 // is a field, so this is an own-property test; a *function* is a method or
9835 // accessor, so this is a brand check.
9836 let key = self.pop();
9837 let object = self.pop();
9838 let Some(target) = object.as_object() else {
9839 return Err(Signal::Throw(
9840 self.make_error("TypeError", "invalid 'in' operand"),
9841 ));
9842 };
9843 let present = match &key {
9844 Value::Object(_) => self.check_brand(target, &key)?,
9845 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
9846 };
9847 self.push(Value::Bool(present));
9848 }
9849 AddBrand => {
9850 // `obj home ->`: create the class brand on `home` if it has none, then give
9851 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
9852 // class definition: only the prototype's copy of the symbol is wanted.
9853 let home = self.pop();
9854 let object = self.pop();
9855 self.add_brand(&object, &home)?;
9856 }
9857 CheckBrand => {
9858 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
9859 // Both stay, because the caller needs them — `nip` halves a read into its
9860 // value and `call_method` uses the pair as receiver and callee.
9861 let function = self.peek(0);
9862 let object = self.peek(1);
9863 let Some(target) = object.as_object() else {
9864 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
9865 };
9866 if !self.check_brand(target, &function)? {
9867 return Err(Signal::Throw(
9868 self.make_error("TypeError", "invalid brand on object"),
9869 ));
9870 }
9871 }
9872 GetLength => {
9873 // `get_length` is the `.length` read; an array and a string answer
9874 // from their own length, anything else from the property.
9875 let target = self.pop();
9876 let value = match &target {
9877 Value::Object(object) => match object.array_length() {
9878 Some(length) => crate::object::length_value(length),
9879 None => self.read_field(&target, "length")?,
9880 },
9881 Value::String(text) => Value::Int(text.utf16_len() as i32),
9882 _ => self.read_field(&target, "length")?,
9883 };
9884 self.push(value);
9885 }
9886 GetField | GetField2 => {
9887 let object = self.pop();
9888 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
9889 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
9890 // just below is what lets the borrow outlive the `&mut self` the lookup
9891 // needs — one refcount bump instead of a key clone plus its drop, on the
9892 // hottest property path there is: every `o.x` and every `o.m()` receiver.
9893 let code = self.frame().code.clone();
9894 let key = &code.atom_keys[a as usize];
9895 let value = self.read_field_cached(&object, key, next)?;
9896 if op == GetField2 {
9897 self.push(object);
9898 }
9899 self.push(value);
9900 }
9901 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
9902 let key = self.pop();
9903 let object = self.pop();
9904 let key = self.propkey(&key)?;
9905 let value = self.read_field_key(&object, &key)?;
9906 if matches!(op, GetArrayEl2 | GetArrayEl3) {
9907 self.push(object);
9908 }
9909 if op == GetArrayEl3 {
9910 // The key goes back in its *value* form, which the compiler stores
9911 // into the target of a destructuring assignment.
9912 self.push(match &key {
9913 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
9914 PropertyKey::String(text) => self.string_wtf8(text.clone()),
9915 });
9916 }
9917 self.push(value);
9918 }
9919 PutField => {
9920 let value = self.pop();
9921 let object = self.pop();
9922 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
9923 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
9924 // only reads. `this.value = …` is the write half of the hottest loop in
9925 // `property:method-call`, and `own_property_key` was 4.8% of the case.
9926 let code = self.frame().code.clone();
9927 let key = &code.atom_keys[a as usize];
9928 self.write_field_key(&object, key, value)?;
9929 }
9930 PutArrayEl => {
9931 let value = self.pop();
9932 let key = self.pop();
9933 let object = self.pop();
9934 let key = self.propkey(&key)?;
9935 self.write_field_key(&object, &key, value)?;
9936 }
9937 DefineField => {
9938 let value = self.pop();
9939 let object = self.pop();
9940 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
9941 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
9942 // three U+FFFD — a property under a different name from the one
9943 // `o["\uD800"]` reads.
9944 let code = self.frame().code.clone();
9945 let key = code.atom_keys[a as usize].clone();
9946 // No naming here. `{m: function(){}}` is named by the *compiler*, which
9947 // emits `set_name` — and only where `NamedEvaluation` applies, so
9948 // `{m: (0, function(){})}` stays anonymous. Naming every function that
9949 // reaches a property definition got that case wrong, and the compiler is
9950 // the only place that can tell the two apart.
9951 if let Some(target) = object.as_object() {
9952 // Only an *array* stores into the element vector. A numeric key
9953 // on an ordinary object is an ordinary property, which is what
9954 // makes `{1: 'a'}` iterate as a key rather than disappear.
9955 let stored = target.is_array()
9956 && key.as_str().and_then(array_index).is_some_and(|index| {
9957 target.array_set(self.heap, index as usize, value.clone())
9958 });
9959 if !stored {
9960 target.define_data_key(&key, value);
9961 }
9962 }
9963 self.push(object);
9964 }
9965 DefineArrayEl => {
9966 // `obj key value -> obj key`. The *value* form of the key is what goes
9967 // back on the stack — the compiler stores it into the pattern's binding —
9968 // so the symbol is not stringified on the way through.
9969 let value = self.pop();
9970 let key_value = self.pop();
9971 let object = self.peek(0);
9972 let key = self.propkey(&key_value)?;
9973 self.write_field_key(&object, &key, value)?;
9974 self.push(key_value);
9975 }
9976 SetHomeObject => {
9977 // `obj func -> obj func`: records the object a method was defined on so
9978 // `super` inside it resolves against that object's prototype.
9979 let function = self.peek(0);
9980 let home = self.peek(1);
9981 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
9982 function.set_home_object(Some(home.clone()));
9983 }
9984 }
9985 Regexp => {
9986 // `pattern flags -> regexp`. A literal compiles here rather than through the
9987 // constructor, which is both what the reference's dedicated opcode is for
9988 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
9989 let flags = self.pop();
9990 let pattern = self.pop();
9991 let pattern = self.to_js_string(&pattern)?;
9992 let flags = self.to_js_string(&flags)?;
9993 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
9994 self.push(Value::Object(object));
9995 }
9996 UsingDisposeInit => {
9997 // The error state a disposal accumulates into. Uninitialised means "no
9998 // failure yet"; anything else is the exception being propagated.
9999 self.push(Value::Uninitialized);
10000 }
10001 UsingCheck => {
10002 // `value -> value, method`: validate and snapshot the disposer now, so a
10003 // later change to `Symbol.dispose` cannot change what gets called, and so a
10004 // value that is not disposable fails before the body runs.
10005 let value = self.pop();
10006 let method = self.using_method_for(&value, a as u8 == 1)?;
10007 self.push(value);
10008 self.push(method);
10009 }
10010 UsingDispose => {
10011 // `error_state -> error_state'`: dispose the variable at `slot` — its value
10012 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
10013 // the pending error.
10014 let slot = self.slot_operand(op, a);
10015 let error_state = self.pop();
10016 let merged = self.using_dispose_once(slot, error_state)?;
10017 self.push(merged);
10018 }
10019 UsingDisposeMerge => {
10020 let new_error = self.pop();
10021 let error_state = self.pop();
10022 let merged = self.merge_dispose_error(new_error, error_state);
10023 self.push(merged);
10024 }
10025 UsingDisposeEnd => {
10026 // A disposal that failed replaces the block's normal completion, so the
10027 // error state becomes a real throw here rather than at the call site.
10028 let error_state = self.pop();
10029 if !matches!(error_state, Value::Uninitialized) {
10030 return Err(Signal::Throw(error_state));
10031 }
10032 }
10033 UsingDisposeAsync => {
10034 // `await using` needs a promise to await and this runtime has no
10035 // `Promise` builtin, so the disposer is called synchronously and its result
10036 // discarded. That is correct for a disposer that returns nothing and is
10037 // reported as a gap rather than silently skipped.
10038 let slot = self.slot_operand(op, a);
10039 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
10040 self.push(error_state);
10041 }
10042 GetSuper => {
10043 // `obj -> obj's prototype`: the starting point of a `super` lookup.
10044 let object = self.pop();
10045 let proto = match &object {
10046 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
10047 _ => Value::Null,
10048 };
10049 self.push(proto);
10050 }
10051 GetSuperValue => {
10052 // `receiver proto key -> value`, searching from `proto` but reporting to
10053 // `receiver`, which is what `super.g` must do for a getter to see `this`.
10054 //
10055 // Three values in, one out: the receiver is *consumed*, not left under the
10056 // result. Leaving it there was invisible for `super.x` in `return` or
10057 // statement position (the result is what gets popped) and corrupted the
10058 // frame everywhere else — `print(super.x)` left the class where the call
10059 // opcode looks for the receiver and called the class itself.
10060 let key = self.pop();
10061 let proto = self.pop();
10062 let receiver = self.pop();
10063 let value = self.super_read(&receiver, &proto, &key)?;
10064 self.push(value);
10065 }
10066 PutSuperValue => {
10067 // `receiver proto key value ->`: a store that starts at `proto` but
10068 // assigns to `receiver`.
10069 let value = self.pop();
10070 let key = self.pop();
10071 let proto = self.pop();
10072 let receiver = self.pop();
10073 self.super_write(&receiver, &proto, &key, value)?;
10074 }
10075 DefineClass => {
10076 // `parent ctor -> ctor proto`: the constructor becomes the class and a
10077 // fresh prototype object lands on top for the methods to go on.
10078 let name = self.atom_text(a as usize);
10079 let (ctor, proto) = self.define_class(&name, b)?;
10080 self.push(ctor);
10081 self.push(Value::Object(proto));
10082 }
10083 DefineClassComputed => {
10084 // `parent ctor key -> ctor proto key`: the computed name stays put so
10085 // `define_field`-style consumers can still read it.
10086 let key = self.pop();
10087 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
10088 let (ctor, proto) = self.define_class(&name, b)?;
10089 self.push(ctor);
10090 self.push(Value::Object(proto));
10091 self.push(key);
10092 }
10093 DefineMethod => {
10094 let function = self.pop();
10095 let object = self.pop();
10096 // The exact key, like `define_field`: a quoted method key may hold an
10097 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
10098 // that `o["\uD800"]` finds.
10099 let code = self.frame().code.clone();
10100 let key = code.atom_keys[a as usize].clone();
10101 // A method's `[[HomeObject]]` is the object it was defined on, which is
10102 // what `super` inside it resolves against.
10103 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
10104 function.set_home_object(Some(object.clone()));
10105 }
10106 if let Some(text) = key.as_wtf8() {
10107 self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
10108 } else {
10109 self.set_function_name(
10110 &function,
10111 &key_with_accessor_prefix(&key.to_string(), b),
10112 );
10113 }
10114 if let Some(array) = object.as_object() {
10115 define_function_property(array, &key, function, b);
10116 }
10117 self.push(object);
10118 }
10119 DefineMethodComputed => {
10120 let function = self.pop();
10121 let key = self.pop();
10122 let object = self.pop();
10123 let key = self.propkey(&key)?;
10124 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
10125 // the name: `super` inside a computed method resolves through it. Without
10126 // this, `class B extends A { [k]() { return super.m() } }` read the
10127 // home object as null and threw.
10128 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
10129 function.set_home_object(Some(object.clone()));
10130 }
10131 match key.as_wtf8() {
10132 Some(text) => {
10133 let name = accessor_prefixed(text, a);
10134 self.set_function_name_wtf8(&function, &name);
10135 }
10136 None => self.set_function_name(
10137 &function,
10138 &key_with_accessor_prefix(&key.to_string(), a),
10139 ),
10140 }
10141 if let Some(array) = object.as_object() {
10142 define_function_property(array, &key, function, a);
10143 }
10144 self.push(object);
10145 }
10146 SetProto => {
10147 let proto = self.pop();
10148 let object = self.pop();
10149 if let Some(target) = object.as_object() {
10150 target.set_proto(proto.as_object().cloned());
10151 }
10152 self.push(object);
10153 }
10154 CopyDataProperties => {
10155 let exclusion = self.pop();
10156 let source = self.pop();
10157 let target = self.peek(0);
10158 self.copy_properties(&target, &source, &exclusion)?;
10159 self.push(source);
10160 self.push(exclusion);
10161 }
10162 ToPropkey => {
10163 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
10164 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
10165 // ordinary `"Symbol(b)"` property.
10166 let value = self.pop();
10167 let key = match self.propkey(&value)? {
10168 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
10169 PropertyKey::String(text) => self.string_wtf8(text),
10170 };
10171 self.push(key);
10172 }
10173 SetName => {
10174 let function = self.peek(0);
10175 let name = self.atom_wtf8(a as usize);
10176 self.set_function_name_wtf8(&function, &name);
10177 }
10178 SetNameComputed => {
10179 let key = self.peek(1);
10180 let function = self.peek(0);
10181 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
10182 self.set_function_name(&function, &name);
10183 }
10184
10185 // -- arrays -----------------------------------------------------
10186 ArrayFrom => {
10187 let count = a as usize;
10188 let elements = self.pop_n(count);
10189 let array = self.new_array(elements);
10190 self.push(Value::Object(array));
10191 }
10192 Append => {
10193 // `array index iterable -> array new_index`
10194 let iterable = self.pop();
10195 self.pop();
10196 let array = self.peek(0);
10197 let added = self.append_enumerate(&array, &iterable)?;
10198 self.push(Value::Int(added));
10199 }
10200
10201 // -- iteration --------------------------------------------------
10202 ForInStart => {
10203 let value = self.pop();
10204 let record = self.for_in_record(&value)?;
10205 self.push(Value::Object(record));
10206 }
10207 ForInNext => {
10208 // `record -> record key done`. The flag is *done*, not "found":
10209 // the compiler tests it with `if_false` to jump back into the body,
10210 // so reporting `true` while keys remain would end the loop at once.
10211 let record = self.peek(0);
10212 match self.for_in_advance(&record)? {
10213 Some(key) => {
10214 let text = self.string(key);
10215 self.push(text);
10216 self.push(Value::Bool(false));
10217 }
10218 None => {
10219 self.push(Value::Undefined);
10220 self.push(Value::Bool(true));
10221 }
10222 }
10223 }
10224 ForOfStart => {
10225 let value = self.pop();
10226 let iterator = self.get_iterator(&value)?;
10227 self.push(iterator.object);
10228 self.push(iterator.next);
10229 self.push(Value::CatchOffset(0));
10230 }
10231 ForOfNext => {
10232 // `iter next catch_offset -> iter next catch_offset value done`.
10233 //
10234 // The operand is how many values sit *above* the iterator triple: a
10235 // destructuring rest element keeps its target array and running index
10236 // there while draining the iterator, so the triple is not at the top.
10237 let extra = a as usize;
10238 let iterator_slot = 2 + extra;
10239 // An exhausted iterator is replaced by `undefined` (see below), so a
10240 // second step must not call `next` again — `Array.from` and a
10241 // destructuring pattern both keep stepping past the end.
10242 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
10243 (Value::Undefined, true)
10244 } else {
10245 let iterator = Iterator {
10246 object: self.peek(iterator_slot),
10247 next: self.peek(1 + extra),
10248 };
10249 self.iterator_step(&iterator)?
10250 };
10251 if done {
10252 // The result's `value` is meaningless once the iterator is done:
10253 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
10254 // rather than binding the generator's return value.
10255 let top = self.frame().stack.len() - 1 - iterator_slot;
10256 self.frame_mut().stack[top] = Value::Undefined;
10257 self.push(Value::Undefined);
10258 self.push(Value::Bool(true));
10259 } else {
10260 self.push(value);
10261 self.push(Value::Bool(false));
10262 }
10263 }
10264 IteratorNext => {
10265 // `iter next catch val -> iter next catch val'`: replace the argument with
10266 // the result of `next(val)`. The triple below stays put, which is why the
10267 // three instructions of the `yield*` loop all address the stack the same way.
10268 let value = self.pop();
10269 let object = self.peek(2);
10270 let next = self.peek(1);
10271 let result = self.call_value(next, object, vec![value])?;
10272 self.push(result);
10273 }
10274 IteratorCall => {
10275 // `iter next catch val -> iter next catch val' flag`.
10276 //
10277 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
10278 // The flag is `true` when the method was missing, which is how the
10279 // caller learns that the inner iterator cannot take part in the
10280 // unwinding.
10281 let value = self.pop();
10282 let object = self.peek(2);
10283 let key = if a & 1 != 0 { "throw" } else { "return" };
10284 let method = self.read_field(&object, key)?;
10285 if matches!(method, Value::Undefined | Value::Null) {
10286 self.push(value);
10287 self.push(Value::Bool(true));
10288 } else {
10289 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
10290 let result = self.call_value(method, object, argument)?;
10291 self.push(result);
10292 self.push(Value::Bool(false));
10293 }
10294 }
10295 IteratorCheckObject => {
10296 if !matches!(self.peek(0), Value::Object(_)) {
10297 return Err(Signal::Throw(
10298 self.make_error("TypeError", "iterator must return an object"),
10299 ));
10300 }
10301 }
10302 IteratorClose => {
10303 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
10304 // calling the iterator's `return` so it can release whatever it holds.
10305 //
10306 // The catch offset goes first, so an exception from `return` is not caught
10307 // by the loop being abandoned. This used to pop the three operands and call
10308 // nothing at all, which made `break` out of a `for of` invisible to an
10309 // iterator with a `return` method.
10310 self.pop();
10311 self.pop();
10312 let iterator = self.pop();
10313 if !matches!(iterator, Value::Undefined) {
10314 let method = self.read_field(&iterator, "return")?;
10315 if !matches!(method, Value::Undefined | Value::Null) {
10316 let result = self.call_value(method, iterator.clone(), Vec::new())?;
10317 // §7.4.6: a `return` that answers a non-object is a TypeError.
10318 if !matches!(result, Value::Object(_)) {
10319 return Err(Signal::Throw(
10320 self.make_error("TypeError", "iterator must return an object"),
10321 ));
10322 }
10323 }
10324 }
10325 }
10326 Import => {
10327 // `import(specifier)`: the options slot is on top and is not read yet.
10328 let _options = self.pop();
10329 let specifier = self.pop();
10330 let promise = self.dynamic_import(specifier)?;
10331 self.push(promise);
10332 }
10333 ForAwaitOfStart => {
10334 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
10335 // `Symbol.iterator` fallback.
10336 let value = self.pop();
10337 let iterator = self.get_async_iterator(&value)?;
10338 self.push(iterator.object);
10339 self.push(iterator.next);
10340 self.push(Value::CatchOffset(0));
10341 }
10342 ForAwaitOfNext => {
10343 // `for await` steps the iterator and leaves the *result* wrapped in a
10344 // promise, so the `await` the compiler emits right after this can suspend
10345 // on it. Unwrapping happens in `iterator_get_value_done`.
10346 let extra = a as usize;
10347 let iterator_slot = 2 + extra;
10348 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
10349 Value::Undefined
10350 } else {
10351 let iterator = Iterator {
10352 object: self.peek(iterator_slot),
10353 next: self.peek(1 + extra),
10354 };
10355 let next = iterator.next.clone();
10356 self.call_value(next, iterator.object, Vec::new())?
10357 };
10358 let promise = self.promise_resolve_value(result)?;
10359 self.push(promise);
10360 }
10361 IteratorGetValueDone => {
10362 // `result -> value done`. A missing result object means the iterator was
10363 // already exhausted, which the loop treats as `done`.
10364 let result = self.pop();
10365 let done = match &result {
10366 Value::Object(object) => self
10367 .get_property(object, "done")?
10368 .is_some_and(|value| value.to_boolean()),
10369 _ => true,
10370 };
10371 if done {
10372 // Clear the iterator object so the `iterator_close` the loop emits on
10373 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
10374 // on normal completion, and this is where a normal completion is
10375 // recognised — the same trick `for_of_next` uses, which also replaces
10376 // the slot with `undefined`.
10377 //
10378 // The layout is fixed because only `for await` emits this opcode:
10379 // `iter next catch [result]`, so the iterator is three below the top.
10380 let depth = self.frame().stack.len();
10381 if depth >= 3 {
10382 self.frame_mut().stack[depth - 3] = Value::Undefined;
10383 }
10384 self.push(Value::Undefined);
10385 self.push(Value::Bool(true));
10386 } else {
10387 let Value::Object(object) = &result else {
10388 self.push(Value::Undefined);
10389 self.push(Value::Bool(true));
10390 return Ok(Step::Continue);
10391 };
10392 let value = self
10393 .get_property(object, "value")?
10394 .unwrap_or(Value::Undefined);
10395 self.push(value);
10396 self.push(Value::Bool(false));
10397 }
10398 }
10399
10400 Delete => {
10401 // `delete obj[key]`, where the key was just pushed. Deleting an array
10402 // index leaves a *hole* rather than closing the gap, and a
10403 // non-configurable property answers `false` and stays.
10404 let key = self.pop();
10405 let target = self.pop();
10406 let key = self.propkey(&key)?;
10407 let text_label = key.as_str().unwrap_or("").to_string();
10408 let deleted = match &target {
10409 Value::Object(object) => {
10410 let object = object.clone();
10411 self.delete_property_key(&object, &key)?
10412 }
10413 // A string's `length` and its index properties are
10414 // non-configurable, so deleting one answers `false`.
10415 Value::String(text) => {
10416 !(text_label == "length"
10417 || array_index(&text_label)
10418 .is_some_and(|index| (index as usize) < text.utf16_len()))
10419 }
10420 // "delete null.a" is a TypeError, not a no-op: the operator needs an
10421 // object to delete from, and only a *boxable* primitive has one.
10422 Value::Undefined | Value::Null => {
10423 return Err(Signal::Throw(
10424 self.make_error("TypeError", "cannot convert to object"),
10425 ));
10426 }
10427 // Any other primitive has no own properties; deleting nothing
10428 // succeeds.
10429 _ => true,
10430 };
10431 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
10432 // `TypeError` rather than a `false` result. Sloppy mode silently reports
10433 // the refusal, which is why the same statement throws here but not there.
10434 if !deleted && self.current_strict() {
10435 return Err(Signal::Throw(
10436 self.make_error("TypeError", "cannot delete property"),
10437 ));
10438 }
10439 self.push(Value::Bool(deleted));
10440 }
10441
10442 // -- exceptions and bookkeeping ---------------------------------
10443 Fclosure | Fclosure8 => {
10444 let value = self.closure(a as usize)?;
10445 self.push(value);
10446 }
10447
10448 other => {
10449 let name = other.info().name;
10450 return Err(Signal::Throw(self.make_error(
10451 "InternalError",
10452 &format!("{name} is not implemented yet"),
10453 )));
10454 }
10455 }
10456 Ok(Step::Continue)
10457 }
10458
10459 // -- operand helpers ----------------------------------------------------
10460
10461 /// The slot index an operand names, taking short forms into account.
10462 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
10463 use Opcode::*;
10464 match op {
10465 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
10466 | SetVarRef0 => 0,
10467 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
10468 | SetVarRef1 => 1,
10469 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
10470 | SetVarRef2 => 2,
10471 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
10472 | SetVarRef3 => 3,
10473 _ => a as usize,
10474 }
10475 }
10476
10477 /// The argument count of a call, taking `call0`…`call3` into account.
10478 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
10479 use Opcode::*;
10480 match op {
10481 Call0 => 0,
10482 Call1 => 1,
10483 Call2 => 2,
10484 Call3 => 3,
10485 _ => a as usize,
10486 }
10487 }
10488
10489 /// The atom's name as a property key.
10490 ///
10491 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
10492 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
10493 /// `String::clone` was a heap allocation and a copy — per property access.
10494 /// The atom at `index`, as a property key.
10495 ///
10496 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
10497 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
10498 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
10499 /// 5.3% of `property:monomorphic`.
10500 /// The atom's text, exactly — including an unpaired surrogate.
10501 ///
10502 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
10503 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
10504 /// `atom_text` below is for the other kind of use, where the atom is a key in the
10505 /// engine's own tables.
10506 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
10507 self.frame()
10508 .code
10509 .code
10510 .atoms
10511 .get(index)
10512 .map(|atom| match atom {
10513 Atom::Str(text) => text.clone(),
10514 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
10515 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
10516 Atom::Null => crate::value::Wtf8::new(String::new()),
10517 })
10518 .unwrap_or_default()
10519 }
10520
10521 fn atom_text(&self, index: usize) -> String {
10522 self.frame()
10523 .code
10524 .code
10525 .atoms
10526 .get(index)
10527 .map(|atom| match atom {
10528 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
10529 // compare it to an identifier, and a surrogate-bearing name is reachable
10530 // through `atom_wtf8` where it matters.
10531 Atom::Str(text) => text.to_string_lossy().into_owned(),
10532 Atom::Index(value) => value.to_string(),
10533 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
10534 // `throw_error`, `delete super.x`) never read it.
10535 Atom::Null => String::new(),
10536 })
10537 .unwrap_or_default()
10538 }
10539
10540 fn constant(&mut self, index: usize) -> JsResult<Value> {
10541 let constant = self.frame().code.code.cpool.get(index).cloned();
10542 Ok(match &constant {
10543 Some(Constant::Number(number)) => Value::Float(*number),
10544 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
10545 Some(Constant::BigInt { digits, radix }) => {
10546 match crate::bigint::BigInt::from_radix(digits, *radix) {
10547 Some(big) => self.bigint(big),
10548 // A literal the parser accepted is always parseable; a failure here
10549 // would be a compiler bug, so it reads as an `InternalError`.
10550 None => {
10551 return Err(Signal::Throw(
10552 self.make_error("InternalError", "unparseable bigint literal"),
10553 ));
10554 }
10555 }
10556 }
10557 Some(Constant::Function(_)) => {
10558 return Err(Signal::Throw(
10559 self.make_error("InternalError", "a bare function constant"),
10560 ));
10561 }
10562 // A tagged template's call site: a frozen array of the cooked chunks with a
10563 // frozen `raw` array beside it, which is what `String.raw` reads back.
10564 Some(Constant::Template { cooked, raw }) => {
10565 let cooked_values: Vec<Value> = cooked
10566 .iter()
10567 .map(|chunk| match chunk {
10568 Some(text) => self.string_wtf8(text.clone()),
10569 None => Value::Undefined,
10570 })
10571 .collect();
10572 let raw_values: Vec<Value> =
10573 raw.iter().map(|text| self.string(text.clone())).collect();
10574 let raw_array = self.new_array(raw_values);
10575 raw_array.set_extensible(false);
10576 let template = self.new_array(cooked_values);
10577 template.define(
10578 "raw",
10579 Property::with_attributes(Value::Object(raw_array), false, false),
10580 );
10581 template.set_extensible(false);
10582 Value::Object(template)
10583 }
10584 _ => Value::Undefined,
10585 })
10586 }
10587
10588 /// The reference cell a closure-variable slot names.
10589 ///
10590 /// Two kinds of binding share this addressing: a genuine closure variable
10591 /// (captured from an enclosing function) lives in this frame's environment,
10592 /// while a *declared global* lives in the realm so that a script, a function
10593 /// declaration and their uses all see one binding. A plain `Global` — an
10594 /// undeclared name that may be satisfied by the global object — has no cell at
10595 /// all, which is how `typeof x` still works for a name that does not exist.
10596 /// The reference cell a closure-variable slot names.
10597 ///
10598 /// The environment is resolved once, when the closure is built, and this is
10599 /// just the lookup afterwards. A *declared global* is in there too, pointing at
10600 /// the realm's cell, so a script, a hoisted function declaration and their uses
10601 /// all share one binding. A plain `Global` — a name the script never declared —
10602 /// is read and written through `get_var`/`put_var` by name instead, which is
10603 /// what lets the global object satisfy it.
10604 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
10605 self.frame().env.cells.get(slot).cloned()
10606 }
10607
10608 /// Whether `slot` refers to a global binding through the reference table.
10609 ///
10610 /// A global's cell in the closure environment only exists so the slot has
10611 /// something to point at; the binding itself lives on the global object (a `var`)
10612 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
10613 /// be routed, not performed on the placeholder.
10614 fn is_global_slot(&self, slot: usize) -> bool {
10615 self.frame()
10616 .code
10617 .code
10618 .closure_vars
10619 .get(slot)
10620 .is_some_and(|c| {
10621 // A module's declarations and imports are *not* globals: their cells are
10622 // the module environment's, filled by the host, so the placeholder routing
10623 // must not apply to them.
10624 matches!(
10625 c.closure_type,
10626 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
10627 )
10628 })
10629 }
10630
10631 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
10632 if self.is_global_slot(slot) {
10633 return self.get_global(slot);
10634 }
10635 Ok(self
10636 .var_ref_cell(slot)
10637 .map(|cell| cell.get())
10638 .unwrap_or(Value::Undefined))
10639 }
10640
10641 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
10642 // A function declaration is hoisted by storing into a global reference before
10643 // the body runs, so this path is also what puts it on the global object.
10644 if self.is_global_slot(slot) {
10645 return self.put_global(slot, value);
10646 }
10647 if let Some(cell) = self.var_ref_cell(slot) {
10648 cell.set(value);
10649 }
10650 Ok(())
10651 }
10652
10653 // -- closures -----------------------------------------------------------
10654
10655 /// Build the closure for the function constant `index`.
10656 ///
10657 /// Every entry in the child's closure table names where its binding lives in
10658 /// *this* frame: a local or argument slot that was marked captured, or a cell
10659 /// this frame is itself holding. That is how a variable three functions deep
10660 /// stays one binding.
10661 fn closure(&mut self, index: usize) -> JsResult<Value> {
10662 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
10663 else {
10664 return Err(Signal::Throw(
10665 self.make_error("InternalError", "fclosure of a non-function"),
10666 ));
10667 };
10668 let mut cells = Vec::with_capacity(function.closure_vars.len());
10669 for closure_var in &function.closure_vars {
10670 let cell = match closure_var.closure_type {
10671 ClosureType::Arg => {
10672 let slot = closure_var.var_idx as usize;
10673 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
10674 }
10675 ClosureType::Local => {
10676 let slot = closure_var.var_idx as usize;
10677 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
10678 }
10679 ClosureType::Ref | ClosureType::GlobalRef => {
10680 // A `Ref` names a cell in this frame's own closure table; a
10681 // `GlobalRef` also starts there, then resolves by name below.
10682 let slot = closure_var.var_idx as usize;
10683 if let Some(cell) = self.frame().env.cells.get(slot) {
10684 cells.push(cell.clone());
10685 continue;
10686 }
10687 -1
10688 }
10689 _ => -1,
10690 };
10691 if cell >= 0 {
10692 let cell = self.frame().cells[cell as usize].clone();
10693 cells.push(cell);
10694 continue;
10695 }
10696 // A global: the cell is created on demand and shared through the realm,
10697 // so every function sees one binding.
10698 let name = closure_var.name.clone();
10699 let cell = match self.realm.globals.get(&name) {
10700 Some(cell) => cell.clone(),
10701 None => {
10702 let cell = self.new_cell(Value::Undefined);
10703 self.realm.globals.insert(name.clone(), cell.clone());
10704 cell
10705 }
10706 };
10707 cells.push(cell);
10708 }
10709 let name = function.name.clone();
10710 // `.length` is the arity before any default or rest parameter, not the number
10711 // of slots a pattern parameter needs.
10712 let length = function.defined_args;
10713 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
10714 // function and an arrow function do not. A *method* also does not, but that is not
10715 // known here — the method is marked when the `[[HomeObject]]` is attached (see
10716 // `set_home_object`), which is the moment it becomes a method.
10717 let function_kind = function.kind;
10718 let constructible =
10719 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
10720 let code = Gc::new(self.heap, CompiledCode::new(*function));
10721 // A closure built inside an `eval` inherits the eval's view of the enclosing
10722 // bindings, so it can still read them once the eval has returned.
10723 let eval_scope = self
10724 .active_eval_scope
10725 .clone()
10726 .or_else(|| self.frame().env.eval_scope.clone());
10727 // A closure sees the variables a direct `eval` declared in the frame it was
10728 // created in — the ones declared before *and after* it, so the same object is
10729 // shared; only the phase bounds which of them are visible.
10730 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
10731 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
10732 let env = Gc::new(
10733 self.heap,
10734 ClosureEnv {
10735 cells,
10736 eval_scope,
10737 local_vars,
10738 local_phase,
10739 },
10740 );
10741 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
10742 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
10743 // the only thing that carries `Symbol.toStringTag`, so without it
10744 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
10745 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
10746 let proto = match function_kind {
10747 js_compile::bytecode::FunctionKind::AsyncGenerator => self
10748 .realm
10749 .async_generator_function_proto
10750 .clone()
10751 .or_else(|| self.realm.function_proto.clone().into()),
10752 js_compile::bytecode::FunctionKind::Generator => self
10753 .realm
10754 .generator_function_proto
10755 .clone()
10756 .or_else(|| self.realm.function_proto.clone().into()),
10757 js_compile::bytecode::FunctionKind::Async => self
10758 .realm
10759 .async_function_proto
10760 .clone()
10761 .or_else(|| self.realm.function_proto.clone().into()),
10762 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
10763 };
10764 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
10765 object.set_constructible(constructible);
10766 object.define(
10767 "length",
10768 Property::name_or_length(Value::Int(length as i32)),
10769 );
10770 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
10771 // that checks the own-property descriptor fails if the property is missing.
10772 object.define("name", Property::name_or_length(self.string(name)));
10773 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
10774 // when `[[Construct]]` is created, so a generator, an async function and an arrow
10775 // function have none of their own. Installing it unconditionally gave
10776 // `Array.fromAsync` (an async function) an own `prototype` property, which
10777 // `builtin.js` checks for absence.
10778 if constructible {
10779 self.install_function_prototype(&object);
10780 }
10781 Ok(Value::Object(object))
10782 }
10783
10784 // -- conversions used by the operators ----------------------------------
10785
10786 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
10787 // `+x` is `ToNumber`, which for a string parses it and for an object runs
10788 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
10789 // string, which then behaves differently in every later comparison.
10790 match value {
10791 Value::Int(_) | Value::Float(_) => Ok(value),
10792 other => Ok(Value::Float(self.to_js_number(&other)?)),
10793 }
10794 }
10795
10796 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
10797 ///
10798 /// Returns the *converted* old value and the new one, because the two callers need
10799 /// different halves: `++x` yields the new value, while `x++` yields the old one and
10800 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
10801 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
10802 /// boolean.
10803 ///
10804 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
10805 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
10806 /// a bigint algorithm then ran exactly once.
10807 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
10808 if let Value::BigInt(big) = &value {
10809 let one = crate::bigint::BigInt::from_i64(1);
10810 let next = if up { big.add(&one) } else { big.sub(&one) };
10811 return Ok((value, self.bigint(next)));
10812 }
10813 let old = self.numeric(value)?;
10814 let new = if up {
10815 increment(old.clone())
10816 } else {
10817 decrement(old.clone())
10818 };
10819 Ok((old, new))
10820 }
10821
10822 fn numeric(&mut self, value: Value) -> JsResult<Value> {
10823 // `ToNumber` on an object runs `ToPrimitive` first, which is how
10824 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
10825 // heard at all. Reading the object's own tag instead (`other.to_number()`)
10826 // turned the whole operand into `NaN` and swallowed the exception.
10827 match value {
10828 Value::Int(_) | Value::Float(_) => Ok(value),
10829 other => Ok(Value::Float(self.to_js_number(&other)?)),
10830 }
10831 }
10832
10833 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
10834 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
10835 match value {
10836 Value::BigInt(big) => Ok((**big).clone()),
10837 // The reference words this the same way for every operator, so a failing
10838 // script reads identically; the operator itself adds nothing a caller can use.
10839 _ => Err(Signal::Throw(
10840 self.make_error("TypeError", "cannot convert bigint to number"),
10841 )),
10842 }
10843 }
10844
10845 /// Arithmetic where at least one operand is a `BigInt`.
10846 ///
10847 /// The two numeric types never mix, so a bigint paired with anything else is an error
10848 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
10849 /// that the relational operators handle it separately.
10850 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10851 use Opcode::*;
10852 let a = self.bigint_operand(&left)?;
10853 let b = self.bigint_operand(&right)?;
10854 let result = match op {
10855 Add => a.add(&b),
10856 Sub => a.sub(&b),
10857 Mul => a.mul(&b),
10858 Div | Mod => {
10859 let Some((quotient, remainder)) = a.div_rem(&b) else {
10860 return Err(Signal::Throw(
10861 self.make_error("RangeError", "division by zero"),
10862 ));
10863 };
10864 if op == Div { quotient } else { remainder }
10865 }
10866 Pow => {
10867 let Some(value) = a.pow(&b) else {
10868 return Err(Signal::Throw(self.make_error(
10869 "RangeError",
10870 "BigInt exponent must be non-negative and not absurdly large",
10871 )));
10872 };
10873 value
10874 }
10875 And => a.bitand(&b),
10876 Or => a.bitor(&b),
10877 Xor => a.bitxor(&b),
10878 Shl | Sar => {
10879 // A shift count is a `BigInt` here, and both directions are exact; a
10880 // negative count would be the other direction, which the spec forbids.
10881 let Some(count) = b.to_i64() else {
10882 return Err(Signal::Throw(
10883 self.make_error("RangeError", "BigInt shift count is too large"),
10884 ));
10885 };
10886 if count < 0 {
10887 return Err(Signal::Throw(self.make_error(
10888 "RangeError",
10889 "BigInt shift count must be non-negative",
10890 )));
10891 }
10892 if op == Shl {
10893 a.shl(count as u64)
10894 } else {
10895 a.shr(count as u64)
10896 }
10897 }
10898 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
10899 _ => {
10900 return Err(Signal::Throw(self.make_error(
10901 "TypeError",
10902 "BigInts have no unsigned right shift, use >> instead",
10903 )));
10904 }
10905 };
10906 Ok(self.bigint(result))
10907 }
10908
10909 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
10910 ///
10911 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
10912 /// is on the mathematical values, and nothing is rounded first.
10913 /// `<`, `<=`, `>`, `>=`.
10914 ///
10915 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
10916 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
10917 /// It is a `?`-returning function for exactly that reason: an object operand can run
10918 /// script, and script can throw. The old version compared `to_number` of the raw
10919 /// values, which answered `false` for every object instead of calling `valueOf` —
10920 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
10921 /// never ran.
10922 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
10923 // The hot arm first: `i < n` with both sides already integers. No conversion, no
10924 // call, nothing that can throw.
10925 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10926 let ordering = Some(left.cmp(right));
10927 return Ok(ordering_answer(op, ordering));
10928 }
10929 // Anything that can run script has to be converted first, in this order.
10930 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
10931 {
10932 (
10933 self.to_primitive(left, Hint::Number)?,
10934 self.to_primitive(right, Hint::Number)?,
10935 )
10936 } else {
10937 (left, right)
10938 };
10939 let ordering = match (&left, &right) {
10940 // The loop condition `i < n` is integer against integer, and it runs once
10941 // per iteration of every loop in every program. Without this arm it took the
10942 // `to_number` path twice, which is a `match` plus a conversion each.
10943 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
10944 (Value::String(a), Value::String(b)) => {
10945 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
10946 }
10947 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
10948 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
10949 // is true even though `2.5` has no bigint form.
10950 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
10951 let b = other.to_number();
10952 if b.is_nan() {
10953 None
10954 } else {
10955 compare_bigint_and_f64(a, b)
10956 }
10957 }
10958 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
10959 let a = other.to_number();
10960 if a.is_nan() {
10961 None
10962 } else {
10963 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
10964 }
10965 }
10966 _ => left.to_number().partial_cmp(&right.to_number()),
10967 };
10968 Ok(ordering_answer(op, ordering))
10969 }
10970
10971 fn binary_add(&mut self) -> JsResult<()> {
10972 let right = self.pop();
10973 let left = self.pop();
10974 // Two integers add without any of the machinery below: no `ToPrimitive` (an
10975 // `Int` is already primitive), no string check, no bigint check, no allocation.
10976 // `x += 1` in a loop is the single most common instruction sequence in real
10977 // script, and it used to walk every one of those checks before reaching the
10978 // same `checked_add`.
10979 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
10980 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
10981 return Ok(());
10982 }
10983 let left = self.primitive_of(left)?;
10984 let right = self.primitive_of(right)?;
10985 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
10986 // that check comes before the bigint one: `"" + 1n` is a string, not a
10987 // mixed-type error.
10988 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
10989 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
10990 // `TypeError`, the one place a symbol and a string do not mix.
10991 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
10992 // between a copy and a rope from their lengths, and a rope is what turns
10993 // `text += "abc"` in a loop from quadratic into linear.
10994 if let (Value::String(left), Value::String(right)) = (&left, &right) {
10995 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
10996 // reports as `InternalError: string too long`.
10997 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
10998 return Err(Signal::Throw(
10999 self.make_error("InternalError", "string too long"),
11000 ));
11001 };
11002 self.push(Value::String(Gc::new(self.heap, joined)));
11003 return Ok(());
11004 }
11005 // At least one operand was not a string, so `ToString` it. This rejects a
11006 // symbol, which is the one place a symbol and a string do not mix.
11007 let left = self.checked_to_wtf8(&left)?;
11008 let right = self.checked_to_wtf8(&right)?;
11009 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
11010 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
11011 let text = left.concat(&right);
11012 self.push(self.string_wtf8(text));
11013 return Ok(());
11014 }
11015 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
11016 // not a conversion.
11017 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
11018 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
11019 self.push(value);
11020 return Ok(());
11021 }
11022 let left = self.numeric(left)?;
11023 let right = self.numeric(right)?;
11024 self.push(add_numbers(left, right));
11025 Ok(())
11026 }
11027
11028 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
11029 self.to_primitive(value, Hint::Default)
11030 }
11031
11032 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
11033 ///
11034 /// The order depends on the hint: the "number" order tries `valueOf` first and
11035 /// `toString` second, the "string" order the other way round, and the default
11036 /// hint uses the number order. A result that is still an object is a `TypeError`,
11037 /// because no built-in `valueOf`/`toString` returns one.
11038 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
11039 let Value::Object(object) = &value else {
11040 return Ok(value);
11041 };
11042 // A Date overrides the default hint to mean "string", which is what
11043 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
11044 // this, `"" + new Date()` would print the milliseconds, not the date.
11045 let hint = if hint == Hint::Default && is_date_object(self, object) {
11046 Hint::String
11047 } else {
11048 hint
11049 };
11050 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
11051 // handed the hint as a string. This is the hook a Date uses for its default hint
11052 // and a script uses to take over conversion entirely.
11053 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
11054 if let Some(Value::Object(function)) = self.get_property_key(object, &key)? {
11055 if !function.is_callable() {
11056 return Err(self.type_error("Symbol.toPrimitive is not a function"));
11057 }
11058 let hint = match hint {
11059 Hint::String => "string",
11060 Hint::Number => "number",
11061 Hint::Default => "default",
11062 };
11063 let hint = self.string(hint);
11064 let result = self.call_value(
11065 Value::Object(function),
11066 Value::Object(object.clone()),
11067 vec![hint],
11068 )?;
11069 if matches!(result, Value::Object(_)) {
11070 return Err(self.type_error("cannot convert object to primitive value"));
11071 }
11072 return Ok(result);
11073 }
11074 let order: [&str; 2] = match hint {
11075 Hint::String => ["toString", "valueOf"],
11076 Hint::Number | Hint::Default => ["valueOf", "toString"],
11077 };
11078 let receiver = object.clone();
11079 for method in order {
11080 if let Some(function) = self.get_property(&receiver, method)?
11081 && matches!(&function, Value::Object(object) if object.is_callable())
11082 {
11083 let result =
11084 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
11085 if !matches!(result, Value::Object(_)) {
11086 return Ok(result);
11087 }
11088 }
11089 }
11090 Err(self.type_error("cannot convert object to primitive value"))
11091 }
11092
11093 /// `ToString` with the object case going through `ToPrimitive`.
11094 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
11095 if matches!(value, Value::Object(_)) {
11096 let primitive = self.to_primitive(value.clone(), Hint::String)?;
11097 return Ok(primitive.to_js_string());
11098 }
11099 Ok(value.to_js_string())
11100 }
11101
11102 /// `ToString` that keeps the string's code units instead of flattening them.
11103 ///
11104 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
11105 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
11106 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
11107 if matches!(value, Value::Symbol(_)) {
11108 return Err(Signal::Throw(
11109 self.make_error("TypeError", "cannot convert symbol to string"),
11110 ));
11111 }
11112 // An object runs `ToPrimitive` first, which may itself produce a symbol.
11113 let value = self.to_primitive(value.clone(), Hint::String)?;
11114 match value {
11115 Value::Symbol(_) => Err(Signal::Throw(
11116 self.make_error("TypeError", "cannot convert symbol to string"),
11117 )),
11118 Value::String(text) => Ok(text.wtf8().clone()),
11119 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
11120 }
11121 }
11122
11123 /// `ToNumber` with the object case going through `ToPrimitive`.
11124 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
11125 let value = if matches!(value, Value::Object(_)) {
11126 self.to_primitive(value.clone(), Hint::Number)?
11127 } else {
11128 value.clone()
11129 };
11130 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
11131 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
11132 // `NaN` to stay total, and the operators check for the bigint themselves — but
11133 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
11134 // refuse, and answering `NaN` made them silently wrong instead.
11135 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
11136 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
11137 match value {
11138 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
11139 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
11140 other => Ok(other.to_number()),
11141 }
11142 }
11143
11144 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
11145 /// [`ElementType::write`].
11146 ///
11147 /// This is separated from the write because both conversions are observable script —
11148 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
11149 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
11150 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
11151 /// setters, and a plain `a[i] = v`.
11152 pub(crate) fn element_value(
11153 &mut self,
11154 element: crate::builtins::typedarray::ElementType,
11155 value: Value,
11156 ) -> JsResult<Value> {
11157 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
11158 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
11159 let primitive = match &value {
11160 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
11161 _ => value,
11162 };
11163 if element.is_bigint() {
11164 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
11165 Ok(Value::BigInt(Gc::new(self.heap, big)))
11166 } else {
11167 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
11168 Ok(Value::Float(self.to_js_number(&primitive)?))
11169 }
11170 }
11171
11172 /// `ToPropertyKey`: what a computed member access uses as its key.
11173 ///
11174 /// A symbol is returned as itself, never stringified — that is what keeps
11175 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
11176 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
11177 match value {
11178 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
11179 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
11180 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
11181 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
11182 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
11183 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
11184 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
11185 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
11186 other.to_js_string(),
11187 ))),
11188 },
11189 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
11190 }
11191 }
11192
11193 /// `ToPropertyKey` for the callers that can only use a string key.
11194 ///
11195 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
11196 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
11197 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
11198 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
11199 /// program continues with a value nobody asked for.
11200 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
11201 use crate::value::Wtf8;
11202 Ok(match value {
11203 // A string key keeps its code units. Going through a lossy `String` would make
11204 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
11205 Value::String(text) => text.wtf8().clone(),
11206 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
11207 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
11208 // falling back to its `ToString` would print `[object Object]`.
11209 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
11210 Value::String(text) => text.wtf8().clone(),
11211 other => Wtf8::new(other.to_js_string()),
11212 },
11213 other => Wtf8::new(other.to_js_string()),
11214 })
11215 }
11216
11217 // -- object operations used by instructions -----------------------------
11218
11219 /// Read `object[key]`, returning `undefined` when the property is missing.
11220 ///
11221 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
11222 /// primitive (looking through its prototype) as well as an object — which is what
11223 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
11224 /// argument needs too.
11225 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
11226 self.read_field_key(object, &PropertyKey::from(key))
11227 }
11228
11229 /// [`Interp::read_field`] with a key that may be a symbol.
11230 ///
11231 /// A symbol key never reaches the string shortcuts: a string's `length` and its
11232 /// indices are string properties, and a symbol named `length` is a different
11233 /// property that a string primitive cannot have.
11234 /// [`Interp::read_field_key`], with an inline cache in front of it.
11235 ///
11236 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
11237 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
11238 /// without this the engine walked the chain and compared ~40 property names on each
11239 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
11240 ///
11241 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
11242 /// missing property. Those answers depend on running code or on state the guard below
11243 /// does not cover, and a wrong answer here is far more expensive than a lookup.
11244 ///
11245 /// A hit is re-validated against the *whole* walked chain, not just the level that
11246 /// answered: the receiver and every prototype down to that level must still be the same
11247 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
11248 /// property-table *lengths* — which is what catches a property appearing on an
11249 /// intermediate prototype and shadowing the cached one.
11250 pub fn read_field_cached(
11251 &mut self,
11252 object: &Value,
11253 key: &PropertyKey,
11254 slot: usize,
11255 ) -> JsResult<Value> {
11256 let index = Self::field_cache_slot(object, key, slot);
11257 let Value::Object(target) = object else {
11258 return self.read_field_key(object, key);
11259 };
11260 if target.proxy_state().is_some() {
11261 return self.read_field_key(object, key);
11262 }
11263 if let Some(cached) = &self.field_cache[index]
11264 && cached.key == *key
11265 && let Some(value) = Self::cached_hit(target, cached)
11266 {
11267 return Ok(value);
11268 }
11269 let value = self.read_field_key(object, key)?;
11270 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
11271 Ok(value)
11272 }
11273
11274 /// Whether a cache entry still describes this lookup, and if so the value.
11275 ///
11276 /// The guard is the whole point of the entry: identity plus property-table length for
11277 /// every level walked. Re-checked per level rather than once at the receiving end,
11278 /// because a shadowing property can appear anywhere along the chain.
11279 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
11280 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
11281 // starts with: a clone is a reference-count bump and a drop, and for
11282 // `property:monomorphic` every single hit takes only this arm.
11283 let (weak, len) = cached.chain[0].as_ref()?;
11284 if !target.upgrades_to(weak) {
11285 return None;
11286 }
11287 if cached.level == 0 {
11288 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
11289 return target.cached_property_at(cached.index, &cached.key, *len);
11290 }
11291 if target.props_len() != *len {
11292 return None;
11293 }
11294 let mut level = 1;
11295 let mut current = target.proto()?;
11296 loop {
11297 let (weak, len) = cached.chain[level].as_ref()?;
11298 if !current.upgrades_to(weak) || current.props_len() != *len {
11299 return None;
11300 }
11301 if level == cached.level as usize {
11302 // The level that answered: the value is only reusable while the key is
11303 // still there and still a plain data property.
11304 return current.cached_data_property(cached.index, &cached.key);
11305 }
11306 current = current.proto()?;
11307 level += 1;
11308 }
11309 }
11310
11311 /// Build a cache entry for a lookup that just went through the slow path.
11312 ///
11313 /// Records the chain only when the answer came from a plain data property at a level
11314 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
11315 /// costs the next lookup the walk it would have cost anyway.
11316 fn record_field_lookup(
11317 target: &Gc<JsObject>,
11318 key: &PropertyKey,
11319 _value: Value,
11320 ) -> Option<FieldCache> {
11321 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
11322 [None, None, None];
11323 let mut current = target.clone();
11324 for level in 0..MAX_CACHED_CHAIN {
11325 chain[level] = Some((current.downgrade(), current.props_len()));
11326 if let Some((found, _)) = current.own_property_index(key) {
11327 // `own_property_index` declines an accessor and a hole, which is exactly
11328 // the set that must not be cached.
11329 return Some(FieldCache {
11330 key: key.clone(),
11331 index: found,
11332 level: level as u8,
11333 chain,
11334 });
11335 }
11336 current = current.proto()?;
11337 }
11338 None
11339 }
11340
11341 /// Which cache slot a lookup uses.
11342 ///
11343 /// Mixes the object's address, the name and the site, so that two properties of one
11344 /// object, and one property of two objects, land in different slots — which is what lets
11345 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
11346 /// other iteration.
11347 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
11348 let mut hash = match object {
11349 Value::Object(object) => object.address(),
11350 _ => 0,
11351 };
11352 hash = hash
11353 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
11354 .rotate_left(17)
11355 .wrapping_add(key.hash_code());
11356 hash = hash.wrapping_add(site.wrapping_mul(31));
11357 // The table is a power of two, so the low bits are the slot.
11358 hash & (FIELD_CACHE_SLOTS - 1)
11359 }
11360
11361 /// Read `key` from `object`, without the inline cache.
11362 ///
11363 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
11364 /// prototype chain, while the cached form answers an own data property from memory.
11365 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
11366 let text = key.as_str().unwrap_or("");
11367 let Value::Object(object) = object else {
11368 // Reading a property of `undefined`/`null` is the classic TypeError.
11369 if object.is_nullish() {
11370 return Err(Signal::Throw(self.make_error(
11371 "TypeError",
11372 &format!("cannot read property '{key}' of {}", object.to_js_string()),
11373 )));
11374 }
11375 // A string has `length` and index access without being boxed.
11376 if let Value::String(value) = object {
11377 if text == "length" {
11378 return Ok(Value::Int(value.utf16_len() as i32));
11379 }
11380 if let Some(index) = array_index(text) {
11381 return Ok(match value.wtf8().unit_at(index as usize) {
11382 Some(unit) => self.string_wtf8(unit),
11383 None => Value::Undefined,
11384 });
11385 }
11386 }
11387 // A property of a primitive is looked up on its prototype: this is what
11388 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
11389 let prototype = match object {
11390 Value::String(_) => self.realm.string_proto.clone(),
11391 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11392 Value::Bool(_) => self.realm.boolean_proto.clone(),
11393 // A symbol's methods live on `Symbol.prototype`, reached the same way —
11394 // `sym.description` reads through the prototype, not off the symbol.
11395 Value::Symbol(_) => self.realm.symbol_proto.clone(),
11396 // …and a bigint's on `BigInt.prototype`, which is how
11397 // `(255n).toString(16)` reaches its method.
11398 Value::BigInt(_) => self.realm.bigint_proto.clone(),
11399 _ => None,
11400 };
11401 if let Some(prototype) = prototype
11402 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
11403 {
11404 return Ok(value);
11405 }
11406 return Ok(Value::Undefined);
11407 };
11408 Ok(self
11409 .get_property_key(object, key)?
11410 .unwrap_or(Value::Undefined))
11411 }
11412
11413 /// The `#name` a private symbol stands for, for error messages.
11414 ///
11415 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
11416 /// was made from.
11417 fn private_name(symbol: &Value) -> Option<String> {
11418 match symbol {
11419 Value::Symbol(symbol) if symbol.is_private() => Some(
11420 symbol
11421 .description()
11422 .map(|text| text.to_string())
11423 .unwrap_or_default(),
11424 ),
11425 _ => None,
11426 }
11427 }
11428
11429 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
11430 ///
11431 /// Every private-field opcode takes the symbol the class stored in its own scope; a
11432 /// non-symbol here would be a compiler bug, and the reference guards it with
11433 /// `JS_ThrowTypeErrorNotASymbol`.
11434 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
11435 match symbol {
11436 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
11437 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
11438 }
11439 }
11440
11441 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
11442 ///
11443 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
11444 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
11445 /// would hit if the parser did not reject it first.
11446 fn define_private_field(
11447 &mut self,
11448 object: &Value,
11449 symbol: &Value,
11450 value: Value,
11451 ) -> JsResult<()> {
11452 let key = self.private_key(symbol)?;
11453 let Some(target) = object.as_object() else {
11454 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11455 };
11456 if !target.is_extensible() {
11457 return Err(Signal::Throw(
11458 self.make_error("TypeError", "object is not extensible"),
11459 ));
11460 }
11461 if target.own_property_key(&key).is_some() {
11462 let name = Self::private_name(symbol).unwrap_or_default();
11463 return Err(Signal::Throw(self.make_error(
11464 "TypeError",
11465 &format!("private class field '{name}' already exists"),
11466 )));
11467 }
11468 target.define_data_key(&key, value);
11469 Ok(())
11470 }
11471
11472 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
11473 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
11474 let key = self.private_key(symbol)?;
11475 let Some(target) = object.as_object() else {
11476 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11477 };
11478 match target.own_property_key(&key) {
11479 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
11480 None => {
11481 let name = Self::private_name(symbol).unwrap_or_default();
11482 Err(Signal::Throw(self.make_error(
11483 "TypeError",
11484 &format!("private class field '{name}' does not exist"),
11485 )))
11486 }
11487 }
11488 }
11489
11490 /// `JS_SetPrivateField`: the store half of the same rule.
11491 fn write_private_field(
11492 &mut self,
11493 object: &Value,
11494 symbol: &Value,
11495 value: Value,
11496 ) -> JsResult<()> {
11497 let key = self.private_key(symbol)?;
11498 let Some(target) = object.as_object() else {
11499 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11500 };
11501 if target.write_value_key(&key, value) {
11502 return Ok(());
11503 }
11504 let name = Self::private_name(symbol).unwrap_or_default();
11505 Err(Signal::Throw(self.make_error(
11506 "TypeError",
11507 &format!("private class field '{name}' does not exist"),
11508 )))
11509 }
11510
11511 /// The `in` half: does `object` have this private field?
11512 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
11513 ///
11514 /// The symbol is created once per class — the first `add_brand` on a given home object
11515 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
11516 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
11517 /// emit for the *instance* brand passes null because all it wants is the symbol.
11518 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
11519 let Some(home_object) = home.as_object() else {
11520 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11521 };
11522 let symbol = match home_object.private_brand() {
11523 Some(symbol) => symbol,
11524 None => {
11525 let symbol = Gc::new(
11526 self.heap,
11527 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
11528 );
11529 home_object.set_private_brand(symbol.clone());
11530 symbol
11531 }
11532 };
11533 let Some(target) = object.as_object() else {
11534 // Not an object: nothing to brand. The reference does the same, and `undefined`
11535 // here would otherwise turn a field initialiser into a TypeError.
11536 return Ok(());
11537 };
11538 if !target.is_extensible() {
11539 return Err(Signal::Throw(
11540 self.make_error("TypeError", "object is not extensible"),
11541 ));
11542 }
11543 if target.carries_brand(&symbol) {
11544 return Err(Signal::Throw(
11545 self.make_error("TypeError", "private method is already present"),
11546 ));
11547 }
11548 target.add_brand(symbol);
11549 Ok(())
11550 }
11551
11552 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
11553 ///
11554 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
11555 /// decides whether to throw.
11556 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
11557 let Some(function) = function.as_object() else {
11558 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11559 };
11560 let Some(home) = function.home_object() else {
11561 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11562 };
11563 let Some(brand) = home.private_brand() else {
11564 return Err(Signal::Throw(
11565 self.make_error("TypeError", "expecting <brand> private field"),
11566 ));
11567 };
11568 Ok(object.carries_brand(&brand))
11569 }
11570
11571 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
11572 let Value::Object(object) = object else {
11573 return Err(Signal::Throw(self.make_error(
11574 "TypeError",
11575 &format!("cannot set property '{key}' of {}", object.to_js_string()),
11576 )));
11577 };
11578 // The write half of the property inline cache, in effect: an own, writable,
11579 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
11580 // decide — no prototype walk (an own property shadows the chain before a setter
11581 // there could matter), no extensibility check (the object already has the key),
11582 // and no `[[DefineOwnProperty]]`.
11583 //
11584 // `this.value = …` inside a method is the whole write side of
11585 // `property:method-call`, and it was reaching `set_property_with_key` with its
11586 // proxy test, its typed-array test, its array-index test and finally a linear
11587 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
11588 //
11589 // Every disqualifier is checked here: a proxy traps the set, an array index and
11590 // `length` live outside the property table, and a typed array's element is stored
11591 // through its view's element type.
11592 if object.proxy_state().is_none()
11593 && !object.is_array()
11594 && object.typed_array_element_type().is_none()
11595 && object.write_value_key(key, value.clone())
11596 {
11597 return Ok(());
11598 }
11599 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
11600 let on_failure = if self.frame().code.code.strict {
11601 DeleteFailure::Throw
11602 } else {
11603 DeleteFailure::Ignore
11604 };
11605 self.set_property_with_key(object, key, value, on_failure)
11606 }
11607
11608 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
11609 ///
11610 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
11611 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
11612 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
11613 /// `Number.parseInt(sym)` — so those callers use this instead.
11614 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
11615 if matches!(value, Value::Symbol(_)) {
11616 return Err(Signal::Throw(
11617 self.make_error("TypeError", "cannot convert symbol to string"),
11618 ));
11619 }
11620 // An object runs `ToPrimitive` first, which may itself produce a symbol —
11621 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
11622 let value = self.to_primitive(value.clone(), Hint::String)?;
11623 if matches!(value, Value::Symbol(_)) {
11624 return Err(Signal::Throw(
11625 self.make_error("TypeError", "cannot convert symbol to string"),
11626 ));
11627 }
11628 Ok(value.to_js_string())
11629 }
11630
11631 /// `ToPropertyKey` for a builtin that takes a key argument.
11632 ///
11633 /// Fallible: a key whose `toString` throws has to propagate that error, both for
11634 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
11635 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
11636 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
11637 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
11638 self.propkey(value)
11639 }
11640
11641 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
11642 ///
11643 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
11644 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
11645 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
11646 /// `RangeError` — and why this cannot be a plain `ToNumber`.
11647 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
11648 let number = match value {
11649 Value::Int(number) => *number as f64,
11650 Value::Float(number) => *number,
11651 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
11652 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
11653 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
11654 // reference answers 0.
11655 Value::Null | Value::Bool(_) => value.to_number(),
11656 _ => {
11657 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
11658 match primitive {
11659 Value::Int(number) => number as f64,
11660 Value::Float(number) => number,
11661 other => {
11662 // `ToString` then `ToNumber`, so a string length goes through the
11663 // full numeric-literal grammar: `"0x00B"` is 11 and `" 5 "` is 5.
11664 // `Value::to_number` on the string already implements exactly that.
11665 let text = self.to_js_string(&other)?;
11666 crate::value::string_to_number(&text)
11667 }
11668 }
11669 }
11670 };
11671 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
11672 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
11673 // is a `RangeError`, not `0`.
11674 if !number.is_finite()
11675 || number.fract() != 0.0
11676 || !(0.0..=u32::MAX as f64).contains(&number)
11677 {
11678 return Err(self.range_error("invalid array length"));
11679 }
11680 Ok(number as u32)
11681 }
11682
11683 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
11684 /// `Object.getOwnPropertySymbols` put in their result array.
11685 pub fn key_value(&self, key: &PropertyKey) -> Value {
11686 match key {
11687 PropertyKey::String(text) => self.string_wtf8(text.clone()),
11688 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11689 }
11690 }
11691
11692 /// Fill in a String exotic object: `_value`, `length` and the index properties.
11693 ///
11694 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
11695 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
11696 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
11697 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
11698 /// the two paths had drifted; this is the one both now use.
11699 ///
11700 /// The indices are *code units*, so an astral character occupies two of them — the
11701 /// same rule `s.length` and `s[i]` follow.
11702 /// Give an already-created object the internal slot that makes it a wrapper of
11703 /// `value`, so the primitive's prototype methods work on it.
11704 ///
11705 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
11706 /// which are wrappers of their own type holding the empty value.
11707 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
11708 self.internal_set(object, "_value", value);
11709 }
11710
11711 pub(crate) fn init_string_wrapper(
11712 &mut self,
11713 object: &Gc<JsObject>,
11714 text: &Gc<crate::value::JsString>,
11715 ) {
11716 object.define(
11717 "length",
11718 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
11719 );
11720 for index in 0..text.utf16_len() {
11721 if let Some(unit) = text.wtf8().unit_at(index) {
11722 object.define(
11723 &index.to_string(),
11724 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
11725 Property::with_attributes(self.string_wtf8(unit), false, true),
11726 );
11727 }
11728 }
11729 object.define_key(
11730 &self.internal_slot("_value"),
11731 Property::with_attributes(Value::String(text.clone()), false, false),
11732 );
11733 }
11734
11735 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
11736 ///
11737 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
11738 /// throws. The wrapper carries its primitive in `_value` — the same slot
11739 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
11740 /// on a boxed value no constructor ever built.
11741 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
11742 let (prototype, primitive) = match value {
11743 Value::Object(object) => return Ok(object.clone()),
11744 Value::String(text) => {
11745 let object = self.new_object(self.realm.string_proto.clone());
11746 self.init_string_wrapper(&object, text);
11747 return Ok(object);
11748 }
11749 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
11750 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
11751 // A symbol and a bigint box into wrappers whose methods live on
11752 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
11753 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
11754 // branch below instead produced an object with *no* prototype, so those
11755 // methods were unreachable on a box.
11756 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
11757 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
11758 Value::Undefined | Value::Null => {
11759 return Err(Signal::Throw(self.make_error(
11760 "TypeError",
11761 &format!("cannot convert {} to object", value.to_js_string()),
11762 )));
11763 }
11764 _ => (None, value.clone()),
11765 };
11766 let object = self.new_object(prototype);
11767 self.internal_set(&object, "_value", primitive);
11768 Ok(object)
11769 }
11770
11771 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
11772 ///
11773 /// Split out for a reader that has to create the object *before* it knows what it wraps:
11774 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
11775 /// written before its primitive, so the placeholder has to exist first and be filled in
11776 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
11777 /// than a second in the deserialiser.
11778 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
11779 let prototype = match value {
11780 Value::String(_) => self.realm.string_proto.clone(),
11781 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
11782 Value::Bool(_) => self.realm.boolean_proto.clone(),
11783 Value::Symbol(_) => self.realm.symbol_proto.clone(),
11784 Value::BigInt(_) => self.realm.bigint_proto.clone(),
11785 _ => {
11786 return Err(Signal::Throw(self.make_error(
11787 "TypeError",
11788 &format!("cannot box {}", value.to_js_string()),
11789 )));
11790 }
11791 };
11792 object.set_proto(prototype);
11793 if let Value::String(text) = value {
11794 self.init_string_wrapper(object, text);
11795 return Ok(());
11796 }
11797 self.internal_set(object, "_value", value.clone());
11798 Ok(())
11799 }
11800
11801 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
11802 ///
11803 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
11804 /// through the `Symbol` function object, so the registry is reachable as a method rather
11805 /// than only from `builtins::symbol`.
11806 pub fn symbol_for(&mut self, key: &str) -> Value {
11807 if let Some(existing) = self.realm.symbol_registry.get(key) {
11808 return existing.clone();
11809 }
11810 let symbol = crate::builtins::symbol::symbol_value(
11811 self,
11812 crate::value::JsSymbol::registered(key.to_string()),
11813 );
11814 self.realm
11815 .symbol_registry
11816 .insert(key.to_string(), symbol.clone());
11817 symbol
11818 }
11819
11820 /// `a == b`, the coercing comparison.
11821 ///
11822 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
11823 /// which is what makes `[] == ""` true: `[]` becomes `""` via
11824 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
11825 /// because the conversion is allowed to call script code, so the two primitive
11826 /// operands are handed back to it.
11827 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
11828 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
11829 return Ok(left.loose_equals(&right));
11830 }
11831 // `null == undefined` holds even though neither is an object.
11832 if matches!(left, Value::Undefined | Value::Null)
11833 && matches!(right, Value::Undefined | Value::Null)
11834 {
11835 return Ok(true);
11836 }
11837 if matches!(left, Value::Undefined | Value::Null)
11838 || matches!(right, Value::Undefined | Value::Null)
11839 {
11840 return Ok(false);
11841 }
11842 // Two objects compare by identity. Only an object *against a primitive* is
11843 // converted, which is why `{} == {}` is false while `[] == ""` is true.
11844 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
11845 return Ok(a.ptr_eq(b));
11846 }
11847 let left = self.to_primitive(left, Hint::Default)?;
11848 let right = self.to_primitive(right, Hint::Default)?;
11849 Ok(left.loose_equals(&right))
11850 }
11851
11852 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
11853 let Value::Object(object) = object else {
11854 return Err(Signal::Throw(
11855 self.make_error("TypeError", "cannot use 'in' on a non-object"),
11856 ));
11857 };
11858 let key = self.propkey(key)?;
11859 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
11860 // trap. One implementation, so an array's derived `length` and its inherited holes
11861 // cannot be right in one caller and wrong in another.
11862 self.has_own_or_inherited(object, &key)
11863 }
11864
11865 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
11866 ///
11867 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
11868 /// whole reason the operator is a hook rather than a prototype walk.
11869 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11870 if let Value::Object(function) = constructor {
11871 let key = self.realm.well_known_key(WellKnown::HasInstance);
11872 let method = self.get_property_key(function, &key)?;
11873 if let Some(method) = method
11874 && !matches!(method, Value::Undefined)
11875 {
11876 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
11877 return Ok(answer.to_boolean());
11878 }
11879 }
11880 self.instance_of(object, constructor)
11881 }
11882
11883 /// `OrdinaryHasInstance`: the prototype walk on its own.
11884 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11885 self.instance_of(object, constructor)
11886 }
11887
11888 /// `IsArray`: an array, or a proxy whose target is one.
11889 ///
11890 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
11891 /// makes `Array.isArray(new Proxy([], {}))` true.
11892 pub fn is_array_value(&self, value: &Value) -> bool {
11893 match value {
11894 Value::Object(object) => {
11895 if let Some(state) = object.proxy_state() {
11896 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
11897 }
11898 object.is_array()
11899 }
11900 _ => false,
11901 }
11902 }
11903
11904 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
11905 ///
11906 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
11907 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
11908 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
11909 /// see [`Interp::enqueue_job_function`].
11910 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
11911 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
11912 // the handler is reported rather than lost — the same reason a `then` reaction needs a
11913 // promise to settle.
11914 let promise = self.new_promise();
11915 self.fulfill_promise(&promise, Value::Undefined);
11916 self.jobs.push_back(Job::Reaction {
11917 handler: Some(function),
11918 argument: Value::Undefined,
11919 rejected: false,
11920 promise,
11921 });
11922 Ok(())
11923 }
11924
11925 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
11926 let Value::Object(target) = object else {
11927 return Ok(false);
11928 };
11929 let Value::Object(function) = constructor else {
11930 return Err(Signal::Throw(self.make_error(
11931 "TypeError",
11932 "right-hand side of 'instanceof' is not callable",
11933 )));
11934 };
11935 let prototype = self.get_property(function, "prototype")?;
11936 let Some(Value::Object(prototype)) = prototype else {
11937 return Ok(false);
11938 };
11939 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
11940 // which is also what makes `proxyOfInstance instanceof C` work.
11941 let mut current = Some(target.clone());
11942 while let Some(object) = current {
11943 if object.ptr_eq(&prototype) {
11944 return Ok(true);
11945 }
11946 current = self.object_prototype_of(&object)?;
11947 }
11948 Ok(false)
11949 }
11950
11951 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
11952 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
11953 if let Some(proto) = self.proxy_get_prototype_of(object)? {
11954 return Ok(proto);
11955 }
11956 if let Some(exotic) = object.exotic()
11957 && let Some(proto) = exotic.get_prototype(self, object)?
11958 {
11959 return Ok(proto);
11960 }
11961 Ok(object.proto())
11962 }
11963
11964 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
11965 pub fn object_set_prototype_of(
11966 &mut self,
11967 object: &Gc<JsObject>,
11968 proto: Option<Gc<JsObject>>,
11969 ) -> JsResult<bool> {
11970 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
11971 return Ok(answer);
11972 }
11973 if let Some(exotic) = object.exotic()
11974 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
11975 {
11976 return Ok(answer);
11977 }
11978 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
11979 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
11980 // inheriting from itself, which every later prototype walk then had to defend
11981 // against — and `Reflect.setPrototypeOf` reported success for an operation the
11982 // language says is impossible.
11983 if let Some(proto) = &proto {
11984 let mut current = Some(proto.clone());
11985 let mut guard = 0;
11986 while let Some(node) = current {
11987 if node.ptr_eq(object) {
11988 return Err(Signal::Throw(
11989 self.make_error("TypeError", "circular prototype chain"),
11990 ));
11991 }
11992 guard += 1;
11993 if guard > 1000 {
11994 break;
11995 }
11996 current = node.proto();
11997 }
11998 }
11999 object.set_proto(proto);
12000 Ok(true)
12001 }
12002
12003 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
12004 ///
12005 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
12006 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
12007 /// already one.
12008 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
12009 // An integer-indexed exotic object answers from `IsValidIntegerIndex` alone
12010 // (§10.4.5.4 step 1.b.i) — the prototype chain is *not* consulted for a canonical
12011 // numeric index. That is observable: a view that has been resized out of bounds
12012 // has no indices, and `2 in view` must then be `false` even when
12013 // `Object.getPrototypeOf(view)[2]` exists. Falling through to the chain answered
12014 // `true`, which is what `TypedArray/out-of-bounds-behaves-like-detached` catches.
12015 // A proxy is excluded because it has no `[[ViewedArrayBuffer]]` slot of its own.
12016 if object.typed_array_parts().is_some()
12017 && object.proxy_state().is_none()
12018 && let Some(index) = key.as_str().and_then(array_index)
12019 {
12020 return Ok(object
12021 .typed_array_length()
12022 .is_some_and(|length| (index as usize) < length));
12023 }
12024 let mut current = Some(object.clone());
12025 // Bounded by the chain, which `object_prototype_of` already guards against cycles in.
12026 let mut guard = 0;
12027 while let Some(node) = current {
12028 guard += 1;
12029 if guard > 1000 {
12030 return Ok(false);
12031 }
12032 let own = self.object_get_own_property(&node, key)?;
12033 if own.is_some() {
12034 return Ok(true);
12035 }
12036 current = self.object_prototype_of(&node)?;
12037 }
12038 Ok(false)
12039 }
12040
12041 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
12042 ///
12043 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
12044 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
12045 /// boolean as well, and it needs the receiver to be the one the caller named.
12046 pub fn set_property_with_key_receiver(
12047 &mut self,
12048 object: &Gc<JsObject>,
12049 key: &PropertyKey,
12050 value: Value,
12051 receiver: Option<&Value>,
12052 on_failure: DeleteFailure,
12053 ) -> JsResult<bool> {
12054 let receiver = receiver
12055 .cloned()
12056 .unwrap_or_else(|| Value::Object(object.clone()));
12057 if object.proxy_state().is_some() {
12058 return match self.proxy_set(object, key, value, &receiver)? {
12059 Some(accepted) => Ok(accepted),
12060 None => Ok(true),
12061 };
12062 }
12063 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
12064 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
12065 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
12066 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
12067 if object.typed_array_element_type().is_some()
12068 && key.as_str().and_then(array_index).is_some()
12069 {
12070 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
12071 self.set_property_with_key_receiver_aware(object, key, value, on_failure, same)?;
12072 return Ok(true);
12073 }
12074 // An own accessor, or one found up the chain, receives the call with `receiver` as
12075 // `this` — which is the whole reason this variant exists.
12076 if let Some(setter) = self.lookup_setter(object, key)? {
12077 self.call_value(setter, receiver, vec![value])?;
12078 return Ok(true);
12079 }
12080 // Otherwise it is an ordinary create-or-write, which the plain path already does —
12081 // carrying the receiver comparison, which a typed array's element store can see.
12082 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
12083 self.set_property_with_key_receiver_aware(object, key, value, on_failure, same)?;
12084 Ok(true)
12085 }
12086
12087 /// The setter `key` resolves to, if it resolves to an accessor.
12088 fn lookup_setter(
12089 &mut self,
12090 object: &Gc<JsObject>,
12091 key: &PropertyKey,
12092 ) -> JsResult<Option<Value>> {
12093 let mut current = Some(object.clone());
12094 let mut guard = 0;
12095 while let Some(node) = current {
12096 guard += 1;
12097 if guard > 1000 {
12098 return Ok(None);
12099 }
12100 if let Some(property) = self.object_get_own_property(&node, key)? {
12101 if property.is_accessor() {
12102 return Ok(property.setter);
12103 }
12104 // A data property stops the walk: the store writes here, not further up.
12105 return Ok(None);
12106 }
12107 current = self.object_prototype_of(&node)?;
12108 }
12109 Ok(None)
12110 }
12111
12112 /// `[[IsExtensible]]`, with the proxy trap when there is one.
12113 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
12114 if let Some(answer) = self.proxy_is_extensible(object)? {
12115 return Ok(answer);
12116 }
12117 if let Some(exotic) = object.exotic()
12118 && let Some(answer) = exotic.is_extensible(self, object)?
12119 {
12120 return Ok(answer);
12121 }
12122 Ok(object.is_extensible())
12123 }
12124
12125 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
12126 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
12127 if let Some(answer) = self.proxy_prevent_extensions(object)? {
12128 return Ok(answer);
12129 }
12130 if let Some(exotic) = object.exotic()
12131 && let Some(answer) = exotic.prevent_extensions(self, object)?
12132 {
12133 return Ok(answer);
12134 }
12135 object.set_extensible(false);
12136 Ok(true)
12137 }
12138
12139 fn copy_properties(
12140 &mut self,
12141 target: &Value,
12142 source: &Value,
12143 exclusion: &Value,
12144 ) -> JsResult<()> {
12145 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
12146 // does contribute: its index properties are own, enumerable and writable, which
12147 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
12148 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
12149 // is a no-op.
12150 let Some(target) = target.as_object() else {
12151 return Ok(());
12152 };
12153 let source_object = match source {
12154 Value::Object(object) => object.clone(),
12155 Value::String(text) => {
12156 // Untaken keys are the string's indices, which are code units.
12157 for index in 0..text.utf16_len() {
12158 if let Some(unit) = text.wtf8().unit_at(index) {
12159 target.define_data(&index.to_string(), self.string_wtf8(unit));
12160 }
12161 }
12162 return Ok(());
12163 }
12164 _ => return Ok(()),
12165 };
12166 // An object *rest* element passes the keys already taken by the literal part as
12167 // an array of strings; a spread passes `null`, which excludes nothing. Only the
12168 // string keys of the exclusion array are meaningful, so an array is read by its
12169 // elements rather than by its own property names.
12170 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
12171 if let Value::Object(list) = exclusion
12172 && let Some(length) = list.array_length()
12173 {
12174 for index in 0..length {
12175 if let Some(value) = list.array_get(index) {
12176 excluded.push(self.propkey_of(&value)?);
12177 }
12178 }
12179 }
12180 let source = &source_object;
12181 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
12182 // Reading the property table directly made every spread of a proxy empty.
12183 let keys = self.object_own_property_keys(source)?;
12184 for as_key in keys {
12185 if as_key.is_symbol() {
12186 // A spread copies string-keyed properties only.
12187 continue;
12188 }
12189 if excluded.contains(&crate::value::Wtf8::new(
12190 as_key.as_str().unwrap_or_default(),
12191 )) {
12192 continue;
12193 }
12194 let enumerable = self
12195 .object_get_own_property(source, &as_key)?
12196 .is_some_and(|property| property.enumerable);
12197 if !enumerable {
12198 continue;
12199 }
12200 let value = self
12201 .get_property_key(source, &as_key)?
12202 .unwrap_or(Value::Undefined);
12203 target.define_data_key(&as_key, value);
12204 }
12205 Ok(())
12206 }
12207
12208 // -- iteration ---------------------------------------------------------
12209
12210 /// One object's own keys in enumeration order: array indices ascending, then the
12211 /// rest in insertion order.
12212 ///
12213 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
12214 /// whether the key is enumerable, which the caller resolves per key because an
12215 /// array's elements are not in the same store as its named properties.
12216 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
12217 // An index can arrive twice, once from the array's element store and once from
12218 // its property map, so the numeric keys go through a map that keeps the
12219 // enumerable answer if either source gave one.
12220 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
12221 for (key, enumerable) in &own {
12222 if let Some(index) = key.as_str().and_then(array_index) {
12223 let entry = numeric.entry(index).or_insert(false);
12224 *entry = *entry || *enumerable;
12225 }
12226 }
12227 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
12228 .into_iter()
12229 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
12230 .collect();
12231 ordered.extend(
12232 own.into_iter()
12233 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
12234 );
12235 ordered
12236 }
12237
12238 /// Build the key list a `for-in` loop walks.
12239 ///
12240 /// The order is the specification's: own properties before inherited ones, and
12241 /// within one object the integer-like keys in ascending numeric order ahead of the
12242 /// string keys in insertion order. A shadowed key only appears once, and a key that
12243 /// is a non-enumerable own property anywhere nearer is skipped entirely.
12244 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
12245 let record = self.new_object(None);
12246 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
12247 // A proxy supplies its own key list, and — the reason this is not just another
12248 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
12249 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
12250 // descriptor there.
12251 if let Value::Object(object) = value
12252 && object.proxy_state().is_some()
12253 {
12254 let own = self
12255 .proxy_own_keys(object)?
12256 .unwrap_or_else(|| object.own_property_keys());
12257 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
12258 let mut numeric: Vec<u32> = Vec::new();
12259 let mut rest: Vec<PropertyKey> = Vec::new();
12260 for key in own {
12261 match key.as_str().and_then(array_index) {
12262 Some(index) => numeric.push(index),
12263 None => rest.push(key),
12264 }
12265 }
12266 numeric.sort_unstable();
12267 ordered.extend(
12268 numeric
12269 .into_iter()
12270 .map(|index| PropertyKey::from(index.to_string())),
12271 );
12272 ordered.extend(rest);
12273 for (index, key) in ordered.into_iter().enumerate() {
12274 record.define_data(&index.to_string(), self.key_value(&key));
12275 }
12276 record.define_data("__index", Value::Int(0));
12277 // The mark that makes `for_in_advance` re-ask the proxy per key.
12278 record.define_data("__proxy", Value::Object(object.clone()));
12279 return Ok(record);
12280 }
12281 if let Value::Object(object) = value {
12282 let mut chain = vec![object.clone()];
12283 chain.extend(object.chain());
12284 // Every own string key the walk has seen, enumerable or not. A
12285 // non-enumerable own property still hides a same-named enumerable one
12286 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
12287 // keeps `x` out of the loop even when the prototype has one.
12288 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
12289 for object in chain {
12290 let mut own: Vec<(crate::value::Wtf8, bool)> = object
12291 .own_property_keys()
12292 .iter()
12293 .filter_map(|key| key.as_wtf8().cloned())
12294 .map(|key| {
12295 let enumerable = object
12296 .own_property(&key.to_string_lossy())
12297 .map(|property| property.enumerable)
12298 .unwrap_or(false);
12299 (key, enumerable)
12300 })
12301 .collect();
12302 if let Some(length) = object.array_length() {
12303 own.retain(|(key, _)| key.as_str() != Some("length"));
12304 for index in 0..length {
12305 if object.array_get(index).is_some() {
12306 own.push((crate::value::Wtf8::new(index.to_string()), true));
12307 }
12308 }
12309 }
12310 // Integer-like keys come first in ascending order, then the rest in
12311 // insertion order — and the ordering is *per object*, not for the chain
12312 // as a whole: one pass over every collected key lifted a prototype's
12313 // `"4"` above the target's own `x`/`y`, which is not the order
12314 // `for…in` reports.
12315 for (key, enumerable) in Self::order_own_keys(own) {
12316 if visited.contains(&key) {
12317 continue;
12318 }
12319 visited.push(key.clone());
12320 if enumerable {
12321 keys.push(key);
12322 }
12323 }
12324 }
12325 }
12326 for (index, key) in keys.into_iter().enumerate() {
12327 record.define_data(&index.to_string(), self.string_wtf8(key));
12328 }
12329 record.define_data("__index", Value::Int(0));
12330 Ok(record)
12331 }
12332
12333 /// The next key of a `for…in` record, `None` when the loop is done.
12334 ///
12335 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
12336 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
12337 /// the loop reaches it, so a handler that stops reporting a key partway through drops
12338 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
12339 /// key the handler had already withdrawn.
12340 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
12341 let Value::Object(record) = record else {
12342 return Ok(None);
12343 };
12344 let proxy = record
12345 .own_property("__proxy")
12346 .and_then(|property| property.value);
12347 loop {
12348 let index = record
12349 .own_property("__index")
12350 .and_then(|property| property.value)
12351 .map(|value| value.to_int32())
12352 .unwrap_or(0);
12353 let Some(candidate) = record
12354 .own_property(&index.to_string())
12355 .and_then(|property| property.value)
12356 else {
12357 return Ok(None);
12358 };
12359 record.define_data("__index", Value::Int(index + 1));
12360 let text = candidate.to_js_string();
12361 let Some(Value::Object(proxy)) = &proxy else {
12362 return Ok(Some(text));
12363 };
12364 // The candidate is already a key string here, so the lookup does not need a
12365 // second `ToPropertyKey` conversion.
12366 let key = PropertyKey::from(text.as_str());
12367 let live = match self.proxy_get_own_property(proxy, &key)? {
12368 Some(descriptor) => descriptor,
12369 // Not a proxy after all, or it lost its state: fall back to the target.
12370 None => proxy.own_property_key(&key),
12371 };
12372 if live.is_some_and(|property| property.enumerable) {
12373 return Ok(Some(text));
12374 }
12375 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
12376 // next one.
12377 }
12378 }
12379
12380 /// The iterator for `for-of`: the object and its `next` method.
12381 ///
12382 /// An object that already carries a `next` method is used as it is — that is what
12383 /// `arr.values()` returns — and only arrays and strings get the built-in
12384 /// sequence iterator.
12385 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
12386 ///
12387 /// Callers that must choose between the iterable and the array-like protocol — the
12388 /// typed-array constructor is the main one — need to ask *before* committing to one.
12389 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
12390 let key = self.realm.well_known_key(WellKnown::Iterator);
12391 let method = self.read_field_key(value, &key)?;
12392 if matches!(method, Value::Undefined | Value::Null) {
12393 return Ok(false);
12394 }
12395 if !matches!(&method, Value::Object(object) if object.is_callable()) {
12396 return Err(Signal::Throw(
12397 self.make_error("TypeError", "Symbol.iterator is not callable"),
12398 ));
12399 }
12400 Ok(true)
12401 }
12402
12403 /// Collect everything an iterable yields.
12404 ///
12405 /// The cap is a guard against a generator that never ends: an unbounded collect would
12406 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
12407 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
12408 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
12409 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
12410 const MAX_ITEMS: usize = 1 << 24;
12411 let iterator = self.get_iterator(value)?;
12412 let mut out = Vec::new();
12413 loop {
12414 let (element, done) = self.iterator_step(&iterator)?;
12415 if done {
12416 return Ok(out);
12417 }
12418 out.push(element);
12419 if out.len() > MAX_ITEMS {
12420 // Close before refusing: the walk is being abandoned, so the iterator's
12421 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
12422 // unrun and a locked resource unreleased.
12423 self.close_iterator_after_throw(&iterator)?;
12424 return Err(self.range_error("iterable is too long to collect"));
12425 }
12426 }
12427 }
12428
12429 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
12430 ///
12431 /// A native constructor calls this once it has validated its arguments, which is the
12432 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
12433 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
12434 /// never reached. The prototype comes from `new.target` when it is an object, and from
12435 /// `default_proto` otherwise.
12436 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12437 let proto = self.ctor_prototype(default_proto)?;
12438 Ok(self.new_object(Some(proto)))
12439 }
12440
12441 /// An **array** whose prototype comes from `new.target`.
12442 ///
12443 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
12444 /// instance from `new.target.prototype`, and building a plain array instead made every
12445 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
12446 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
12447 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
12448 Ok(JsObject::array(self.heap, Some(proto), 0))
12449 }
12450
12451 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
12452 ///
12453 /// The `Option` form is for the constructors that build their instance in a helper which
12454 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
12455 /// from `await`'s internal promise, and only the first has a `new.target`.
12456 fn ctor_prototype_opt(
12457 &mut self,
12458 default_proto: Option<Gc<JsObject>>,
12459 ) -> JsResult<Option<Gc<JsObject>>> {
12460 let Some(target) = self.pending_new_target.clone() else {
12461 return Ok(default_proto);
12462 };
12463 let Some(target) = target.as_object().cloned() else {
12464 return Ok(default_proto);
12465 };
12466 match self.get_property(&target, "prototype")? {
12467 Some(Value::Object(proto)) => Ok(Some(proto)),
12468 _ => Ok(default_proto),
12469 }
12470 }
12471
12472 /// `new.target.prototype`, or `default_proto` when this is a plain call.
12473 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
12474 let Some(target) = self.pending_new_target.clone() else {
12475 return Ok(default_proto);
12476 };
12477 let Some(target) = target.as_object().cloned() else {
12478 return Ok(default_proto);
12479 };
12480 match self.get_property(&target, "prototype")? {
12481 Some(Value::Object(proto)) => Ok(proto),
12482 _ => Ok(default_proto),
12483 }
12484 }
12485
12486 /// `CreateDataPropertyOrThrow(O, key, value)`.
12487 ///
12488 /// A *definition*, not an assignment. The difference is visible the moment the target
12489 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
12490 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
12491 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
12492 /// refused (`configurable: false`).
12493 ///
12494 /// The fast path exists because this is called once per element by `map`, `filter`,
12495 /// `slice` and friends: a plain array with no custom element descriptors and a writable
12496 /// `length` can store straight into its element vector.
12497 pub fn create_data_property_or_throw(
12498 &mut self,
12499 object: &Gc<JsObject>,
12500 index: usize,
12501 value: Value,
12502 ) -> JsResult<()> {
12503 if object.is_array()
12504 && object.elements_writable()
12505 && !object.has_element_descriptors()
12506 && object.is_extensible()
12507 && object.array_set(self.heap, index, value.clone())
12508 {
12509 return Ok(());
12510 }
12511 let key = PropertyKey::from(index.to_string());
12512 let property = Property {
12513 value: Some(value),
12514 writable: true,
12515 enumerable: true,
12516 configurable: true,
12517 ..Property::default()
12518 };
12519 // `CreateDataProperty` always asks for the default attributes, so it can only ever
12520 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
12521 // the rest. Checking here rather than inside `object_define_own_property` is
12522 // deliberate: that function receives a fully-populated `Property` and cannot tell
12523 // an omitted attribute from an explicit `false`, so the generic check it would need
12524 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
12525 // writable property (that cost eight `Object/defineProperty` tests).
12526 if let Some(existing) = self.object_get_own_property(object, &key)?
12527 && !existing.configurable
12528 {
12529 return Err(self.type_error("cannot create the property"));
12530 }
12531 if self.object_define_own_property(object, &key, property)? {
12532 return Ok(());
12533 }
12534 Err(self.type_error("cannot create the property"))
12535 }
12536
12537 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
12538 ///
12539 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
12540 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
12541 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
12542 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
12543 /// run user code and both can throw.
12544 pub fn species_constructor(
12545 &mut self,
12546 object: &Gc<JsObject>,
12547 default: Value,
12548 ) -> JsResult<Value> {
12549 let Some(constructor) = self.get_property(object, "constructor")? else {
12550 return Ok(default);
12551 };
12552 let constructor = match constructor {
12553 Value::Undefined => return Ok(default),
12554 Value::Object(constructor) => constructor,
12555 _ => return Err(self.type_error("constructor is not an object")),
12556 };
12557 let key = self.realm.well_known_key(WellKnown::Species);
12558 let species = self.get_property_key(&constructor, &key)?;
12559 match species {
12560 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
12561 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
12562 Some(_) => Err(self.type_error("species is not a constructor")),
12563 }
12564 }
12565
12566 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
12567 ///
12568 /// The result is an array of `length` holes whose prototype comes from
12569 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
12570 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
12571 /// is why the `IsArray` check is the first step and not an optimisation.
12572 pub fn array_species_create(
12573 &mut self,
12574 original: &Value,
12575 length: usize,
12576 ) -> JsResult<Gc<JsObject>> {
12577 let Some(object) = original.as_object().cloned() else {
12578 return Ok(self.new_array_of_length(length));
12579 };
12580 if !object.is_array() {
12581 return Ok(self.new_array_of_length(length));
12582 }
12583 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
12584 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
12585 let Some(constructor) = self.get_property(&object, "constructor")? else {
12586 return Ok(self.new_array_of_length(length));
12587 };
12588 let species = match constructor {
12589 Value::Undefined => return Ok(self.new_array_of_length(length)),
12590 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
12591 return Ok(self.new_array_of_length(length));
12592 }
12593 Value::Object(constructor) => {
12594 let key = self.realm.well_known_key(WellKnown::Species);
12595 match self.get_property_key(&constructor, &key)? {
12596 None | Some(Value::Undefined) | Some(Value::Null) => {
12597 return Ok(self.new_array_of_length(length));
12598 }
12599 Some(species) => species,
12600 }
12601 }
12602 _ => return Ok(self.new_array_of_length(length)),
12603 };
12604 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
12605 // that is merely callable is the `create-species-non-ctor` case.
12606 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
12607 return Err(self.type_error("species is not a constructor"));
12608 }
12609 let created = self.construct(species.clone(), species, vec![Value::Int(length as i32)])?;
12610 let Some(created) = created.as_object().cloned() else {
12611 return Err(self.type_error("species constructor did not answer an object"));
12612 };
12613 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
12614 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
12615 // object, and `create-species-with-non-writable-property` asserts exactly that.
12616 // The length is set for the array case; the generic case is the caller's
12617 // `Set(A, "length", …)`.
12618 if created.is_array() {
12619 created.array_set_length(self.heap, length);
12620 }
12621 Ok(created)
12622 }
12623
12624 /// Whether `object` is this realm's `%Array%`.
12625 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
12626 self.realm
12627 .array_constructor
12628 .as_ref()
12629 .is_some_and(|array| array.ptr_eq(object))
12630 }
12631
12632 /// A fresh `length`-hole array with the intrinsic prototype.
12633 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
12634 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
12635 array.array_set_length(self.heap, length);
12636 array
12637 }
12638
12639 /// Whether this call is a construction, i.e. `new.target` is defined.
12640 ///
12641 /// A native constructor receives `this = undefined` (it builds its own instance), so it
12642 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
12643 /// The native function currently executing, if any.
12644 pub fn current_native(&self) -> Option<Gc<JsObject>> {
12645 self.current_native.clone()
12646 }
12647
12648 /// Whether this call is a construction, i.e. `new.target` is defined.
12649 pub fn is_constructing(&self) -> bool {
12650 self.pending_new_target.is_some()
12651 }
12652
12653 /// The `TypeError` a constructor too primitive to have a wrapper raises.
12654 ///
12655 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
12656 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
12657 /// happens inside the native function, which is why the trace carries an
12658 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
12659 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
12660 /// constructor`, and an unnamed one reports the leading space of `" is not a
12661 /// constructor"` because the reference formats the empty name as it is.
12662 ///
12663 /// It is also the answer for a `new.target` that cannot be named at all — not a
12664 /// function, or a throwing `name` getter — where the reference falls back to the bare
12665 /// `not a constructor`.
12666 pub fn not_a_constructor_error(&mut self) -> Signal {
12667 let target = self.pending_new_target.clone().unwrap_or(Value::Undefined);
12668 self.not_a_constructor_error_for(target)
12669 }
12670
12671 /// The same `TypeError` for an explicit target, for the callers that check
12672 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
12673 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
12674 let target = match target {
12675 Value::Object(target) if target.is_callable() => target,
12676 _ => return self.type_error("not a constructor"),
12677 };
12678 let name = match self.get_property(&target, "name") {
12679 Ok(Some(value)) => value.to_js_string(),
12680 _ => return self.type_error("not a constructor"),
12681 };
12682 self.type_error(format!("{name} is not a constructor"))
12683 }
12684
12685 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
12686 ///
12687 /// True whenever `new.target` is not the callee itself, or when it has no usable
12688 /// `prototype` — the cases where reading the property is observable at all.
12689 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
12690 match &self.pending_new_target {
12691 Some(Value::Object(target)) => !target.ptr_eq(callee),
12692 Some(_) => true,
12693 None => false,
12694 }
12695 }
12696
12697 /// The symbol key for one of the engine's own hidden slots.
12698 ///
12699 /// Cached on the realm, so every object of a kind shares one key and a slot can be
12700 /// read back by name.
12701 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
12702 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
12703 return PropertyKey::Symbol(symbol.clone());
12704 }
12705 let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
12706 self.realm
12707 .internal_slots
12708 .borrow_mut()
12709 .insert(name, Value::Symbol(symbol.clone()));
12710 PropertyKey::Symbol(symbol)
12711 }
12712
12713 /// Read a hidden slot, or `None` when the object has none of that name.
12714 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
12715 let slots = self.realm.internal_slots.borrow();
12716 let Value::Symbol(symbol) = slots.get(name)? else {
12717 return None;
12718 };
12719 object
12720 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
12721 .and_then(|property| property.value)
12722 }
12723
12724 /// Define a hidden slot.
12725 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
12726 let key = self.internal_slot(name);
12727 object.define_key(&key, Property::with_attributes(value, false, false));
12728 }
12729
12730 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
12731 ///
12732 /// The method is looked up on the value (through its prototype), called with no
12733 /// arguments, and its result becomes the iterator. A generator gets here through
12734 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
12735 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
12736 ///
12737 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
12738 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
12739 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
12740 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
12741 /// does, and a user-defined iterable works without a special case.
12742 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
12743 /// `Symbol.iterator`.
12744 ///
12745 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
12746 /// iterable is legal there, and each value it produces is simply already settled by
12747 /// the time the `await` around it runs.
12748 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12749 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
12750 let method = self.read_field_key(value, &async_key)?;
12751 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
12752 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
12753 // is *present but not callable* is a TypeError — it does not mean "try the other
12754 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
12755 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
12756 // guard is there to catch.
12757 let absent = matches!(method, Value::Undefined | Value::Null);
12758 if !absent {
12759 let Value::Object(object) = &method else {
12760 return Err(Signal::Throw(
12761 self.make_error("TypeError", "value is not iterable"),
12762 ));
12763 };
12764 if !object.is_callable() {
12765 return Err(Signal::Throw(
12766 self.make_error("TypeError", "value is not iterable"),
12767 ));
12768 }
12769 }
12770 if absent {
12771 return self.get_iterator(value);
12772 }
12773 let iterator = self.call_value(method, value.clone(), Vec::new())?;
12774 if !matches!(iterator, Value::Object(_)) {
12775 return Err(Signal::Throw(
12776 self.make_error("TypeError", "iterator is not an object"),
12777 ));
12778 }
12779 let next = self.read_field(&iterator, "next")?;
12780 Ok(Iterator {
12781 object: iterator,
12782 next,
12783 })
12784 }
12785
12786 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
12787 let key = self.realm.well_known_key(WellKnown::Iterator);
12788 let method = self.read_field_key(value, &key)?;
12789 let Value::Object(function) = &method else {
12790 return Err(Signal::Throw(self.make_error(
12791 "TypeError",
12792 &format!("{} is not iterable", value.to_js_string()),
12793 )));
12794 };
12795 if !function.is_callable() {
12796 return Err(Signal::Throw(self.make_error(
12797 "TypeError",
12798 &format!("{} is not iterable", value.to_js_string()),
12799 )));
12800 }
12801 let iterator = self.call_value(method, value.clone(), Vec::new())?;
12802 // The spec requires an object here; a primitive iterator has no `next` to call
12803 // and would fail one step later with a confusing message.
12804 if !matches!(iterator, Value::Object(_)) {
12805 return Err(Signal::Throw(
12806 self.make_error("TypeError", "iterator is not an object"),
12807 ));
12808 }
12809 let next = self.read_field(&iterator, "next")?;
12810 Ok(Iterator {
12811 object: iterator,
12812 next,
12813 })
12814 }
12815
12816 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
12817 /// cannot replace it.
12818 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
12819 let method = self.read_field(&iterator.object, "return")?;
12820 if matches!(method, Value::Undefined | Value::Null) {
12821 return Ok(());
12822 }
12823 if !matches!(&method, Value::Object(object) if object.is_callable()) {
12824 return Err(self.type_error("iterator return is not a function"));
12825 }
12826 self.call_value(method, iterator.object.clone(), Vec::new())?;
12827 Ok(())
12828 }
12829
12830 /// One step of an internal iterator: the value and whether it is exhausted.
12831 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
12832 // A real iterator (`next` is a function) answers with a result object.
12833 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
12834 let result =
12835 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
12836 let Some(result) = result.as_object().cloned() else {
12837 return Err(self.type_error("iterator result is not an object"));
12838 };
12839 let done = self
12840 .get_property(&result, "done")?
12841 .is_some_and(|value| value.to_boolean());
12842 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
12843 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
12844 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
12845 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
12846 // made an unrelated `value` getter observable after the loop was over.
12847 if done {
12848 return Ok((Value::Undefined, true));
12849 }
12850 let value = self
12851 .get_property(&result, "value")?
12852 .unwrap_or(Value::Undefined);
12853 return Ok((value, false));
12854 }
12855 // An iterator whose `next` is not callable is treated as exhausted, which is
12856 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
12857 // that are not iterable at all.
12858 Ok((Value::Undefined, true))
12859 }
12860
12861 /// `[...iterable]`: append everything the iterator yields, and answer the next
12862 /// index.
12863 ///
12864 /// This goes through the same iterator machinery `for-of` uses rather than copying
12865 /// an array's elements, because a spread source is any iterable: a string spreads
12866 /// into its characters and an array iterator spreads into its results. Handling
12867 /// only arrays made `[..."ab"]` come out empty with no error at all.
12868 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
12869 let Some(target) = array.as_object().cloned() else {
12870 return Ok(0);
12871 };
12872 let start = target.array_length().unwrap_or(0);
12873 let mut added = 0;
12874 let iterator = self.get_iterator(iterable)?;
12875 loop {
12876 let (value, done) = self.iterator_step(&iterator)?;
12877 if done {
12878 break;
12879 }
12880 target.array_set(self.heap, start + added, value);
12881 added += 1;
12882 }
12883 Ok((start + added) as i32)
12884 }
12885
12886 /// How an uncaught exception is reported.
12887 ///
12888 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
12889 /// with `ToString` — `js_std_dump_error` is three lines that end in
12890 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
12891 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
12892 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
12893 ///
12894 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
12895 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
12896 /// `toString`"; it does call it, but only for objects of a class it does not know how
12897 /// to walk, and never for errors, arrays or plain objects.
12898 ///
12899 /// A printer that fails must not take the reporter down with it, so that case falls
12900 /// back to the `ToString` rendering.
12901 pub fn describe_exception(&mut self, value: &Value) -> String {
12902 match crate::print::sprint(self, value) {
12903 Ok(text) => text,
12904 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
12905 }
12906 }
12907
12908 /// The file name of whatever is running, innermost frame first.
12909 ///
12910 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
12911 /// innermost frame's file name, without distinguishing a module body from a plain
12912 /// script. `import()` uses it as the base for a relative specifier, which is why
12913 /// `import('./x.js')` inside a script resolves next to the script and not next to the
12914 /// process's working directory.
12915 pub fn script_or_module_name(&self) -> Option<String> {
12916 self.script_or_module_name_at(0)
12917 }
12918
12919 /// [`Interp::script_or_module_name`] `level` frames further out.
12920 ///
12921 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
12922 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
12923 /// frame without a file name is skipped rather than counted, because a native call
12924 /// pushes no frame of its own and so cannot be a level.
12925 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
12926 self.frames
12927 .iter()
12928 .rev()
12929 .filter_map(|frame| frame.code.code.filename.clone())
12930 .nth(level)
12931 }
12932
12933 /// The current call stack, formatted the way `qjs` prints `error.stack`.
12934 ///
12935 /// One ` at name (file:line:col)` line per active frame, innermost first. The
12936 /// position is the one recorded for the instruction each frame is stopped on, which
12937 /// is why the compiler builds a pc-to-position table per function: without it a
12938 /// trace could only name the function, not the line inside it.
12939 ///
12940 /// A frame whose code has no positions prints just `(file)`, matching the
12941 /// reference's output for stripped bytecode.
12942 pub fn stack_trace(&self) -> String {
12943 self.stack_trace_skipping(0)
12944 }
12945
12946 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
12947 fn stack_trace_skipping(&self, skip: usize) -> String {
12948 // One ordered list, innermost first, so `skip` counts the same thing whether the
12949 // frames it leaves out are native or bytecode. Indices rather than references: a
12950 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
12951 let depth = self.frames.len();
12952 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
12953 // A native entered while `at` bytecode frames were live was called *from* the
12954 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
12955 // entered at the current depth are therefore innermost of all.
12956 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
12957 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
12958 if *at == wanted {
12959 order.push((true, index));
12960 }
12961 }
12962 };
12963 push_natives(&mut order, depth);
12964 for index in (0..depth).rev() {
12965 order.push((false, index));
12966 push_natives(&mut order, index);
12967 }
12968 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
12969 // barrier. Natives entered at exactly the barrier depth are the eval entry point
12970 // itself (`evalScript (native)`), and the reference leaves those out too.
12971 if let Some(barrier) = self.trace_barriers.last().copied() {
12972 order.retain(|(is_native, index)| match is_native {
12973 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
12974 false => *index >= barrier,
12975 });
12976 }
12977
12978 let mut out = String::new();
12979 for (is_native, index) in order.into_iter().skip(skip) {
12980 match is_native {
12981 true => {
12982 out.push_str(" at ");
12983 let (native, _) = &self.native_frames[index];
12984 let name = native
12985 .own_property("name")
12986 .and_then(|property| property.value)
12987 .map(|value| value.to_js_string())
12988 .unwrap_or_default();
12989 out.push_str(&name);
12990 out.push_str(" (native)\n");
12991 }
12992 false => {
12993 let frame = &self.frames[index];
12994 let code = &frame.code.code;
12995 let file = code.filename.as_deref().unwrap_or("<input>");
12996 // The name comes from the function *object*, not from the compiled code:
12997 // an anonymous function expression is named by the property it is stored
12998 // in (`{valueOf: function(){}}`), which only the object knows.
12999 let bound_name = match &frame.callee {
13000 Value::Object(object) => {
13001 object
13002 .own_property("name")
13003 .and_then(|property| match property.value {
13004 Some(Value::String(text)) if !text.wtf8().is_empty() => {
13005 Some(text.to_string_lossy().into_owned())
13006 }
13007 _ => None,
13008 })
13009 }
13010 _ => None,
13011 };
13012 // No callee object means the body was entered by the host, so the
13013 // name has to come from the compiled code. Two cases differ:
13014 //
13015 // * an *unnamed* function of any kind — the reference reads the
13016 // `name` property, finds it empty, and prints `<anonymous>`;
13017 // * a *module* body, which has no `name` property at all: the
13018 // reference builds that function object with `js_closure2` and
13019 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
13020 // so a trace reaching it also prints `<anonymous>` — while a
13021 // *script* body prints `<eval>`, its `name`.
13022 let unnamed = code.name.is_empty() || code.module.is_some();
13023 out.push_str(" at ");
13024 match bound_name.as_deref() {
13025 Some(name) => out.push_str(name),
13026 None if unnamed => out.push_str("<anonymous>"),
13027 None => out.push_str(&code.name),
13028 }
13029 match code.position_at(frame.at as u32) {
13030 Some((line, column)) => {
13031 out.push_str(&format!(" ({file}:{line}:{column})\n"));
13032 }
13033 None => out.push_str(&format!(" ({file})\n")),
13034 }
13035 }
13036 }
13037 }
13038 out
13039 }
13040
13041 /// Give an anonymous function the name of the property it is stored in.
13042 ///
13043 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
13044 /// enumerable and not configurable, and a function that already has a real name
13045 /// keeps it.
13046 ///
13047 /// "Already named" means a *non-empty* name: every function object is created with
13048 /// a `name` of `""` so the property exists on all of them, and treating that empty
13049 /// string as a name left every anonymous function nameless — which is how a stack
13050 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
13051 /// `SetFunctionName`, for a name that came from source text.
13052 fn set_function_name(&mut self, function: &Value, name: &str) {
13053 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
13054 }
13055
13056 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
13057 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
13058 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
13059 let Value::Object(object) = function else {
13060 return;
13061 };
13062 // `SetFunctionName` applies to *functions* and classes only, and only when they are
13063 // anonymous. Without the callability guard, `{value: someObject}` renamed
13064 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
13065 // on the right-hand side of a property. That is how a `zipKeyed` result object
13066 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
13067 // has no `NamedEvaluation` at all.
13068 if !object.is_callable() {
13069 return;
13070 }
13071 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
13072 && !existing.wtf8().is_empty()
13073 {
13074 return;
13075 }
13076 let text = self.string_wtf8(name.clone());
13077 object.define("name", Property::name_or_length(text));
13078 }
13079
13080 // -- global declarations -----------------------------------------------
13081
13082 /// Declare a global binding, creating its reference cell.
13083 /// Declare a `var` or function global, whose home is the global object.
13084 ///
13085 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
13086 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
13087 /// such as `print`, or a redeclaration — is left alone.
13088 pub fn declare_var_global(&mut self, name: &str) {
13089 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
13090 // global object is exactly the leak `typeof my_var === "undefined"` after
13091 // `eval("var my_var=2")` rules out.
13092 if let Some(scope) = self.eval_scope.as_mut() {
13093 scope.entry(name.to_string()).or_insert(Value::Undefined);
13094 return;
13095 }
13096 // A sloppy direct eval declares into its *caller's* variable environment. Doing
13097 // this on the global object instead made `eval("var c = 1")` inside a parameter
13098 // list overwrite a global `c`, and made two calls to the same function share one
13099 // binding.
13100 if let Some(cell) = self.declare_eval_local(name) {
13101 cell.set(Value::Undefined);
13102 return;
13103 }
13104 let global = self.realm.global.clone();
13105 if global.own_property(name).is_some() {
13106 return;
13107 }
13108 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
13109 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
13110 // whole point of that trick and what lets `Object.defineProperty` reshape it
13111 // afterwards. `eval_scope` is `Some` while an eval is running.
13112 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
13113 global.define(
13114 name,
13115 Property {
13116 value: Some(Value::Undefined),
13117 writable: true,
13118 enumerable: true,
13119 configurable: from_eval,
13120 ..Property::default()
13121 },
13122 );
13123 }
13124
13125 /// Declare a *lexical* global binding, which starts in its dead zone.
13126 ///
13127 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
13128 /// global object and is created when its initialiser runs.
13129 pub fn declare_global(&mut self, name: &str, is_const: bool) {
13130 if is_const {
13131 self.realm.lexical_consts.insert(name.to_string());
13132 }
13133 if !self.realm.globals.contains_key(name) {
13134 // `Uninitialized` rather than `Undefined`: the binding exists but is not
13135 // readable until its initialiser runs, and that is what `let x` before
13136 // `x = 1` has to observe.
13137 let cell = self.new_cell(Value::Uninitialized);
13138 self.realm.globals.insert(name.to_string(), cell);
13139 self.realm.declared.push(name.to_string());
13140 }
13141 }
13142}
13143
13144/// The bytecode and environment of a function object, if it is a bytecode function.
13145///
13146/// Extracted before a call so no borrow of the object is held across it.
13147fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
13148 function.with(|data| match &data.kind {
13149 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
13150 _ => None,
13151 })
13152}
13153
13154/// A native call target, extracted before the call so no borrow is held.
13155enum NativeCall {
13156 Native(NativeFn),
13157 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
13158 /// not hold that object's `RefCell` borrow.
13159 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
13160 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
13161 Bound {
13162 target: Value,
13163 this: Value,
13164 leading: Vec<Value>,
13165 },
13166 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
13167 Revoker(crate::object::ProxyRef),
13168 /// A promise's `resolve`.
13169 PromiseResolve(Gc<JsObject>),
13170 /// A promise's `reject`.
13171 PromiseReject(Gc<JsObject>),
13172 /// The executor `NewPromiseCapability(C)` hands a user constructor.
13173 CapabilityExecutor {
13174 state: Gc<JsObject>,
13175 },
13176 /// One leg of a `then` that settles through a user capability.
13177 ThenShim {
13178 handler: Option<Value>,
13179 resolve: Value,
13180 reject: Value,
13181 fulfilled: bool,
13182 },
13183 /// One continuation of an `await`.
13184 AwaitResume {
13185 coroutine: Gc<JsObject>,
13186 promise: Gc<JsObject>,
13187 kind: ResumeKind,
13188 },
13189 /// One element of a `Promise` combinator settling.
13190 CombinatorSettle {
13191 state: Gc<JsObject>,
13192 index: usize,
13193 fulfilled: bool,
13194 },
13195 /// One of `Promise.prototype.finally`'s two shims.
13196 FinallyShim {
13197 callback: Option<Value>,
13198 fulfilled: bool,
13199 constructor: Value,
13200 },
13201 /// Settle a promise with a fixed outcome.
13202 SettlePromise {
13203 promise: Gc<JsObject>,
13204 value: Value,
13205 rejected: bool,
13206 },
13207 /// Continue an async generator after its `await` settled.
13208 GeneratorResume {
13209 generator: Gc<JsObject>,
13210 promise: Gc<JsObject>,
13211 kind: ResumeKind,
13212 },
13213 /// Read a module namespace's binding out of its cell.
13214 ModuleBinding(Gc<Cell>),
13215 /// Finish a completed async generator's `return(v)` once `v` has settled.
13216 CompletedReturn {
13217 generator: Gc<JsObject>,
13218 promise: Gc<JsObject>,
13219 rejected: bool,
13220 },
13221 /// Answer a pending async-generator method with `{value, done}`.
13222 YieldResult {
13223 generator: Gc<JsObject>,
13224 promise: Gc<JsObject>,
13225 done: bool,
13226 },
13227 /// One step of `AsyncDisposableStack.disposeAsync`.
13228 DisposeStep {
13229 remaining: Gc<JsObject>,
13230 promise: Gc<JsObject>,
13231 error: Value,
13232 rejected: bool,
13233 },
13234}
13235
13236/// What a store does when the object refuses the write.
13237#[derive(Clone, Copy, PartialEq, Eq)]
13238pub enum DeleteFailure {
13239 /// Raise a `TypeError`, which is what strict mode and every built-in does.
13240 Throw,
13241 /// Ignore the write, which is what a sloppy-mode assignment does.
13242 Ignore,
13243}
13244
13245/// Whether `object` is a `Date` instance, by the class tag it carries.
13246///
13247/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
13248/// builtins module depending on the interpreter's conversion order.
13249fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
13250 interp
13251 .internal_get(object, "_class")
13252 .is_some_and(|value| value.to_js_string() == "Date")
13253}
13254
13255/// Which type `ToPrimitive` prefers when it converts an object.
13256#[derive(Clone, Copy, PartialEq, Eq)]
13257pub enum Hint {
13258 /// The default hint, which behaves like [`Hint::Number`].
13259 Default,
13260 /// `Number(obj)` and the arithmetic operators.
13261 Number,
13262 /// `String(obj)` and `ToPropertyKey`.
13263 String,
13264}
13265
13266/// Which table a binding slot indexes, for the messages that name it.
13267#[derive(Clone, Copy)]
13268enum VarSlot {
13269 Loc,
13270 Closure,
13271}
13272
13273/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
13274fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
13275 Ok(this)
13276}
13277
13278/// An internal iterator: the sequence plus a cursor.
13279pub(crate) struct Iterator {
13280 pub(crate) object: Value,
13281 pub(crate) next: Value,
13282}
13283
13284/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
13285/// and plain `a` for a method.
13286///
13287/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
13288/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
13289/// reads `at get a (file:1:2)`.
13290/// The same prefixing, for a name that may hold an unpaired surrogate.
13291fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
13292 let prefix = match flags & 3 {
13293 1 => "get ",
13294 2 => "set ",
13295 _ => return key.clone(),
13296 };
13297 let mut units: Vec<u16> = prefix.encode_utf16().collect();
13298 units.extend_from_slice(&key.to_units());
13299 crate::value::Wtf8::from_units(&units)
13300}
13301
13302fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
13303 match flags & 3 {
13304 1 => format!("get {key}"),
13305 2 => format!("set {key}"),
13306 _ => key.to_string(),
13307 }
13308}
13309
13310/// Define a method or accessor property, per the `define_method` flag byte.
13311///
13312/// The low two bits pick value/getter/setter and bit 2 marks the property
13313/// enumerable.
13314///
13315/// A getter and a setter arrive as two separate `define_method` instructions, and the
13316/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
13317/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
13318/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
13319/// `JS_DefineProperty`, which leaves the other half alone.
13320fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
13321 let enumerable = flags & 4 != 0;
13322 let kind = flags & 3;
13323 let existing = object.own_property_key(key);
13324 let property = match kind {
13325 1 => Property {
13326 getter: Some(function),
13327 // The setter half, if this literal already defined one.
13328 setter: existing
13329 .filter(Property::is_accessor)
13330 .and_then(|p| p.setter),
13331 enumerable,
13332 configurable: true,
13333 ..Property::default()
13334 },
13335 2 => Property {
13336 getter: existing
13337 .filter(Property::is_accessor)
13338 .and_then(|p| p.getter),
13339 setter: Some(function),
13340 enumerable,
13341 configurable: true,
13342 ..Property::default()
13343 },
13344 _ => Property {
13345 value: Some(function),
13346 writable: true,
13347 enumerable,
13348 configurable: true,
13349 ..Property::default()
13350 },
13351 };
13352 object.define_key(key, property);
13353}
13354
13355// ---------------------------------------------------------------------------
13356// Operand decoding
13357// ---------------------------------------------------------------------------
13358
13359/// How `print` renders a value: the reference's `JS_PrintValue`.
13360///
13361/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
13362/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
13363/// The format is reproduced closely because the test suite compares output text:
13364///
13365/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
13366/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
13367/// * a cycle prints `[circular N]` with `N` the stack index of the object;
13368/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
13369/// end print as `<N empty item(s)>`;
13370/// * a string is quoted inside a container but raw at the top level, which is why
13371/// `print("x")` and `print(["x"])` differ.
13372pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
13373 // A string argument is printed raw: `js_print` converts it with `ToString`
13374 // instead of dumping it, and the quoting only appears inside a container.
13375 if let Value::String(text) = value {
13376 return text.to_string_lossy().into_owned();
13377 }
13378 let mut printer = Printer {
13379 interp,
13380 out: String::new(),
13381 stack: Vec::new(),
13382 };
13383 printer.value(value, 0);
13384 printer.out
13385}
13386
13387/// The internal class name an object carries, when it has one.
13388fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
13389 interp
13390 .internal_get(object, "_class")
13391 .map(|value| value.to_js_string())
13392}
13393
13394/// A string property, looked up the way `GetProperty` does: own first, then the
13395/// prototype chain. Needed because the print formatter holds the interpreter
13396/// immutably and so cannot run getters.
13397fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
13398 let mut current = Some(object.clone());
13399 // Bounded, because a prototype cycle would otherwise loop forever.
13400 for _ in 0..100 {
13401 let node = current?;
13402 if let Some(property) = node.own_property(name)
13403 && let Some(value) = property.value
13404 {
13405 return Some(value.to_js_string());
13406 }
13407 current = node.with(|data| data.proto.clone());
13408 }
13409 None
13410}
13411
13412/// The `JS_PrintValue` state: output, and the objects currently being printed.
13413struct Printer<'a, 'rt> {
13414 /// Kept for the class-name lookups that typed arrays and `Date` will need.
13415 #[allow(dead_code)]
13416 interp: &'a Interp<'rt>,
13417 out: String,
13418 stack: Vec<Gc<JsObject>>,
13419}
13420
13421impl Printer<'_, '_> {
13422 /// Depth past which a container is summarised by its class name.
13423 const MAX_DEPTH: usize = 2;
13424
13425 fn value(&mut self, value: &Value, level: usize) {
13426 match value {
13427 Value::Undefined
13428 | Value::Uninitialized
13429 | Value::Hole
13430 | Value::CatchOffset(_)
13431 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
13432 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
13433 // The printer writes a bigint the way the language spells one, so a dump is
13434 // unambiguous about which kind of number it is showing.
13435 Value::BigInt(big) => {
13436 self.out.push_str(&big.to_decimal_string());
13437 self.out.push('n');
13438 }
13439 Value::Null => self.out.push_str("null"),
13440 Value::Bool(true) => self.out.push_str("true"),
13441 Value::Bool(false) => self.out.push_str("false"),
13442 Value::Int(number) => self.out.push_str(&number.to_string()),
13443 Value::Float(number) => {
13444 self.out
13445 .push_str(&crate::value::number_to_string_for_print(*number));
13446 }
13447 Value::String(text) => self.print_string(&text.to_string_lossy()),
13448 Value::Object(object) => self.object(object, level),
13449 }
13450 }
13451
13452 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
13453 // A cycle is reported rather than followed; the index is where the object
13454 // already sits in the print stack, which is what the reference shows.
13455 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
13456 self.out.push_str(&format!("[circular {index}]"));
13457 return;
13458 }
13459 if object.is_callable() {
13460 let name = object
13461 .own_property("name")
13462 .and_then(|property| property.value)
13463 .map(|value| value.to_js_string())
13464 .unwrap_or_default();
13465 if name.is_empty() {
13466 self.out.push_str("[Function (anonymous)]");
13467 } else {
13468 self.out.push_str(&format!("[Function {name}]"));
13469 }
13470 return;
13471 }
13472 if level >= Self::MAX_DEPTH {
13473 let class = if object.is_array() { "Array" } else { "Object" };
13474 self.out.push_str(&format!("[{class}]"));
13475 return;
13476 }
13477 // `Date` and `Error` print as themselves rather than as bags of properties:
13478 // the ISO string, and `Name: message` followed by the trace.
13479 if let Some(class) = class_of(self.interp, object) {
13480 if class == "Date" {
13481 self.date(object);
13482 return;
13483 }
13484 if class == "Error" {
13485 self.error(object);
13486 return;
13487 }
13488 }
13489 self.stack.push(object.clone());
13490 if object.is_array() {
13491 self.array(object, level);
13492 } else {
13493 self.plain_object(object, level);
13494 }
13495 self.stack.pop();
13496 }
13497
13498 /// A Date prints as its ISO string; an invalid one falls through to the plain
13499 /// object form, the way the reference falls back when `toISOString` throws.
13500 fn date(&mut self, object: &Gc<JsObject>) {
13501 let value = self
13502 .interp
13503 .internal_get(object, "_date_value")
13504 .map(|value| value.to_number());
13505 match value.and_then(crate::builtins::date::iso_string) {
13506 Some(text) => self.out.push_str(&text),
13507 None => self.plain_object(object, 0),
13508 }
13509 }
13510
13511 /// `Name: message`, then the trace with its trailing newline removed.
13512 fn error(&mut self, object: &Gc<JsObject>) {
13513 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
13514 self.out.push_str(&name);
13515 if let Some(message) = inherited(object, "message")
13516 && !message.is_empty()
13517 {
13518 self.out.push_str(": ");
13519 self.out.push_str(&message);
13520 }
13521 if let Some(stack) = inherited(object, "stack") {
13522 self.out.push('\n');
13523 self.out.push_str(stack.trim_end_matches('\n'));
13524 }
13525 }
13526
13527 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
13528 let elements = object.array_elements().unwrap_or_default();
13529 self.out.push_str("[ ");
13530 // An interior hole means the array is "sparse": the reference prints those
13531 // as `index: value` pairs and says nothing about the holes themselves, while
13532 // a hole run at the end becomes a single `<N empty items>` note.
13533 let last_present = elements
13534 .iter()
13535 .rposition(|value| !matches!(value, Value::Hole));
13536 let has_interior_hole = match last_present {
13537 Some(last) => elements[..last]
13538 .iter()
13539 .any(|value| matches!(value, Value::Hole)),
13540 None => false,
13541 };
13542 let mut first = true;
13543 if has_interior_hole {
13544 let mut index = 0;
13545 while index < elements.len() {
13546 let value = &elements[index];
13547 if matches!(value, Value::Hole) {
13548 index += 1;
13549 continue;
13550 }
13551 if !first {
13552 self.out.push_str(", ");
13553 }
13554 first = false;
13555 self.out.push_str(&format!("{index}: "));
13556 self.value(value, level + 1);
13557 index += 1;
13558 }
13559 } else {
13560 for (index, value) in elements.iter().enumerate() {
13561 if matches!(value, Value::Hole) {
13562 continue;
13563 }
13564 if !first {
13565 self.out.push_str(", ");
13566 }
13567 first = false;
13568 let _ = index;
13569 self.value(value, level + 1);
13570 }
13571 if let Some(last) = last_present {
13572 let trailing = elements.len() - last - 1;
13573 if trailing > 0 {
13574 if !first {
13575 self.out.push_str(", ");
13576 }
13577 self.out.push_str(&format!(
13578 "<{trailing} empty item{}>",
13579 if trailing > 1 { "s" } else { "" }
13580 ));
13581 }
13582 } else if !elements.is_empty() {
13583 let count = elements.len();
13584 self.out.push_str(&format!(
13585 "<{count} empty item{}>",
13586 if count > 1 { "s" } else { "" }
13587 ));
13588 }
13589 }
13590 self.out.push_str(" ]");
13591 }
13592
13593 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
13594 self.out.push_str("{ ");
13595 let mut first = true;
13596 for key in object.own_keys() {
13597 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
13598 continue;
13599 };
13600 if !property.enumerable {
13601 continue;
13602 }
13603 if !first {
13604 self.out.push_str(", ");
13605 }
13606 first = false;
13607 self.out
13608 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
13609 &key.to_string_lossy(),
13610 )));
13611 self.out.push_str(": ");
13612 // An accessor has no value to dump; the reference names the half that
13613 // exists instead of calling it.
13614 if property.is_accessor() {
13615 let text = match (property.getter.is_some(), property.setter.is_some()) {
13616 (true, true) => "[Getter/Setter]",
13617 (false, true) => "[Setter]",
13618 _ => "[Getter]",
13619 };
13620 self.out.push_str(text);
13621 } else {
13622 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
13623 }
13624 }
13625 self.out.push_str(" }");
13626 }
13627
13628 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
13629 fn print_string(&mut self, text: &str) {
13630 self.out.push('"');
13631 for character in text.chars() {
13632 match character {
13633 '"' => self.out.push_str("\\\""),
13634 '\\' => self.out.push_str("\\\\"),
13635 '\n' => self.out.push_str("\\n"),
13636 '\r' => self.out.push_str("\\r"),
13637 '\t' => self.out.push_str("\\t"),
13638 c if (c as u32) < 0x20 => {
13639 self.out.push_str(&format!("\\u{:04x}", c as u32));
13640 }
13641 c => self.out.push(c),
13642 }
13643 }
13644 self.out.push('"');
13645 }
13646}
13647
13648/// How `print` renders a value.
13649///
13650/// `ToString`, except that negative zero keeps its sign — the reference's host
13651/// printer does that while `String(-0)` is `"0"`.
13652pub fn display(value: &Value) -> String {
13653 match value {
13654 Value::Float(number) => crate::value::number_to_string_for_print(*number),
13655 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
13656 "undefined".to_string()
13657 }
13658 other => other.to_js_string(),
13659 }
13660}
13661
13662// ---------------------------------------------------------------------------
13663// Numeric operators
13664// ---------------------------------------------------------------------------
13665
13666/// `a + b` keeping the `Int` representation when it fits.
13667fn add_numbers(left: Value, right: Value) -> Value {
13668 match (&left, &right) {
13669 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
13670 Some(sum) => Value::Int(sum),
13671 None => Value::Float(*a as f64 + *b as f64),
13672 },
13673 _ => Value::Float(left.to_number() + right.to_number()),
13674 }
13675}
13676
13677/// The arithmetic operators other than `+`, which needs string concatenation.
13678fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13679 use Opcode::*;
13680 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
13681 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
13682 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
13683 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
13684 return Ok(match op {
13685 And => Value::Int(x & y),
13686 Or => Value::Int(x | y),
13687 Xor => Value::Int(x ^ y),
13688 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
13689 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
13690 Shr => match (*x as u32) >> ((*y as u32) & 31) {
13691 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
13692 shifted => Value::Float(shifted as f64),
13693 },
13694 Sub => match x.checked_sub(*y) {
13695 Some(value) => Value::Int(value),
13696 None => Value::Float(*x as f64 - *y as f64),
13697 },
13698 _ => return arithmetic_slow(op, left, right),
13699 });
13700 }
13701 arithmetic_slow(op, left, right)
13702}
13703
13704/// [`arithmetic`] for everything the integer fast path above does not take.
13705fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
13706 use Opcode::*;
13707 let (a, b) = (left.to_number(), right.to_number());
13708 Ok(match op {
13709 Sub => match (&left, &right) {
13710 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
13711 Some(value) => Value::Int(value),
13712 None => Value::Float(a - b),
13713 },
13714 _ => Value::Float(a - b),
13715 },
13716 Mul => Value::Float(a * b),
13717 Div => Value::Float(a / b),
13718 Mod => Value::Float(js_mod(a, b)),
13719 Pow => Value::Float(a.powf(b)),
13720 And => Value::Int(left.to_int32() & right.to_int32()),
13721 Or => Value::Int(left.to_int32() | right.to_int32()),
13722 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
13723 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
13724 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
13725 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
13726 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
13727 // fits the small-integer representation stays an `Int`; the rest become a
13728 // float, which is how the reference keeps `n >>> 0` non-negative.
13729 Shr => {
13730 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
13731 match i32::try_from(shifted) {
13732 Ok(value) => Value::Int(value),
13733 Err(_) => Value::Float(shifted as f64),
13734 }
13735 }
13736 _ => Value::Float(a),
13737 })
13738}
13739
13740/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
13741///
13742/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
13743/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
13744/// slow path where the rules live.
13745fn is_number(value: &Value) -> bool {
13746 matches!(value, Value::Int(_) | Value::Float(_))
13747}
13748
13749/// The `Value::Bool` a comparison operator answers for `ordering`.
13750///
13751/// `None` is the unordered case — a `NaN` on either side — and every operator answers
13752/// false for it, including `<=` and `>=`.
13753fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
13754 use Opcode::*;
13755 let answer = match (op, ordering) {
13756 (_, None) => false,
13757 (Lt, Some(ordering)) => ordering.is_lt(),
13758 (Lte, Some(ordering)) => ordering.is_le(),
13759 (Gt, Some(ordering)) => ordering.is_gt(),
13760 (Gte, Some(ordering)) => ordering.is_ge(),
13761 _ => false,
13762 };
13763 Value::Bool(answer)
13764}
13765
13766/// `%`, which follows the sign of the dividend rather than Rust's.
13767fn js_mod(left: f64, right: f64) -> f64 {
13768 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
13769 return f64::NAN;
13770 }
13771 if right.is_infinite() {
13772 return left;
13773 }
13774 let remainder = left % right;
13775 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
13776 // the spec makes the sign match the dividend.
13777 if remainder == 0.0 {
13778 0.0f64.copysign(left)
13779 } else {
13780 remainder
13781 }
13782}
13783
13784fn negate(value: Value) -> Value {
13785 match value {
13786 Value::Int(0) => Value::Float(-0.0),
13787 Value::Int(i) => Value::Int(-i),
13788 other => Value::Float(-other.to_number()),
13789 }
13790}
13791
13792fn increment(value: Value) -> Value {
13793 match value {
13794 Value::Int(i) => match i.checked_add(1) {
13795 Some(next) => Value::Int(next),
13796 None => Value::Float(i as f64 + 1.0),
13797 },
13798 other => Value::Float(other.to_number() + 1.0),
13799 }
13800}
13801
13802fn decrement(value: Value) -> Value {
13803 match value {
13804 Value::Int(i) => match i.checked_sub(1) {
13805 Some(next) => Value::Int(next),
13806 None => Value::Float(i as f64 - 1.0),
13807 },
13808 other => Value::Float(other.to_number() - 1.0),
13809 }
13810}
13811
13812/// Compare a `BigInt` with an `f64` on their mathematical values.
13813///
13814/// Neither side is rounded to the other's precision: the number is split into its integer
13815/// part (compared as an exact bigint) and its fraction, which is what decides the answer
13816/// when the integer parts are equal. An infinite value is larger than every bigint.
13817fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
13818 use std::cmp::Ordering;
13819 if number.is_nan() {
13820 return None;
13821 }
13822 if number.is_infinite() {
13823 return Some(if number > 0.0 {
13824 Ordering::Less
13825 } else {
13826 Ordering::Greater
13827 });
13828 }
13829 let truncated = number.trunc();
13830 // A number wider than `i128` still has an exact integer part, but no bigint form we can
13831 // build cheaply; the sign of the difference is all that is needed, so compare against
13832 // the bigint's own magnitude instead.
13833 if truncated.abs() >= 1.7e38 {
13834 let big_as_f64 = big.to_f64();
13835 return big_as_f64.partial_cmp(&number);
13836 }
13837 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
13838 match big.cmp(&integer) {
13839 Ordering::Equal => {
13840 // Same integer part: the fraction decides, and a negative number's fraction is
13841 // below the integer (`-1.5` truncates to `-1`).
13842 if number > truncated {
13843 Some(Ordering::Less)
13844 } else if number < truncated {
13845 Some(Ordering::Greater)
13846 } else {
13847 Some(Ordering::Equal)
13848 }
13849 }
13850 other => Some(other),
13851 }
13852}