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 **intrinsic** `%Object.prototype.toString%`.
93 ///
94 /// Not a lookup on `Object.prototype`: `Array.prototype.toString` names the intrinsic
95 /// directly, so `delete Object.prototype.toString` does not change its fallback
96 /// (`Array/prototype/toString/non-callable-join-string-tag` deletes it and then calls
97 /// `Array.prototype.toString` on a dozen receivers).
98 pub object_proto_to_string: Option<Gc<JsObject>>,
99 /// The `%Array%` constructor, so `ArraySpeciesCreate` can recognise "the default".
100 pub array_constructor: Option<Gc<JsObject>>,
101 /// The `%Promise%` constructor, for the same reason in `NewPromiseCapability`.
102 pub promise_constructor: Option<Gc<JsObject>>,
103 /// Reference cells for globals declared by the script.
104 ///
105 /// A declared global is read with `get_var` (by name) but written with
106 /// `put_var_ref` (through the cell), so the cell is what makes a function
107 /// declaration and its uses agree on one binding.
108 pub globals: BTreeMap<String, Gc<Cell>>,
109 /// Names of the globals that came from a *declaration*, which are
110 /// non-configurable properties of the global object.
111 pub declared: Vec<String>,
112 /// Names among the lexical globals that are `const`.
113 ///
114 /// `const`-ness cannot be read back off the bytecode in every case: a closure that
115 /// refers to a global `const` gets a `GlobalRef` entry whose flags the forwarding
116 /// path does not carry, so a store through it would look like a plain `let`. The
117 /// realm records it once, at declaration, and answers for every reader.
118 pub lexical_consts: BTreeSet<String>,
119 /// The error constructors by class name, so a runtime error can throw a real
120 /// `TypeError` instance rather than a look-alike object.
121 pub errors: BTreeMap<&'static str, Gc<JsObject>>,
122 /// `String.prototype`, used by `ToString` on primitives and by the boxing path.
123 pub string_proto: Option<Gc<JsObject>>,
124 /// `Number.prototype`.
125 pub number_proto: Option<Gc<JsObject>>,
126 /// `Boolean.prototype`.
127 pub boolean_proto: Option<Gc<JsObject>>,
128 /// `BigInt.prototype`.
129 pub bigint_proto: Option<Gc<JsObject>>,
130 /// `Error.prototype`, the prototype of every error instance.
131 pub error_proto: Gc<JsObject>,
132 /// `Date.prototype`, so the constructor can build an instance in the
133 /// function-call form (`Date()` returns a string) without going through `new`.
134 pub date_proto: Gc<JsObject>,
135 /// `%ThrowTypeError%`, the single frozen thrower behind every restricted property.
136 ///
137 /// §10.2.4 makes it *one* object per realm, and the identity is observable: test262's
138 /// whole `ThrowTypeError/` directory finds it through
139 /// `Object.getOwnPropertyDescriptor(function(){"use strict"; return arguments;}(),
140 /// "callee").get` and then asserts on its `length`, `name`, prototype and frozenness.
141 /// Creating a fresh one per property would make
142 /// `getOwnPropertyDescriptor(Function.prototype, "caller").get ===
143 /// getOwnPropertyDescriptor(Function.prototype, "arguments").get` false.
144 pub throw_type_error: Option<Gc<JsObject>>,
145 /// `%GeneratorPrototype%`, the prototype of every generator object.
146 pub generator_proto: Gc<JsObject>,
147 /// `Promise.prototype`, the prototype of every promise.
148 pub promise_proto: Option<Gc<JsObject>>,
149 /// `%AsyncGeneratorPrototype%`, the prototype of every `async function*` result.
150 pub async_generator_proto: Option<Gc<JsObject>>,
151 /// `%AsyncIteratorPrototype%`, the prototype of `%AsyncGeneratorPrototype%`.
152 ///
153 /// It carries exactly two methods — `@@asyncIterator` and `@@asyncDispose` — and is the
154 /// object test262 reaches through
155 /// `Object.getPrototypeOf(Object.getPrototypeOf(generator.prototype))`.
156 pub async_iterator_proto: Option<Gc<JsObject>>,
157 /// `Symbol.prototype`.
158 pub symbol_proto: Option<Gc<JsObject>>,
159 /// The symbols behind the engine's own hidden slots: `_value`, `_class`,
160 /// `_date_value`.
161 ///
162 /// These are *symbol* keys on purpose. A `"_value"` property is visible to
163 /// `Object.getOwnPropertyNames`, so `new Number(1)` reported an own property the
164 /// language does not have and `new Error()` listed `_class` beside `message` and
165 /// `stack` — and a caller that copies every own property (which
166 /// `Object.create(null, props)` effectively does) tried to write an internal name and
167 /// threw. A symbol key is invisible to `getOwnPropertyNames`, `Object.keys`, `for…in`
168 /// and `JSON.stringify`, while remaining an ordinary traced property.
169 ///
170 /// `RefCell` because interning is memoisation rather than observable state: filling the
171 /// cache through a shared borrow is a detail, not a mutation of the realm. That is what
172 /// lets [`Interp::internal_set`] work from `&self`, which `make_error` needs — an error
173 /// built while reporting a failure must not require an exclusive borrow.
174 pub internal_slots: std::cell::RefCell<BTreeMap<&'static str, Value>>,
175
176 /// The `Symbol.for` registry: `key -> symbol`.
177 ///
178 /// Scoped to the realm, which is what makes `Symbol.for("k")` answer the same
179 /// symbol every time within one script while a fresh realm starts empty.
180 pub symbol_registry: BTreeMap<String, Value>,
181 /// `RegExp.prototype`, filled in by the `RegExp` builtin.
182 pub regexp_proto: Option<Gc<JsObject>>,
183 /// The `RegExp` constructor.
184 pub regexp_ctor: Option<Gc<JsObject>>,
185 /// `SuppressedError.prototype`, which `using` builds its aggregates from.
186 ///
187 /// The prototype rather than the constructor on purpose: a script that replaces
188 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
189 /// error wrapping, which the `using` test suite checks explicitly.
190 pub suppressed_error_proto: Option<Gc<JsObject>>,
191 /// The `DisposableStack` prototype, for `move`'s intrinsic construction.
192 pub disposable_stack_proto: Option<Gc<JsObject>>,
193 /// `Map.prototype`.
194 pub map_proto: Option<Gc<JsObject>>,
195 /// `Set.prototype`.
196 pub set_proto: Option<Gc<JsObject>>,
197 /// Every live `FinalizationRegistry`, held weakly.
198 ///
199 /// The cleanup callback has to run from a *safe point* — a place where script is not
200 /// already executing and no engine borrow is held — and the collector cannot enumerate
201 /// heap objects by type. Registering each registry here gives the drain a list to walk.
202 ///
203 /// The handles are weak on purpose: a registry the script dropped must be collectable,
204 /// and it must not be resurrected merely because the drain knew about it. Entries whose
205 /// target has expired are swept out as the drain walks, so the vector does not grow
206 /// without bound in a program that creates many short-lived registries.
207 pub finalization_registries: Vec<WeakGc<JsObject>>,
208 /// `ArrayBuffer.prototype`.
209 pub array_buffer_proto: Option<Gc<JsObject>>,
210 /// `%TypedArray%.prototype`, the prototype every view type inherits from.
211 pub typed_array_proto: Option<Gc<JsObject>>,
212 /// One prototype per view type, in [`builtins::typedarray::ELEMENT_TYPES`] order.
213 ///
214 /// A typed array answers `map`/`filter`/`slice` with a *new view of the same type*, and
215 /// the result has to carry the per-type prototype — otherwise `r.constructor.name` is
216 /// `"Object"` and `r instanceof Int32Array` is false.
217 pub typed_array_protos: Vec<Gc<JsObject>>,
218 /// `DataView.prototype`.
219 pub data_view_proto: Option<Gc<JsObject>>,
220 /// The `AsyncDisposableStack` prototype.
221 pub async_disposable_stack_proto: Option<Gc<JsObject>>,
222 /// `Iterator.prototype`.
223 pub iterator_proto: Option<Gc<JsObject>>,
224 /// The `Iterator` constructor itself.
225 ///
226 /// `Iterator.prototype.constructor` is an accessor whose getter has to answer this
227 /// object, and the getter is a bare `fn` pointer that cannot capture it — so the only
228 /// place it can live is the realm.
229 pub iterator_ctor: Option<Gc<JsObject>>,
230 /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
231 ///
232 /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
233 /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
234 /// `[object Iterator Helper]`).
235 pub iterator_helper_proto: Option<Gc<JsObject>>,
236 /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
237 /// that was not already an `Iterator`.
238 ///
239 /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
240 /// untouched and does *not* override `@@toStringTag`, so
241 /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
242 pub iterator_wrap_proto: Option<Gc<JsObject>>,
243 /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
244 pub generator_function_proto: Option<Gc<JsObject>>,
245 /// `%AsyncFunction.prototype%`.
246 pub async_function_proto: Option<Gc<JsObject>>,
247 /// `%AsyncGeneratorFunction.prototype%`.
248 pub async_generator_function_proto: Option<Gc<JsObject>>,
249 /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
250 ///
251 /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
252 /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
253 /// prototype per iterator made every array iterator's prototype distinct.
254 pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
255 /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
256 ///
257 /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
258 /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
259 /// both faster and impossible to break from a script.
260 well_known_symbols: WellKnownSymbols,
261 /// The classes the host registered, and the prototype each one hands its instances.
262 pub host_classes: HostClasses,
263}
264
265/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
266///
267/// One per realm, because a class id is only meaningful within the runtime that handed it
268/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
269/// a host class cannot collide.
270pub struct HostClasses {
271 /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
272 /// `JS_GetOpaque(val, 0)` has to match nothing.
273 next_id: u32,
274 /// What each registered class does.
275 defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
276 /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
277 ///
278 /// A strong reference, so the prototype a host installed outlives every script
279 /// reference to it — which is what `JS_SetClassProto` promises.
280 protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
281}
282
283impl HostClasses {
284 fn new() -> HostClasses {
285 HostClasses {
286 next_id: 1,
287 defs: std::collections::BTreeMap::new(),
288 protos: std::collections::BTreeMap::new(),
289 }
290 }
291
292 /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
293 pub fn register(&mut self, def: ClassDef) -> ClassId {
294 let id = ClassId::from_raw(self.next_id);
295 self.next_id += 1;
296 self.defs.insert(id, std::rc::Rc::new(def));
297 id
298 }
299
300 /// Register `def` under an id the caller already has (`JS_NewClass`).
301 ///
302 /// The C API splits "get an id" from "register a class" because a module may be
303 /// initialised lazily; registering twice under one id replaces the definition, and an
304 /// object created under the old one keeps the old behaviour, since it carries its own
305 /// reference.
306 pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
307 if !id.is_valid() {
308 return false;
309 }
310 // Keep the counter past any id handed out explicitly, so a later `register` cannot
311 // reuse one.
312 self.next_id = self.next_id.max(id.get() + 1);
313 self.defs.insert(id, std::rc::Rc::new(def));
314 true
315 }
316
317 /// What `id` was registered with.
318 pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
319 self.defs.get(&id).cloned()
320 }
321
322 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
323 pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
324 self.protos.insert(id, proto);
325 }
326
327 /// The prototype installed for `id`, if the host installed one.
328 pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
329 self.protos.get(&id).cloned()
330 }
331
332 /// How many classes the host registered.
333 pub fn len(&self) -> usize {
334 self.defs.len()
335 }
336
337 /// Whether no class has been registered.
338 pub fn is_empty(&self) -> bool {
339 self.defs.is_empty()
340 }
341}
342
343impl Default for HostClasses {
344 fn default() -> HostClasses {
345 HostClasses::new()
346 }
347}
348
349/// One binding of the frame that called `eval`, so the eval'd code can read and
350/// write it by name.
351struct EvalBinding {
352 /// The name it was declared with.
353 name: String,
354 /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
355 /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
356 /// a function that declares `a` must find that `a`.
357 frame: usize,
358 /// Which table of that frame it lives in.
359 slot: EvalSlot,
360 /// The slot index within that table.
361 index: usize,
362}
363
364/// Which table of a frame an [`EvalBinding`] indexes.
365#[derive(Clone, Copy)]
366enum EvalSlot {
367 Arg,
368 Local,
369}
370
371/// One activation record.
372struct Frame {
373 /// The bytecode being run.
374 code: Gc<CompiledCode>,
375 /// The cells this closure captured.
376 env: Gc<ClosureEnv>,
377 /// The `this` binding.
378 this: Value,
379 /// Argument slots, sized to the declared parameter count.
380 args: Vec<Value>,
381 /// How many values the caller actually passed, which is what `arguments.length`
382 /// reports and what `...rest` slices from.
383 passed_count: usize,
384 /// The passed values, **only when they do not fit in [`Self::args`]**.
385 ///
386 /// `args` is sized to the declared parameters, so a call that passes no more than
387 /// that already holds every passed value in its first `passed_count` slots — copying
388 /// them here as well was two writes and a buffer per call, on the hottest path in
389 /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
390 /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
391 /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
392 /// its own copy.
393 ///
394 /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
395 /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
396 /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
397 /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
398 /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
399 /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
400 #[allow(clippy::box_collection)]
401 passed_overflow: Option<Box<Vec<Value>>>,
402 /// Local slots.
403 locals: Vec<Value>,
404 /// Reference cells for this frame's own captured bindings.
405 cells: Vec<Gc<Cell>>,
406 /// The operand stack.
407 stack: Vec<Value>,
408 /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
409 local_vars: Option<Gc<LocalVars>>,
410
411 /// Index of the next instruction, not a byte offset.
412 ///
413 /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
414 /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
415 /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
416 /// `Frame`, and `frames.push` copies the whole struct on every call.
417 pc: usize,
418 /// Byte offset of the instruction being executed, which is what a stack trace
419 /// reports. `pc` has already moved past it by the time an instruction runs.
420 ///
421 /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
422 at: usize,
423 /// The callee, so a native builtin can tell which constructor it is.
424 callee: Value,
425 /// `new.target`: the constructor under `new`, `undefined` for a plain call.
426 new_target: Value,
427 /// What this frame costs against [`Interp::stack_limit`], in bytes.
428 ///
429 /// Cached rather than recomputed because it is charged on every call and a call is the
430 /// hottest thing in the interpreter.
431 cost: usize,
432 /// [`Interp::stack_used`] before this frame was pushed.
433 ///
434 /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
435 /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
436 /// leave the counter wrong. There are eight places that drop frames; one subtraction
437 /// forgotten in any of them would leak budget until the depth limit moved.
438 stack_base: usize,
439 /// Whether this frame's body ended in a `tail_call`.
440 ///
441 /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
442 /// with its own frame just like `call` does and only skips storing the result
443 /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
444 /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
445 /// pushed as usual, and this marker makes its return value the *caller's* return
446 /// value without running the instructions after the call.
447 tail: bool,
448}
449
450impl Frame {
451 /// Read a local slot, taking the frame as `self`.
452 ///
453 /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
454 /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
455 /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
456 /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
457 /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
458 #[inline]
459 fn read_loc(&self, slot: usize) -> Value {
460 let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
461 if cell == -1 {
462 return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
463 }
464 match self.cells.get(cell as usize) {
465 Some(cell) => cell.get(),
466 None => Value::Undefined,
467 }
468 }
469
470 /// [`Self::read_loc`] for an argument slot.
471 #[inline]
472 fn read_arg(&self, slot: usize) -> Value {
473 let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
474 if cell == -1 {
475 return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
476 }
477 match self.cells.get(cell as usize) {
478 Some(cell) => cell.get(),
479 None => Value::Undefined,
480 }
481 }
482
483 /// The values the caller actually passed, which is what `arguments` exposes.
484 ///
485 /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
486 fn passed(&self) -> &[Value] {
487 match &self.passed_overflow {
488 Some(values) => values,
489 None => &self.args[..self.passed_count],
490 }
491 }
492
493 /// The decoded instructions of the function this frame runs.
494 ///
495 /// A method rather than `frame.code.insns` at the call site so that the borrow is
496 /// obviously of the frame — the dispatch loop holds one across a `get`.
497 fn insns(&self) -> &[crate::insn::Insn] {
498 &self.code.insns
499 }
500}
501
502impl js_gc::Trace for Frame {
503 fn trace(&self, tracer: &mut js_gc::Tracer) {
504 self.code.trace(tracer);
505 self.env.trace(tracer);
506 self.this.trace(tracer);
507 for value in &self.args {
508 value.trace(tracer);
509 }
510 for value in self.passed() {
511 value.trace(tracer);
512 }
513 for value in &self.locals {
514 value.trace(tracer);
515 }
516 for cell in &self.cells {
517 cell.trace(tracer);
518 }
519 if let Some(local_vars) = &self.local_vars {
520 tracer.visit(local_vars);
521 }
522 for value in &self.stack {
523 value.trace(tracer);
524 }
525 self.callee.trace(tracer);
526 self.new_target.trace(tracer);
527 }
528}
529
530/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
531/// emitted `if_false` treats as "keep going".
532/// How many finished frames' value buffers are kept for reuse.
533const RECYCLE_SLOTS: usize = 8;
534
535/// The largest buffer worth keeping. See [`Interp::free_values`].
536const RECYCLE_MAX_CAPACITY: usize = 4096;
537
538const RESUME_NEXT: i32 = 0;
539/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
540/// generator fall into its `return_async`.
541const RESUME_RETURN: i32 = 1;
542/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
543/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
544/// must forward the exception into the inner iterator rather than finish.
545const RESUME_THROW: i32 = 2;
546
547/// One microtask.
548///
549/// The queue holds *data* rather than closures because its contents are GC values: a
550/// closure would be invisible to the collector, and a pending reaction is exactly the
551/// kind of thing that must keep its handlers and its promise alive.
552pub enum Job {
553 /// A `then` reaction about to run.
554 Reaction {
555 /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
556 handler: Option<Value>,
557 /// The value or reason to call it with.
558 argument: Value,
559 /// Whether the source promise rejected, which decides the pass-through kind.
560 rejected: bool,
561 /// The promise the answer settles.
562 promise: Gc<JsObject>,
563 },
564 /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
565 Thenable {
566 /// The `then` that was found on the value.
567 then: Value,
568 /// The thenable itself, which becomes `then`'s `this`.
569 value: Value,
570 /// The promise being resolved.
571 promise: Gc<JsObject>,
572 },
573 /// A pending `import(specifier)`.
574 Import {
575 /// The specifier, already converted to a string.
576 specifier: String,
577 /// The module that asked, which the specifier resolves against.
578 referrer: String,
579 /// The promise `import()` handed back.
580 promise: Gc<JsObject>,
581 },
582 /// An async generator resuming after the value it awaited settled.
583 GeneratorResume {
584 /// The async generator to continue.
585 generator: Gc<JsObject>,
586 /// The promise the pending method returned.
587 promise: Gc<JsObject>,
588 /// Whether this delivers the value or raises the reason.
589 kind: ResumeKind,
590 /// The settled value, or the rejection reason.
591 value: Value,
592 },
593 /// An async function resuming after the value it awaited settled.
594 Resume {
595 /// The body, parked in a coroutine.
596 coroutine: Gc<JsObject>,
597 /// The promise the async function handed its caller.
598 promise: Gc<JsObject>,
599 /// Whether this resumption delivers a value or raises one.
600 kind: ResumeKind,
601 /// The settled value, or the rejection reason.
602 value: Value,
603 },
604}
605
606/// One macro-task: work the event loop owes the script but has not run yet.
607///
608/// The microtask queue ([`Job`]) is different: those run before the host regains control.
609/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
610/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
611/// logic: the engine decides *what* is due, the host decides *how to wait*.
612///
613/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
614/// reference counting even though nothing else references it — the same rule the `HostFn`
615/// documentation states from the other side (a host closure must not hold a `Gc`, so the
616/// `Gc` lives here instead).
617pub enum Task {
618 /// A `setTimeout` that is due at `due_at`.
619 ///
620 /// There is no `setInterval` variant because the reference has no `os.setInterval` at
621 /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
622 /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
623 /// would give this engine a timer the reference cannot produce, with nothing to
624 /// compare it against.
625 Timer {
626 /// The id `setTimeout` returned, for `clearTimeout`.
627 id: i32,
628 /// What to call when it fires.
629 callback: Value,
630 /// When it becomes runnable, as a monotonic instant.
631 due_at: std::time::Instant,
632 },
633}
634
635/// A descriptor the host has to poll, and which directions have a handler.
636///
637/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
638/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
639/// blocks on it, and the host reports back through [`Interp::fire_fd`].
640#[derive(Debug, Clone, Copy, PartialEq, Eq)]
641pub struct FdInterest {
642 /// The descriptor to watch.
643 pub fd: i32,
644 /// Whether `os.setReadHandler` registered a callback.
645 pub read: bool,
646 /// Whether `os.setWriteHandler` registered a callback.
647 pub write: bool,
648}
649
650/// The callbacks registered for one descriptor, per direction.
651#[derive(Default)]
652pub(crate) struct FdHandlers {
653 /// `os.setReadHandler`'s callback.
654 pub read: Option<Value>,
655 /// `os.setWriteHandler`'s callback.
656 pub write: Option<Value>,
657}
658
659/// The file name `eval` reports, which the reference does not inherit from the caller.
660///
661/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
662/// reference and the names show up in stack traces.
663/// The description of the private symbol a class brand is made from.
664///
665/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
666/// place no script can reach, since no expression can name a private symbol.
667const BRAND_DESCRIPTION: &str = "brand";
668
669/// One validated property lookup.
670///
671/// Covers both own-property hits and prototype hits. The second kind was deliberately left
672/// uncached at first ("a prototype hit depends on more than the object and the name"), and
673/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
674/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
675/// names on every iteration (measured: 100 ns per call over an empty loop).
676pub struct FieldCache {
677 /// The name, so two different properties of one object do not collide.
678 key: PropertyKey,
679 /// Where the value was found, relative to the chain below.
680 index: usize,
681 /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
682 level: u8,
683 /// The receiver and every prototype down to (and including) the level that answered,
684 /// each with the length of its property table at the time.
685 ///
686 /// That length is the whole guard, and it is sufficient for the ways the answer can
687 /// change without a lookup: adding or deleting any property moves it, and a
688 /// same-length rewrite is caught by `cached_data_property` re-checking the key and
689 /// refusing an accessor. Storing the *whole* chain — not just the object that answered
690 /// — is what catches a property appearing on an *intermediate* prototype and shadowing
691 /// the one that was cached.
692 ///
693 /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
694 /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
695 chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
696}
697
698/// How many links of a prototype chain a [`FieldCache`] remembers.
699///
700/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
701/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
702/// at three.
703const MAX_CACHED_CHAIN: usize = 3;
704
705/// A remembered global-variable lookup.
706///
707/// A `var` global is an ordinary property of the global object, so reading one walks the
708/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
709/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
710/// fixed by the bytecode, and the slot in the object's table only changes if the global
711/// object is mutated, which the index-and-name check below catches.
712pub struct GlobalCache {
713 /// The global object the lookup was resolved on, weakly.
714 object: js_gc::WeakGc<JsObject>,
715 /// Index of the data property in the global object's table.
716 index: usize,
717}
718
719/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
720const GLOBAL_CACHE_SLOTS: usize = 1024;
721
722/// How many property lookups are remembered.
723///
724/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
725/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
726/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
727/// lookup itself. Making it bigger stops helping: the working set of a real program's
728/// property sites is bounded by its code size.
729const FIELD_CACHE_SLOTS: usize = 4096;
730
731/// How much the heap may grow past the last `out of memory` before saying it again.
732///
733/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
734/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
735/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
736/// because it looks like it works. The reference gets this for free: it fails inside
737/// `js_malloc`, and its printing path happens not to allocate.
738///
739/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
740/// allocating is stopped within a rounding error of the limit) and far above what a
741/// handler needs.
742const OOM_HYSTERESIS: usize = 64 * 1024;
743
744/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
745pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
746
747/// How many instructions run between polls of [`Interp::interrupt`].
748///
749/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
750/// order of magnitude on both implementations — which is what lets a C driver compare its
751/// output byte for byte (see `scripts/m15-capi.sh --embed`).
752pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
753
754/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
755///
756/// Chosen so that the byte budget is what actually decides for every ordinary
757/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
758/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
759/// millions of frames.
760pub const MAX_FRAMES: usize = 200_000;
761
762const EVAL_FILE: &str = "<input>";
763
764/// The file name `std.evalScript` reports.
765const EVAL_SCRIPT_FILE: &str = "<evalScript>";
766
767/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
768///
769/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
770/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
771fn clamp_delay(delay_ms: f64) -> std::time::Duration {
772 // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
773 // on a float, which reads as a typo even when it is deliberate. Both NaN and a
774 // non-positive delay mean "due now".
775 if delay_ms.is_nan() || delay_ms <= 0.0 {
776 return std::time::Duration::ZERO;
777 }
778 std::time::Duration::from_secs_f64(delay_ms / 1000.0)
779}
780
781impl js_gc::Trace for Task {
782 fn trace(&self, tracer: &mut js_gc::Tracer) {
783 let Task::Timer { callback, .. } = self;
784 callback.trace(tracer);
785 }
786}
787
788/// What one turn of the event loop did, so the caller cannot spin by accident.
789///
790/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
791/// core until the timer is due. Naming the three cases makes the wait explicit.
792#[derive(Debug, Clone, Copy, PartialEq, Eq)]
793pub enum Turn {
794 /// Something ran. Call again immediately — there may be more ready work.
795 Ran,
796 /// Nothing is runnable, but descriptors are registered: the host must poll
797 /// [`Interp::pending_fds`] for at most this long, then report readiness with
798 /// [`Interp::fire_fd`].
799 ///
800 /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
801 /// the failure this project treats as worst — a handler that silently never fires —
802 /// so the two cannot be confused by accident.
803 Poll(std::time::Duration),
804 /// Nothing is runnable yet, but something is pending. Block at most this long, then
805 /// call again.
806 Wait(std::time::Duration),
807 /// Nothing is pending at all: the loop is done.
808 Done,
809}
810
811impl js_gc::Trace for Job {
812 fn trace(&self, tracer: &mut js_gc::Tracer) {
813 match self {
814 Job::Reaction {
815 handler,
816 argument,
817 promise,
818 ..
819 } => {
820 if let Some(handler) = handler {
821 handler.trace(tracer);
822 }
823 argument.trace(tracer);
824 tracer.visit(promise);
825 }
826 Job::Thenable {
827 then,
828 value,
829 promise,
830 } => {
831 then.trace(tracer);
832 value.trace(tracer);
833 tracer.visit(promise);
834 }
835 Job::Resume {
836 coroutine,
837 promise,
838 value,
839 ..
840 } => {
841 tracer.visit(coroutine);
842 tracer.visit(promise);
843 value.trace(tracer);
844 }
845 Job::Import { promise, .. } => tracer.visit(promise),
846 Job::GeneratorResume {
847 generator,
848 promise,
849 value,
850 ..
851 } => {
852 tracer.visit(generator);
853 tracer.visit(promise);
854 value.trace(tracer);
855 }
856 }
857 }
858}
859
860/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
861#[derive(Debug, Clone, Copy, PartialEq, Eq)]
862pub enum ResumeKind {
863 /// The generator was just created and is being run to its first suspension.
864 Start,
865 /// `next(v)`.
866 Next,
867 /// `return(v)`.
868 Return,
869 /// `throw(e)`.
870 Throw,
871}
872
873/// A generator object's saved execution.
874///
875/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
876/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
877/// separately allocated buffers.
878pub struct GeneratorState {
879 /// The detached frame, or `None` once the generator has finished or while it runs.
880 frame: Option<Frame>,
881 /// How far it got.
882 phase: GeneratorPhase,
883 /// Whether the last suspension was an `await` rather than a `yield`.
884 ///
885 /// The two resume with *different stack shapes*: a `yield` is re-entered with the
886 /// value and a magic number, because the emitted code branches on which method
887 /// resumed it, while an `await` simply continues with its value. Getting this wrong
888 /// leaves an extra value on the operand stack that the next instruction then
889 /// consumes — a wrong answer rather than a crash.
890 parked_on_await: bool,
891 /// Whether the last suspension was a `yield*` rather than a plain `yield`.
892 ///
893 /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
894 /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
895 /// has to be forwarded into the inner iterator's `throw` method instead — which is the
896 /// `rethrow` branch the compiled delegation emits — because that is the whole point of
897 /// delegating. Tracking it as part of the phase, the way the reference splits
898 /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
899 /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
900 /// exception and never reached `xs.throw`.
901 parked_on_yield_star: bool,
902 /// Pending `next`/`return`/`throw` calls, oldest first.
903 ///
904 /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
905 /// called back to back must answer in that order, with the second call's value
906 /// arriving at the *second* `yield`. Running each call straight into the body — which
907 /// is what this engine did before — delivered the last queued value to whichever
908 /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
909 /// `a === b ===` the final argument.
910 ///
911 /// The front entry is the one being served; it stays there (with `async_busy` set)
912 /// until its promise settles, because an `await` inside the body is a suspension of
913 /// the *driver*, not the end of the request.
914 requests: std::collections::VecDeque<AsyncRequest>,
915 /// Whether the front request is in flight.
916 async_busy: bool,
917 /// Whether this came from an `async function*`.
918 ///
919 /// A sync generator and an async one share `ObjectKind::Generator`, so without this
920 /// flag `%AsyncGeneratorPrototype%.next` happily ran a sync generator's body:
921 /// `AsyncGeneratorValidate` has to tell them apart
922 /// (`AsyncGeneratorPrototype/next/this-val-not-async-generator.js`).
923 pub is_async: bool,
924}
925
926/// How one async-generator request ended.
927enum AsyncOutcome {
928 /// The method answered this `{value, done}`.
929 Value(Value),
930 /// The body threw.
931 Error(Value),
932}
933
934/// One queued `next`/`return`/`throw` on an async generator: the reference's
935/// `JSAsyncGeneratorRequest`.
936pub struct AsyncRequest {
937 /// Which method was called.
938 kind: ResumeKind,
939 /// Its argument.
940 value: Value,
941 /// The promise the method answered.
942 promise: Gc<JsObject>,
943}
944
945/// Which of §27.5.3.3's states a generator is in.
946#[derive(Debug, Clone, Copy, PartialEq, Eq)]
947enum GeneratorPhase {
948 /// Created, `initial_yield` reached, body not entered.
949 SuspendedStart,
950 /// Parked at a `yield`.
951 SuspendedYield,
952 /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
953 Executing,
954 /// Finished; the frame is gone.
955 Completed,
956}
957
958impl js_gc::Trace for GeneratorState {
959 fn trace(&self, tracer: &mut js_gc::Tracer) {
960 if let Some(frame) = &self.frame {
961 frame.trace(tracer);
962 }
963 for request in &self.requests {
964 request.value.trace(tracer);
965 tracer.visit(&request.promise);
966 }
967 }
968}
969
970/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
971/// them in.
972///
973/// Each is a field rather than a map entry because the runtime reads them on hot paths
974/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
975/// failure — reaching a default here means the builtin did not install, and every
976/// accessor panics rather than silently answering `undefined`.
977///
978/// [`builtins::symbol`]: crate::builtins::symbol
979#[derive(Default)]
980pub struct WellKnownSymbols {
981 /// The symbol values, positionally. Empty until `Symbol` installs.
982 symbols: Vec<Value>,
983}
984
985/// Which well-known symbol a caller wants.
986///
987/// A typed accessor beats passing a name around: a typo is a compile error rather than
988/// an `undefined` key that quietly matches nothing.
989#[derive(Debug, Clone, Copy, PartialEq, Eq)]
990pub enum WellKnown {
991 /// `Symbol.toPrimitive`.
992 ToPrimitive,
993 /// `Symbol.iterator`.
994 Iterator,
995 /// `Symbol.match`.
996 Match,
997 /// `Symbol.matchAll`.
998 MatchAll,
999 /// `Symbol.replace`.
1000 Replace,
1001 /// `Symbol.search`.
1002 Search,
1003 /// `Symbol.split`.
1004 Split,
1005 /// `Symbol.toStringTag`.
1006 ToStringTag,
1007 /// `Symbol.isConcatSpreadable`.
1008 IsConcatSpreadable,
1009 /// `Symbol.hasInstance`.
1010 HasInstance,
1011 /// `Symbol.species`.
1012 Species,
1013 /// `Symbol.unscopables`.
1014 Unscopables,
1015 /// `Symbol.asyncIterator`.
1016 AsyncIterator,
1017 /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
1018 Disposable,
1019 /// `Symbol.asyncDispose` — the awaited form.
1020 AsyncDisposable,
1021}
1022
1023impl WellKnown {
1024 /// The index `Symbol`'s installer creates this symbol at.
1025 fn index(self) -> usize {
1026 match self {
1027 WellKnown::ToPrimitive => 0,
1028 WellKnown::Iterator => 1,
1029 WellKnown::Match => 2,
1030 WellKnown::MatchAll => 3,
1031 WellKnown::Replace => 4,
1032 WellKnown::Search => 5,
1033 WellKnown::Split => 6,
1034 WellKnown::ToStringTag => 7,
1035 WellKnown::IsConcatSpreadable => 8,
1036 WellKnown::HasInstance => 9,
1037 WellKnown::Species => 10,
1038 WellKnown::Unscopables => 11,
1039 WellKnown::AsyncIterator => 12,
1040 WellKnown::Disposable => 13,
1041 WellKnown::AsyncDisposable => 14,
1042 }
1043 }
1044}
1045
1046impl Realm {
1047 /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1048 pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1049 self.well_known_symbols.symbols = symbols;
1050 }
1051
1052 /// A well-known symbol.
1053 pub fn well_known(&self, which: WellKnown) -> Value {
1054 self.well_known_symbols
1055 .symbols
1056 .get(which.index())
1057 .cloned()
1058 .unwrap_or(Value::Undefined)
1059 }
1060
1061 /// The well-known symbol as a property key.
1062 pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1063 match self.well_known(which) {
1064 Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1065 // Unreachable once `Symbol` has installed; an empty string key matches
1066 // nothing, which degrades to "the object has no such method".
1067 _ => PropertyKey::from(String::new()),
1068 }
1069 }
1070}
1071
1072/// The interpreter: a realm plus a frame stack.
1073pub struct Interp<'a> {
1074 /// The heap everything is allocated on.
1075 pub heap: &'a Heap,
1076 /// The realm.
1077 pub realm: Realm,
1078 /// Active frames, outermost first.
1079 frames: Vec<Frame>,
1080 /// Value buffers from frames that have finished, reused by the next call.
1081 ///
1082 /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1083 /// the locals and the operand stack — and free all four on return. `call:recursion`
1084 /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1085 /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1086 ///
1087 /// Bounded in both directions: a few buffers per kind, and none larger than
1088 /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1089 /// and keeping its buffer would pin that memory for the rest of the run.
1090 free_values: Vec<Vec<Value>>,
1091 /// A strict-mode `eval`'s own variable scope, while its script runs.
1092 ///
1093 /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1094 /// become a global. Name lookups still fall through to the realm, which is why
1095 /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1096 eval_scope: Option<BTreeMap<String, Value>>,
1097 /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1098 /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1099 eval_depth: usize,
1100 /// The calling frame's own bindings, which the running `eval` can read and write.
1101 ///
1102 /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1103 /// come from the frame, and a write is applied back to the frame (or to the cell
1104 /// the frame captured) when the eval finishes. That is what makes
1105 /// `f("a = 3")` visible to the caller as `a === 3`.
1106 eval_bindings: Vec<EvalBinding>,
1107 /// The calling frame's `arguments`, while an `eval` runs.
1108 ///
1109 /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1110 /// own yet still has to see the caller's `arguments`.
1111 eval_arguments: Option<Value>,
1112 /// The `with` objects live at the moment the running `eval` started, innermost first.
1113 ///
1114 /// `None` outside an eval, which is what keeps a finished block's object from
1115 /// shadowing ordinary bytecode reads.
1116 eval_with: Option<Vec<Gc<JsObject>>>,
1117 /// The bindings the running direct `eval` makes visible, as name → cell.
1118 ///
1119 /// Set for the duration of an eval and then restored, but every closure created
1120 /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1121 /// `eval("f = () => i")` work after the eval has returned.
1122 active_eval_scope: Option<Gc<EvalScope>>,
1123 /// The frame that called the direct `eval` currently running, if any.
1124 ///
1125 /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1126 /// on the global object, which is what keeps
1127 /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1128 /// gives each call its own `x`.
1129 eval_caller: Option<Option<usize>>,
1130 /// The caller's `new.target`, while an `eval` runs.
1131 ///
1132 /// The eval'd code is a script with no constructor of its own, so it inherits the
1133 /// one the enclosing function was called with.
1134 eval_new_target: Option<Value>,
1135 /// `new.target` for the frame about to be pushed.
1136 ///
1137 /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1138 /// value reaches the frame without threading a parameter through every call site.
1139 ///
1140 /// A **native** has no frame, so `call_value` takes it the same way and moves it to
1141 /// [`Interp::active_new_target`] for the duration of the call. Without that, a plain
1142 /// `native()` made from inside a constructor body saw the enclosing `new.target` — the
1143 /// value was parked for the outer call and never consumed.
1144 pending_new_target: Option<Value>,
1145 /// `new.target` of the call currently running, for [`Interp::current_new_target`].
1146 ///
1147 /// `undefined` outside a `new` call.
1148 active_new_target: Value,
1149 /// Names of the native functions currently executing, outermost first.
1150 ///
1151 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1152 /// trace still names it with `(native)` instead of a position, so the names are
1153 /// tracked separately and stitched into [`Interp::stack_trace`].
1154 ///
1155 /// The third field is how many bytecode frames were live when the native was entered,
1156 /// which is what places it *among* them rather than before all of them. Native
1157 /// functions used to be emitted up front on the grounds that they never re-enter
1158 /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1159 /// The natives currently running, innermost last: the function object and the
1160 /// depth it was entered at.
1161 ///
1162 /// The *name* is deliberately not stored. It used to be, read with
1163 /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1164 /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1165 /// benchmark. A stack trace is built rarely; it can read the name then.
1166 native_frames: Vec<(Gc<JsObject>, usize)>,
1167 /// The native function currently executing, for the ones that have to know *which*
1168 /// function they are — a typed-array constructor reads its element type off itself.
1169 ///
1170 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1171 /// reports whatever the enclosing bytecode frame was called with.
1172 current_native: Option<Gc<JsObject>>,
1173 /// Text written by `print` and friends, in order.
1174 ///
1175 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1176 /// once at the end, which is also when upstream's line buffering becomes
1177 /// visible for the cases compared here.
1178 pub output: String,
1179 /// Where `print` also writes, as it goes. `output` keeps the full log for
1180 /// [`crate::Context::output`]; this is the live copy, flushed per line.
1181 ///
1182 /// Both exist on purpose. A host that gives a script a sink sees output *when it
1183 /// happens* — which is what a timer callback's `console.log` has to do, and what the
1184 /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1185 /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1186 /// would show a script's output all at once when it finished.
1187 pub output_sink: Option<Box<dyn std::io::Write>>,
1188 /// Where recent property reads found their value.
1189 ///
1190 /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1191 /// table remembering *which object* and *which entry of its property table* answered a
1192 /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1193 /// can move; the property can become an accessor), which is what makes a stale entry a
1194 /// miss rather than a wrong answer.
1195 ///
1196 /// The object is held weakly: a cache that held it strongly would keep up to
1197 /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1198 /// program cannot see and cannot work around.
1199 pub field_cache: Vec<Option<FieldCache>>,
1200 /// Global lookups, by binding slot. See [`GlobalCache`].
1201 global_cache: Vec<Option<GlobalCache>>,
1202 /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1203 /// under its limit. See [`Interp::check_memory`].
1204 pub oom_reported_at: usize,
1205 /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1206 /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1207 ///
1208 /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1209 /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1210 /// host that wants to stop a runaway script must not have to wait for it to return.
1211 ///
1212 /// Two things this cannot do, both of them differences a host can observe:
1213 ///
1214 /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1215 /// uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1216 /// needs a signal that the `catch` machinery does not see, which is a change to
1217 /// [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1218 /// a host that stops the script itself.
1219 /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1220 /// also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1221 /// both, so the difference is when the counter hits zero, not whether it will.
1222 pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1223 /// Instructions until the next [`Interp::interrupt`] poll.
1224 pub interrupt_counter: u32,
1225 /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1226 ///
1227 /// A separate field from [`Interp::uncatchable`] because the two live for different
1228 /// spans. This one is the host's standing request; it survives the start of an
1229 /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1230 /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1231 /// for both was the first attempt and it did nothing at all: the outermost `execute`
1232 /// cleared it before the script it was set for had a chance to throw.
1233 pub uncatchable_next: bool,
1234 /// Whether the exception now unwinding may be caught by a `catch`.
1235 ///
1236 /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1237 /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1238 /// a host stopping a runaway loop is not fought by the loop.
1239 ///
1240 /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1241 /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1242 /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1243 /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1244 pub uncatchable: bool,
1245 /// The most stack a JavaScript call chain may use, in bytes of frame state.
1246 ///
1247 /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1248 /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1249 /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1250 /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1251 /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1252 /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1253 ///
1254 /// The numbers come out close for the same reason a C frame and a heap frame of this
1255 /// shape cost about the same (both are a few hundred bytes, dominated by the value
1256 /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1257 /// and this engine lands in the same neighbourhood — measured, not fudged, by
1258 /// `crates/quickjs-cli/tests/limits.rs`.
1259 pub stack_limit: usize,
1260 /// The most frames that may be live at once, whatever the byte budget says.
1261 ///
1262 /// A second bound for a reason the reference does not have: our frames cost less than
1263 /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1264 /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1265 /// `--stack-size 1G` from being a memory bomb.
1266 pub max_frames: usize,
1267 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1268 ///
1269 /// Script execution does not return until this has drained, which is what makes
1270 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1271 /// than never. Reactions append to it while it drains, so the loop is a `while` and
1272 /// not a `for`.
1273 pub(crate) jobs: std::collections::VecDeque<Job>,
1274 /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1275 ///
1276 /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1277 /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1278 pub(crate) tasks: Vec<Task>,
1279 /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1280 /// barrier'd evaluation started.
1281 ///
1282 /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1283 /// lets a REPL report an error from the line it just evaluated without also reporting
1284 /// its own readline loop.
1285 trace_barriers: Vec<usize>,
1286 /// `os.signal` handlers, keyed by signal number.
1287 ///
1288 /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1289 /// a handler cannot be freed while it is still registered.
1290 pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1291 /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1292 ///
1293 /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1294 /// that is only reachable from a host closure could be freed while still registered.
1295 pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1296 /// The next timer id.
1297 ///
1298 /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1299 /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1300 next_timer_id: i32,
1301 /// Errors thrown by timer callbacks, already rendered.
1302 ///
1303 /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1304 /// that throws has no promise behind it. Both are reported by the host at the end of
1305 /// the loop, but only one is fixed up by a later `.catch`.
1306 timer_errors: Vec<String>,
1307 /// The module registry, keyed by canonical name.
1308 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1309 /// How the host turns a specifier into bytes.
1310 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1311 /// The module the host was asked to run, for `import.meta.main`.
1312 pub main_module_name: Option<String>,
1313 /// Module bodies currently running, innermost last.
1314 ///
1315 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1316 /// this is the only place that knows which module that is.
1317 pub module_stack: Vec<String>,
1318 /// Rejections that no handler has claimed, with the promise they belong to.
1319 ///
1320 /// A `then` registered later prunes its entry, which is why the promise is kept: the
1321 /// reason alone cannot say whether somebody eventually listened.
1322 unhandled: Vec<(Gc<JsObject>, Value)>,
1323}
1324
1325impl<'a> Interp<'a> {
1326 /// Build an interpreter over `heap`, with a fresh realm.
1327 pub fn new(heap: &'a Heap) -> Interp<'a> {
1328 let object_proto = JsObject::ordinary(heap, None);
1329 let function_proto = JsObject::function(
1330 heap,
1331 Some(object_proto.clone()),
1332 Callable::Native {
1333 func: |_, _, _| Ok(Value::Undefined),
1334 own_instance: false,
1335 },
1336 );
1337 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1338 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1339 let mut interp = Interp {
1340 heap,
1341 realm: Realm {
1342 global,
1343 object_proto,
1344 function_proto,
1345 array_proto,
1346 array_constructor: None,
1347 promise_constructor: None,
1348 object_proto_to_string: None,
1349 globals: BTreeMap::new(),
1350 declared: Vec::new(),
1351 lexical_consts: BTreeSet::new(),
1352 errors: BTreeMap::new(),
1353 string_proto: None,
1354 number_proto: None,
1355 boolean_proto: None,
1356 bigint_proto: None,
1357 error_proto: JsObject::ordinary(heap, None),
1358 date_proto: JsObject::ordinary(heap, None),
1359 throw_type_error: None,
1360 generator_proto: JsObject::ordinary(heap, None),
1361 promise_proto: None,
1362 async_generator_proto: None,
1363 async_iterator_proto: None,
1364 symbol_proto: None,
1365 symbol_registry: BTreeMap::new(),
1366 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1367 regexp_proto: None,
1368 regexp_ctor: None,
1369 suppressed_error_proto: None,
1370 disposable_stack_proto: None,
1371 map_proto: None,
1372 set_proto: None,
1373 finalization_registries: Vec::new(),
1374 array_buffer_proto: None,
1375 typed_array_proto: None,
1376 typed_array_protos: Vec::new(),
1377 data_view_proto: None,
1378 async_disposable_stack_proto: None,
1379 iterator_proto: None,
1380 iterator_ctor: None,
1381 iterator_helper_proto: None,
1382 iterator_wrap_proto: None,
1383 generator_function_proto: None,
1384 async_function_proto: None,
1385 async_generator_function_proto: None,
1386 iterator_protos: std::collections::BTreeMap::new(),
1387 well_known_symbols: WellKnownSymbols::default(),
1388 host_classes: HostClasses::new(),
1389 },
1390 frames: Vec::new(),
1391 free_values: Vec::new(),
1392 global_cache: {
1393 let mut cache = Vec::new();
1394 cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1395 cache
1396 },
1397 eval_scope: None,
1398 eval_depth: 0,
1399 eval_bindings: Vec::new(),
1400 eval_arguments: None,
1401 eval_with: None,
1402 active_eval_scope: None,
1403 eval_caller: None,
1404 pending_new_target: None,
1405 active_new_target: Value::Undefined,
1406 eval_new_target: None,
1407 native_frames: Vec::new(),
1408 current_native: None,
1409 output: String::new(),
1410 output_sink: None,
1411 field_cache: {
1412 let mut cache = Vec::new();
1413 cache.resize_with(FIELD_CACHE_SLOTS, || None);
1414 cache
1415 },
1416 oom_reported_at: 0,
1417 interrupt: None,
1418 interrupt_counter: INTERRUPT_POLL_INTERVAL,
1419 uncatchable_next: false,
1420 uncatchable: false,
1421 // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1422 // absent.
1423 stack_limit: DEFAULT_STACK_SIZE,
1424 max_frames: MAX_FRAMES,
1425 jobs: std::collections::VecDeque::new(),
1426 tasks: Vec::new(),
1427 trace_barriers: Vec::new(),
1428 signal_handlers: std::collections::BTreeMap::new(),
1429 fd_handlers: std::collections::BTreeMap::new(),
1430 next_timer_id: 1,
1431 timer_errors: Vec::new(),
1432 modules: std::collections::BTreeMap::new(),
1433 module_loader: None,
1434 main_module_name: None,
1435 module_stack: Vec::new(),
1436 unhandled: Vec::new(),
1437 };
1438 crate::builtins::install(&mut interp);
1439 interp
1440 }
1441
1442 // -- allocation helpers -------------------------------------------------
1443
1444 /// A new string value.
1445 /// A `BigInt` value from a computed big integer.
1446 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1447 Value::BigInt(Gc::new(self.heap, value))
1448 }
1449
1450 /// A string value from bytes that are already WTF-8, which is how a string with an
1451 /// unpaired surrogate reaches a `Value`.
1452 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1453 Value::string_wtf8(self.heap, text)
1454 }
1455
1456 /// A new string value, from text that is valid UTF-8.
1457 pub fn string(&self, text: impl Into<String>) -> Value {
1458 Value::string(self.heap, text)
1459 }
1460
1461 /// A new ordinary object with the given prototype.
1462 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1463 JsObject::ordinary(self.heap, proto)
1464 }
1465
1466 // -- host classes -------------------------------------------------------
1467
1468 /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1469 pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1470 self.realm.host_classes.register(def)
1471 }
1472
1473 /// Register `def` under an id the host already holds (`JS_NewClass`).
1474 ///
1475 /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1476 /// `JS_NewClass`.
1477 pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1478 self.realm.host_classes.define(id, def)
1479 }
1480
1481 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1482 pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1483 self.realm.host_classes.set_proto(id, proto);
1484 }
1485
1486 /// The prototype installed for `id`, if any.
1487 pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1488 self.realm.host_classes.proto(id)
1489 }
1490
1491 /// A new instance of `id` (`JS_NewObjectProtoClass`).
1492 ///
1493 /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1494 /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1495 /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1496 /// host installed none.
1497 ///
1498 /// Answers `None` for an id that was never registered: the C API would return an
1499 /// exception, and silently making an ordinary object instead would move the failure to
1500 /// the first `JS_GetOpaque` that no longer matches.
1501 pub fn new_host_object(
1502 &mut self,
1503 proto: Option<Gc<JsObject>>,
1504 class_id: ClassId,
1505 ) -> Option<Gc<JsObject>> {
1506 let class = self.realm.host_classes.def(class_id)?;
1507 let proto = proto
1508 .or_else(|| self.realm.host_classes.proto(class_id))
1509 .or_else(|| Some(self.realm.object_proto.clone()));
1510 Some(JsObject::host_object(self.heap, proto, class_id, class))
1511 }
1512
1513 /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1514 ///
1515 /// `None` covers both answers the C API gives as a null pointer — the value is not an
1516 /// object, it is an object of another class, or the class never got a payload. A host
1517 /// that has to tell them apart uses [`JsObject::host_class_id`].
1518 pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1519 let object = value.as_object()?;
1520 if object.host_class_id()? != class_id {
1521 return None;
1522 }
1523 object.host_opaque()
1524 }
1525
1526 /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1527 pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1528 match value.as_object() {
1529 Some(object) => object.set_host_opaque(opaque),
1530 None => false,
1531 }
1532 }
1533
1534 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1535 ///
1536 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1537 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1538 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1539 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1540 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1541 /// said `[object Object]` instead of `[object Array Iterator]`.
1542 ///
1543 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1544 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1545 /// its own.
1546 pub fn new_iterator_prototype(
1547 &mut self,
1548 tag: &str,
1549 next: crate::object::NativeFn,
1550 ) -> Gc<JsObject> {
1551 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1552 return existing.clone();
1553 }
1554 let parent = self.realm.iterator_proto.clone();
1555 let proto = self.new_object(parent);
1556 let next = self.new_native("next", 0, next);
1557 proto.define(
1558 "next",
1559 Property::with_attributes(Value::Object(next), true, false),
1560 );
1561 let key = self.realm.well_known_key(WellKnown::Iterator);
1562 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1563 proto.define_key(
1564 &key,
1565 Property::with_attributes(Value::Object(identity), true, false),
1566 );
1567 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1568 let tag_value = self.string(tag);
1569 // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1570 // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1571 // checks it.
1572 proto.define_key(&tag_key, Property::configurable_only(tag_value));
1573 self.realm
1574 .iterator_protos
1575 .insert(tag.to_string(), proto.clone());
1576 proto
1577 }
1578
1579 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1580 ///
1581 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1582 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1583 /// produced. That is why the two branches are not merged.
1584 pub fn object_own_property_keys(
1585 &mut self,
1586 object: &Gc<JsObject>,
1587 ) -> JsResult<Vec<PropertyKey>> {
1588 if let Some(keys) = self.proxy_own_keys(object)? {
1589 return Ok(keys);
1590 }
1591 // Integer-like keys ascending, then the string keys in insertion order, then the
1592 // symbols — the order every schema that walks an object expects.
1593 let entries = object.property_entries();
1594 let mut numeric: Vec<u32> = Vec::new();
1595 // An integer-indexed exotic object reports its indices as own keys even though they
1596 // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1597 // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1598 // order). The length is asked per call, so a resizable buffer's view reports the
1599 // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1600 if object.typed_array_parts().is_some() {
1601 for index in 0..object.typed_array_length().unwrap_or(0) {
1602 // `u32::try_from` cannot fail for a real length, but the length is a
1603 // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1604 // as an array index and one element beyond is not.
1605 match u32::try_from(index) {
1606 Ok(index) => numeric.push(index),
1607 Err(_) => break,
1608 }
1609 }
1610 }
1611 let mut strings: Vec<PropertyKey> = Vec::new();
1612 let mut symbols: Vec<PropertyKey> = Vec::new();
1613 for (key, _) in entries {
1614 match &key {
1615 // A class-private name is never reported by any enumeration: that is the
1616 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1617 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1618 // symbol skip, `Object.assign`) therefore cannot see it.
1619 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1620 PropertyKey::Symbol(_) => symbols.push(key),
1621 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1622 Some(index) => {
1623 if !numeric.contains(&index) {
1624 numeric.push(index);
1625 }
1626 }
1627 None => strings.push(key),
1628 },
1629 }
1630 }
1631 // An array's `length` is an own property from the moment the array exists, so it
1632 // sits **before** every string key added afterwards — `arr.a = 1; arr.length` lists
1633 // as `["length", "a"]`, not `["a", "length"]`
1634 // (`getOwnPropertyNames/order-after-define-property`). It is synthesised rather
1635 // than stored in the property table, which is why it has to be placed here.
1636 if object.is_array() && object.proxy_state().is_none() {
1637 // Unconditionally: `Object.defineProperty(arr, "length", …)` files `length` in
1638 // the property table, at whatever position the *define* happened, but the key
1639 // lists it as the array's oldest string property because that is what it is.
1640 if let Some(position) = strings
1641 .iter()
1642 .position(|key| key.as_str() == Some("length"))
1643 {
1644 strings.remove(position);
1645 }
1646 strings.insert(0, PropertyKey::from("length"));
1647 }
1648 numeric.sort_unstable();
1649 let mut keys: Vec<PropertyKey> = numeric
1650 .into_iter()
1651 .map(|index| PropertyKey::from(index.to_string()))
1652 .collect();
1653 keys.extend(strings);
1654 keys.extend(symbols);
1655 Ok(keys)
1656 }
1657
1658 /// The state behind a promise object, or `None` when `object` is not one.
1659 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1660 object.with(|data| match &data.kind {
1661 ObjectKind::Promise(state) => Some(state.clone()),
1662 _ => None,
1663 })
1664 }
1665
1666 /// A new pending promise.
1667 pub fn new_promise(&mut self) -> Gc<JsObject> {
1668 // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1669 // the one place every promise is built, and a subclass that builds its instances
1670 // somewhere else would be invisible to `instanceof`.
1671 let default = self.realm.promise_proto.clone();
1672 // A throwing `new.target.prototype` getter cannot be reported from here — this is
1673 // the raw promise constructor and its result is not `JsResult` — so the rejection is
1674 // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1675 // `prototype` getter therefore still gets a working promise; the alternative is a
1676 // panic, and the throwing path is covered by `Promise`'s own argument validation.
1677 let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1678 let promise = JsObject::ordinary(self.heap, proto);
1679 promise.with_mut(|data| {
1680 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1681 crate::object::PromiseState::default(),
1682 )));
1683 });
1684 promise
1685 }
1686
1687 /// Fulfil `promise`, unless it has already settled.
1688 ///
1689 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1690 /// after `reject`, changes nothing.
1691 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1692 let Some(state) = self.promise_state(promise) else {
1693 return;
1694 };
1695 let reactions = {
1696 let mut state = state.borrow_mut();
1697 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1698 return;
1699 }
1700 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1701 std::mem::take(&mut state.reactions)
1702 };
1703 self.queue_reactions(reactions, value, false);
1704 }
1705
1706 /// Reject `promise`, unless it has already settled.
1707 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1708 let Some(state) = self.promise_state(promise) else {
1709 return;
1710 };
1711 let reactions = {
1712 let mut state = state.borrow_mut();
1713 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1714 return;
1715 }
1716 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1717 std::mem::take(&mut state.reactions)
1718 };
1719 // Remember it only when nothing is listening *now*; a `then` registered later
1720 // prunes the entry in `perform_then`.
1721 if reactions.is_empty() {
1722 self.unhandled.push((promise.clone(), reason.clone()));
1723 }
1724 self.queue_reactions(reactions, reason, true);
1725 }
1726
1727 /// Queue one job per reaction.
1728 ///
1729 /// This is what makes `then` asynchronous even on an already-settled promise:
1730 /// `p.then(f); g()` calls `g` first.
1731 fn queue_reactions(
1732 &mut self,
1733 reactions: Vec<crate::object::PromiseReaction>,
1734 argument: Value,
1735 rejected: bool,
1736 ) {
1737 for reaction in reactions {
1738 let handler = if rejected {
1739 reaction.on_rejected.clone()
1740 } else {
1741 reaction.on_fulfilled.clone()
1742 };
1743 self.jobs.push_back(Job::Reaction {
1744 handler,
1745 argument: argument.clone(),
1746 rejected,
1747 promise: reaction.promise,
1748 });
1749 }
1750 }
1751
1752 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1753 /// resolve/reject pair.
1754 ///
1755 /// The pair are callable objects rather than Rust closures, because the script gets
1756 /// them and may stash them for later.
1757 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1758 let promise = self.new_promise();
1759 // Both handlers are built-ins with an empty name and length 1, in
1760 // `length`-then-`name` order — `reject-function-property-order` reads the order back
1761 // off `Object.getOwnPropertyNames`.
1762 let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1763 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1764 (promise, Value::Object(resolve), Value::Object(reject))
1765 }
1766
1767 /// §27.2.1.5 `NewPromiseCapability(C)`.
1768 ///
1769 /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1770 /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1771 /// decide what capability it hands back. That is the whole mechanism behind subclassing
1772 /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1773 /// silently ignored argument.
1774 ///
1775 /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1776 /// the engine's own executor is exactly what `new_promise_capability` builds.
1777 pub fn new_promise_capability_for(
1778 &mut self,
1779 constructor: &Value,
1780 ) -> JsResult<(Value, Value, Value)> {
1781 let Some(object) = constructor.as_object().cloned() else {
1782 return Err(self.type_error("promise constructor is not a constructor"));
1783 };
1784 if !object.is_constructor() {
1785 return Err(self.type_error("promise constructor is not a constructor"));
1786 }
1787 if self
1788 .realm
1789 .promise_constructor
1790 .as_ref()
1791 .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1792 {
1793 let (promise, resolve, reject) = self.new_promise_capability();
1794 return Ok((Value::Object(promise), resolve, reject));
1795 }
1796 let state = self.new_object(Some(self.realm.object_proto.clone()));
1797 // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1798 // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1799 // which only a *custom* constructor can observe, and none of the combinator tests
1800 // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1801 let executor = self.builtin_function(
1802 "",
1803 2,
1804 Callable::CapabilityExecutor {
1805 state: state.clone(),
1806 },
1807 );
1808 let promise = self.construct(
1809 Value::Object(object.clone()),
1810 Value::Object(object),
1811 vec![Value::Object(executor)],
1812 )?;
1813 // The pair is read *after* the constructor returns, so a constructor that never
1814 // called its executor, or called it with non-callables, is the spec's step 11
1815 // `TypeError` — not something the engine can paper over.
1816 let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1817 return Err(self.type_error("promise executor never ran"));
1818 };
1819 let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1820 return Err(self.type_error("promise executor never ran"));
1821 };
1822 for handler in [&resolve, &reject] {
1823 if !matches!(handler, Value::Object(object) if object.is_callable()) {
1824 return Err(self.type_error("promise capability handler is not callable"));
1825 }
1826 }
1827 Ok((promise, resolve, reject))
1828 }
1829
1830 /// §27.2.3.1 `PromiseResolve(C, x)`.
1831 ///
1832 /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1833 /// an `x` that is already a promise of exactly this constructor is handed back
1834 /// unchanged, and anything else gets a fresh capability from `C`.
1835 pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1836 if let Value::Object(object) = &value
1837 && self.promise_state(object).is_some()
1838 {
1839 // `x.constructor === C` means "already the right kind", so no capability is
1840 // built — which is observable through a `resolve` that counts its calls.
1841 let x_constructor = self.get_property(object, "constructor")?;
1842 let same = match (
1843 x_constructor.as_ref().and_then(Value::as_object),
1844 constructor.as_object(),
1845 ) {
1846 (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1847 _ => false,
1848 };
1849 if same {
1850 return Ok(value);
1851 }
1852 }
1853 let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1854 self.call_value(resolve, Value::Undefined, vec![value])?;
1855 Ok(promise)
1856 }
1857
1858 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1859 /// promise, as `{ value: completion }`.
1860 ///
1861 /// The three cases are the reference's, and they differ on purpose:
1862 ///
1863 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1864 /// exception before any promise exists;
1865 /// * a **runtime** error rejects the returned promise;
1866 /// * success resolves it with `{ value }`, where the value is the script's completion
1867 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1868 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1869 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1870 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1871 ///
1872 /// # What this does not do
1873 ///
1874 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1875 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1876 /// the parser and the suspension machinery to accept a suspended top-level script, and
1877 /// is not implemented — such source is a syntax error here. Everything else about the
1878 /// flag is reproduced.
1879 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1880 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1881 // too, and the reference truncates that one at the same place as a runtime failure.
1882 if barrier {
1883 let depth = self.frames.len();
1884 self.trace_barriers.push(depth);
1885 }
1886 // Compiled before the promise exists, so a parse failure propagates as a throw
1887 // instead of being folded into a rejection.
1888 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1889 Ok(compiled) => compiled,
1890 Err(error) => {
1891 if barrier {
1892 self.trace_barriers.pop();
1893 }
1894 return Err(error);
1895 }
1896 };
1897 // An async body answers its own promise, and that promise is what the reference
1898 // hands back — the same object, not a wrapper around it. Its resolution value is
1899 // the `{value}` object the compiled epilogue built.
1900 if compiled.kind.is_async() {
1901 let strict = compiled.strict;
1902 let promise = self.run_eval_script(compiled, strict)?;
1903 if barrier {
1904 self.trace_barriers.pop();
1905 }
1906 return Ok(promise);
1907 }
1908 let (promise, resolve, reject) = self.new_promise_capability();
1909 let strict = compiled.strict;
1910 match self.run_eval_script(compiled, strict) {
1911 Ok(value) => {
1912 // `{ value }` is a plain object, so resolving with it adopts nothing even
1913 // when the completion value is itself a promise.
1914 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1915 self.set_property(&wrapped, "value", value)?;
1916 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1917 }
1918 Err(Signal::Throw(error)) => {
1919 self.call_value(reject, Value::Undefined, vec![error])?;
1920 }
1921 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1922 }
1923 if barrier {
1924 self.trace_barriers.pop();
1925 }
1926 Ok(Value::Object(promise))
1927 }
1928
1929 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1930 ///
1931 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1932 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1933 /// timer table, where the collector already scans it.
1934 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1935 let (promise, resolve, _reject) = self.new_promise_capability();
1936 let resolve = self.new_host_function(
1937 "resolve",
1938 1,
1939 Box::new(
1940 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1941 let value = args.first().cloned().unwrap_or(Value::Undefined);
1942 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1943 },
1944 ),
1945 );
1946 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1947 // timer table is part of what the collector walks.
1948 self.schedule_timer(Value::Object(resolve), delay_ms);
1949 Ok(Value::Object(promise))
1950 }
1951
1952 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1953 /// new promise resolved with it.
1954 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1955 if let Value::Object(object) = &value
1956 && self.promise_state(object).is_some()
1957 {
1958 return Ok(value);
1959 }
1960 let promise = self.new_promise();
1961 self.resolve_promise_with(&promise, value)?;
1962 Ok(Value::Object(promise))
1963 }
1964
1965 /// §27.2.4.7 `PromiseResolve(%Promise%, value)`.
1966 ///
1967 /// The difference from [`Interp::promise_resolve_value`] is step 1.a: when `value` is
1968 /// already a promise, its **`constructor` is read**, and only if that is the intrinsic
1969 /// `%Promise%` is `value` returned unchanged. A getter placed on `constructor` is
1970 /// therefore observable — which is exactly what
1971 /// `AsyncGeneratorPrototype/return/return-*-broken-promise*.js` use to check that the
1972 /// `AsyncGeneratorAwaitReturn` path goes through `PromiseResolve` rather than a private
1973 /// shortcut.
1974 pub fn promise_resolve_intrinsic(&mut self, value: Value) -> JsResult<Value> {
1975 if let Value::Object(object) = &value
1976 && self.promise_state(object).is_some()
1977 {
1978 let constructor = self.get_property(object, "constructor")?;
1979 let same = match (&constructor, &self.realm.promise_constructor) {
1980 (Some(Value::Object(found)), Some(intrinsic)) => found.ptr_eq(intrinsic),
1981 _ => false,
1982 };
1983 if same {
1984 return Ok(value);
1985 }
1986 }
1987 let promise = self.new_promise();
1988 self.resolve_promise_with(&promise, value)?;
1989 Ok(Value::Object(promise))
1990 }
1991
1992 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1993 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1994 // Resolving a promise with itself is a `TypeError`. The check exists because the
1995 // alternative is a chain of self-reactions that never settles.
1996 if let Value::Object(object) = &value
1997 && object.ptr_eq(promise)
1998 {
1999 // The spec rejects *and* throws, so both the promise and the caller see it.
2000 let thrown = self.type_error("cannot resolve a promise with itself");
2001 let Signal::Throw(error) = thrown.clone() else {
2002 unreachable!("type_error always throws")
2003 };
2004 self.reject_promise(promise, error);
2005 return Err(thrown);
2006 }
2007 let then = match &value {
2008 Value::Object(object) => self.get_property(object, "then")?,
2009 _ => None,
2010 };
2011 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
2012 if !callable_then {
2013 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
2014 self.fulfill_promise(promise, value);
2015 return Ok(());
2016 }
2017 // Adopting a thenable is asynchronous — `then` is called from a job, never from
2018 // inside `resolve`, so a script cannot make a promise settle synchronously.
2019 self.jobs.push_back(Job::Thenable {
2020 then: then.expect("checked callable"),
2021 value,
2022 promise: promise.clone(),
2023 });
2024 Ok(())
2025 }
2026
2027 /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
2028 ///
2029 /// `C.resolve` is user code and may answer a plain thenable rather than one of this
2030 /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
2031 ///
2032 /// The property read is **not** short-circuitable even for a real promise: the spec says
2033 /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
2034 /// expects it to run. Skipping the read for promises not only lost the throw, it made
2035 /// the combinator's loop infinite — the test's iterator never sets `done`.
2036 pub fn invoke_then(
2037 &mut self,
2038 thenable: Value,
2039 on_fulfilled: Value,
2040 on_rejected: Value,
2041 ) -> JsResult<()> {
2042 let then = match &thenable {
2043 Value::Object(object) => self.get_property(object, "then")?,
2044 primitive => {
2045 let boxed = self.object_from(primitive)?;
2046 self.get_property(&boxed, "then")?
2047 }
2048 };
2049 let Some(then) = then else {
2050 return Err(self.type_error("thenable has no then method"));
2051 };
2052 if !matches!(&then, Value::Object(object) if object.is_callable()) {
2053 return Err(self.type_error("then is not a function"));
2054 }
2055 self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
2056 Ok(())
2057 }
2058
2059 /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
2060 ///
2061 /// `Promise.prototype.then` in one step: register a reaction and answer the derived
2062 /// promise.
2063 pub fn perform_then(
2064 &mut self,
2065 promise: &Gc<JsObject>,
2066 on_fulfilled: Option<Value>,
2067 on_rejected: Option<Value>,
2068 ) -> JsResult<Value> {
2069 let Some(state) = self.promise_state(promise) else {
2070 return Err(self.type_error("not a promise"));
2071 };
2072 // Whether a rejection handler is being attached decides whether a recorded
2073 // rejection stops being unhandled, so it is read before the values are moved.
2074 let has_rejection_handler = on_rejected.is_some();
2075 let derived = self.new_promise();
2076 let reaction = crate::object::PromiseReaction {
2077 on_fulfilled,
2078 on_rejected,
2079 promise: derived.clone(),
2080 };
2081 let settled = {
2082 let mut state = state.borrow_mut();
2083 // A rejection somebody reacts to is no longer unhandled.
2084 state.handled = true;
2085 match &state.status {
2086 crate::object::PromiseStatus::Pending => {
2087 state.reactions.push(reaction.clone());
2088 None
2089 }
2090 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2091 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2092 }
2093 };
2094 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2095 // later, means somebody is listening after all.
2096 if has_rejection_handler {
2097 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2098 }
2099 if let Some((argument, rejected)) = settled {
2100 let handler = if rejected {
2101 reaction.on_rejected
2102 } else {
2103 reaction.on_fulfilled
2104 };
2105 self.jobs.push_back(Job::Reaction {
2106 handler,
2107 argument,
2108 rejected,
2109 promise: reaction.promise,
2110 });
2111 }
2112 Ok(Value::Object(derived))
2113 }
2114
2115 /// The rejections nobody listened to, formatted the way the reference reports them.
2116 ///
2117 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2118 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2119 /// unhandled at the point the queue drains, because a `then` may still be attached
2120 /// before the host acts on it.
2121 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2122 let entries = std::mem::take(&mut self.unhandled);
2123 // Somebody may have attached a handler after the rejection was recorded, so the
2124 // promise is the authority rather than the list.
2125 let still_unhandled: Vec<Value> = entries
2126 .into_iter()
2127 .filter_map(|(promise, reason)| {
2128 let handled = self
2129 .promise_state(&promise)
2130 .map(|state| state.borrow().handled)
2131 .unwrap_or(true);
2132 (!handled).then_some(reason)
2133 })
2134 .collect();
2135 still_unhandled
2136 .into_iter()
2137 .map(|reason| {
2138 let text = self.describe_exception(&reason);
2139 let stack = match &reason {
2140 Value::Object(object) => self
2141 .get_property(object, "stack")
2142 .ok()
2143 .flatten()
2144 .map(|value| value.to_js_string())
2145 // `stack` carries a trailing newline of its own, which would leave
2146 // a blank line between two reported rejections.
2147 .map(|text| text.trim_end().to_string())
2148 .unwrap_or_default(),
2149 _ => String::new(),
2150 };
2151 if stack.is_empty() {
2152 format!("Possibly unhandled promise rejection: {text}")
2153 } else {
2154 format!("Possibly unhandled promise rejection: {text}\n{stack}")
2155 }
2156 })
2157 .collect()
2158 }
2159
2160 /// Run the microtask queue to exhaustion.
2161 ///
2162 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2163 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2164 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2165 ///
2166 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2167 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2168 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2169 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2170 crate::builtins::json::parse_text(self, text, true)
2171 }
2172
2173 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2174 ///
2175 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2176 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2177 /// immediately, and `setTimeout(f, -1)` is ordinary code.
2178 ///
2179 /// The callback is called with **no arguments**. The reference stores only the function
2180 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2181 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2182 /// extra arguments arrive as `undefined`.
2183 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2184 let id = self.next_timer_id;
2185 // Wrap rather than grow: the id reaches the script as an `Int32`.
2186 self.next_timer_id = if self.next_timer_id == i32::MAX {
2187 1
2188 } else {
2189 self.next_timer_id + 1
2190 };
2191 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2192 self.tasks.push(Task::Timer {
2193 id,
2194 callback,
2195 due_at,
2196 });
2197 id
2198 }
2199
2200 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2201 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2202 pub fn cancel_timer(&mut self, id: i32) -> bool {
2203 let before = self.tasks.len();
2204 self.tasks.retain(|task| match task {
2205 Task::Timer { id: task_id, .. } => *task_id != id,
2206 });
2207 self.tasks.len() != before
2208 }
2209
2210 /// How long until the earliest pending timer, or `None` when none is pending.
2211 pub fn next_timeout(&self) -> Option<std::time::Duration> {
2212 let now = std::time::Instant::now();
2213 self.tasks
2214 .iter()
2215 .map(|task| match task {
2216 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2217 })
2218 .min()
2219 }
2220
2221 /// Run one turn of the event loop.
2222 ///
2223 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2224 /// run at most one due timer, then drain again. The blocking belongs to the caller
2225 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2226 /// is how it asks.
2227 ///
2228 /// One timer per turn rather than all of them: a timer callback may schedule another
2229 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2230 /// starve the microtask queue.
2231 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2232 self.drain_jobs()?;
2233 let now = std::time::Instant::now();
2234 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2235 // followed by `setTimeout(g, 1)` must run `g` first.
2236 let due = self
2237 .tasks
2238 .iter()
2239 .enumerate()
2240 .filter(|(_, task)| match task {
2241 Task::Timer { due_at, .. } => *due_at <= now,
2242 })
2243 .min_by_key(|(_, task)| match task {
2244 Task::Timer { due_at, .. } => *due_at,
2245 })
2246 .map(|(index, _)| index);
2247 let Some(index) = due else {
2248 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2249 // descriptor is registered but no timer is closer, so a script that never
2250 // touches the descriptor still gets control back. Without a cap a handler on a
2251 // descriptor that is never ready would block for as long as the host allows.
2252 let timeout = self
2253 .next_timeout()
2254 .unwrap_or(std::time::Duration::from_secs(10))
2255 .min(std::time::Duration::from_secs(10));
2256 if !self.fd_handlers.is_empty() {
2257 // Blocking on a timer while descriptors are registered would starve them,
2258 // and blocking on the descriptors while a timer is due would delay it; the
2259 // host polls with the earlier of the two deadlines, which this timeout is.
2260 return Ok(Turn::Poll(timeout));
2261 }
2262 return Ok(match self.next_timeout() {
2263 Some(wait) => Turn::Wait(wait),
2264 None => Turn::Done,
2265 });
2266 };
2267 let Task::Timer { callback, .. } = self.tasks.remove(index);
2268 let this = Value::Undefined;
2269 // A throwing timer callback must not stop the loop: the reference reports it and
2270 // keeps going, because the alternative is that one bad timer silently stops every
2271 // later one.
2272 // No arguments: see `schedule_timer` — the reference calls the callback bare.
2273 match self.call_value(callback, this, Vec::new()) {
2274 Ok(_) => {}
2275 Err(Signal::Throw(value)) => {
2276 let text = self.describe_exception(&value);
2277 self.timer_errors.push(text);
2278 }
2279 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2280 }
2281 self.drain_jobs()?;
2282 Ok(Turn::Ran)
2283 }
2284
2285 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2286 ///
2287 /// `callback` of `None` unregisters that direction, and an entry with neither direction
2288 /// left is removed — the reference does the same, so a script can rely on
2289 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2290 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2291 let entry = self.fd_handlers.entry(fd).or_default();
2292 if readable {
2293 entry.read = callback;
2294 } else {
2295 entry.write = callback;
2296 }
2297 if entry.read.is_none() && entry.write.is_none() {
2298 self.fd_handlers.remove(&fd);
2299 }
2300 }
2301
2302 /// Register or clear an `os.signal` handler.
2303 ///
2304 /// `None` removes it; the host separately restores the default disposition or sets
2305 /// ignore, because which of those happened is the script's choice (`null` versus
2306 /// `undefined`) and not something this table can express.
2307 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2308 match handler {
2309 Some(handler) => {
2310 self.signal_handlers.insert(signal, handler);
2311 }
2312 None => {
2313 self.signal_handlers.remove(&signal);
2314 }
2315 }
2316 }
2317
2318 /// Run the handler for `signal`, reporting whether one ran.
2319 ///
2320 /// A throwing handler is reported and the loop continues, like a timer's.
2321 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2322 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2323 return Ok(false);
2324 };
2325 match self.call_value(handler, Value::Undefined, Vec::new()) {
2326 Ok(_) => {}
2327 Err(Signal::Throw(value)) => {
2328 let text = self.describe_exception(&value);
2329 self.timer_errors.push(text);
2330 }
2331 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2332 }
2333 self.drain_jobs()?;
2334 Ok(true)
2335 }
2336
2337 /// The descriptors the host has to poll, and in which direction.
2338 ///
2339 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2340 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2341 /// `os_poll` asks for.
2342 pub fn pending_fds(&self) -> Vec<FdInterest> {
2343 self.fd_handlers
2344 .iter()
2345 .map(|(fd, entry)| FdInterest {
2346 fd: *fd,
2347 read: entry.read.is_some(),
2348 write: entry.write.is_some(),
2349 })
2350 .collect()
2351 }
2352
2353 /// Call the handler registered for `fd`, reporting whether one ran.
2354 ///
2355 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2356 /// poll iteration and then restarts the loop, because the handler may have changed the
2357 /// registration list underneath it; doing the same here keeps a handler that
2358 /// unregisters itself from being called with stale state.
2359 ///
2360 /// A throwing handler is reported and the loop continues — a bad handler must not stop
2361 /// every later one, exactly as with timers.
2362 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2363 let Some(entry) = self.fd_handlers.get(&fd) else {
2364 return Ok(false);
2365 };
2366 let callback = if readable {
2367 entry.read.clone()
2368 } else if writable {
2369 entry.write.clone()
2370 } else {
2371 None
2372 };
2373 let Some(callback) = callback else {
2374 return Ok(false);
2375 };
2376 self.drain_jobs()?;
2377 match self.call_value(callback, Value::Undefined, Vec::new()) {
2378 Ok(_) => {}
2379 Err(Signal::Throw(value)) => {
2380 let text = self.describe_exception(&value);
2381 self.timer_errors.push(text);
2382 }
2383 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2384 }
2385 self.drain_jobs()?;
2386 Ok(true)
2387 }
2388
2389 /// Take the errors timer callbacks threw, leaving the list empty.
2390 pub fn take_timer_errors(&mut self) -> Vec<String> {
2391 std::mem::take(&mut self.timer_errors)
2392 }
2393
2394 /// Whether anything is still pending: a microtask or a timer.
2395 pub fn has_pending_work(&self) -> bool {
2396 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2397 }
2398
2399 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2400 pub fn has_pending_timers_or_jobs(&self) -> bool {
2401 !self.jobs.is_empty() || !self.tasks.is_empty()
2402 }
2403
2404 /// Run every queued microtask, including ones queued while draining.
2405 pub fn drain_jobs(&mut self) -> JsResult<()> {
2406 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2407 // would spin forever, so the drain is bounded the way the call stack is.
2408 let mut budget = 1_000_000usize;
2409 while let Some(job) = self.jobs.pop_front() {
2410 if budget == 0 {
2411 return Err(Signal::Throw(
2412 self.make_error("InternalError", "promise job queue did not drain"),
2413 ));
2414 }
2415 budget -= 1;
2416 self.run_job(job)?;
2417 // `FinalizationRegistry` at the job boundary: this is the safe point where the
2418 // engine may run script that the script itself did not ask for. Doing it here
2419 // rather than from a drop hook is what keeps the callback out of arbitrary
2420 // engine bookkeeping — see `builtins::weak`'s header.
2421 crate::builtins::weak::drain_finalizers(self)?;
2422 }
2423 // A script that queued no jobs may still have dropped targets, so the checkpoint
2424 // runs once more after the queue empties.
2425 crate::builtins::weak::drain_finalizers(self)?;
2426 Ok(())
2427 }
2428
2429 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2430 ///
2431 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2432 /// `None` and is swept out here. This is also where the realm learns that a registry
2433 /// died, which is why it is a mutation rather than a read.
2434 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2435 let handles = std::mem::take(&mut self.realm.finalization_registries);
2436 let mut live = Vec::with_capacity(handles.len());
2437 for handle in handles {
2438 let Some(object) = handle.upgrade() else {
2439 continue;
2440 };
2441 let Some(state) = object.finalization_state() else {
2442 continue;
2443 };
2444 live.push((object.clone(), *state));
2445 self.realm.finalization_registries.push(object.downgrade());
2446 }
2447 live
2448 }
2449
2450 /// Run one microtask.
2451 fn run_job(&mut self, job: Job) -> JsResult<()> {
2452 match job {
2453 Job::Reaction {
2454 handler: None,
2455 argument,
2456 rejected,
2457 promise,
2458 } => {
2459 // No handler: the settlement passes straight through to the derived
2460 // promise, which is why `p.catch(f)` ignores fulfilments.
2461 if rejected {
2462 self.reject_promise(&promise, argument);
2463 } else {
2464 self.fulfill_promise(&promise, argument);
2465 }
2466 Ok(())
2467 }
2468 Job::Reaction {
2469 handler: Some(handler),
2470 argument,
2471 promise,
2472 ..
2473 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2474 Ok(answer) => {
2475 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2476 self.reject_promise(&promise, error);
2477 }
2478 Ok(())
2479 }
2480 Err(Signal::Throw(reason)) => {
2481 self.reject_promise(&promise, reason);
2482 Ok(())
2483 }
2484 Err(other) => Err(other),
2485 },
2486 Job::Thenable {
2487 then,
2488 value,
2489 promise,
2490 } => {
2491 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2492 // the value it produces settles `promise`.
2493 // The thenable's `then` gets this promise's own pair, so whatever it
2494 // produces settles `promise`.
2495 // `length: 1`, `name: ""` — a resolve/reject function is a
2496 // `%Promise.prototype.then%`-style pair, not a bare native. Building them
2497 // with `JsObject::function` left `length` at 0, which a test reads straight
2498 // off the function (`finally/resolved-observable-then-calls-argument`
2499 // requires `resolve.length === 1` for the pair handed to a thenable).
2500 let resolve =
2501 self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
2502 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
2503 match self.call_value(
2504 then,
2505 value,
2506 vec![Value::Object(resolve), Value::Object(reject)],
2507 ) {
2508 Ok(_) => Ok(()),
2509 Err(Signal::Throw(reason)) => {
2510 self.reject_promise(&promise, reason);
2511 Ok(())
2512 }
2513 Err(other) => Err(other),
2514 }
2515 }
2516 Job::Resume {
2517 coroutine,
2518 promise,
2519 kind,
2520 value,
2521 } => self.drive_async(&coroutine, &promise, kind, value),
2522 Job::GeneratorResume {
2523 generator,
2524 promise,
2525 kind,
2526 value,
2527 } => self.step_async_generator(&generator, &promise, kind, value),
2528 Job::Import {
2529 specifier,
2530 referrer,
2531 promise,
2532 } => {
2533 self.run_dynamic_import(&specifier, &referrer, &promise);
2534 Ok(())
2535 }
2536 }
2537 }
2538
2539 /// One element of a `Promise` combinator settled.
2540 ///
2541 /// The shared state object holds the result array, the number still outstanding, and
2542 /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2543 /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2544 /// to settle, only whatever `Sub` said a capability is.
2545 ///
2546 /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2547 /// and `any` must ignore every later settlement, and `all` must not report a second
2548 /// rejection after the first.
2549 fn settle_combinator(
2550 &mut self,
2551 state: &Gc<JsObject>,
2552 index: usize,
2553 fulfilled: bool,
2554 value: Value,
2555 ) -> JsResult<()> {
2556 let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2557 // Each element settles at most once: a thenable may call `onFulfilled` twice
2558 // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2559 // call a no-op. Without it the second call decremented `remaining` again and settled
2560 // `all` with a short values array (`call-resolve-element-items`).
2561 let done = field("done");
2562 let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2563 let settled = field("settled").is_some_and(|value| value.to_boolean());
2564 if settled {
2565 return Ok(());
2566 }
2567 if let Some(Value::Object(done)) = &done {
2568 if done
2569 .array_get(index)
2570 .is_some_and(|value| value.to_boolean())
2571 {
2572 return Ok(());
2573 }
2574 done.array_set(self.heap, index, Value::Bool(true));
2575 }
2576 let resolve = field("resolve");
2577 let reject = field("reject");
2578 let keys = field("keys");
2579 let results = field("results").and_then(|value| value.as_object().cloned());
2580 // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2581 // promise: the handler is a plain function the constructor chose.
2582 let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2583 if let Some(handler) = handler {
2584 interp.call_value(handler, Value::Undefined, vec![value])?;
2585 }
2586 Ok(())
2587 };
2588 match kind {
2589 // `race`: the first settlement wins and stops the rest.
2590 3 => {
2591 state.define_data("settled", Value::Bool(true));
2592 let handler = if fulfilled { resolve } else { reject };
2593 settle_with(self, handler, value)?;
2594 return Ok(());
2595 }
2596 // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2597 // the first rejection wins outright.
2598 0 | 4 if !fulfilled => {
2599 state.define_data("settled", Value::Bool(true));
2600 settle_with(self, reject, value)?;
2601 return Ok(());
2602 }
2603 // `any`: the first fulfilment wins.
2604 2 if fulfilled => {
2605 state.define_data("settled", Value::Bool(true));
2606 settle_with(self, resolve, value)?;
2607 return Ok(());
2608 }
2609 _ => {}
2610 }
2611 let Some(results) = &results else {
2612 return Ok(());
2613 };
2614 match kind {
2615 4 => {
2616 results.array_set(self.heap, index, value);
2617 }
2618 0 => {
2619 results.array_set(self.heap, index, value);
2620 }
2621 // `allSettled` (and its keyed twin) never rejects; each slot records what
2622 // happened.
2623 1 | 5 => {
2624 let record = self.new_object(Some(self.realm.object_proto.clone()));
2625 if fulfilled {
2626 record.define_data("status", self.string("fulfilled"));
2627 record.define_data("value", value);
2628 } else {
2629 record.define_data("status", self.string("rejected"));
2630 record.define_data("reason", value);
2631 }
2632 results.array_set(self.heap, index, Value::Object(record));
2633 }
2634 // `any`: a rejection is parked in the errors array and the sweep continues.
2635 2 => {
2636 results.array_set(self.heap, index, value);
2637 }
2638 _ => {}
2639 }
2640 let remaining = field("remaining")
2641 .map(|value| value.to_int32())
2642 .unwrap_or(0);
2643 let left = remaining - 1;
2644 state.define_data("remaining", Value::Int(left));
2645 if left != 0 {
2646 return Ok(());
2647 }
2648 state.define_data("settled", Value::Bool(true));
2649 match kind {
2650 0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2651 // The keyed result: an ordinary object with a **null** prototype, holding the
2652 // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2653 4 | 5 => {
2654 let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2655 settle_with(self, resolve, keyed)?;
2656 }
2657 2 => {
2658 // The rejection is an `AggregateError` whose `errors` is the results array
2659 // itself — the slots are the reasons, in input order.
2660 let errors = results.array_elements().unwrap_or_default();
2661 let error = self.aggregate_error(errors, "all promises were rejected");
2662 settle_with(self, reject, error)?;
2663 }
2664 _ => {}
2665 }
2666 Ok(())
2667 }
2668
2669 /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2670 ///
2671 /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2672 /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2673 /// prototype is load-bearing in both directions: a key called `toString` must not
2674 /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2675 /// (`resolves-empty-object.js`).
2676 pub(crate) fn keyed_result_object(
2677 &mut self,
2678 keys: Option<&Value>,
2679 values: &Gc<JsObject>,
2680 ) -> JsResult<Value> {
2681 let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2682 return Ok(Value::Object(self.new_object(None)));
2683 };
2684 let result = self.new_object(None);
2685 let count = values.array_length().unwrap_or(0);
2686 for index in 0..count {
2687 let Some(key) = keys.array_get(index) else {
2688 continue;
2689 };
2690 let Some(value) = values.array_get(index) else {
2691 continue;
2692 };
2693 let property = Property::with_attributes(value, true, true);
2694 match &key {
2695 Value::Symbol(symbol) => {
2696 result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2697 }
2698 other => {
2699 let text = self.to_js_string(other)?;
2700 result.define_key(&PropertyKey::from(text.as_str()), property);
2701 }
2702 }
2703 }
2704 Ok(Value::Object(result))
2705 }
2706
2707 /// Build an async function's result: a promise whose body runs as a coroutine.
2708 pub fn new_async_function(
2709 &mut self,
2710 function: Value,
2711 this: Value,
2712 args: Vec<Value>,
2713 ) -> JsResult<Value> {
2714 let promise = self.new_promise();
2715 let coroutine = self.new_coroutine(function, this, args)?;
2716 if let Err(Signal::Throw(reason)) =
2717 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2718 {
2719 self.reject_promise(&promise, reason);
2720 }
2721 Ok(Value::Object(promise))
2722 }
2723
2724 /// The coroutine an async body runs in.
2725 ///
2726 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2727 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2728 /// than growing a second state machine. The difference is only in the ending — a
2729 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2730 /// Run `code` as an async function body, answering the promise it settles.
2731 ///
2732 /// Used for a module with top-level `await`: its body is an async function whose
2733 /// caller is the host, so there is no function object to pass through
2734 /// [`Interp::new_async_function`].
2735 pub fn run_async_body(
2736 &mut self,
2737 code: Gc<CompiledCode>,
2738 env: Gc<ClosureEnv>,
2739 this: Value,
2740 ) -> JsResult<Value> {
2741 let promise = self.new_promise();
2742 let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2743 if let Err(Signal::Throw(reason)) =
2744 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2745 {
2746 self.reject_promise(&promise, reason);
2747 }
2748 Ok(Value::Object(promise))
2749 }
2750
2751 fn new_coroutine(
2752 &mut self,
2753 function: Value,
2754 this: Value,
2755 args: Vec<Value>,
2756 ) -> JsResult<Gc<JsObject>> {
2757 let Some(object) = function.as_object().cloned() else {
2758 return Err(self.type_error("not a function"));
2759 };
2760 let Some((code, env)) = bytecode_of(&object) else {
2761 return Err(self.type_error("not a function"));
2762 };
2763 self.new_coroutine_from(code, env, this, args)
2764 }
2765
2766 /// Build a coroutine over an already-resolved body.
2767 fn new_coroutine_from(
2768 &mut self,
2769 code: Gc<CompiledCode>,
2770 env: Gc<ClosureEnv>,
2771 this: Value,
2772 args: Vec<Value>,
2773 ) -> JsResult<Gc<JsObject>> {
2774 let function = Value::Undefined;
2775 self.push_frame(code, env, this, args, function)?;
2776 let frame = self.frames.pop().expect("push_frame just pushed it");
2777 let state = GeneratorState {
2778 frame: Some(frame),
2779 phase: GeneratorPhase::SuspendedStart,
2780 parked_on_await: false,
2781 parked_on_yield_star: false,
2782 requests: std::collections::VecDeque::new(),
2783 async_busy: false,
2784 // An `async function` body is driven by `drive_async`, never by the generator
2785 // protocol, and the object is not reachable from script.
2786 is_async: false,
2787 };
2788 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2789 coroutine.with_mut(|data| {
2790 data.kind = ObjectKind::Generator(Box::new(state));
2791 });
2792 Ok(coroutine)
2793 }
2794
2795 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2796 /// `await` and `value` is what it awaited.
2797 fn resume_coroutine(
2798 &mut self,
2799 coroutine: &Gc<JsObject>,
2800 kind: ResumeKind,
2801 value: Value,
2802 ) -> JsResult<(Value, bool)> {
2803 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2804 ObjectKind::Generator(state) => {
2805 let is_async = state.is_async;
2806 Some(std::mem::replace(
2807 state.as_mut(),
2808 GeneratorState {
2809 frame: None,
2810 phase: GeneratorPhase::Executing,
2811 parked_on_await: false,
2812 parked_on_yield_star: false,
2813 requests: std::collections::VecDeque::new(),
2814 async_busy: false,
2815 is_async,
2816 },
2817 ))
2818 }
2819 _ => None,
2820 }) else {
2821 return Err(self.type_error("not a coroutine"));
2822 };
2823 let result = self.step_generator(&mut state, kind, value);
2824 coroutine.with_mut(|data| {
2825 data.kind = ObjectKind::Generator(Box::new(state));
2826 });
2827 let (value, done, _ready, _reason) = result?;
2828 Ok((value, done))
2829 }
2830
2831 /// Advance an async body and settle its promise with the outcome.
2832 fn drive_async(
2833 &mut self,
2834 coroutine: &Gc<JsObject>,
2835 promise: &Gc<JsObject>,
2836 kind: ResumeKind,
2837 value: Value,
2838 ) -> JsResult<()> {
2839 match self.resume_coroutine(coroutine, kind, value) {
2840 Ok((value, true)) => {
2841 // `Ok` with `done` means the body finished *normally*, even when it was
2842 // resumed by a `throw` — `try { await p } catch {}` completes by
2843 // returning. Only the `Err` arm below is a rejection.
2844 //
2845 // Resolving rather than fulfilling matters: `return promise` in an async
2846 // body adopts the inner promise, so `async function f(){ return
2847 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2848 // promise.
2849 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2850 self.reject_promise(promise, reason);
2851 }
2852 Ok(())
2853 }
2854 Ok((value, false)) => {
2855 // Parked on `await`: follow what it awaited and resume with the outcome.
2856 let awaited = match self.promise_resolve_value(value) {
2857 Ok(awaited) => awaited,
2858 Err(Signal::Throw(error)) => {
2859 self.reject_promise(promise, error);
2860 return Ok(());
2861 }
2862 Err(other) => return Err(other),
2863 };
2864 self.hook_await(awaited, coroutine, promise)
2865 }
2866 Err(Signal::Throw(reason)) => {
2867 self.reject_promise(promise, reason);
2868 Ok(())
2869 }
2870 Err(other) => Err(other),
2871 }
2872 }
2873
2874 /// Arrange for `coroutine` to resume when `awaited` settles.
2875 fn hook_await(
2876 &mut self,
2877 awaited: Value,
2878 coroutine: &Gc<JsObject>,
2879 promise: &Gc<JsObject>,
2880 ) -> JsResult<()> {
2881 let resumed = JsObject::function(
2882 self.heap,
2883 Some(self.realm.function_proto.clone()),
2884 Callable::AwaitResume {
2885 coroutine: coroutine.clone(),
2886 promise: promise.clone(),
2887 kind: ResumeKind::Next,
2888 },
2889 );
2890 let raised = JsObject::function(
2891 self.heap,
2892 Some(self.realm.function_proto.clone()),
2893 Callable::AwaitResume {
2894 coroutine: coroutine.clone(),
2895 promise: promise.clone(),
2896 kind: ResumeKind::Throw,
2897 },
2898 );
2899 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2900 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2901 let Value::Object(awaited) = &awaited else {
2902 self.jobs.push_back(Job::Resume {
2903 coroutine: coroutine.clone(),
2904 promise: promise.clone(),
2905 kind: ResumeKind::Next,
2906 value: awaited,
2907 });
2908 return Ok(());
2909 };
2910 self.perform_then(
2911 awaited,
2912 Some(Value::Object(resumed)),
2913 Some(Value::Object(raised)),
2914 )?;
2915 Ok(())
2916 }
2917
2918 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2919 /// things an engine keeps outside it — array elements and an array's `length`.
2920 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2921 if let Some(property) = object.own_property_key(key) {
2922 return Some(property);
2923 }
2924 // A typed array's indices are bytes in its buffer, so a descriptor for one has to
2925 // be synthesized too — and every one of them is a plain writable, enumerable,
2926 // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
2927 // `undefined` before this, which made `key-is-numericindex` fail on its own
2928 // side effect check.
2929 //
2930 // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
2931 // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
2932 // likewise not elements however numeric they look.
2933 if object.typed_array_element_type().is_some()
2934 && let Some(numeric) = canonical_numeric_index(key)
2935 && numeric.is_finite()
2936 && numeric.fract() == 0.0
2937 && !(numeric == 0.0 && numeric.is_sign_negative())
2938 && numeric >= 0.0
2939 && (numeric as usize) < object.typed_array_length().unwrap_or(0)
2940 {
2941 let value = object.typed_array_element(numeric as usize)?;
2942 return Some(Property::data(value));
2943 }
2944 // An array's elements live in their own vector rather than the property table, so
2945 // a descriptor for one has to be synthesized — with the attributes an element has.
2946 if let Some(index) = key.as_str().and_then(array_index)
2947 && let Some(value) = object.array_get(index as usize)
2948 && !matches!(value, Value::Hole)
2949 {
2950 return Some(Property::data(value));
2951 }
2952 // `length` is an own property of an array that is not in its property table
2953 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2954 // and non-enumerable.
2955 if key.as_str() == Some("length")
2956 && let Some(length) = object.array_length()
2957 {
2958 return Some(Property {
2959 value: Some(crate::object::length_value(length)),
2960 writable: object.length_writable(),
2961 enumerable: false,
2962 configurable: false,
2963 getter: None,
2964 setter: None,
2965 descriptor_fields: None,
2966 });
2967 }
2968 None
2969 }
2970
2971 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2972 pub fn object_get_own_property(
2973 &mut self,
2974 object: &Gc<JsObject>,
2975 key: &PropertyKey,
2976 ) -> JsResult<Option<Property>> {
2977 if let Some(answer) = self.proxy_get_own_property(object, key)? {
2978 return Ok(answer);
2979 }
2980 if let Some(exotic) = object.exotic()
2981 && let Some(answer) = exotic.get_own_property(self, object, key)?
2982 {
2983 return Ok(answer);
2984 }
2985 // A mapped `arguments` index is a data property as far as script can see: the
2986 // accessor pair that aliases the parameter is plumbing, and exposing it would
2987 // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
2988 // report a `get` where the spec has a `[[Value]]`.
2989 if let Some(index) = key.as_str().and_then(crate::object::array_index)
2990 && let Some(cell) = object.mapped_argument_cell(index as usize)
2991 {
2992 // Non-configurable is *not* the default: an ordinary mapped index is
2993 // configurable, and only becomes non-configurable once something
2994 // redefines it. Preserve whatever the property table currently says.
2995 // The attributes come from whatever the property table holds, because they
2996 // can be changed independently of the mapping; only the *value* and the
2997 // data-property *kind* are the accessor's secret.
2998 let flags = Self::ordinary_own_property(object, key);
2999 if let Some(existing) = &flags
3000 && !existing.is_accessor()
3001 {
3002 // Already demapped: the table entry is the answer, not the cell.
3003 return Ok(flags);
3004 }
3005 return Ok(Some(Property {
3006 value: Some(cell.get()),
3007 writable: true,
3008 enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
3009 configurable: flags.as_ref().is_some_and(|p| p.configurable),
3010 ..Property::default()
3011 }));
3012 }
3013 Ok(Self::ordinary_own_property(object, key))
3014 }
3015
3016 /// §7.3.40 `SetterThatIgnoresPrototypeProperties(thisValue, home, propertyKey, value)`.
3017 ///
3018 /// Written for `Error.prototype.stack`'s setter and the exact mechanism
3019 /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
3020 /// abstract operation here rather than a private helper in `error.rs`.
3021 ///
3022 /// The name is the whole point: the setter must behave as if the prototype were not
3023 /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3024 /// the accessor for every error object in the realm. Everything below follows from that:
3025 ///
3026 /// 1. `thisValue` must be an object — otherwise `TypeError`.
3027 /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3028 /// accessor's own home an error rather than a self-shadow.
3029 /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3030 /// either has a string or has made a mistake.
3031 /// 4. An existing *own* property decides the path — an own setter is called, an own
3032 /// non-writable data property is a `TypeError` — and only a missing own property
3033 /// falls through to defining one.
3034 /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3035 /// traps and a non-extensible receiver is a `TypeError`.
3036 ///
3037 /// The installed shape is writable + configurable, not enumerable.
3038 pub fn setter_that_ignores_prototype_properties(
3039 &mut self,
3040 this_value: Value,
3041 home: &Gc<JsObject>,
3042 property_key: &str,
3043 args: &[Value],
3044 ) -> JsResult<Value> {
3045 self.setter_that_ignores_prototype_properties_key(
3046 this_value,
3047 home,
3048 &PropertyKey::from(property_key),
3049 args,
3050 )
3051 }
3052
3053 /// [`Interp::setter_that_ignores_prototype_properties`] for a key that may be a symbol.
3054 ///
3055 /// `Iterator.prototype[@@toStringTag]`'s setter is the symbol-keyed caller.
3056 pub fn setter_that_ignores_prototype_properties_key(
3057 &mut self,
3058 this_value: Value,
3059 home: &Gc<JsObject>,
3060 key: &PropertyKey,
3061 args: &[Value],
3062 ) -> JsResult<Value> {
3063 let Some(receiver) = this_value.as_object().cloned() else {
3064 return Err(self.type_error("setter called on a non-object"));
3065 };
3066 if Gc::ptr_eq(&receiver, home) {
3067 return Err(self.type_error("cannot assign to the accessor's own home object"));
3068 }
3069 // No type check here: §7.3.40 takes an arbitrary `v`, and
3070 // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3071 // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3072 // before calling this.
3073 let value = args.first().cloned().unwrap_or(Value::Undefined);
3074 // Step 4: an own property on the receiver changes what happens, and there are three
3075 // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3076 // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3077 // `Set` with `throw = true`, and a test exists for each.
3078 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
3079 if existing.is_accessor() && existing.setter.is_none() {
3080 // A getter-only own accessor cannot be written through.
3081 return Err(self.type_error("no setter for the own property"));
3082 }
3083 // Everything else — an own data property, or an own accessor *with* a setter —
3084 // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3085 // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3086 // an own user setter receives the value (`setter-own-accessor`), because
3087 // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3088 // setter directly is the difference between one code path and two that can
3089 // disagree.
3090 self.set_property_with_key(
3091 &receiver,
3092 key,
3093 value.clone(),
3094 crate::interp::DeleteFailure::Throw,
3095 )?;
3096 return Ok(Value::Undefined);
3097 }
3098 let property = Property {
3099 value: Some(value.clone()),
3100 writable: true,
3101 // Enumerable, despite the accessor it shadows not being. The reference installs
3102 // it that way and six cases check it (`setter-creates-own-property` and friends).
3103 enumerable: true,
3104 configurable: true,
3105 ..Property::default()
3106 };
3107 if !self.object_define_own_property(&receiver, key, property)? {
3108 return Err(self.type_error("the receiver refused the definition"));
3109 }
3110 Ok(Value::Undefined)
3111 }
3112
3113 /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3114 ///
3115 /// The indices of a typed array are not properties at all — they are bytes in the
3116 /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3117 /// fly. That makes their descriptor shape fixed: every valid index is writable,
3118 /// enumerable and configurable, so a definition can only ever change the *value*, and
3119 /// every other descriptor is refused rather than applied.
3120 ///
3121 /// The order of the checks is the spec's, and two of them are load-bearing:
3122 ///
3123 /// * the index is validated **before** the value is converted, because the conversion
3124 /// itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3125 /// detaches from a `valueOf` and still expects `true` with no store, which only
3126 /// happens when the index was valid on the way in;
3127 /// * the store is attempted even when the index has gone out of bounds by the time the
3128 /// conversion finishes, because the store is a silent no-op rather than a failure —
3129 /// the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3130 /// the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3131 ///
3132 /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3133 /// the existing element, which is harmless here: every valid index is already
3134 /// writable, enumerable and configurable, so a `false` in the merged property can only
3135 /// have come from the descriptor having named `false`.
3136 fn integer_indexed_define_own_property(
3137 &mut self,
3138 object: &Gc<JsObject>,
3139 numeric: f64,
3140 property: &Property,
3141 ) -> JsResult<bool> {
3142 // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3143 // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3144 if !typed_array_index_is_valid(object, numeric) {
3145 return Ok(false);
3146 }
3147 // Step 6: the indices are data properties, so an accessor descriptor is refused
3148 // rather than converted. `Object.defineProperty` turns the `false` into a
3149 // `TypeError`; `Reflect.defineProperty` reports it.
3150 if property.is_accessor() {
3151 return Ok(false);
3152 }
3153 // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3154 // definition that asks for anything else cannot be honoured.
3155 if !property.writable || !property.enumerable || !property.configurable {
3156 return Ok(false);
3157 }
3158 // Step 10: only a descriptor that names a value stores anything.
3159 let Some(value) = property.value.clone() else {
3160 return Ok(true);
3161 };
3162 let Some(element) = object.typed_array_element_type() else {
3163 return Ok(false);
3164 };
3165 let stored = self.element_value(element, value)?;
3166 if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3167 return Err(self.type_error(reason));
3168 }
3169 Ok(true)
3170 }
3171
3172 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3173 pub fn object_define_own_property(
3174 &mut self,
3175 object: &Gc<JsObject>,
3176 key: &PropertyKey,
3177 property: Property,
3178 ) -> JsResult<bool> {
3179 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3180 return Ok(accepted);
3181 }
3182 // A proxy always answers above — with `Some` from its trap, or with `None` when
3183 // the trap is absent, and then the definition belongs to the **target**
3184 // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3185 // when there is no trap). Falling through to the ordinary path here defined the
3186 // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3187 // property the target never saw.
3188 if object.proxy_state().is_some() {
3189 let Some((target, _handler)) = self.proxy_parts(object)? else {
3190 return Err(self.type_error("cannot use a proxy that has been revoked"));
3191 };
3192 return self.object_define_own_property(&target, key, property);
3193 }
3194 // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3195 // they accept exactly one descriptor shape. This has to happen before the
3196 // ordinary path, which would happily store a data property next to the buffer —
3197 // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3198 // and `TypedArray/prototype/set` are about this section.
3199 if object.typed_array_element_type().is_some()
3200 && let Some(index) = canonical_numeric_index(key)
3201 {
3202 return self.integer_indexed_define_own_property(object, index, &property);
3203 }
3204 // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3205 // non-extensible object. The check lives here rather than in the callers because
3206 // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3207 // `Array.prototype.filter` uses to store its result, and a species object made
3208 // non-extensible by its own constructor must make that a `TypeError`
3209 // (`target-array-non-extensible`).
3210 // Note the `is_none()`: an already-present property may still be **redefined** on a
3211 // non-extensible object, and only *adding* one is refused (as Distinct from
3212 // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3213 // properties — testing extensibility before looking for the property made every
3214 // `Object.freeze` of an ordinary object refuse its own second step).
3215 if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3216 return Ok(false);
3217 }
3218 // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3219 // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3220 // an omitted field is left alone). Merging here rather than at each call site is
3221 // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3222 // the value and `enumerable` in place.
3223 //
3224 // The merge is a no-op when the property is absent: there is nothing to keep.
3225 let was_partial = property.descriptor_fields.is_some();
3226 let property = match property.descriptor_fields {
3227 None => property,
3228 Some(fields) => {
3229 let base = self.object_get_own_property(object, key)?;
3230 let mut merged = base.clone().unwrap_or_default();
3231 // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3232 // descriptor names, and switching kind discards the other half —
3233 // `{set: f}` on a data property is an accessor with no getter, not a data
3234 // property whose `get` happens to be absent.
3235 let wants_accessor = fields.get || fields.set;
3236 let wants_data = fields.value || fields.writable;
3237 if wants_accessor {
3238 merged.value = None;
3239 merged.writable = false;
3240 merged.getter = property.getter.clone();
3241 merged.setter = property.setter.clone();
3242 } else if wants_data {
3243 merged.getter = None;
3244 merged.setter = None;
3245 if fields.value {
3246 merged.value = property.value.clone();
3247 }
3248 if fields.writable {
3249 merged.writable = property.writable;
3250 }
3251 }
3252 if fields.enumerable {
3253 merged.enumerable = property.enumerable;
3254 }
3255 if fields.configurable {
3256 merged.configurable = property.configurable;
3257 }
3258 merged.descriptor_fields = None;
3259 merged
3260 }
3261 };
3262 // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3263 // descriptor. `define_property_on` runs the same check before it calls here, so an
3264 // ordinary object is already covered; what is *not* is the forwarding a proxy does
3265 // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3266 // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3267 // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3268 // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3269 // own define would have refused.
3270 //
3271 // Only partial descriptors are validated here. A whole `Property` passed by an
3272 // internal caller (`Property::data(…)`) carries attributes that say nothing about
3273 // what the descriptor "named", and those callers rely on the write landing.
3274 if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3275 // Every branch below is gated on `!existing.configurable`: a *configurable*
3276 // property may be reshaped however the descriptor likes, which is why an
3277 // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3278 // must succeed. Testing only `writable` refused that and broke
3279 // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3280 let same_kind = existing.is_accessor() == property.is_accessor();
3281 if !same_kind {
3282 // Step 4: a non-configurable property may not change kind.
3283 if !existing.configurable {
3284 return Ok(false);
3285 }
3286 } else if existing.is_accessor() {
3287 // Step 6: an accessor's halves are its value.
3288 if !existing.configurable
3289 && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3290 || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3291 {
3292 return Ok(false);
3293 }
3294 } else if !existing.configurable && !existing.writable {
3295 // Step 7: a non-configurable *and* non-writable data property's value is
3296 // fixed, and it may not become writable again.
3297 if property.writable {
3298 return Ok(false);
3299 }
3300 let current = existing.value.clone().unwrap_or(Value::Undefined);
3301 let requested = property.value.clone().unwrap_or(Value::Undefined);
3302 if !current.same_value(&requested) {
3303 return Ok(false);
3304 }
3305 }
3306 // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3307 // is frozen with it.
3308 if !existing.configurable
3309 && (property.configurable || property.enumerable != existing.enumerable)
3310 {
3311 return Ok(false);
3312 }
3313 }
3314 // A host class that intercepts definitions owns the attributes of the properties it
3315 // defines: `_class`-style storage on the native side is the usual reason.
3316 if let Some(exotic) = object.exotic()
3317 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3318 {
3319 return Ok(accepted);
3320 }
3321 // An array index is stored in the element vector, which can hold a plain value and
3322 // nothing else. An accessor — or a data property with non-default attributes —
3323 // therefore has to live in the property table, and the element slot is blanked so
3324 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3325 // {get})` stored the accessor where no read ever looked, and the array kept
3326 // answering its old value.
3327 // An array's `length` is not stored in the property table, so defining it has to
3328 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3329 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3330 // {value: 1})` reported success and changed nothing.
3331 if key.as_str() == Some("length") && object.is_array() {
3332 // `{writable: false}` on `length` does not change the length, but it does make
3333 // it read-only — after which neither a later `{writable: true}` nor a store
3334 // past the end may succeed.
3335 if property.value.is_none() {
3336 if !object.length_writable() && property.writable {
3337 return Ok(false);
3338 }
3339 object.set_length_writable(property.writable);
3340 return Ok(true);
3341 }
3342 if !object.length_writable() {
3343 return Ok(false);
3344 }
3345 }
3346 if key.as_str() == Some("length")
3347 && object.is_array()
3348 && let Some(value) = property.value.clone()
3349 {
3350 let requested = value.to_number();
3351 let valid = requested.is_finite()
3352 && requested >= 0.0
3353 && requested.fract() == 0.0
3354 && requested <= u32::MAX as f64;
3355 if !valid {
3356 return Err(self.range_error("invalid array length"));
3357 }
3358 // Truncating deletes the elements above the new length, and a non-configurable
3359 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3360 // makes `a.length = 2` fail rather than quietly drop it.
3361 let current = object.array_length().unwrap_or(0);
3362 let requested = requested as usize;
3363 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3364 // §10.4.2.4 `ArraySetLength` step 3.i.2: the refusal still applies
3365 // `[[Writable]]: false` when the descriptor asked for it — the length is
3366 // left at its old value but locked. Returning `false` alone left it
3367 // writable, which `verifyProperty` catches
3368 // (`defineProperties/15.2.3.7-6-a-164`).
3369 if property
3370 .descriptor_fields
3371 .is_some_and(|fields| fields.writable)
3372 && !property.writable
3373 && object.length_writable()
3374 {
3375 object.set_length_writable(false);
3376 }
3377 return Ok(false);
3378 }
3379 object.array_set_length(self.heap, requested);
3380 return Ok(true);
3381 }
3382 let plain = property.writable
3383 && property.enumerable
3384 && property.configurable
3385 && !property.is_accessor();
3386 if let Some(index) = key.as_str().and_then(array_index)
3387 && object.is_array()
3388 {
3389 // Growing the array needs a writable `length`: after
3390 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3391 // be added.
3392 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3393 return Ok(false);
3394 }
3395 if plain && property.value.is_some() {
3396 // An ordinary element: the vector is where a read looks first, so it has
3397 // to be the vector that changes — unless the index is too far out to be
3398 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3399 // one property, because past its own limit it stores the index as an
3400 // ordinary key. Falling through to `define_key` below is the same choice,
3401 // and the alternative was worse: the store used to be *dropped* and the
3402 // length left at 0, which is a silent wrong answer.
3403 let value = property.value.clone().unwrap_or(Value::Undefined);
3404 object.delete_key(key);
3405 if object.array_set(self.heap, index as usize, value) {
3406 return Ok(true);
3407 }
3408 // Past the dense limit the element lives in the table like any property.
3409 object.note_element_descriptor();
3410 object.define_key(key, property);
3411 // A sparse store past the dense limit still extends `length`, which is what
3412 // `a[a.length] = v` relies on — but only extends: shortening would delete
3413 // the sparse properties above the index, including this one.
3414 if index as usize + 1 > object.array_length().unwrap_or(0) {
3415 object.array_set_length(self.heap, index as usize + 1);
3416 }
3417 return Ok(true);
3418 }
3419 // A non-plain element — an accessor, or an attribute that is not the default —
3420 // lives in the table while the slot becomes a hole. Recording it keeps every
3421 // later `a[i] = v` off the dense path, where the write would have shadowed the
3422 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3423 // replace the accessor with a plain data property.
3424 object.note_element_descriptor();
3425 object.define_key(key, property);
3426 // The slot stays, so `length` does not shrink; a hole is not an element, so
3427 // the table entry is now what a read finds.
3428 object.array_set(self.heap, index as usize, Value::Hole);
3429 // `ArraySetLength` step 2 of `OrdinaryDefineOwnProperty`'s index branch —
3430 // `length = index + 1` — applies whatever the descriptor's *attributes* are,
3431 // not just to a plain one: `Object.defineProperty(a, 4294967294, {value: 100})`
3432 // makes `a.length` 4294967295 (`defineProperty/15.2.3.6-4-183`).
3433 if index as usize + 1 > object.array_length().unwrap_or(0) {
3434 object.array_set_length(self.heap, index as usize + 1);
3435 }
3436 return Ok(true);
3437 }
3438 object.define_key(key, property);
3439 Ok(true)
3440 }
3441
3442 /// Build a proxy object over `target`, with its traps read from `handler`.
3443 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3444 JsObject::proxy(self.heap, target, handler)
3445 }
3446
3447 /// The `revoke` function for a proxy's slots.
3448 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3449 let revoke = JsObject::function(
3450 self.heap,
3451 Some(self.realm.function_proto.clone()),
3452 Callable::Revoker(slots),
3453 );
3454 // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3455 // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3456 // inherited from `Function.prototype` reads the same but fails the three cases that
3457 // check the own-property list (`revocation-function-{length,name,property-order}`).
3458 revoke.define("length", Property::name_or_length(Value::Int(0)));
3459 revoke.define("name", Property::name_or_length(self.string("")));
3460 revoke
3461 }
3462
3463 /// A new array.
3464 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3465 let array = JsObject::array(
3466 self.heap,
3467 Some(self.realm.array_proto.clone()),
3468 elements.len(),
3469 );
3470 for (index, element) in elements.into_iter().enumerate() {
3471 array.array_set(self.heap, index, element);
3472 }
3473 array
3474 }
3475
3476 /// A new native function object.
3477 ///
3478 /// The observable `name` and `length` are installed as properties here, which is
3479 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3480 /// so `f.name = "x"` behaves like the writable property it is.
3481 /// A native constructor that builds its own instance after validating its arguments.
3482 ///
3483 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3484 /// check runs before `new.target.prototype` is read.
3485 pub fn new_native_ctor(
3486 &self,
3487 name: impl Into<String>,
3488 length: u32,
3489 func: NativeFn,
3490 ) -> Gc<JsObject> {
3491 let function = JsObject::function(
3492 self.heap,
3493 Some(self.realm.function_proto.clone()),
3494 Callable::Native {
3495 func,
3496 own_instance: true,
3497 },
3498 );
3499 function.set_constructible(true);
3500 function.define(
3501 "length",
3502 Property::name_or_length(Value::Int(length as i32)),
3503 );
3504 function.define("name", Property::name_or_length(self.string(name)));
3505 function
3506 }
3507
3508 /// A native constructor that lets `new` build the instance first.
3509 ///
3510 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3511 /// validation that must precede reading `new.target.prototype`, so the object can be
3512 /// created before the implementation runs. Distinct from [`Interp::new_native`],
3513 /// which makes a *method* and therefore not a constructor at all.
3514 pub fn new_native_constructor(
3515 &self,
3516 name: impl Into<String>,
3517 length: u32,
3518 func: NativeFn,
3519 ) -> Gc<JsObject> {
3520 let function = self.new_native(name, length, func);
3521 function.set_constructible(true);
3522 function
3523 }
3524
3525 /// A new host function object: a native closure that carries its own state.
3526 ///
3527 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3528 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3529 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3530 /// this safe: the closure must not capture a `Gc`.
3531 pub fn new_host_function(
3532 &self,
3533 name: impl Into<String>,
3534 length: u32,
3535 func: crate::object::HostFn,
3536 ) -> Gc<JsObject> {
3537 self.new_host_inner(name.into(), length, func, false)
3538 }
3539
3540 /// A host constructor: `new` hands it `this = undefined`, so it validates its
3541 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3542 pub fn new_host_ctor(
3543 &self,
3544 name: impl Into<String>,
3545 length: u32,
3546 func: crate::object::HostFn,
3547 ) -> Gc<JsObject> {
3548 let function = self.new_host_inner(name.into(), length, func, true);
3549 function.set_constructible(true);
3550 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3551 // installs its own methods on it, so it starts as a plain object.
3552 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3553 function.define(
3554 "prototype",
3555 Property {
3556 value: Some(Value::Object(proto)),
3557 writable: true,
3558 enumerable: false,
3559 configurable: false,
3560 ..Property::default()
3561 },
3562 );
3563 function
3564 }
3565
3566 fn new_host_inner(
3567 &self,
3568 name: String,
3569 length: u32,
3570 func: crate::object::HostFn,
3571 own_instance: bool,
3572 ) -> Gc<JsObject> {
3573 let function = JsObject::function(
3574 self.heap,
3575 Some(self.realm.function_proto.clone()),
3576 Callable::Host {
3577 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3578 own_instance,
3579 },
3580 );
3581 function.define(
3582 "length",
3583 Property::name_or_length(Value::Int(length as i32)),
3584 );
3585 function.define("name", Property::name_or_length(self.string(name)));
3586 function
3587 }
3588
3589 /// A callable object with the `length`/`name` a built-in function has, in that order.
3590 ///
3591 /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3592 /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3593 /// [`JsObject::function`] defines neither, which is why every capability helper built
3594 /// with it reported no own `length` and no own `name` at all.
3595 ///
3596 /// The attributes are the spec's for a built-in: not writable, not enumerable,
3597 /// configurable.
3598 pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3599 let function =
3600 JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3601 function.define(
3602 "length",
3603 Property::name_or_length(Value::Int(length as i32)),
3604 );
3605 function.define("name", Property::name_or_length(self.string(name)));
3606 function
3607 }
3608
3609 /// A new native function object.
3610 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3611 let function = JsObject::function(
3612 self.heap,
3613 Some(self.realm.function_proto.clone()),
3614 Callable::Native {
3615 func,
3616 own_instance: false,
3617 },
3618 );
3619 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3620 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3621 // `length,name` and this listed `name,length`. A bytecode function already gets it
3622 // the right way round; only native ones were built backwards.
3623 function.define(
3624 "length",
3625 Property::name_or_length(Value::Int(length as i32)),
3626 );
3627 function.define("name", Property::name_or_length(self.string(name)));
3628 function
3629 }
3630
3631 /// A new bound function.
3632 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3633 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3634 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3635 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3636 let constructible = target
3637 .as_object()
3638 .is_some_and(|target| target.is_constructor());
3639 let bound = JsObject::function(
3640 self.heap,
3641 Some(self.realm.function_proto.clone()),
3642 Callable::Bound { target, this, args },
3643 );
3644 bound.set_constructible(constructible);
3645 bound
3646 }
3647
3648 /// A new reference cell.
3649 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3650 Gc::new(self.heap, Cell::new(value))
3651 }
3652
3653 // -- running ------------------------------------------------------------
3654
3655 /// Evaluate `code` as a script body and return its completion value.
3656 /// Compile and run `source` for the engine's own use, returning its completion value.
3657 ///
3658 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3659 /// needs to be a real async function, and the engine already runs those as coroutines,
3660 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3661 ///
3662 /// Differences from [`Self::eval_in_global`], both deliberate:
3663 ///
3664 /// * It does **not** drain the microtask queue. Install runs while the realm is still
3665 /// being built, and the source is an IIFE that only constructs a closure, so there
3666 /// is nothing to drain — and draining here would run script-queued jobs in the
3667 /// middle of `install`.
3668 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3669 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3670 /// and it should not look like the user wrote something wrong.
3671 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3672 let program = match js_parse::parse_script(source) {
3673 Ok(program) => program,
3674 Err(error) => {
3675 let message = format!("builtin source does not parse: {error}");
3676 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3677 }
3678 };
3679 let mut code = match js_compile::compile_script_with_source(&program, source) {
3680 Ok(code) => code,
3681 Err(error) => {
3682 let message = format!("builtin source does not compile: {}", error.message);
3683 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3684 }
3685 };
3686 // The frame has to name something, and `<builtin>` is what a stack trace through
3687 // this code should say.
3688 code.set_filename("<builtin>");
3689 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3690 let closure_vars = compiled.code.closure_vars.clone();
3691 let env = self.global_env(&closure_vars);
3692 let this = Value::Object(self.realm.global.clone());
3693 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3694 }
3695
3696 /// Run an already-parsed script and drain the microtasks it queued.
3697 ///
3698 /// The drain is what lets an `async` function's body advance past its first `await`
3699 /// before the host sees the result: nothing else pumps the job queue.
3700 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3701 let this = Value::Object(self.realm.global.clone());
3702 self.run_script_with_this(code, this)
3703 }
3704
3705 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3706 ///
3707 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3708 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3709 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3710 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3711 /// state the next script evaluation tripped over.
3712 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3713 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3714 let closure_vars = compiled.code.closure_vars.clone();
3715 let env = self.global_env(&closure_vars);
3716 let callee = Value::Undefined;
3717 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3718 // The script is done, so the microtasks it queued run before the host sees the
3719 // result. Without this an `async` function's body would never advance past its
3720 // first `await`, because nothing else drains the queue.
3721 self.drain_jobs()?;
3722 Ok(result)
3723 }
3724
3725 /// Compile and run `source` in global scope, returning its completion value.
3726 ///
3727 /// This is what `eval` and `new Function` use. Running it as a script means it
3728 /// sees the global object and nothing else, which is right for `eval("1+1")` and
3729 /// for a `Function` body; a *direct* eval that reads a local variable would need
3730 /// the compiler to hand its variable environment over, which is not implemented.
3731 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3732 self.eval_in_global_named(source, EVAL_FILE, false)
3733 }
3734
3735 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3736 ///
3737 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3738 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3739 /// through the code, so they cannot share one constant.
3740 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3741 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3742 }
3743
3744 /// Evaluate `source` as a global script, reported under `file`.
3745 ///
3746 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3747 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3748 /// from inside a C callback, where the interpreter is the running one rather than a
3749 /// context's own.
3750 pub fn eval_in_global_named(
3751 &mut self,
3752 source: &str,
3753 file: &str,
3754 barrier: bool,
3755 ) -> JsResult<Value> {
3756 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3757 // eval-created global binding — configurable, unlike a script's own `var`.
3758 self.eval_depth += 1;
3759 if barrier {
3760 let depth = self.frames.len();
3761 self.trace_barriers.push(depth);
3762 }
3763 let result = self.eval_in_global_inner(source, file);
3764 if barrier {
3765 self.trace_barriers.pop();
3766 }
3767 self.eval_depth -= 1;
3768 result
3769 }
3770
3771 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3772 let compiled = self.compile_global_script(source, file, false)?;
3773 let strict = compiled.strict;
3774 self.run_eval_script(compiled, strict)
3775 }
3776
3777 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3778 ///
3779 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3780 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3781 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3782 /// direct eval's is.
3783 pub fn eval_script_with_this(
3784 &mut self,
3785 source: &str,
3786 file: &str,
3787 this: Value,
3788 ) -> JsResult<Value> {
3789 let program = match js_parse::parse_script(source) {
3790 Ok(program) => program,
3791 Err(error) => {
3792 return Err(Signal::Throw(self.syntax_error_at(
3793 file,
3794 error.span.start.line,
3795 error.span.start.column,
3796 &error.message,
3797 )));
3798 }
3799 };
3800 let mut compiled = match js_compile::compile_script(&program) {
3801 Ok(compiled) => compiled,
3802 Err(error) => {
3803 return Err(Signal::Throw(self.syntax_error_at(
3804 file,
3805 error.span.start.line,
3806 error.span.start.column,
3807 &error.message,
3808 )));
3809 }
3810 };
3811 compiled.set_filename(file);
3812 self.run_script_with_this(compiled, this)
3813 }
3814
3815 /// Parse and compile `source` as a global script, without running it.
3816 ///
3817 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3818 /// before a promise exists to reject — while still evaluating in the same eval context
3819 /// (direct-eval strictness, `new.target`, `super`).
3820 fn compile_global_script(
3821 &mut self,
3822 source: &str,
3823 file: &str,
3824 async_body: bool,
3825 ) -> JsResult<CompiledFunction> {
3826 // A *direct* eval inherits the strictness of the code that called it, which is
3827 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3828 // implicit global. The caller's frame is the innermost one here, because a
3829 // native function does not push a frame of its own.
3830 let strict = self.current_strict();
3831 // `eval` runs in the caller's function context, so `new.target` is legal here
3832 // even though the source is a bare script — and so is `super.x` when the caller
3833 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3834 // caller's, which is what `special_object 4` already does.
3835 let context = js_parse::EvalContext {
3836 in_method: self.enclosing_home_object().is_some(),
3837 // `super()` belongs to a derived constructor, and an eval'd body is not a
3838 // constructor at all: the caller frame's `this` is already built.
3839 in_derived_constructor: false,
3840 };
3841 // A *global* eval is not a function body: `new.target` and `super` are out of
3842 // reach there. Its `{async: true}` form differs in the other direction — the body
3843 // may `await` — so the two flags are independent and the reference sets both from
3844 // the eval type rather than from the caller.
3845 let parsed = if async_body {
3846 js_parse::parse_suspensible_global_eval(source, strict)
3847 } else {
3848 js_parse::parse_eval_script_in(source, strict, context)
3849 };
3850 let program = match parsed {
3851 Ok(program) => program,
3852 Err(error) => {
3853 // The message is bare: the position lives in `fileName`,
3854 // `lineNumber`, `columnNumber` and the stack frame above, which is where
3855 // the reference puts it. An `invalid source: L:C: ` prefix made
3856 // `e.message` differ from the reference while the stack already agreed.
3857 return Err(Signal::Throw(self.syntax_error_at(
3858 file,
3859 error.span.start.line,
3860 error.span.start.column,
3861 &error.message,
3862 )));
3863 }
3864 };
3865 let mut compiled = match if async_body {
3866 js_compile::compile_script_suspensible(&program)
3867 } else {
3868 js_compile::compile_script(&program)
3869 } {
3870 Ok(compiled) => compiled,
3871 // A construct the compiler does not handle yet is reported the same way a
3872 // parse error is: it happens before anything runs, so the trace is the
3873 // position in the source followed by the caller.
3874 Err(error) => {
3875 return Err(Signal::Throw(self.syntax_error_at(
3876 file,
3877 error.span.start.line,
3878 error.span.start.column,
3879 &error.message,
3880 )));
3881 }
3882 };
3883 compiled.set_filename(file);
3884 Ok(compiled)
3885 }
3886
3887 /// Run an `eval`'d script in the caller's scope.
3888 ///
3889 /// Three things have to come from the calling frame, because the eval'd code is a
3890 /// script and would otherwise see only the global object:
3891 ///
3892 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3893 /// * `arguments`, exposed as a binding of the eval's own scope, so
3894 /// `f("arguments.length", 1)` sees the caller's arguments;
3895 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3896 /// `eval("var v = 1")` into the global object.
3897 ///
3898 /// Locals of the calling function are *not* reachable: that needs the compiler to
3899 /// hand its variable environment over, which this milestone does not do.
3900 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3901 // `this` and `arguments` come from the innermost frame only — those are not
3902 // lexical — while the name bindings come from the whole chain of frames, part
3903 // of it being ordinary scope resolution.
3904 // An arrow has no `this` of its own, so an `eval` inside one inherits the
3905 // enclosing function's receiver — the lexical `this` the arrow was compiled to
3906 // read from its closure.
3907 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3908 // variable environment is the innermost frame of all: an arrow's own body is where
3909 // `var`s declared by an `eval` inside it belong.
3910 let caller_index = self
3911 .frames
3912 .iter()
3913 .rposition(|frame| !frame.code.code.is_arrow)
3914 .or_else(|| self.frames.len().checked_sub(1));
3915 let env_index = self.frames.len().checked_sub(1);
3916 let caller = caller_index.and_then(|index| self.frames.get(index));
3917 let (this, passed) = match caller {
3918 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3919 // No frame at all: the eval is running at the top level, so there is
3920 // nothing to inherit and the global receiver is right.
3921 None => (Value::Object(self.realm.global.clone()), Vec::new()),
3922 };
3923 // Innermost frame first, so the first binding found for a name is the one that
3924 // shadows the rest. A script frame (`<eval>`) contributes nothing.
3925 let mut bindings: Vec<EvalBinding> = Vec::new();
3926 // The calling function's own bindings, resolved by the compiler at the call
3927 // site. That table is the only reliable answer when a name is declared twice in
3928 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3929 // body means, and guessing by declaration order picks the wrong one as soon as
3930 // two loops in a row use the same name.
3931 // Only a *direct* eval sees the caller's scope. The compiler records a site for
3932 // every direct call — a bare `eval(...)` callee — so finding one at the current
3933 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3934 // callee to a value first and leave no site behind.
3935 let mut direct = false;
3936 let mut resolved_here = false;
3937 if let Some(frame) = self.frames.last() {
3938 let (line, column) = frame
3939 .code
3940 .code
3941 .position_at(frame.at as u32)
3942 .unwrap_or_default();
3943 // The nearest site at or before the current position, not an exact match:
3944 // the recorded position of the `call` instruction is the callee's, which
3945 // sits a few columns inside the call expression the compiler recorded. A
3946 // site is unique per call, so "the closest one behind us" identifies it.
3947 if let Some(site) = frame
3948 .code
3949 .code
3950 .eval_sites
3951 .iter()
3952 .filter(|site| (site.line, site.column) <= (line, column))
3953 .max_by_key(|site| (site.line, site.column))
3954 {
3955 direct = true;
3956 resolved_here = true;
3957 for binding in &site.bindings {
3958 // An enclosing function's frame sits `owner` levels below the one
3959 // running the call.
3960 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3961 else {
3962 continue;
3963 };
3964 bindings.push(EvalBinding {
3965 name: binding.name.clone(),
3966 frame,
3967 slot: if binding.is_arg {
3968 EvalSlot::Arg
3969 } else {
3970 EvalSlot::Local
3971 },
3972 index: binding.index as usize,
3973 });
3974 }
3975 }
3976 }
3977 for frame_index in (0..self.frames.len()).rev() {
3978 // Skip the innermost frame's flat scan when the compiler already answered
3979 // for it; an enclosing frame still needs one, because the eval resolves
3980 // those names dynamically.
3981 if resolved_here && frame_index == self.frames.len() - 1 {
3982 continue;
3983 }
3984 let frame = &self.frames[frame_index];
3985 for (index, arg) in frame.code.code.args.iter().enumerate() {
3986 bindings.push(EvalBinding {
3987 name: arg.name.clone(),
3988 frame: frame_index,
3989 slot: EvalSlot::Arg,
3990 index,
3991 });
3992 }
3993 for (index, local) in frame.code.code.vars.iter().enumerate() {
3994 bindings.push(EvalBinding {
3995 name: local.name.clone(),
3996 frame: frame_index,
3997 slot: EvalSlot::Local,
3998 index,
3999 });
4000 }
4001 }
4002 let mut seen = BTreeSet::new();
4003 bindings.retain(|binding| seen.insert(binding.name.clone()));
4004
4005 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4006 // elements is all the spec's ordinary uses need.
4007 //
4008 // Known divergence: this is bound for a *global* eval too, where there is no
4009 // caller and the reference throws `'arguments' is not defined`. Deciding properly
4010 // needs "does the calling frame have an `arguments` of its own", which is not
4011 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4012 // script or eval body does not, and `eval(b)` passes the callee as a value so even
4013 // the call-site detection does not answer it. Modelled as a binding in the caller's
4014 // variable environment, this would fall out; that is a larger change than the one
4015 // this comment is attached to.
4016 let arguments = Value::Object(self.new_array(passed));
4017
4018 // Only a *strict* eval gets a variable environment of its own. A sloppy one
4019 // declares its `var`s in the caller's — which for a top-level eval is the global
4020 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4021 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4022 // vanish into a scope nobody reads back from.
4023 let previous_scope = if code_strict {
4024 self.eval_scope.replace(BTreeMap::new())
4025 } else {
4026 None
4027 };
4028 let previous_arguments = self.eval_arguments.replace(arguments);
4029 let previous_with = self.eval_with.replace(self.with_objects());
4030 let inherited_new_target = self
4031 .frames
4032 .iter()
4033 .rev()
4034 .find(|frame| !frame.code.code.is_arrow)
4035 .map(|frame| frame.new_target.clone());
4036 let previous_new_target = self
4037 .eval_new_target
4038 .replace(inherited_new_target.unwrap_or(Value::Undefined));
4039 let eval_cells = self.eval_cells_for(&bindings);
4040 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4041 // A sloppy direct eval declares its `var`s in the caller's variable environment;
4042 // `declare_eval_local` needs to know which frame that is.
4043 // An indirect eval gets the global environment, so nothing of the caller's is
4044 // recorded as the place its `var`s belong.
4045 let previous_caller = self
4046 .eval_caller
4047 .replace(if direct { env_index } else { None });
4048 // The cell-based view of the same bindings, which is what a closure created
4049 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4050 // whose compiler did not put a binding in a cell simply does not appear here —
4051 // reads and writes still work through `eval_bindings`, they just cannot outlive
4052 // the eval.
4053 let previous_eval_scope = self
4054 .active_eval_scope
4055 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4056 let compiled = Gc::new(self.heap, CompiledCode::new(code));
4057 let closure_vars = compiled.code.closure_vars.clone();
4058 let env = self.global_env(&closure_vars);
4059 let callee = Value::Undefined;
4060 // An async body does not run here: it becomes a coroutine and answers a promise,
4061 // which is what makes `await` legal in it. `this` still has to be the caller's
4062 // (for a global eval, the global object), because `this` is not part of `await`.
4063 let result = if compiled.code.kind.is_async() {
4064 self.run_async_body(compiled, env, this)
4065 } else {
4066 self.execute(compiled, env, this, Vec::new(), callee)
4067 };
4068 self.eval_scope = previous_scope;
4069 self.eval_arguments = previous_arguments;
4070 self.eval_with = previous_with;
4071 self.eval_new_target = previous_new_target;
4072 self.eval_bindings = previous_bindings;
4073 self.eval_caller = previous_caller;
4074 self.active_eval_scope = previous_eval_scope;
4075 result
4076 }
4077
4078 /// The cell-backed subset of `bindings`, in the same priority order.
4079 ///
4080 /// Both lookup routes have to agree — the eval's own reads go through
4081 /// [`Interp::eval_binding_value`] and the closures it builds go through
4082 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4083 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4084 /// is not in a cell simply does not appear: reads and writes still work, they just
4085 /// cannot be handed to a closure that outlives the eval.
4086 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4087 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4088 for binding in bindings {
4089 let Some(frame) = self.frames.get(binding.frame) else {
4090 continue;
4091 };
4092 let cell = match binding.slot {
4093 EvalSlot::Arg => frame
4094 .code
4095 .arg_cell
4096 .get(binding.index)
4097 .copied()
4098 .unwrap_or(-1),
4099 EvalSlot::Local => frame
4100 .code
4101 .loc_cell
4102 .get(binding.index)
4103 .copied()
4104 .unwrap_or(-1),
4105 };
4106 if cell < 0 {
4107 continue;
4108 }
4109 if let Some(cell) = frame.cells.get(cell as usize) {
4110 names.push((binding.name.clone(), cell.clone()));
4111 }
4112 }
4113 names
4114 }
4115
4116 /// A `SyntaxError` that reports where in the source it happened.
4117 ///
4118 /// Compile-time failures never run, so they have no frame of their own; the
4119 /// reference still puts the position first in the trace, with no function name and
4120 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4121 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4122 /// reference borrows), which is how a script reads the position without parsing
4123 /// the trace.
4124 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4125 ///
4126 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4127 /// `columnNumber`, which is how the reference prints one. A positionless error
4128 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4129 /// the reference raises it from `js_resolve_module`, where there is no position.
4130 pub(crate) fn syntax_error_plain(
4131 &mut self,
4132 error: &js_parse::SyntaxError,
4133 file: &str,
4134 ) -> Value {
4135 if error.positionless {
4136 return self.make_error("SyntaxError", &error.message);
4137 }
4138 self.syntax_error_at(
4139 file,
4140 error.span.start.line,
4141 error.span.start.column,
4142 &error.message,
4143 )
4144 }
4145
4146 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4147 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
4148 let value = self.make_error("SyntaxError", message);
4149 if let Value::Object(object) = &value {
4150 let text = self.string(blamed);
4151 // `stack` is an own data property, and the reference keeps it
4152 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4153 object.define("stack", Property::with_attributes(text, true, false));
4154 let name = self.string(file);
4155 object.define("fileName", Property::with_attributes(name, true, true));
4156 object.define(
4157 "lineNumber",
4158 Property::with_attributes(Value::Int(line as i32), true, true),
4159 );
4160 object.define(
4161 "columnNumber",
4162 Property::with_attributes(Value::Int(column as i32), true, true),
4163 );
4164 }
4165 value
4166 }
4167
4168 /// Run a compiled script whose completion value is a function, returning it.
4169 ///
4170 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4171 /// get the closure out, which keeps the constant-pool plumbing in one place.
4172 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4173 self.run_script(code)
4174 }
4175
4176 /// The environment of a script or of any function compiled at global scope:
4177 /// every entry is a global binding, so each one resolves to the realm's cell.
4178 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4179 let mut cells = Vec::with_capacity(closure_vars.len());
4180 for closure_var in closure_vars {
4181 let cell = match closure_var.closure_type {
4182 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4183 if closure_var.is_lexical =>
4184 {
4185 // A lexical declaration: the cell is created here holding the
4186 // dead-zone marker, which is what makes the binding exist and
4187 // unreadable before its initialiser runs.
4188 self.declare_global(&closure_var.name, closure_var.is_const);
4189 self.realm.globals[&closure_var.name].clone()
4190 }
4191 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4192 // A `var` or function declaration becomes a property of the global
4193 // object, and it exists from here on — which is why
4194 // `print(v); var v = 1` prints `undefined` instead of raising.
4195 // Declaring it at instantiation time (rather than at the
4196 // initialiser) is also what makes it non-configurable: the store
4197 // then lands on an existing property instead of creating one.
4198 self.declare_var_global(&closure_var.name);
4199 // The cell is a placeholder that nothing indexes; it cannot be
4200 // omitted because the slot has to hold something.
4201 self.new_cell(Value::Undefined)
4202 }
4203 _ => {
4204 // An undeclared global is read by name; the cell is a
4205 // placeholder that nothing indexes.
4206 self.new_cell(Value::Undefined)
4207 }
4208 };
4209 cells.push(cell);
4210 }
4211 Gc::new(
4212 self.heap,
4213 ClosureEnv {
4214 cells,
4215 eval_scope: None,
4216 local_vars: None,
4217 local_phase: 1,
4218 },
4219 )
4220 }
4221
4222 /// Push a frame and run until it returns.
4223 pub(crate) fn execute(
4224 &mut self,
4225 code: Gc<CompiledCode>,
4226 env: Gc<ClosureEnv>,
4227 this: Value,
4228 args: Vec<Value>,
4229 callee: Value,
4230 ) -> JsResult<Value> {
4231 let depth = self.frames.len();
4232 if depth == 0 {
4233 // A throw that reached the host ends the *active* mode: the next one is catchable
4234 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4235 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4236 // for the throw that evaluation will raise.
4237 self.uncatchable = false;
4238 }
4239 self.push_frame(code, env, this, args, callee)?;
4240 loop {
4241 // The fast loop first: it runs whole runs of records with `pc` in a register.
4242 //
4243 // `step`'s `pc` lives in the frame, so every instruction writes it back and
4244 // reads it again — a store, a load and two bounds checks that a loop body does
4245 // not need, because nothing outside the loop can run in between. This is the
4246 // classic split: advance a register, and only spill it when leaving.
4247 //
4248 // `Some(value)` means the function ended by running off the end of its
4249 // instruction array, which is a normal return.
4250 let step = match self.run_fast() {
4251 Ok(Some(value)) => Ok(Step::Return(value)),
4252 Ok(None) => self.step(),
4253 Err(signal) => Err(signal),
4254 };
4255 match step {
4256 Ok(Step::Continue) => {}
4257 Ok(Step::Return(value)) => {
4258 self.pop_frame();
4259 // A frame that ended in a `tail_call` hands its value straight to
4260 // its caller: nothing after the call can run, so every frame above
4261 // the callee unwinds with the same value. See [`Frame::tail`] —
4262 // the reference does not reuse frames either, so recursion depth
4263 // and the stack-overflow limit behave the same way.
4264 while self.frames.len() > depth && self.frame().tail {
4265 self.pop_frame();
4266 }
4267 if self.frames.len() == depth {
4268 return Ok(value);
4269 }
4270 // The caller resumes with the value on its stack.
4271 self.frames
4272 .last_mut()
4273 .expect("a caller is live")
4274 .stack
4275 .push(value);
4276 }
4277 Err(Signal::Throw(value)) => {
4278 // The host's standing request becomes the active mode for this unwind,
4279 // and is consumed here so it does not leak into the next throw.
4280 if self.uncatchable_next {
4281 self.uncatchable_next = false;
4282 self.uncatchable = true;
4283 }
4284 // An uncatchable throw walks past every `catch` on the way out. The
4285 // frames are still popped, because the values they hold have to be
4286 // dropped — only the search for a handler is skipped.
4287 if self.uncatchable {
4288 while self.frames.len() > depth {
4289 self.frames.pop();
4290 }
4291 return Err(Signal::Throw(value));
4292 }
4293 // A handler lives on the stack of the frame that is throwing —
4294 // `catch` pushed it there — so this frame gets the first chance
4295 // to catch before it is popped.
4296 let value = value;
4297 loop {
4298 if self.frames.len() <= depth {
4299 return Err(Signal::Throw(value));
4300 }
4301 if self.catch_here(value.clone()).is_some() {
4302 break;
4303 }
4304 self.frames.pop();
4305 }
4306 }
4307 // A `yield` in a frame that `execute` is running directly means a
4308 // generator body was entered as an ordinary call, which only happens if
4309 // the generator check in `call_or_push` was bypassed.
4310 Ok(Step::Suspend(_)) => {
4311 return Err(Signal::Throw(self.make_error(
4312 "InternalError",
4313 "a generator body ran as an ordinary call",
4314 )));
4315 }
4316 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4317 }
4318 }
4319 }
4320
4321 /// Install a handler for `value` if this frame has one, resuming at it.
4322 ///
4323 /// The scan is the reference's: walk the frame's stack downwards looking for the
4324 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
4325 /// `0` is an enumerator marker rather than a handler — it exists so that a
4326 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
4327 /// here and the unwinding continues.
4328 fn catch_here(&mut self, value: Value) -> Option<()> {
4329 let frame = self.frames.last_mut()?;
4330 while let Some(top) = frame.stack.pop() {
4331 if let Value::CatchOffset(offset) = top {
4332 if offset == 0 {
4333 continue;
4334 }
4335 frame.stack.push(value);
4336 frame.pc = offset as usize;
4337 return Some(());
4338 }
4339 }
4340 None
4341 }
4342
4343 fn push_frame(
4344 &mut self,
4345 code: Gc<CompiledCode>,
4346 env: Gc<ClosureEnv>,
4347 this: Value,
4348 mut args: Vec<Value>,
4349 callee: Value,
4350 ) -> JsResult<()> {
4351 // Two bounds, and the byte budget is the one that decides in practice. The
4352 // reference's message is `stack overflow` on an `InternalError`, not V8's
4353 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4354 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4355 let frame_cost = Self::frame_cost(&code);
4356 let stack_base = self.stack_used();
4357 if self.frames.len() >= self.max_frames
4358 || stack_base.saturating_add(frame_cost) > self.stack_limit
4359 {
4360 return Err(Signal::Throw(
4361 self.make_error("InternalError", "stack overflow"),
4362 ));
4363 }
4364 let arg_count = code.code.args.len();
4365 // How many were actually passed, which `arguments.length` reports and
4366 // `assert(x)` depends on: a call with one argument must not look like a call
4367 // with one argument and an explicit `undefined`.
4368 let passed = args.len();
4369 // Missing arguments are `undefined` in their slots; extra ones are dropped
4370 // from the slots but still reachable through `arguments`.
4371 //
4372 // A call that passes no more than the declared parameters needs **no** copy:
4373 // after the resize below, `args[..passed]` *is* the passed values. Only the
4374 // extra ones — which `truncate` is about to drop — have to be kept, and they are
4375 // the rare case. This used to copy every call: one `Value` clone per argument
4376 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4377 let passed_overflow = (passed > arg_count).then(|| {
4378 let mut values = self.take_values(passed, Value::Undefined);
4379 values[..passed].clone_from_slice(&args[..passed]);
4380 values
4381 });
4382 // Only when the counts differ, which for the overwhelmingly common call — as many
4383 // arguments as parameters — is never. `resize` followed by `truncate` on equal
4384 // lengths is two length compares and nothing else, but this is the hottest few
4385 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4386 if passed != arg_count {
4387 args.resize(arg_count, Value::Undefined);
4388 args.truncate(arg_count);
4389 }
4390 let cell_count = code.code.var_ref_count as usize;
4391 let mut cells = Vec::with_capacity(cell_count);
4392 for _ in 0..cell_count {
4393 cells.push(self.new_cell(Value::Undefined));
4394 }
4395 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4396 // A captured argument lives in its cell, not in the argument slot, so the
4397 // incoming value has to be moved there before the body runs.
4398 for (slot, cell) in code.arg_cell.iter().enumerate() {
4399 if *cell >= 0
4400 && let Some(value) = args.get(slot).cloned()
4401 {
4402 cells[*cell as usize].set(value);
4403 }
4404 }
4405 // Sloppy mode substitutes the global object for a missing receiver and boxes a
4406 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4407 // reports `object`. Strict mode passes the value through untouched.
4408 let this = if code.code.strict {
4409 this
4410 } else if this.is_nullish() {
4411 Value::Object(self.realm.global.clone())
4412 } else if matches!(this, Value::Object(_)) {
4413 this
4414 } else {
4415 match crate::builtins::this_object(self, &this) {
4416 Ok(boxed) => Value::Object(boxed),
4417 Err(_) => this,
4418 }
4419 };
4420 let stack_depth = code.code.stack_size as usize + 1;
4421 // Taken before the `push` borrows `self.frames`, because the operand stack comes
4422 // out of the same recycle pool the locals did.
4423 let stack = self.take_values(stack_depth, Value::Undefined);
4424 self.frames.push(Frame {
4425 code,
4426 env,
4427 this,
4428 args,
4429 passed_count: passed,
4430 passed_overflow: passed_overflow.map(Box::new),
4431 locals,
4432 cells,
4433 local_vars: None,
4434 // Exactly the depth the compiler computed, so the operand stack never
4435 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4436 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4437 // the buffer between calls, so "exactly" costs nothing after the first one.
4438 stack,
4439 pc: 0,
4440 at: 0,
4441 callee,
4442 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4443 cost: frame_cost,
4444 stack_base,
4445 tail: false,
4446 });
4447 Ok(())
4448 }
4449
4450 /// A value buffer of `len` slots, from the recycle pool when there is one.
4451 ///
4452 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4453 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4454 // A frame with no locals asks for nothing, and that is most frames: taking a
4455 // buffer out of the pool, clearing it and resizing it to zero is four operations
4456 // and a pool pop for an empty `Vec`, which is free to construct.
4457 if len == 0 {
4458 return Vec::new();
4459 }
4460 let mut buffer = self.free_values.pop().unwrap_or_default();
4461 buffer.clear();
4462 buffer.resize(len, fill);
4463 buffer
4464 }
4465
4466 /// Return a finished frame's value buffers for the next call to reuse.
4467 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4468 for mut buffer in [
4469 std::mem::take(&mut frame.locals),
4470 frame
4471 .passed_overflow
4472 .take()
4473 .map(|buffer| *buffer)
4474 .unwrap_or_default(),
4475 std::mem::take(&mut frame.stack),
4476 ] {
4477 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4478 // GC root: it kept every value the frame held reachable, which is invisible
4479 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4480 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4481 // exactly that within one run — the target `{}` of a finished IIFE was still
4482 // in its operand stack, in the pool.
4483 buffer.clear();
4484 // A buffer with no capacity is what `Vec::new` is; putting it back would just
4485 // fill the pool with nothing to offer.
4486 if free_values.len() < RECYCLE_SLOTS
4487 && buffer.capacity() > 0
4488 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4489 {
4490 free_values.push(buffer);
4491 }
4492 }
4493 }
4494
4495 /// Pop a finished frame and keep its buffers.
4496 ///
4497 /// Every place that drops a frame goes through here: a recycled buffer is also where
4498 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4499 /// nothing but the reuse.
4500 fn pop_frame(&mut self) -> Option<()> {
4501 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4502 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4503 let last = self.frames.len().checked_sub(1)?;
4504 Self::recycle(&mut self.free_values, &mut self.frames[last]);
4505 self.frames.truncate(last);
4506 Some(())
4507 }
4508
4509 /// Poll the host's interrupt handler, if one is installed.
4510 ///
4511 /// The counter is what keeps this off the hot path when nobody asked: the early return is
4512 /// one `Option` test, and with no handler installed the whole function is that test —
4513 /// `check_memory` next door already costs more, so this cannot be what shows up in a
4514 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4515 #[inline]
4516 fn check_interrupt(&mut self) -> JsResult<()> {
4517 if self.interrupt.is_none() {
4518 return Ok(());
4519 }
4520 if self.interrupt_counter > 0 {
4521 self.interrupt_counter -= 1;
4522 return Ok(());
4523 }
4524 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4525 // The closure is taken out for the duration so that a handler which re-enters the
4526 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4527 let mut handler = self.interrupt.take().expect("checked above");
4528 let abort = handler();
4529 self.interrupt = Some(handler);
4530 if abort {
4531 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4532 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4533 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4534 // documentation says.
4535 self.uncatchable = true;
4536 return Err(Signal::Throw(
4537 self.make_error("InternalError", "interrupted"),
4538 ));
4539 }
4540 Ok(())
4541 }
4542
4543 /// A memory checkpoint: does the heap still fit under its limit?
4544 ///
4545 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4546 /// a `Cell` read and a predictable branch, and the point of asking that often is that
4547 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4548 /// only at calls would let it run until the machine died, which is the exact failure
4549 /// `--memory-limit` exists to prevent.
4550 ///
4551 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4552 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4553 /// script that catches it, drops the reference and carries on is legitimate: measured
4554 /// on `qjs --memory-limit 1M`, the engine recovers.
4555 fn check_memory(&mut self) -> JsResult<()> {
4556 // One `Cell` read and a predictable branch when no limit is set, and an integer
4557 // compare when one is. Containers report their own growth as it happens
4558 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4559 // walking it here was the first version and it was O(live) per 256 instructions,
4560 // which turned a 100k-element push loop into a five-minute one.
4561 let Some(limit) = self.heap.memory_limit() else {
4562 return Ok(());
4563 };
4564 let used = self.heap.used_bytes();
4565 if used <= limit {
4566 // Back under the limit — a collection or a dropped reference did it. The next
4567 // time it goes over is a new failure, not a repeat of this one.
4568 self.oom_reported_at = 0;
4569 return Ok(());
4570 }
4571 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4572 // block runs normally after `out of memory` — it allocates nothing, so nothing
4573 // fails. A check that re-fired on every instruction made the handler itself throw,
4574 // which is a dead end: the error became unobservable from script.
4575 //
4576 // Comparing against the total at the last report gives the same behaviour: the
4577 // handler runs while the total is unchanged, and the very next allocation over the
4578 // limit fails.
4579 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4580 {
4581 return Ok(());
4582 }
4583 self.oom_reported_at = used;
4584 Err(Signal::Throw(
4585 self.make_error("InternalError", "out of memory"),
4586 ))
4587 }
4588
4589 /// Fail before allocating `payload` bytes, if they would not fit.
4590 ///
4591 /// For the allocations whose size comes from script data — `new Array(n)`,
4592 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4593 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4594 /// answering NULL for the one big request.
4595 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4596 if self.heap.fits(payload) {
4597 return Ok(());
4598 }
4599 Err(Signal::Throw(
4600 self.make_error("InternalError", "out of memory"),
4601 ))
4602 }
4603
4604 /// Bytes of frame state the live call chain accounts for.
4605 pub fn stack_used(&self) -> usize {
4606 match self.frames.last() {
4607 Some(frame) => frame.stack_base + frame.cost,
4608 None => 0,
4609 }
4610 }
4611
4612 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4613 ///
4614 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4615 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4616 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4617 /// instead. That is the whole difference between the two models: it rations C stack, we
4618 /// ration frame state, and both quantities are dominated by the value slots — which is
4619 /// why the two depths come out comparable rather than merely proportional.
4620 fn frame_cost(code: &CompiledCode) -> usize {
4621 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4622 std::mem::size_of::<Frame>()
4623 + std::mem::size_of::<Value>() * slots
4624 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4625 }
4626
4627 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4628 ///
4629 /// Only names the eval created are here: a name the frame already declared statically
4630 /// is written through to its own slot instead, so this cannot shadow a real local.
4631 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4632 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4633 let (local_vars, phase) = self.visible_local_vars()?;
4634 if !local_vars.contains(name) {
4635 return None;
4636 }
4637 local_vars.get(name, phase)
4638 }
4639
4640 /// The variables a direct `eval` declared, as the code currently running sees them.
4641 ///
4642 /// Inside an eval that is the *caller's* set — the eval's own variable environment
4643 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4644 /// else it is the current frame's, falling back to the frame the closure was created
4645 /// in.
4646 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4647 ///
4648 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4649 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4650 /// refcount operations (the clone out of the frame, the drop at the end of the match)
4651 /// just to be asked `is_none`.
4652 fn has_visible_local_vars(&self) -> bool {
4653 let index = match self.eval_caller.flatten() {
4654 Some(caller) => caller,
4655 None => match self.frames.len().checked_sub(1) {
4656 Some(top) => top,
4657 None => return false,
4658 },
4659 };
4660 match self.frames.get(index) {
4661 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4662 None => false,
4663 }
4664 }
4665
4666 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4667 // While an `eval` runs, its own frame is on top but its variable environment is
4668 // the *caller's* — so the caller is what the lookup has to start from.
4669 let (index, phase) = match self.eval_caller.flatten() {
4670 Some(caller) => (
4671 caller,
4672 if self.in_parameter_list_at(caller) {
4673 0
4674 } else {
4675 1
4676 },
4677 ),
4678 None => (
4679 self.frames.len().checked_sub(1)?,
4680 if self.in_parameter_list() { 0 } else { 1 },
4681 ),
4682 };
4683 let frame = self.frames.get(index)?;
4684 // The frame's own variables, or — for an arrow, which has no variable environment
4685 // of its own — the one it was created in, which `ClosureEnv` carries.
4686 if let Some(local_vars) = frame.local_vars.clone() {
4687 return Some((local_vars, phase));
4688 }
4689 frame
4690 .env
4691 .local_vars
4692 .clone()
4693 .map(|local_vars| (local_vars, frame.env.local_phase))
4694 }
4695
4696 /// Whether the innermost frame is still evaluating its parameter list.
4697 ///
4698 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4699 /// and a closure created there may only see that much of [`LocalVars`].
4700 fn in_parameter_list(&self) -> bool {
4701 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4702 }
4703
4704 /// [`Interp::in_parameter_list`] for a specific frame.
4705 fn in_parameter_list_at(&self, frame: usize) -> bool {
4706 let Some(frame) = self.frames.get(frame) else {
4707 return false;
4708 };
4709 let code = &frame.code.code;
4710 if !code.has_parameter_expressions {
4711 return false;
4712 }
4713 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4714 // function as its body and let a direct `eval` act accordingly.
4715 if code.body_start == (0, 0) {
4716 return false;
4717 }
4718 match code.position_at(frame.at as u32) {
4719 Some(position) => position < code.body_start,
4720 None => false,
4721 }
4722 }
4723
4724 fn frame(&self) -> &Frame {
4725 self.frames.last().expect("a frame is live")
4726 }
4727
4728 fn frame_mut(&mut self) -> &mut Frame {
4729 self.frames.last_mut().expect("a frame is live")
4730 }
4731
4732 // -- slot access --------------------------------------------------------
4733
4734 /// Move a local's value out, leaving `undefined` in the slot.
4735 ///
4736 /// `None` for a captured slot: its value lives in a cell shared with every closure
4737 /// that closed over it, so it can never be exclusively ours and must not be taken.
4738 ///
4739 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4740 /// for every read and fatal for this one — a clone is exactly the second handle that
4741 /// rules out growing the string in place.
4742 fn take_loc(&mut self, slot: usize) -> Option<Value> {
4743 let frame = self.frames.last_mut()?;
4744 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4745 return None;
4746 }
4747 frame
4748 .locals
4749 .get_mut(slot)
4750 .map(|value| std::mem::replace(value, Value::Undefined))
4751 }
4752
4753 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4754 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4755 ///
4756 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4757 /// it** — the value is put back before the general path runs — so a `valueOf` that
4758 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4759 /// error as it would have without the fusion. This is why the in-place attempt is a
4760 /// `take` and not a `get`: an optimisation that changes what an exception observes is
4761 /// a wrong answer with a good excuse.
4762 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4763 // The take is `matches!`-guarded on the *right* operand only, and the taken value
4764 // is put back on every path that does not append. An earlier version wrote the two
4765 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4766 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4767 // through with its value already taken and dropped: the general path below then
4768 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4769 // A wrong answer, from an optimisation, with every test green.
4770 if matches!(right, Value::String(_))
4771 && let Some(taken) = self.take_loc(slot)
4772 {
4773 if let Value::String(mut left) = taken {
4774 let appended = match left.get_mut() {
4775 Some(string) => string.append_in_place(
4776 // The pattern is the one `matches!` just checked.
4777 match &right {
4778 Value::String(text) => text,
4779 _ => unreachable!("guarded above"),
4780 },
4781 ),
4782 None => None,
4783 };
4784 self.put_loc(slot, Value::String(left));
4785 if let Some(added) = appended {
4786 // The buffer grew where it stood, so the heap's running total has to
4787 // be told: `measure_used` would report the new length, and the two must
4788 // agree or the subtraction at free time leaves the counter wrong.
4789 self.heap.adjust_payload(added as isize);
4790 return Ok(());
4791 }
4792 } else {
4793 self.put_loc(slot, taken);
4794 }
4795 }
4796 // The two-number case, without an operand stack round trip. Everything below
4797 // this point is the *general* path: push both, call `binary_add`, pop the answer,
4798 // store it — five operations and two `Value` clones for what is one integer add.
4799 // `AddImmLoc` already answers this shape that way; the fusion above it was written
4800 // for string append and never got the numeric half, so `t += i` — a counting loop
4801 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4802 let left = self.get_loc(slot);
4803 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4804 self.put_loc(
4805 slot,
4806 match a.checked_add(*b) {
4807 Some(sum) => Value::Int(sum),
4808 None => Value::Float(*a as f64 + *b as f64),
4809 },
4810 );
4811 return Ok(());
4812 }
4813 self.push(left);
4814 self.push(right);
4815 self.binary_add()?;
4816 let value = self.pop();
4817 self.put_loc(slot, value);
4818 Ok(())
4819 }
4820
4821 fn get_arg(&self, slot: usize) -> Value {
4822 self.frame().read_arg(slot)
4823 }
4824
4825 fn put_arg(&mut self, slot: usize, value: Value) {
4826 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4827 if cell == -1 {
4828 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4829 *slot = value;
4830 }
4831 } else {
4832 self.frame().cells[cell as usize].set(value);
4833 }
4834 }
4835
4836 fn get_loc(&self, slot: usize) -> Value {
4837 // The cell mapping is `-1` for every slot that was not captured — which is all of
4838 // them in a function that creates no closure. `Frame::read_loc` tests that first,
4839 // so the common case is one array read and a clone: 20% of every loop iteration
4840 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4841 // sample of `dispatch:arith`).
4842 self.frame().read_loc(slot)
4843 }
4844
4845 fn put_loc(&mut self, slot: usize, value: Value) {
4846 // One borrow instead of three, and the cell check on the frame we already hold.
4847 let frame = self.frames.last_mut().expect("a frame is live");
4848 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4849 if cell < 0 {
4850 if let Some(slot) = frame.locals.get_mut(slot) {
4851 *slot = value;
4852 }
4853 } else if let Some(cell) = frame.cells.get(cell as usize) {
4854 cell.set(value);
4855 }
4856 }
4857
4858 // -- globals ------------------------------------------------------------
4859
4860 /// The name a global-slot operand refers to.
4861 fn global_name(&self, slot: usize) -> String {
4862 self.frame()
4863 .code
4864 .code
4865 .closure_vars
4866 .get(slot)
4867 .map(|c| c.name.clone())
4868 .unwrap_or_default()
4869 }
4870
4871 /// The facts about a global binding that decide where it lives.
4872 ///
4873 /// A script's globals split in two, and the split is observable: `var` and
4874 /// function declarations become properties of the global object (`globalThis.v`
4875 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4876 /// declarations live in the global *lexical* environment and are invisible there
4877 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4878 /// `is_lexical` flag means the answer is already in the bytecode.
4879 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4880 let name = self.global_name(slot);
4881 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4882 // while forwarding a reference through a nested function is built with the
4883 // flags cleared, so `const c` would look like an ordinary `var` from inside a
4884 // closure. Presence in the realm's lexical table is the same fact, recorded
4885 // once, and every slot sees it.
4886 let lexical = self.realm.globals.contains_key(&name);
4887 let is_const = self.realm.lexical_consts.contains(&name);
4888 (name, lexical, is_const)
4889 }
4890
4891 /// The value of `name` in the innermost active `with` object, if any.
4892 ///
4893 /// The active objects are the [`VarKind::With`] locals of every frame still running,
4894 /// innermost frame first and innermost block first within one. Walking frames rather
4895 /// than keeping a separate stack is what makes a closure called from inside a `with`
4896 /// see it, and what keeps the object alive only as long as the block is.
4897 /// The innermost active `with` object that has `name`, if any.
4898 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4899 let objects = self.eval_with.clone().unwrap_or_default();
4900 for object in objects {
4901 let key = self.string(name.to_string());
4902 if self
4903 .has_property(&key, &Value::Object(object.clone()))
4904 .ok()?
4905 {
4906 return Some(object);
4907 }
4908 }
4909 None
4910 }
4911
4912 /// Every active `with` object, innermost first.
4913 fn with_objects(&self) -> Vec<Gc<JsObject>> {
4914 let mut objects = Vec::new();
4915 for frame in self.frames.iter().rev() {
4916 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4917 if var.kind != js_compile::VarKind::With {
4918 continue;
4919 }
4920 // A captured binding lives in its cell and not in the slot list, so the
4921 // cell is consulted first — a closure created inside the block is exactly
4922 // what makes the object captured. Before the store runs the slot still
4923 // holds `undefined`, and a `with` object is always boxed, so a non-object
4924 // entry is simply not in scope yet.
4925 let value = frame
4926 .code
4927 .loc_cell
4928 .get(index)
4929 .copied()
4930 .filter(|cell| *cell >= 0)
4931 .and_then(|cell| frame.cells.get(cell as usize))
4932 .map(|cell| cell.get())
4933 .or_else(|| frame.locals.get(index).cloned());
4934 if let Some(Value::Object(object)) = value {
4935 objects.push(object);
4936 }
4937 }
4938 }
4939 objects
4940 }
4941
4942 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4943 for object in self.eval_with.clone().unwrap_or_default() {
4944 let key = self.string(name.to_string());
4945 if self.has_property(&key, &Value::Object(object.clone()))? {
4946 return Ok(Some(self.read_field(&Value::Object(object), name)?));
4947 }
4948 }
4949 Ok(None)
4950 }
4951
4952 /// Whether every scope between here and the global object is an ordinary one.
4953 ///
4954 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4955 /// bytecode resolved; when any is live the general path has to run in full order. When
4956 /// none is — every ordinary program — a global read is a property read and nothing
4957 /// else, and that is worth caching.
4958 fn scopes_are_plain(&self) -> bool {
4959 self.eval_caller.is_none()
4960 && self.eval_with.is_none()
4961 && self.eval_arguments.is_none()
4962 && self.eval_bindings.is_empty()
4963 && self.eval_scope.is_none()
4964 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4965 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4966 // its `ClosureEnv`, so the test has to be the same one the general path makes.
4967 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4968 // upstream corpus caught and no unit test did.
4969 && !self.has_visible_local_vars()
4970 && self.frame().env.eval_scope.is_none()
4971 }
4972
4973 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4974 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4975 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4976 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4977 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4978 // borrow outlive the `&mut self` the lookup needs.
4979 //
4980 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4981 // forwarded through a nested function has its flags cleared, so the flag cannot
4982 // be believed.
4983 let code = self.frame().code.clone();
4984 let name = code
4985 .code
4986 .closure_vars
4987 .get(slot)
4988 .map(|c| c.name.as_str())
4989 .unwrap_or_default();
4990 let lexical = self.realm.globals.contains_key(name);
4991 // The common case, first: an ordinary global `var`, with a cache in front of the
4992 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
4993 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
4994 // cache hit and return without touching any of it.
4995 if !lexical && self.scopes_are_plain() {
4996 return self.get_plain_global(name, slot);
4997 }
4998 if name == "arguments"
4999 && let Some(arguments) = &self.eval_arguments
5000 {
5001 return Ok(arguments.clone());
5002 }
5003 // A `with` block around the *call site* is part of the scope an `eval` sees, so
5004 // the objects live when the eval started are consulted before anything else. The
5005 // snapshot is taken at entry rather than scanning the frames on every read: a
5006 // block that has already finished still leaves its object in the slot, and a
5007 // bytecode read outside the block must not see it.
5008 if let Some(value) = self.with_lookup(name)? {
5009 return Ok(value);
5010 }
5011 // A variable a direct `eval` declared shadows everything the compiler resolved,
5012 // including an enclosing function's binding: the eval put it in the caller's own
5013 // variable environment, which is nearer than any captured scope.
5014 if let Some((local_vars, phase)) = self.visible_local_vars()
5015 && let Some(cell) = local_vars.get(name, phase)
5016 {
5017 return Ok(cell.get());
5018 }
5019 // The frame that called `eval` is the innermost scope the eval'd code sees, so
5020 // its local `a` wins over a global `a`.
5021 if let Some(value) = self.eval_binding_value(name) {
5022 return Ok(value);
5023 }
5024 // A closure created by an `eval` resolves its free names against the bindings
5025 // that eval saw, even after the eval (and its frames) are gone.
5026 if let Some(cell) = self
5027 .frame()
5028 .env
5029 .eval_scope
5030 .as_ref()
5031 .and_then(|scope| scope.get(name))
5032 {
5033 let value = cell.get();
5034 if matches!(value, Value::Uninitialized) {
5035 return Err(self.throw_reference(name));
5036 }
5037 return Ok(value);
5038 }
5039 // A binding declared by the strict `eval` currently running shadows anything
5040 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5041 if let Some(scope) = &self.eval_scope
5042 && let Some(value) = scope.get(name)
5043 {
5044 return Ok(value.clone());
5045 }
5046 if lexical {
5047 // A lexical global is a binding in a side table, so the dead zone is
5048 // visible and it is nowhere on the global object.
5049 if let Some(cell) = self.realm.globals.get(name) {
5050 let value = cell.get();
5051 if matches!(value, Value::Uninitialized) {
5052 return Err(self.throw_reference(name));
5053 }
5054 return Ok(value);
5055 }
5056 return Err(self.throw_reference(name));
5057 }
5058 // A `var` global is an ordinary property, so the prototype chain and the
5059 // global object's own builtins are all reachable through it.
5060 match self.get_property(&self.realm.global.clone(), name)? {
5061 Some(value) => Ok(value),
5062 None => Err(self.throw_reference(name)),
5063 }
5064 }
5065
5066 /// Read a plain global `var`: a cached own data property, or the full lookup.
5067 ///
5068 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5069 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5070 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5071 let object = self.realm.global.clone();
5072 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5073 if let Some(cached) = &self.global_cache[site]
5074 && object.upgrades_to(&cached.object)
5075 && let Some(value) = object.data_property_at(cached.index, name)
5076 {
5077 return Ok(value);
5078 }
5079 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5080 // chain exactly as before, then remember the answer if it is worth remembering.
5081 let Some(value) = self.get_property(&object, name)? else {
5082 return Err(self.throw_reference(name));
5083 };
5084 if let Some(index) = object.own_data_index(name) {
5085 self.global_cache[site] = Some(GlobalCache {
5086 object: object.downgrade(),
5087 index,
5088 });
5089 }
5090 Ok(value)
5091 }
5092
5093 /// Store to a global binding.
5094 ///
5095 /// Returns a signal when the store is refused: a `const` global may only be
5096 /// written by its initialiser, and a non-configurable `var` global may not be
5097 /// deleted but is always writable.
5098 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5099 let (name, lexical, is_const) = self.global_binding(slot);
5100
5101 // An assignment inside a `with` writes through to the object that supplies the
5102 // name, which for an `eval` means consulting the same chain `get_global` does.
5103 if let Some(owner) = self.with_owner(&name) {
5104 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5105 return Ok(());
5106 }
5107 // A variable the running eval *declared* takes the write before any caller
5108 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5109 // environment even when an enclosing function has a `var c` of its own.
5110 if self.eval_caller.flatten().is_some()
5111 && let Some((local_vars, phase)) = self.visible_local_vars()
5112 && local_vars.contains(&name)
5113 && let Some(cell) = local_vars.get(&name, phase)
5114 {
5115 cell.set(value);
5116 return Ok(());
5117 }
5118 // A binding of the frame that called `eval` takes the write, which is what
5119 // makes `f("a = 3")` change the caller's `a`.
5120 if self.set_eval_binding(&name, &value)? {
5121 return Ok(());
5122 }
5123 // A closure that outlived its `eval` writes through to the same cell it reads.
5124 if let Some(cell) = self
5125 .frame()
5126 .env
5127 .eval_scope
5128 .as_ref()
5129 .and_then(|scope| scope.get(&name))
5130 .cloned()
5131 {
5132 cell.set(value);
5133 return Ok(());
5134 }
5135 // Inside a strict `eval`, a name it declared itself is stored there. An
5136 // *assignment* to a name nobody declared is not a declaration, so it falls
5137 // through: strict mode raises `ReferenceError` for it, which is what
5138 // `eval("1 + (@not_def = 1)")` has to do.
5139 if let Some(scope) = self.eval_scope.as_mut()
5140 && scope.contains_key(&name)
5141 {
5142 scope.insert(name, value);
5143 return Ok(());
5144 }
5145 if lexical {
5146 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5147 if is_const && !matches!(cell.get(), Value::Uninitialized) {
5148 return Err(self.read_only_global(&name));
5149 }
5150 cell.set(value);
5151 return Ok(());
5152 }
5153 // Writing an undeclared lexical global is a `ReferenceError` in strict
5154 // mode and a silent global creation otherwise; creating the cell here
5155 // keeps both paths from losing the value.
5156 let cell = self.new_cell(value);
5157 self.realm.globals.insert(name, cell);
5158 return Ok(());
5159 }
5160 // A variable a direct `eval` declared in this call shadows the global object, even
5161 // when the global already has a property of that name — `var c = "global"` at the
5162 // top level must not capture `eval("var c = 1")` inside a function.
5163 if let Some((local_vars, phase)) = self.visible_local_vars()
5164 && local_vars.contains(&name)
5165 && let Some(cell) = local_vars.get(&name, phase)
5166 {
5167 cell.set(value);
5168 return Ok(());
5169 }
5170 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5171 // remembered a global's slot index since M12b, but the *store* side never did: it
5172 // converted the name to a `PropertyKey` (two allocations) and then scanned the
5173 // global object's whole table — which holds every builtin — on every assignment to
5174 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5175 // full global lookup per iteration; measured with a counter, `s` as a global made
5176 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5177 //
5178 // Re-validated exactly like the read: same object, same index, still the name, and
5179 // — the one extra check a store needs — still writable. A global that is an
5180 // accessor, non-writable, or inherited fails here and falls through to the full
5181 // path below, which reports the failure the way it always did.
5182 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5183 let global = self.realm.global.clone();
5184 if let Some(cached) = &self.global_cache[site]
5185 && global.upgrades_to(&cached.object)
5186 && global.write_data_at(cached.index, &name, value.clone())
5187 {
5188 return Ok(());
5189 }
5190 match global.own_property(&name) {
5191 // A `var` global is writable, so the store goes straight through — but
5192 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5193 // store (a non-writable or accessor-without-setter global) is a silent
5194 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5195 // split every other assignment has.
5196 Some(_) => {
5197 let on_failure = if self.current_strict() {
5198 DeleteFailure::Throw
5199 } else {
5200 DeleteFailure::Ignore
5201 };
5202 let result = self.set_property_with(&global, &name, value, on_failure);
5203 // Teach the cache the slot for a plain writable own data property, which is
5204 // what a declared `var` is. Without this the fast path above could never
5205 // fire for a global that is only ever *written* — its entry would have to
5206 // be put there by a read of the same slot, and a write-only loop has none.
5207 if result.is_ok()
5208 && let Some(index) = global.own_data_index(&name)
5209 {
5210 self.global_cache[site] = Some(GlobalCache {
5211 object: global.downgrade(),
5212 index,
5213 });
5214 }
5215 result
5216 }
5217 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5218 // declaration creates a *configurable* property, which is what makes it
5219 // deletable and is the one way a global differs from a declared `var`.
5220 // In strict mode the same store is a `ReferenceError` instead: that is the
5221 // whole point of strict mode, and creating the global silently meant
5222 // `"use strict"; x = 1` looked like it worked.
5223 None => {
5224 if self.current_strict() {
5225 return Err(self.throw_reference(&name));
5226 }
5227 // A direct eval declares here rather than on the global object: its
5228 // `var`s belong to the caller's variable environment. `declare_eval_local`
5229 // also covers a plain assignment to a variable an earlier eval made.
5230 if let Some(cell) = self.declare_eval_local(&name) {
5231 cell.set(value);
5232 return Ok(());
5233 }
5234 global.define_data(&name, value);
5235 Ok(())
5236 }
5237 }
5238 }
5239
5240 /// The value of a binding of the frame that called `eval`, if there is one.
5241 fn eval_binding_value(&self, name: &str) -> Option<Value> {
5242 let binding = self
5243 .eval_bindings
5244 .iter()
5245 .find(|binding| binding.name == name)?;
5246 let owner = self.frames.get(binding.frame)?;
5247 let (slot, index) = (binding.slot, binding.index);
5248 Some(match slot {
5249 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5250 cell if cell >= 0 => owner
5251 .cells
5252 .get(cell as usize)
5253 .map(|cell| cell.get())
5254 .unwrap_or(Value::Undefined),
5255 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5256 },
5257 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5258 cell if cell >= 0 => owner
5259 .cells
5260 .get(cell as usize)
5261 .map(|cell| cell.get())
5262 .unwrap_or(Value::Undefined),
5263 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5264 },
5265 })
5266 }
5267
5268 /// Write to a binding of the frame that called `eval`.
5269 ///
5270 /// `Ok(false)` means no binding matched and the caller should keep looking. A
5271 /// matched binding can still refuse the store, which is why this is fallible: a
5272 /// `const` is read-only everywhere, and a named function expression's own name is
5273 /// read-only in strict mode.
5274 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5275 let Some(binding) = self
5276 .eval_bindings
5277 .iter()
5278 .find(|binding| binding.name == name)
5279 else {
5280 return Ok(false);
5281 };
5282 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5283 let strict = self.current_strict();
5284 let Some(owner) = self.frames.get_mut(frame) else {
5285 return Ok(false);
5286 };
5287 match slot {
5288 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5289 cell if cell >= 0 => {
5290 if let Some(cell) = owner.cells.get(cell as usize) {
5291 cell.set(value.clone());
5292 }
5293 }
5294 _ => {
5295 if let Some(slot) = owner.args.get_mut(index) {
5296 *slot = value.clone();
5297 }
5298 }
5299 },
5300 EvalSlot::Local => {
5301 let declared = owner.code.code.vars.get(index);
5302 // A `const` is read-only even through `eval`. The realm records this for
5303 // globals (see `lexical_consts`), but a local's `const`-ness is only in
5304 // the bytecode, so this is where it has to be enforced.
5305 if declared.is_some_and(|var| var.is_const) {
5306 return Err(self.read_only_local(name));
5307 }
5308 // The name of a named function expression is read-only too, but only
5309 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5310 // such a name is ignored, the same as a direct store would be.
5311 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5312 return if strict {
5313 Err(self.read_only_local(name))
5314 } else {
5315 Ok(true)
5316 };
5317 }
5318 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5319 cell if cell >= 0 => {
5320 if let Some(cell) = owner.cells.get(cell as usize) {
5321 cell.set(value.clone());
5322 }
5323 }
5324 _ => {
5325 if let Some(slot) = owner.locals.get_mut(index) {
5326 *slot = value.clone();
5327 }
5328 }
5329 }
5330 }
5331 }
5332 Ok(true)
5333 }
5334
5335 /// The `TypeError` an assignment to a read-only binding raises.
5336 fn read_only_local(&self, name: &str) -> Signal {
5337 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5338 }
5339
5340 /// Declare `name` as a variable of the frame that called the running `eval`.
5341 ///
5342 /// `None` when there is no direct eval in progress, or it was called from the top
5343 /// level — then the caller's variable environment *is* the global one and the
5344 /// existing path is right.
5345 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5346 let caller = self.eval_caller.flatten()?;
5347 // The bottom frame is the top-level script, whose variable environment *is* the
5348 // global one — so `eval("var x = 1")` at the top level still creates a global.
5349 if caller == 0 {
5350 return None;
5351 }
5352 // A name the eval's *own* variable environment already binds is not a new
5353 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5354 // `arguments`, and creating a second binding would leave the first — the one
5355 // closures read — untouched. A binding of an *outer* frame does not count: a
5356 // declaration shadows it rather than writing through.
5357 if self
5358 .eval_bindings
5359 .iter()
5360 .any(|binding| binding.name == name && binding.frame == caller)
5361 {
5362 return None;
5363 }
5364 let phase = if self.in_parameter_list_at(caller) {
5365 0
5366 } else {
5367 1
5368 };
5369 self.frame_local_vars(caller)?;
5370 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5371 if let Some(cell) = local_vars.get(name, 1) {
5372 return Some(cell);
5373 }
5374 let cell = self.new_cell(Value::Undefined);
5375 Some(local_vars.declare(name, phase, cell))
5376 }
5377
5378 /// Make sure `frame` has a `LocalVars`, creating it on demand.
5379 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5380 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5381 return Some(local_vars.clone());
5382 }
5383 let local_vars = Gc::new(self.heap, LocalVars::new());
5384 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5385 Some(local_vars)
5386 }
5387
5388 /// Whether the realm already has a binding for `name`, lexically or as an *own*
5389 /// property of the global object. Used to decide whether a store inside an
5390 /// `eval` writes through to the realm or declares a binding of its own.
5391 ///
5392 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5393 /// write to `Object.prototype.toString`, and must not shadow it either.
5394 fn global_knows(&mut self, name: &str) -> bool {
5395 if self.realm.globals.contains_key(name) {
5396 return true;
5397 }
5398 self.realm.global.own_property(name).is_some()
5399 }
5400
5401 /// Whether the code currently running is strict.
5402 ///
5403 /// Read off the frame's function, which is where the parser's answer ended up; a
5404 /// native function never runs strict-only checks, and there is no frame at all
5405 /// before the first script.
5406 pub fn current_strict(&self) -> bool {
5407 self.frames
5408 .last()
5409 .is_some_and(|frame| frame.code.code.strict)
5410 }
5411
5412 /// Initialise a declared global, which is what ends its dead zone.
5413 ///
5414 /// A `var` global becomes a property of the global object: writable, so a later
5415 /// assignment goes through, and non-configurable, so `delete` refuses.
5416 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5417 let (name, lexical, _) = self.global_binding(slot);
5418 // A `var` declared by the strict `eval` currently running belongs to the
5419 // eval's scope, not to the global object: `eval("var v = 1")` must not make
5420 // `typeof v` answer `"number"` afterwards. A name the realm already has is
5421 // initialised in place, which is what a re-declaration inside eval does.
5422 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5423 self.eval_scope
5424 .as_mut()
5425 .expect("checked above")
5426 .insert(name, value);
5427 return Ok(());
5428 }
5429 if let Some(scope) = self.eval_scope.as_mut()
5430 && scope.contains_key(&name)
5431 {
5432 scope.insert(name, value);
5433 return Ok(());
5434 }
5435 if lexical {
5436 // The cell exists (created at declaration time) holding the dead-zone
5437 // marker; storing the value is what makes the binding readable.
5438 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5439 cell.set(value);
5440 return Ok(());
5441 }
5442 let cell = self.new_cell(value);
5443 self.realm.globals.insert(name, cell);
5444 return Ok(());
5445 }
5446 let global = self.realm.global.clone();
5447 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5448 // to answer `false` and leave the binding in place. `with_attributes` ties
5449 // `configurable` to `writable`, so the property is built field by field.
5450 global.define(
5451 &name,
5452 Property {
5453 value: Some(value),
5454 writable: true,
5455 enumerable: true,
5456 configurable: false,
5457 ..Property::default()
5458 },
5459 );
5460 Ok(())
5461 }
5462
5463 /// The `TypeError` a store to a `const` global raises.
5464 fn read_only_global(&self, name: &str) -> Signal {
5465 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5466 }
5467
5468 // -- properties ---------------------------------------------------------
5469
5470 /// Read `object[key]`, following the prototype chain.
5471 ///
5472 /// An inherited accessor runs with the *receiver* as `this`, which is why the
5473 /// lookup returns the owner rather than just the value.
5474 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5475 self.get_property_key(object, &PropertyKey::from(key))
5476 }
5477
5478 /// [`Interp::get_property`] with a key that may be a symbol.
5479 pub fn get_property_key(
5480 &mut self,
5481 object: &Gc<JsObject>,
5482 key: &PropertyKey,
5483 ) -> JsResult<Option<Value>> {
5484 self.get_property_key_for(object, None, key)
5485 }
5486
5487 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5488 ///
5489 /// The receiver matters when the property is found on a *prototype*: a getter has to
5490 /// see the object the read started from. For a primitive that is the primitive
5491 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5492 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5493 /// the owner.
5494 pub fn get_property_key_for(
5495 &mut self,
5496 object: &Gc<JsObject>,
5497 receiver: Option<&Value>,
5498 key: &PropertyKey,
5499 ) -> JsResult<Option<Value>> {
5500 // A proxy answers for itself, before any of the shortcuts below: `new
5501 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5502 // have.
5503 if object.proxy_state().is_some() {
5504 let receiver = receiver
5505 .cloned()
5506 .unwrap_or_else(|| Value::Object(object.clone()));
5507 return self.proxy_get(object, &receiver, key);
5508 }
5509 // A host class's `get_property` trap replaces the whole read, prototype walk
5510 // included — that is what makes a native accessor free rather than a JavaScript
5511 // getter call.
5512 if let Some(exotic) = object.exotic() {
5513 let receiver_value = receiver
5514 .cloned()
5515 .unwrap_or_else(|| Value::Object(object.clone()));
5516 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5517 return Ok(Some(value));
5518 }
5519 // With no `get_property` trap, a `get_own_property` trap still answers for the
5520 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5521 // and the hook lives exactly there. A key the trap reports as absent is still
5522 // looked for on the prototype, which is why the search resumes *above*.
5523 if let Some(property) = exotic.get_own_property(self, object, key)? {
5524 return match property {
5525 Some(property) => self.read_property(property, object, receiver),
5526 None => match lookup_key_above(object, key) {
5527 Some((_, property)) => self.read_property(property, object, receiver),
5528 None => Ok(None),
5529 },
5530 };
5531 }
5532 }
5533 // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
5534 // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
5535 // The `[[Get]]` short-circuit therefore belongs to this one arm.
5536 //
5537 // Constructibility is exactly the split the reference makes: `function f(){}` and
5538 // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
5539 // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
5540 // function" — it *is* the predicate, which is why no extra marker is needed.
5541 if let Some(text) = key.as_str()
5542 && (text == "caller" || text == "arguments")
5543 && object.is_constructor()
5544 && object.is_callable()
5545 && !object.is_bound_function()
5546 // …and only when the body is **sloppy**. A strict body reaches the
5547 // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
5548 // whole `Function/15.3.5.4_2-*gs` family is written against
5549 // (`onlyStrict`, so every function in them is strict).
5550 && !object.function_is_strict()
5551 && object.own_property(text).is_none()
5552 {
5553 return Ok(Some(Value::Undefined));
5554 }
5555 // The element-vector and `length` shortcuts are string-only: an array index
5556 // has no symbol spelling.
5557 if let Some(text) = key.as_str() {
5558 if let Some(value) = self.own_element(object, text) {
5559 return Ok(Some(value));
5560 }
5561 // `length` is not stored as a property: an array's length is its element
5562 // count, and keeping one copy of it is what makes `push`/`pop` and
5563 // `a.length = n` agree.
5564 if let Some(length) = object.array_length()
5565 && text == "length"
5566 {
5567 // Not `Value::Int(length as i32)`: see [`length_value`].
5568 return Ok(Some(crate::object::length_value(length)));
5569 }
5570 }
5571 // A proxy or a hooked exotic object anywhere above `object` makes the static
5572 // table walk below wrong: a proxy's own table is *empty by design* (the properties
5573 // live on its target), so the walk skipped that link entirely and everything behind
5574 // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
5575 // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
5576 // -target-is-proxy.js` are the four.
5577 if Self::chain_needs_dispatch(object) {
5578 return self.walk_get(object, receiver, key);
5579 }
5580 match lookup_key(object, key) {
5581 Some((_, property)) => self.read_property(property, object, receiver),
5582 None => Ok(None),
5583 }
5584 }
5585
5586 /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
5587 /// answer for itself.
5588 ///
5589 /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
5590 /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
5591 /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
5592 /// an inherited getter the object the read started from.
5593 fn walk_get(
5594 &mut self,
5595 start: &Gc<JsObject>,
5596 receiver: Option<&Value>,
5597 key: &PropertyKey,
5598 ) -> JsResult<Option<Value>> {
5599 let receiver = receiver
5600 .cloned()
5601 .unwrap_or_else(|| Value::Object(start.clone()));
5602 let mut current = Some(start.clone());
5603 while let Some(holder) = current {
5604 // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
5605 // has to ask it, not read its (empty) own-property table. `Object.create(new
5606 // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
5607 // instead found nothing.
5608 if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
5609 return Ok(Some(value));
5610 }
5611 // A host class's `get_property` trap replaces the whole read for that holder,
5612 // prototype walk included — the same rule `get_property_key_for` applies to the
5613 // first object.
5614 if let Some(exotic) = holder.exotic()
5615 && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
5616 {
5617 return Ok(Some(value));
5618 }
5619 if let Some(property) = self.object_get_own_property(&holder, key)? {
5620 return self.read_property(property, &holder, Some(&receiver));
5621 }
5622 current = self.object_prototype_of(&holder)?;
5623 }
5624 Ok(None)
5625 }
5626
5627 /// Whether `object` or anything above it has properties that cannot be read out of a
5628 /// property table — a proxy, or an exotic object with a `get_own_property` hook.
5629 ///
5630 /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
5631 /// is the hot path for every property read; this is the check that decides whether it
5632 /// is safe to take it.
5633 fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
5634 object
5635 .chain()
5636 .iter()
5637 .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
5638 }
5639
5640 /// The value a property read answers.
5641 ///
5642 /// One place rather than three, because an accessor has to run with the *receiver* as
5643 /// `this` whether the descriptor came from the property table, an exotic
5644 /// `get_own_property` trap, or a prototype above one.
5645 fn read_property(
5646 &mut self,
5647 property: Property,
5648 object: &Gc<JsObject>,
5649 receiver: Option<&Value>,
5650 ) -> JsResult<Option<Value>> {
5651 if property.is_accessor() {
5652 match &property.getter {
5653 Some(getter) if !matches!(getter, Value::Undefined) => {
5654 let receiver = receiver
5655 .cloned()
5656 .unwrap_or_else(|| Value::Object(object.clone()));
5657 self.call_value(getter.clone(), receiver, Vec::new())
5658 .map(Some)
5659 }
5660 // An accessor with no getter reads as `undefined`.
5661 _ => Ok(Some(Value::Undefined)),
5662 }
5663 } else {
5664 Ok(property.value)
5665 }
5666 }
5667
5668 /// `super.key` — start the search at `proto`, but report to `receiver`.
5669 ///
5670 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5671 /// found on the prototype of a class has to see the *instance* as `this`, and a
5672 /// plain property read off `proto` would lose that.
5673 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5674 let start = self.require_object(proto)?;
5675 let key = self.propkey(key)?;
5676 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5677 if matches!(proto, Value::Null) {
5678 return Ok(Value::Undefined);
5679 }
5680 match lookup_key(&start, &key) {
5681 Some((_, property)) if property.is_accessor() => match &property.getter {
5682 Some(getter) if !matches!(getter, Value::Undefined) => {
5683 self.call_value(getter.clone(), receiver.clone(), Vec::new())
5684 }
5685 _ => Ok(Value::Undefined),
5686 },
5687 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5688 None => Ok(Value::Undefined),
5689 }
5690 }
5691
5692 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5693 ///
5694 /// A setter found on the prototype runs with `receiver` as `this`; a data property
5695 /// is shadowed by a new own property on the receiver, the same rule an ordinary
5696 /// assignment follows.
5697 fn super_write(
5698 &mut self,
5699 receiver: &Value,
5700 proto: &Value,
5701 key: &Value,
5702 value: Value,
5703 ) -> JsResult<()> {
5704 let target = self.require_object(receiver)?;
5705 let key = self.propkey(key)?;
5706 if !matches!(proto, Value::Null)
5707 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5708 {
5709 if property.is_accessor() {
5710 if let Some(setter) = &property.setter
5711 && !matches!(setter, Value::Undefined)
5712 {
5713 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5714 }
5715 return Ok(());
5716 }
5717 // A data property on the prototype is writable or not; reading `owner` at
5718 // all is only for the attribute check.
5719 if !property.writable {
5720 return Err(self.type_error(format!("'{key}' is read-only")));
5721 }
5722 let _ = owner;
5723 }
5724 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5725 }
5726
5727 /// The object a `super` operation needs, or the `TypeError` the spec raises.
5728 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5729 match value.as_object() {
5730 Some(object) => Ok(object.clone()),
5731 None => Err(Signal::Throw(
5732 self.make_error("TypeError", "value is not an object"),
5733 )),
5734 }
5735 }
5736
5737 /// Build the class object `define_class` produces.
5738 ///
5739 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5740 /// whose prototype property is a fresh object inheriting from the parent's
5741 /// prototype, and whose own prototype is the parent constructor — which is what makes
5742 /// a static method inherited too.
5743 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5744 let ctor = self.pop();
5745 let parent = self.pop();
5746 let Value::Object(function) = &ctor else {
5747 return Err(Signal::Throw(
5748 self.make_error("TypeError", "class constructor must be a function"),
5749 ));
5750 };
5751 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5752 // but gives the instances no prototype at all.
5753 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5754 match &parent {
5755 Value::Null => (Some(self.realm.function_proto.clone()), None),
5756 Value::Object(parent_class) => {
5757 if !parent_class.is_callable() {
5758 return Err(Signal::Throw(
5759 self.make_error("TypeError", "parent class must be constructor"),
5760 ));
5761 }
5762 let proto = self.get_property(parent_class, "prototype")?;
5763 match proto {
5764 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5765 Some(Value::Null) => (Some(parent_class.clone()), None),
5766 _ => {
5767 return Err(Signal::Throw(self.make_error(
5768 "TypeError",
5769 "parent prototype must be an object or null",
5770 )));
5771 }
5772 }
5773 }
5774 _ => {
5775 return Err(Signal::Throw(
5776 self.make_error("TypeError", "parent class must be constructor"),
5777 ));
5778 }
5779 }
5780 } else {
5781 (
5782 Some(self.realm.function_proto.clone()),
5783 Some(self.realm.object_proto.clone()),
5784 )
5785 };
5786 let proto = self.new_object(parent_proto);
5787 function.set_proto(parent_ctor);
5788 // A class is not callable without `new`, and its `prototype` is not writable —
5789 // both follow from being a class and are what `class A {}; A()` throws on.
5790 function.set_class_constructor(true);
5791 function.set_home_object(None);
5792 self.set_function_name(&ctor, name);
5793 self.define_class_properties(function, &ctor, &proto)?;
5794 Ok((ctor, proto))
5795 }
5796
5797 /// Give the constructor its `prototype` and `length`, and the prototype its
5798 /// `constructor` back-pointer.
5799 fn define_class_properties(
5800 &mut self,
5801 function: &Gc<JsObject>,
5802 ctor: &Value,
5803 proto: &Gc<JsObject>,
5804 ) -> JsResult<()> {
5805 proto.define(
5806 "constructor",
5807 Property::with_attributes(ctor.clone(), true, false),
5808 );
5809 function.define(
5810 "prototype",
5811 Property::prototype_of(Value::Object(proto.clone()), false),
5812 );
5813 if let Some((code, _)) = bytecode_of(function) {
5814 let length = code.code.defined_args;
5815 function.define(
5816 "length",
5817 Property::name_or_length(Value::Int(length as i32)),
5818 );
5819 }
5820 Ok(())
5821 }
5822
5823 /// The own array element `key` names, if this object has one.
5824 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5825 // A typed array's elements live in its buffer, not in a property list: reading one
5826 // goes through the view's element type so a bounds check and a detached buffer are
5827 // both handled there.
5828 //
5829 // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
5830 // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
5831 // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
5832 // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
5833 // consulted. Testing with `array_index` rejected all three, which let a throwing
5834 // getter installed on `TypedArray.prototype["-1"]` run.
5835 if object.typed_array_parts().is_some() {
5836 let property_key = PropertyKey::from(key);
5837 let numeric = canonical_numeric_index(&property_key)?;
5838 if typed_array_index_is_valid(object, numeric) {
5839 return object.typed_array_element(numeric as usize);
5840 }
5841 // Canonical, but not a valid index: `undefined`, and *final*.
5842 return Some(Value::Undefined);
5843 }
5844 let index = array_index(key)?;
5845 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5846 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5847 // search early, which is why `Array.prototype[1] = 9` could not be seen through
5848 // `[1,,3][1]`.
5849 match object.array_get(index as usize) {
5850 Some(Value::Hole) | None => None,
5851 other => other,
5852 }
5853 }
5854
5855 /// Store `object[key] = value`, honouring setters and inherited properties.
5856 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5857 self.set_property_with(object, key, value, DeleteFailure::Throw)
5858 }
5859
5860 /// Store a property, choosing what to do when the object refuses.
5861 ///
5862 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5863 /// mode, which is the one place assignment differs by mode. Native code (the array
5864 /// methods, `JSON`) always asks for the throw.
5865 pub fn set_property_with(
5866 &mut self,
5867 object: &Gc<JsObject>,
5868 key: &str,
5869 value: Value,
5870 on_failure: DeleteFailure,
5871 ) -> JsResult<()> {
5872 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5873 }
5874
5875 /// [`Interp::set_property_with`] with a key that may be a symbol.
5876 pub fn set_property_with_key(
5877 &mut self,
5878 object: &Gc<JsObject>,
5879 key: &PropertyKey,
5880 value: Value,
5881 on_failure: DeleteFailure,
5882 ) -> JsResult<()> {
5883 self.set_property_with_key_receiver_aware(object, key, value, on_failure)
5884 }
5885
5886 /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
5887 ///
5888 /// The receiver split lives one level up, in
5889 /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
5890 /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
5891 /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
5892 /// stores into `object` itself, which is why the element branch below converts `V`
5893 /// before asking whether the index is valid: `V` may put it back in bounds
5894 /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
5895 fn set_property_with_key_receiver_aware(
5896 &mut self,
5897 object: &Gc<JsObject>,
5898 key: &PropertyKey,
5899 value: Value,
5900 on_failure: DeleteFailure,
5901 ) -> JsResult<()> {
5902 // A proxy's `set` trap decides, and its `false` means the same thing an
5903 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5904 if object.proxy_state().is_some() {
5905 let receiver = Value::Object(object.clone());
5906 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5907 return match (accepted, on_failure) {
5908 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5909 (false, DeleteFailure::Throw) => {
5910 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5911 }
5912 };
5913 }
5914 }
5915 // A host class's `set_property` trap decides for itself. `Some(false)` is a
5916 // refusal and means exactly what a proxy's `false` means.
5917 if let Some(exotic) = object.exotic() {
5918 let receiver = Value::Object(object.clone());
5919 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5920 return match (accepted, on_failure) {
5921 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5922 (false, DeleteFailure::Throw) => {
5923 Err(self.type_error(format!("property '{key}' is read-only")))
5924 }
5925 };
5926 }
5927 }
5928 // The element and `length` shortcuts only exist for string keys: an array
5929 // index has no symbol spelling, and a symbol named `length` is an ordinary
5930 // property.
5931 let text = key.as_str();
5932 // A typed array's elements are a window onto its buffer: the store has to go
5933 // through the view's element type so the value is wrapped (or clamped) and so an
5934 // out-of-range or detached write is a silent no-op, as the spec says.
5935 //
5936 // The key test is `CanonicalNumericIndexString`, like every other index operation
5937 // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
5938 // does not exist, so they do nothing and leave no own property behind
5939 // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
5940 // path, which created a property named `"-0"`.
5941 //
5942 // The conversion comes **first**, before the index is checked at all, and that
5943 // order is observable twice over:
5944 //
5945 // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
5946 // has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
5947 // then store the converted value;
5948 // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
5949 // `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
5950 // run and its exception to escape.
5951 //
5952 // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
5953 // validity check, not a validity check that skips the conversion. The store itself
5954 // is a no-op when the index is invalid by then, which is why no extra guard is
5955 // needed around `typed_array_set`.
5956 if let Some(element) = object.typed_array_element_type()
5957 && let Some(numeric) = canonical_numeric_index(key)
5958 {
5959 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5960 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5961 // in `Interp`, because it is script-observable and the storage borrow inside
5962 // `typed_array_set` must not be held across it.
5963 let stored = self.element_value(element, value)?;
5964 if typed_array_index_is_valid(object, numeric)
5965 && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
5966 {
5967 return Err(self.type_error(reason));
5968 }
5969 return Ok(());
5970 }
5971 if let Some(text) = text
5972 && let Some(index) = array_index(text)
5973 && object.is_array()
5974 {
5975 // An accessor defined on an index lives in the property table while the
5976 // element slot is a hole, so the store has to go through the property first.
5977 // Writing the vector directly skipped the setter entirely.
5978 if let Some(existing) = object.own_property_key(key) {
5979 if existing.is_accessor() {
5980 return match existing.setter.clone() {
5981 Some(setter) if !matches!(setter, Value::Undefined) => {
5982 let receiver = Value::Object(object.clone());
5983 self.call_value(setter, receiver, vec![value]).map(|_| ())
5984 }
5985 _ => match on_failure {
5986 DeleteFailure::Throw => Err(self.type_error(format!(
5987 "cannot set property '{text}', it has only a getter"
5988 ))),
5989 DeleteFailure::Ignore => Ok(()),
5990 },
5991 };
5992 }
5993 if !existing.writable {
5994 return match on_failure {
5995 DeleteFailure::Throw => {
5996 Err(self.type_error(format!("'{text}' is read-only")))
5997 }
5998 DeleteFailure::Ignore => Ok(()),
5999 };
6000 }
6001 }
6002 {
6003 // Growing the array needs a writable `length`.
6004 if (index as usize) >= object.array_length().unwrap_or(0)
6005 && !object.length_writable()
6006 {
6007 return match on_failure {
6008 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6009 DeleteFailure::Ignore => Ok(()),
6010 };
6011 }
6012 // Adding an index past the end makes the array longer, which a
6013 // non-extensible array refuses.
6014 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6015 return match on_failure {
6016 DeleteFailure::Throw => Err(self.type_error(format!(
6017 "cannot add property '{key}', object is not extensible"
6018 ))),
6019 DeleteFailure::Ignore => Ok(()),
6020 };
6021 }
6022 if object.element_is_locked(index) {
6023 return match on_failure {
6024 DeleteFailure::Throw => {
6025 Err(self.type_error(format!("'{key}' is read-only")))
6026 }
6027 DeleteFailure::Ignore => Ok(()),
6028 };
6029 }
6030 // The element vector is only half of `[[Set]]` for an index: the
6031 // prototype chain is consulted first, and a setter there answers instead
6032 // of the element store. This branch used to write the element directly, so
6033 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6034 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6035 // the reference calls the setter and the array keeps no own index.
6036 //
6037 // An *exotic* prototype has no entry to find, because its indices live
6038 // outside the property table — `Object.setPrototypeOf([], typedArray)`
6039 // then looked like "nothing on the chain" and the store created the
6040 // element, where the view's `[[Set]]` answers `true` and does nothing for
6041 // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6042 // checks the array's `length` stays 0). So the dispatch comes first.
6043 if !object.has_own_key(key)
6044 && let Some(proto) = object.proto()
6045 && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6046 {
6047 let receiver = Value::Object(object.clone());
6048 let accepted =
6049 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6050 return if accepted {
6051 Ok(())
6052 } else {
6053 match on_failure {
6054 DeleteFailure::Throw => {
6055 Err(self.type_error(format!("'{key}' is read-only")))
6056 }
6057 DeleteFailure::Ignore => Ok(()),
6058 }
6059 };
6060 }
6061 if let Some((owner, property)) = lookup_key(object, key)
6062 && !owner.ptr_eq(object)
6063 {
6064 match &property {
6065 property if property.is_accessor() => {
6066 match &property.setter {
6067 Some(setter) if !matches!(setter, Value::Undefined) => {
6068 let receiver = Value::Object(object.clone());
6069 self.call_value(setter.clone(), receiver, vec![value])?;
6070 }
6071 _ => {
6072 return match on_failure {
6073 DeleteFailure::Throw => Err(self.type_error(format!(
6074 "cannot set property '{text}', it has only a getter"
6075 ))),
6076 DeleteFailure::Ignore => Ok(()),
6077 };
6078 }
6079 }
6080 return Ok(());
6081 }
6082 property if !property.writable => {
6083 return match on_failure {
6084 DeleteFailure::Throw => {
6085 Err(self.type_error(format!("'{text}' is read-only")))
6086 }
6087 DeleteFailure::Ignore => Ok(()),
6088 };
6089 }
6090 _ => {}
6091 }
6092 }
6093 if object.array_set(self.heap, index as usize, value.clone()) {
6094 return Ok(());
6095 }
6096 // Past the dense limit the slot is too far out to be worth one `Value`
6097 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6098 // constant time by keeping the index as an ordinary property. The store
6099 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6100 // to a legal program.
6101 object.define_key(key, Property::with_attributes(value, true, true));
6102 // Extend, never shorten: the index may be *inside* the current length (a
6103 // huge `length` with a sparse store), and shortening would delete the
6104 // sparse properties above it — including the one just stored.
6105 if index as usize + 1 > object.array_length().unwrap_or(0) {
6106 object.array_set_length(self.heap, index as usize + 1);
6107 }
6108 return Ok(());
6109 }
6110 }
6111 if text == Some("length") && object.is_array() {
6112 if !object.length_writable() {
6113 return match on_failure {
6114 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6115 DeleteFailure::Ignore => Ok(()),
6116 };
6117 }
6118 // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6119 // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6120 // answered `NaN`, which left the assignment silently ignored
6121 // (`S15.4.5.2_A3_T2`).
6122 let length = self.to_js_number(&value)?;
6123 // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6124 // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6125 // `RangeError`s; the old code only tested "finite and non-negative" and then
6126 // truncated, so `[].length = 4294967297` quietly produced a length no array can
6127 // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6128 let valid = length.is_finite()
6129 && length >= 0.0
6130 && length.fract() == 0.0
6131 && length <= u32::MAX as f64;
6132 if !valid {
6133 return Err(self.range_error("invalid array length"));
6134 }
6135 {
6136 let length = length as usize;
6137 // `a.length = n` with `n` below a non-configurable element cannot
6138 // drop that element, so the whole assignment fails. The spec makes
6139 // this a `TypeError` rather than a silent no-op, in any mode.
6140 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6141 // Sloppy mode stops the truncation at the blocking element
6142 // instead of failing; strict mode raises.
6143 // Both modes stop at the blocking element; they differ in
6144 // whether that is reported. The reference truncates *then*
6145 // throws, so the array is left in the shortened state.
6146 object.array_truncate(self.heap, blocked + 1);
6147 return match on_failure {
6148 DeleteFailure::Throw => {
6149 Err(self.type_error(format!("cannot delete property '{blocked}'")))
6150 }
6151 DeleteFailure::Ignore => Ok(()),
6152 };
6153 }
6154 object.array_set_length(self.heap, length);
6155 return Ok(());
6156 }
6157 }
6158 // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6159 // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6160 // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6161 //
6162 // The prototype step is a dispatch, not a lookup. Walking the chain here and
6163 // applying whatever came back is the same thing for an ordinary prototype and
6164 // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6165 // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6166 // answers "not mine, the receiver is not me" without touching the buffer. This
6167 // code used to find nothing owned by `o`, find no property on the view either,
6168 // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6169 // object and never converted (`key-is-valid-index-prototype-chain-set`,
6170 // `key-is-canonical-invalid-index-prototype-chain-set`).
6171 //
6172 // The read-only and accessor rules of step 1 are what make
6173 // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6174 // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6175 let own = match self.lookup_for_write(object, key)? {
6176 Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6177 _ => None,
6178 };
6179 if let Some(property) = own {
6180 if property.is_accessor() {
6181 return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6182 Some(setter) => {
6183 let receiver = Value::Object(object.clone());
6184 self.call_value(setter, receiver, vec![value])?;
6185 Ok(())
6186 }
6187 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6188 // Sloppy code swallows that refusal, strict code raises — the same
6189 // rule the read-only *data* property below follows, and skipping it
6190 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6191 // return silently. The reference answers `TypeError: 'x' is
6192 // read-only`.
6193 None => match on_failure {
6194 DeleteFailure::Throw => {
6195 Err(self.type_error(format!("'{key}' is read-only")))
6196 }
6197 DeleteFailure::Ignore => Ok(()),
6198 },
6199 };
6200 }
6201 // An own non-writable data property stops here: nothing may change it.
6202 if !property.writable {
6203 return match on_failure {
6204 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6205 DeleteFailure::Ignore => Ok(()),
6206 };
6207 }
6208 // An existing writable own property keeps its attributes: only the value
6209 // moves. Redefining instead would reset them, which is how a
6210 // non-configurable global `var` used to become deletable.
6211 if object.write_value_key(key, value.clone()) {
6212 return Ok(());
6213 }
6214 }
6215 // Step 2: hand the store to the prototype, with `object` as the receiver.
6216 if let Some(proto) = object.proto() {
6217 let receiver = Value::Object(object.clone());
6218 let accepted =
6219 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6220 return if accepted {
6221 Ok(())
6222 } else {
6223 match on_failure {
6224 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6225 DeleteFailure::Ignore => Ok(()),
6226 }
6227 };
6228 }
6229 // Step 3: create one, and a non-extensible object cannot.
6230 if !object.is_extensible() {
6231 return match on_failure {
6232 DeleteFailure::Throw => Err(self.type_error(format!(
6233 "cannot add property {key}, object is not extensible"
6234 ))),
6235 DeleteFailure::Ignore => Ok(()),
6236 };
6237 }
6238 object.define_data_key(key, value);
6239 Ok(())
6240 }
6241
6242 /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6243 ///
6244 /// The distinction the fast path above does not need: it is called with the store's
6245 /// receiver already being the object it writes to. Here `object` is the one whose
6246 /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6247 /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6248 /// and not a write to `object`.
6249 ///
6250 /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6251 /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6252 /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6253 /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6254 /// descriptor on the prototype refuses instead, which is the same rule that keeps
6255 /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6256 ///
6257 /// Answers `false` where the spec says `false`; the caller turns that into the
6258 /// strict-mode `TypeError` or the sloppy-mode silence.
6259 fn ordinary_set_with_receiver(
6260 &mut self,
6261 object: &Gc<JsObject>,
6262 receiver: &Value,
6263 key: &PropertyKey,
6264 value: Value,
6265 on_failure: DeleteFailure,
6266 ) -> JsResult<bool> {
6267 // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6268 if object.proxy_state().is_some() {
6269 return Ok(self
6270 .proxy_set(object, key, value, receiver)?
6271 .unwrap_or(true));
6272 }
6273 // A host class decides for itself, with the receiver the caller named.
6274 if let Some(exotic) = object.exotic()
6275 && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6276 {
6277 return Ok(accepted);
6278 }
6279 // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6280 // rather than the receiver, but the receiver may still *be* the view:
6281 // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6282 // itself as receiver, and then the first half applies — convert `V` once, store
6283 // if the index is valid, answer `true` either way. The conversion is the observable
6284 // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6285 //
6286 // Only the second half, a view that is *not* the receiver, skips the conversion
6287 // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6288 // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6289 // below with the value still unconverted.
6290 if object.typed_array_element_type().is_some()
6291 && let Some(numeric) = canonical_numeric_index(key)
6292 {
6293 if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6294 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6295 return Ok(true);
6296 }
6297 if !typed_array_index_is_valid(object, numeric) {
6298 return Ok(true);
6299 }
6300 }
6301 let own = self.object_get_own_property(object, key)?;
6302 if let Some(own) = own {
6303 if own.is_accessor() {
6304 return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6305 Some(setter) => {
6306 self.call_value(setter, receiver.clone(), vec![value])?;
6307 Ok(true)
6308 }
6309 None => Ok(false),
6310 };
6311 }
6312 // A non-writable data descriptor refuses, own or inherited. Either way the
6313 // receiver must not gain a shadowing property.
6314 if !own.writable {
6315 return Ok(false);
6316 }
6317 // Step 1.d: the *receiver's* own descriptor decides whether it can be
6318 // created or written, and it is created as an ordinary data property.
6319 let Some(receiver_object) = receiver.as_object().cloned() else {
6320 return Ok(false);
6321 };
6322 return match self.object_get_own_property(&receiver_object, key)? {
6323 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6324 Some(existing) => self.object_define_own_property(
6325 &receiver_object,
6326 key,
6327 Property {
6328 value: Some(value),
6329 ..existing
6330 },
6331 ),
6332 None => {
6333 self.object_define_own_property(&receiver_object, key, Property::data(value))
6334 }
6335 };
6336 }
6337 // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6338 if let Some(proto) = object.proto() {
6339 return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6340 }
6341 // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6342 // *default* data descriptor here, so control falls into step 2 exactly as if the
6343 // target had owned a writable property — which means the **receiver's** own
6344 // descriptor is asked for before the write. Skipping that question went straight to
6345 // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6346 // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6347 // exactly those calls).
6348 let Some(receiver_object) = receiver.as_object().cloned() else {
6349 return Ok(false);
6350 };
6351 match self.object_get_own_property(&receiver_object, key)? {
6352 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6353 Some(existing) => self.object_define_own_property(
6354 &receiver_object,
6355 key,
6356 Property {
6357 value: Some(value),
6358 ..existing
6359 },
6360 ),
6361 None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6362 }
6363 }
6364
6365 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6366 ///
6367 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6368 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6369 /// a virtual accessor gets its setter run without implementing `set_property` at all.
6370 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6371 /// the prototype, so the walk resumes above the object.
6372 fn lookup_for_write(
6373 &mut self,
6374 object: &Gc<JsObject>,
6375 key: &PropertyKey,
6376 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6377 let Some(exotic) = object.exotic() else {
6378 return Ok(lookup_key(object, key));
6379 };
6380 Ok(match exotic.get_own_property(self, object, key)? {
6381 Some(Some(property)) => Some((object.clone(), property)),
6382 Some(None) => lookup_key_above(object, key),
6383 None => lookup_key(object, key),
6384 })
6385 }
6386
6387 /// Delete `object[key]`.
6388 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6389 self.delete_property_key(object, &PropertyKey::from(key))
6390 }
6391
6392 /// [`Interp::delete_property`] with a key that may be a symbol.
6393 pub fn delete_property_key(
6394 &mut self,
6395 object: &Gc<JsObject>,
6396 key: &PropertyKey,
6397 ) -> JsResult<bool> {
6398 // A proxy decides for itself, and may even throw; the invariant checks live in
6399 // `proxy_delete`.
6400 if let Some(answer) = self.proxy_delete(object, key)? {
6401 return Ok(answer);
6402 }
6403 // A host class's `delete_property` trap decides; `false` is a refusal, which the
6404 // caller reports as a failed delete.
6405 if let Some(exotic) = object.exotic()
6406 && let Some(answer) = exotic.delete_property(self, object, key)?
6407 {
6408 return Ok(answer);
6409 }
6410 // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6411 // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6412 // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6413 // one answers `false` because the elements are non-configurable. The prototype
6414 // chain is not consulted either, which is what makes a throwing getter on
6415 // `TypedArray.prototype["-1"]` stay unrun.
6416 if object.typed_array_parts().is_some()
6417 && object.proxy_state().is_none()
6418 && let Some(numeric) = canonical_numeric_index(key)
6419 {
6420 return Ok(!typed_array_index_is_valid(object, numeric));
6421 }
6422 let mapped_index = key.as_str().and_then(array_index);
6423 if let Some(index) = mapped_index
6424 && let Some(length) = object.array_length()
6425 && (index as usize) < length
6426 {
6427 // An accessor defined on an index lives in the property table rather than the
6428 // element vector, so both have to be cleared: `delete` after
6429 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6430 object.delete_key(key);
6431 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6432 // index stops answering `in`.
6433 if object.element_is_undeletable(index) {
6434 return Ok(false);
6435 }
6436 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6437 // so a later `defineProperty(arguments, "0", {value})` writes to the object
6438 // and no longer through to the parameter. A refused delete leaves the
6439 // mapping alone.
6440 object.drop_mapped_argument(index as usize);
6441 object.array_set(self.heap, index as usize, Value::Hole);
6442 return Ok(true);
6443 }
6444 // An array's `length` is a non-configurable own property that lives outside the
6445 // property table, so `delete_key` finds nothing and reports success — `Reflect
6446 // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6447 // §10.4.4.1 step 3 refuses it.
6448 if key.as_str() == Some("length") && object.array_length().is_some() {
6449 return Ok(false);
6450 }
6451 // The same for an object that is not an array: only a delete that actually
6452 // removed the property ends the alias.
6453 let deleted = object.delete_key(key);
6454 if deleted && let Some(index) = mapped_index {
6455 object.drop_mapped_argument(index as usize);
6456 }
6457 Ok(deleted)
6458 }
6459
6460 // -- proxy traps --------------------------------------------------------
6461 //
6462 // A proxy's internal methods all look the same: ask the handler for the trap, call it
6463 // with the target and the operation's own arguments, then check the answer against
6464 // the target. The checks are not decoration — they are what stops a proxy from
6465 // reporting a `non-configurable` property as missing, which would let a frozen object
6466 // be rewritten by standing in front of it.
6467
6468 /// The target and handler of `object`, or `None` when it is not a proxy.
6469 ///
6470 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6471 /// one has to fail: the slots the traps would have been read from are gone.
6472 fn proxy_parts(&mut self, object: &Gc<JsObject>) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6473 let Some(state) = object.proxy_state() else {
6474 return Ok(None);
6475 };
6476 let state = state.borrow();
6477 match (&state.target, &state.handler) {
6478 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
6479 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
6480 }
6481 }
6482
6483 /// Call `handler[name]`, or answer `None` when the trap is absent.
6484 ///
6485 /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
6486 /// and only a value that is neither is `IsCallable`-checked and refused. Treating
6487 /// `null` as "present but not callable" made every `{ get: null }` proxy throw
6488 /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
6489 /// one per trap plus the `target-is-proxy` variants.
6490 ///
6491 /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
6492 /// this cannot simply be "any non-callable means no trap".
6493 fn proxy_trap(
6494 &mut self,
6495 handler: &Value,
6496 name: &str,
6497 args: Vec<Value>,
6498 ) -> JsResult<Option<Value>> {
6499 let Value::Object(table) = handler else {
6500 return Err(self.type_error("proxy handler is not an object"));
6501 };
6502 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
6503 match trap {
6504 Value::Undefined | Value::Null => Ok(None),
6505 Value::Object(function) if function.is_callable() => {
6506 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
6507 Ok(Some(answer))
6508 }
6509 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
6510 }
6511 }
6512
6513 /// Whether the target's own property `key` is one it refuses to lose.
6514 ///
6515 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
6516 /// its value behind the target's back.
6517 ///
6518 /// A **method**, not a free function, because §10.5.1's invariants say
6519 /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
6520 /// property table directly finds nothing (a proxy's table is empty by design), so every
6521 /// invariant check silently passed for a proxy target. That is what
6522 /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
6523 /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
6524 /// where an array's elements and its `length` — both fixed, both outside the table —
6525 /// are covered.
6526 fn fixed_property(
6527 &mut self,
6528 target: &Gc<JsObject>,
6529 key: &PropertyKey,
6530 ) -> JsResult<Option<Property>> {
6531 Ok(self
6532 .object_get_own_property(target, key)?
6533 .filter(|property| !property.configurable))
6534 }
6535
6536 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
6537 fn proxy_get(
6538 &mut self,
6539 object: &Gc<JsObject>,
6540 receiver: &Value,
6541 key: &PropertyKey,
6542 ) -> JsResult<Option<Value>> {
6543 let Some((target, handler)) = self.proxy_parts(object)? else {
6544 return Ok(None);
6545 };
6546 let key_value = self.key_value(key);
6547 let Some(result) = self.proxy_trap(
6548 &handler,
6549 "get",
6550 vec![Value::Object(target.clone()), key_value, receiver.clone()],
6551 )?
6552 else {
6553 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
6554 // inherited getter still sees the proxy.
6555 return Ok(Some(
6556 self.get_property_key_for(&target, Some(receiver), key)?
6557 .unwrap_or(Value::Undefined),
6558 ));
6559 };
6560 if let Some(fixed) = self.fixed_property(&target, key)? {
6561 if fixed.is_accessor() {
6562 // A fixed accessor with no getter must read as `undefined`.
6563 let has_getter = fixed
6564 .getter
6565 .as_ref()
6566 .is_some_and(|getter| !matches!(getter, Value::Undefined));
6567 if !has_getter && !matches!(result, Value::Undefined) {
6568 return Err(self.type_error(format!(
6569 "proxy 'get' must report undefined for the non-configurable property '{key}'"
6570 )));
6571 }
6572 } else if !fixed.writable {
6573 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6574 if !fixed_value.same_value(&result) {
6575 return Err(self.type_error(format!(
6576 "proxy 'get' disagrees with the non-configurable property '{key}'"
6577 )));
6578 }
6579 }
6580 }
6581 Ok(Some(result))
6582 }
6583
6584 /// `[[Set]]` on a proxy.
6585 ///
6586 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
6587 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
6588 /// read-only store has.
6589 fn proxy_set(
6590 &mut self,
6591 object: &Gc<JsObject>,
6592 key: &PropertyKey,
6593 value: Value,
6594 receiver: &Value,
6595 ) -> JsResult<Option<bool>> {
6596 let Some((target, handler)) = self.proxy_parts(object)? else {
6597 return Ok(None);
6598 };
6599 let key_value = self.key_value(key);
6600 let Some(result) = self.proxy_trap(
6601 &handler,
6602 "set",
6603 vec![
6604 Value::Object(target.clone()),
6605 key_value,
6606 value.clone(),
6607 receiver.clone(),
6608 ],
6609 )?
6610 else {
6611 // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
6612 // given — not the target. `OrdinarySet` step 3 is
6613 // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
6614 // object whose prototype is a typed array has to reach the proxy's own
6615 // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
6616 // calls and expects exactly one. Storing on the target instead put the value
6617 // in the target and never consulted the trap.
6618 let accepted = self.ordinary_set_with_receiver(
6619 &target,
6620 receiver,
6621 key,
6622 value,
6623 DeleteFailure::Ignore,
6624 )?;
6625 return Ok(Some(accepted));
6626 };
6627 if !result.to_boolean() {
6628 return Ok(Some(false));
6629 }
6630 if let Some(fixed) = self.fixed_property(&target, key)? {
6631 if fixed.is_accessor() {
6632 let has_setter = fixed
6633 .setter
6634 .as_ref()
6635 .is_some_and(|setter| !matches!(setter, Value::Undefined));
6636 if !has_setter {
6637 return Err(self.type_error(format!(
6638 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
6639 )));
6640 }
6641 } else if !fixed.writable {
6642 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6643 if !fixed_value.same_value(&value) {
6644 return Err(self.type_error(format!(
6645 "proxy 'set' changed the non-configurable property '{key}'"
6646 )));
6647 }
6648 }
6649 }
6650 // A new property cannot appear on a target that refuses new properties.
6651 if self.object_get_own_property(&target, key)?.is_none()
6652 && !self.object_is_extensible(&target)?
6653 {
6654 return Err(self.type_error(format!(
6655 "proxy 'set' added '{key}' to a non-extensible target"
6656 )));
6657 }
6658 Ok(Some(true))
6659 }
6660
6661 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
6662 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6663 let Some((target, handler)) = self.proxy_parts(object)? else {
6664 return Ok(None);
6665 };
6666 let key_value = self.key_value(key);
6667 let Some(result) = self.proxy_trap(
6668 &handler,
6669 "has",
6670 vec![Value::Object(target.clone()), key_value],
6671 )?
6672 else {
6673 return Ok(Some(self.has_own_or_inherited(&target, key)?));
6674 };
6675 if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
6676 return Err(self.type_error(format!(
6677 "proxy 'has' denied the non-configurable property '{key}'"
6678 )));
6679 }
6680 // A non-extensible target cannot grow, so every own property it *has* is fixed.
6681 if !result.to_boolean()
6682 && !self.object_is_extensible(&target)?
6683 && self.object_get_own_property(&target, key)?.is_some()
6684 {
6685 return Err(self.type_error(format!(
6686 "proxy 'has' denied the own property '{key}' of a non-extensible target"
6687 )));
6688 }
6689 Ok(Some(result.to_boolean()))
6690 }
6691
6692 /// `[[Delete]]` on a proxy.
6693 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6694 let Some((target, handler)) = self.proxy_parts(object)? else {
6695 return Ok(None);
6696 };
6697 let key_value = self.key_value(key);
6698 let Some(result) = self.proxy_trap(
6699 &handler,
6700 "deleteProperty",
6701 vec![Value::Object(target.clone()), key_value],
6702 )?
6703 else {
6704 return Ok(Some(self.delete_property_key(&target, key)?));
6705 };
6706 if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
6707 return Err(self.type_error(format!(
6708 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
6709 )));
6710 }
6711 if result.to_boolean()
6712 && !self.object_is_extensible(&target)?
6713 && self.object_get_own_property(&target, key)?.is_some()
6714 {
6715 return Err(self.type_error(format!(
6716 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
6717 )));
6718 }
6719 Ok(Some(result.to_boolean()))
6720 }
6721
6722 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
6723 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
6724 let Some((target, handler)) = self.proxy_parts(object)? else {
6725 return Ok(None);
6726 };
6727 let Some(result) =
6728 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
6729 else {
6730 // No trap: the target's own keys, already in the order an object reports.
6731 return Ok(Some(self.object_own_property_keys(&target)?));
6732 };
6733 // `CreateListFromArrayLike` with the string-or-symbol restriction.
6734 let list = self.list_from_array_like(&result, true)?;
6735 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
6736 for value in list {
6737 let key = self.propkey(&value)?;
6738 if keys.contains(&key) {
6739 return Err(self.type_error(format!(
6740 "proxy 'ownKeys' returned the duplicate key '{key}'"
6741 )));
6742 }
6743 keys.push(key);
6744 }
6745 // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
6746 // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
6747 // table is empty, which made every check below vacuous.
6748 let target_keys = self.object_own_property_keys(&target)?;
6749 let extensible = self.object_is_extensible(&target)?;
6750 for key in &target_keys {
6751 if keys.contains(key) {
6752 continue;
6753 }
6754 if self.fixed_property(&target, key)?.is_some() {
6755 return Err(self.type_error(format!(
6756 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
6757 )));
6758 }
6759 if !extensible {
6760 return Err(self.type_error(format!(
6761 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
6762 )));
6763 }
6764 }
6765 if !extensible {
6766 // §10.5.11 step 12: the lists must match one for one, in any order.
6767 if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
6768 {
6769 return Err(
6770 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
6771 );
6772 }
6773 }
6774 Ok(Some(keys))
6775 }
6776
6777 /// `[[GetOwnProperty]]` on a proxy.
6778 fn proxy_get_own_property(
6779 &mut self,
6780 object: &Gc<JsObject>,
6781 key: &PropertyKey,
6782 ) -> JsResult<Option<Option<Property>>> {
6783 let Some((target, handler)) = self.proxy_parts(object)? else {
6784 return Ok(None);
6785 };
6786 let key_value = self.key_value(key);
6787 let Some(result) = self.proxy_trap(
6788 &handler,
6789 "getOwnPropertyDescriptor",
6790 vec![Value::Object(target.clone()), key_value],
6791 )?
6792 else {
6793 // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
6794 // property table. Two things ride on that choice: a target that is itself a
6795 // proxy has to re-dispatch (its own table is empty, so reading it reported
6796 // `undefined` for every key, `Object.keys` then dropped them all), and an array's
6797 // indices and `length` live outside the table and need the ordinary synthesis.
6798 // `object_get_own_property` does both.
6799 return Ok(Some(self.object_get_own_property(&target, key)?));
6800 };
6801 // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
6802 // `ToPropertyDescriptor` runs, because that operation would box the primitive
6803 // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
6804 // empty descriptor instead of refusing.
6805 if !matches!(result, Value::Undefined | Value::Object(_)) {
6806 return Err(self.type_error(
6807 "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
6808 ));
6809 }
6810 let target_desc = self.object_get_own_property(&target, key)?;
6811 let extensible = self.object_is_extensible(&target)?;
6812 let Some(descriptor) = (match result {
6813 Value::Undefined => None,
6814 _ => Some(self.property_from_descriptor(&result)?),
6815 }) else {
6816 // Steps 12.a–12.d: reporting absent is allowed only when the target's own
6817 // descriptor is configurable *and* the target can still grow back.
6818 if let Some(target_desc) = &target_desc {
6819 if !target_desc.configurable {
6820 return Err(self.type_error(format!(
6821 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
6822 )));
6823 }
6824 if !extensible {
6825 return Err(self.type_error(format!(
6826 "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
6827 )));
6828 }
6829 }
6830 return Ok(Some(None));
6831 };
6832 // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
6833 // which is a stronger requirement than "the target is not contradicting it" — the
6834 // four branches below are each one test262 case.
6835 if !descriptor.configurable {
6836 let Some(target_desc) = &target_desc else {
6837 return Err(self.type_error(format!(
6838 "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
6839 )));
6840 };
6841 if target_desc.configurable {
6842 return Err(self.type_error(format!(
6843 "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
6844 )));
6845 }
6846 let target_is_data = !target_desc.is_accessor();
6847 let result_is_data = !descriptor.is_accessor();
6848 if result_is_data && !target_is_data {
6849 return Err(self.type_error(format!(
6850 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6851 )));
6852 }
6853 if target_is_data && !target_desc.writable {
6854 if !result_is_data {
6855 return Err(self.type_error(format!(
6856 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6857 )));
6858 }
6859 if descriptor.writable {
6860 return Err(self.type_error(format!(
6861 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
6862 )));
6863 }
6864 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
6865 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
6866 if !fixed_value.same_value(&reported) {
6867 return Err(self.type_error(format!(
6868 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
6869 )));
6870 }
6871 }
6872 // Step 16.d: a reported *read-only* data property needs a real read-only data
6873 // property behind it. Missing this let a trap bolt a frozen property onto a
6874 // writable target intent (`resultdesc-is-not-configurable-not-writable-
6875 // targetdesc-is-writable`).
6876 if result_is_data && !descriptor.writable {
6877 if !target_is_data {
6878 return Err(self.type_error(format!(
6879 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6880 )));
6881 }
6882 if target_desc.writable {
6883 return Err(self.type_error(format!(
6884 "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
6885 )));
6886 }
6887 }
6888 if descriptor.is_accessor() {
6889 // Step 16.e: a getter the target does not have may not be invented, and
6890 // vice versa.
6891 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
6892 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
6893 (Some(a), Some(b)) => a.same_value(b),
6894 _ => false,
6895 };
6896 if !same(&target_desc.getter, &descriptor.getter)
6897 || !same(&target_desc.setter, &descriptor.setter)
6898 {
6899 return Err(self.type_error(format!(
6900 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
6901 )));
6902 }
6903 }
6904 }
6905 // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
6906 // where the target's own is locked. Without it a handler could advertise
6907 // `{value: 1, configurable: true}` for a non-configurable property, and a caller
6908 // that believed it would try to redefine something it cannot.
6909 if descriptor.configurable
6910 && let Some(target_desc) = &target_desc
6911 && !target_desc.configurable
6912 {
6913 return Err(self.type_error(format!(
6914 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
6915 )));
6916 }
6917 // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
6918 // through the trap either, however well-formed the descriptor is. This is the
6919 // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
6920 // the frozen target does not own.
6921 if !extensible {
6922 let Some(target_desc) = &target_desc else {
6923 return Err(self.type_error(format!(
6924 "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
6925 )));
6926 };
6927 if target_desc.is_accessor() == descriptor.is_accessor() {
6928 let target_is_data = !target_desc.is_accessor();
6929 let result_is_data = !descriptor.is_accessor();
6930 if target_is_data && !target_desc.writable && descriptor.writable {
6931 return Err(self.type_error(format!(
6932 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
6933 )));
6934 }
6935 if !result_is_data && !target_is_data {
6936 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
6937 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
6938 (Some(a), Some(b)) => a.same_value(b),
6939 _ => false,
6940 };
6941 if !same(&target_desc.getter, &descriptor.getter)
6942 || !same(&target_desc.setter, &descriptor.setter)
6943 {
6944 return Err(self.type_error(format!(
6945 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
6946 )));
6947 }
6948 }
6949 }
6950 }
6951 Ok(Some(Some(descriptor)))
6952 }
6953
6954 /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
6955 ///
6956 /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
6957 /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
6958 /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
6959 /// for a data property. `Property` cannot express "this field is absent", so the whole
6960 /// property path is skipped and the descriptor is assembled here field by field.
6961 ///
6962 /// `current` is the property the trap reported, used only to tell a data property from
6963 /// an accessor.
6964 pub fn proxy_seal_property(
6965 &mut self,
6966 object: &Gc<JsObject>,
6967 key: &PropertyKey,
6968 frozen: bool,
6969 current: &Property,
6970 ) -> JsResult<bool> {
6971 let Some((_target, handler)) = self.proxy_parts(object)? else {
6972 return Err(self.type_error("not a proxy"));
6973 };
6974 let descriptor = self.new_object(None);
6975 descriptor.define_data("configurable", Value::Bool(false));
6976 if frozen && !current.is_accessor() {
6977 descriptor.define_data("writable", Value::Bool(false));
6978 }
6979 let key_value = self.key_value(key);
6980 let target = object
6981 .proxy_state()
6982 .and_then(|state| state.borrow().target.clone());
6983 let Some(target) = target else {
6984 return Err(self.type_error("cannot use a proxy that has been revoked"));
6985 };
6986 let Some(result) = self.proxy_trap(
6987 &handler,
6988 "defineProperty",
6989 vec![Value::Object(target), key_value, Value::Object(descriptor)],
6990 )?
6991 else {
6992 // No trap means the definition belongs to the target; `false` is its answer.
6993 return Ok(false);
6994 };
6995 Ok(result.to_boolean())
6996 }
6997
6998 /// `[[DefineOwnProperty]]` on a proxy.
6999 fn proxy_define_property(
7000 &mut self,
7001 object: &Gc<JsObject>,
7002 key: &PropertyKey,
7003 property: Property,
7004 ) -> JsResult<Option<bool>> {
7005 let Some((target, handler)) = self.proxy_parts(object)? else {
7006 return Ok(None);
7007 };
7008 let key_value = self.key_value(key);
7009 let descriptor = self.descriptor_from_property(&property);
7010 let Some(result) = self.proxy_trap(
7011 &handler,
7012 "defineProperty",
7013 vec![Value::Object(target.clone()), key_value, descriptor],
7014 )?
7015 else {
7016 // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7017 // going" answer and `object_define_own_property` turns it into exactly that
7018 // forwarding — see the note there. (Reading it as "not a proxy" would define
7019 // the property on the proxy object itself, whose table is empty and which no
7020 // read ever consults.)
7021 return Ok(None);
7022 };
7023 if !result.to_boolean() {
7024 return Ok(Some(false));
7025 }
7026 // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7027 // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7028 // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7029 // and treating them alike made four cases pass a descriptor the target contradicts.
7030 let target_desc = self.object_get_own_property(&target, key)?;
7031 let extensible = self.object_is_extensible(&target)?;
7032 let named = property
7033 .descriptor_fields
7034 .unwrap_or(crate::object::DescriptorFields {
7035 value: false,
7036 writable: false,
7037 enumerable: false,
7038 configurable: false,
7039 get: false,
7040 set: false,
7041 });
7042 if named.configurable && !property.configurable {
7043 let Some(target_desc) = &target_desc else {
7044 return Err(self.type_error(format!(
7045 "proxy 'defineProperty' invented the non-configurable '{key}'"
7046 )));
7047 };
7048 if target_desc.configurable {
7049 return Err(self.type_error(format!(
7050 "proxy 'defineProperty' made '{key}' non-configurable"
7051 )));
7052 }
7053 }
7054 // Step 11's other half: reporting that a property was made *configurable* needs a
7055 // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7056 // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7057 // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7058 // target`).
7059 if named.configurable
7060 && property.configurable
7061 && let Some(target_desc) = &target_desc
7062 && !target_desc.configurable
7063 {
7064 return Err(
7065 self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7066 );
7067 }
7068 // Step 12: a property cannot be reported *made writable* when the target's copy is
7069 // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7070 // the trap is allowed to claim a definition it did not perform, as long as the
7071 // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7072 // legal, and refusing it broke the commonest way to seed a proxy).
7073 if named.writable
7074 && property.writable
7075 && let Some(target_desc) = &target_desc
7076 && !target_desc.writable
7077 {
7078 return Err(self.type_error(format!(
7079 "proxy 'defineProperty' made the read-only '{key}' writable"
7080 )));
7081 }
7082 // Step 13: making a property read-only needs an existing read-only property.
7083 if named.writable
7084 && !property.writable
7085 && let Some(target_desc) = &target_desc
7086 && !target_desc.is_accessor()
7087 && target_desc.writable
7088 {
7089 return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7090 }
7091 // Step 14: a non-writable, non-configurable property's value is fixed.
7092 if named.value
7093 && let Some(target_desc) = &target_desc
7094 && !target_desc.is_accessor()
7095 && !target_desc.writable
7096 && !target_desc.configurable
7097 {
7098 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7099 let reported = property.value.clone().unwrap_or(Value::Undefined);
7100 if !fixed_value.same_value(&reported) {
7101 return Err(self.type_error(format!(
7102 "proxy 'defineProperty' changed the value of '{key}'"
7103 )));
7104 }
7105 }
7106 // Step 15: a non-extensible target cannot grow.
7107 if target_desc.is_none() && !extensible {
7108 return Err(self.type_error(format!(
7109 "proxy 'defineProperty' added '{key}' to a non-extensible target"
7110 )));
7111 }
7112 Ok(Some(true))
7113 }
7114
7115 /// `[[GetPrototypeOf]]` on a proxy.
7116 fn proxy_get_prototype_of(
7117 &mut self,
7118 object: &Gc<JsObject>,
7119 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7120 let Some((target, handler)) = self.proxy_parts(object)? else {
7121 return Ok(None);
7122 };
7123 let Some(result) = self.proxy_trap(
7124 &handler,
7125 "getPrototypeOf",
7126 vec![Value::Object(target.clone())],
7127 )?
7128 else {
7129 // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7130 // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7131 // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7132 // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7133 // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7134 return Ok(Some(self.object_prototype_of(&target)?));
7135 };
7136 let proto = match &result {
7137 Value::Null => None,
7138 Value::Object(proto) => Some(proto.clone()),
7139 _ => {
7140 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7141 }
7142 };
7143 if !self.object_is_extensible(&target)? {
7144 let actual = self.object_prototype_of(&target)?;
7145 if !same_proto(proto.as_ref(), actual.as_ref()) {
7146 return Err(self.type_error(
7147 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7148 ));
7149 }
7150 }
7151 Ok(Some(proto))
7152 }
7153
7154 /// `[[SetPrototypeOf]]` on a proxy.
7155 fn proxy_set_prototype_of(
7156 &mut self,
7157 object: &Gc<JsObject>,
7158 proto: Option<Gc<JsObject>>,
7159 ) -> JsResult<Option<bool>> {
7160 let Some((target, handler)) = self.proxy_parts(object)? else {
7161 return Ok(None);
7162 };
7163 let proto_value = match &proto {
7164 Some(proto) => Value::Object(proto.clone()),
7165 None => Value::Null,
7166 };
7167 let Some(result) = self.proxy_trap(
7168 &handler,
7169 "setPrototypeOf",
7170 vec![Value::Object(target.clone()), proto_value],
7171 )?
7172 else {
7173 // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7174 // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7175 // its stored prototype overwritten behind its back.
7176 return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7177 };
7178 if result.to_boolean()
7179 && !self.object_is_extensible(&target)?
7180 && !same_proto(
7181 Some(&proto).and_then(|p| p.clone()).as_ref(),
7182 self.object_prototype_of(&target)?.as_ref(),
7183 )
7184 {
7185 return Err(self.type_error(
7186 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7187 ));
7188 }
7189 Ok(Some(result.to_boolean()))
7190 }
7191
7192 /// `[[IsExtensible]]` on a proxy.
7193 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7194 let Some((target, handler)) = self.proxy_parts(object)? else {
7195 return Ok(None);
7196 };
7197 let Some(result) = self.proxy_trap(
7198 &handler,
7199 "isExtensible",
7200 vec![Value::Object(target.clone())],
7201 )?
7202 else {
7203 return Ok(Some(self.object_is_extensible(&target)?));
7204 };
7205 // The answer is not the proxy's to invent: it must agree with the target, or a
7206 // script could learn `false` while the target keeps accepting new properties.
7207 if result.to_boolean() != self.object_is_extensible(&target)? {
7208 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7209 }
7210 Ok(Some(result.to_boolean()))
7211 }
7212
7213 /// `[[PreventExtensions]]` on a proxy.
7214 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7215 let Some((target, handler)) = self.proxy_parts(object)? else {
7216 return Ok(None);
7217 };
7218 let Some(result) = self.proxy_trap(
7219 &handler,
7220 "preventExtensions",
7221 vec![Value::Object(target.clone())],
7222 )?
7223 else {
7224 // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7225 // its answer can be `false`.
7226 return Ok(Some(self.object_prevent_extensions(&target)?));
7227 };
7228 if result.to_boolean() && self.object_is_extensible(&target)? {
7229 return Err(self.type_error(
7230 "proxy 'preventExtensions' reported success but the target is still extensible",
7231 ));
7232 }
7233 Ok(Some(result.to_boolean()))
7234 }
7235
7236 /// `[[Call]]` on a proxy, through the `apply` trap.
7237 fn proxy_apply(
7238 &mut self,
7239 object: &Gc<JsObject>,
7240 this: Value,
7241 args: Vec<Value>,
7242 ) -> JsResult<Option<Value>> {
7243 let Some((target, handler)) = self.proxy_parts(object)? else {
7244 return Ok(None);
7245 };
7246 // The trap gets the arguments as one array, which is the shape the spec passes
7247 // and the shape `apply` traps are written against (`args[0]` is the first one).
7248 let arguments = self.new_array(args.clone());
7249 let this_for_trap = this.clone();
7250 let Some(result) = self.proxy_trap(
7251 &handler,
7252 "apply",
7253 vec![
7254 Value::Object(target.clone()),
7255 this_for_trap,
7256 Value::Object(arguments),
7257 ],
7258 )?
7259 else {
7260 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7261 };
7262 Ok(Some(result))
7263 }
7264
7265 /// `[[Construct]]` on a proxy, through the `construct` trap.
7266 fn proxy_construct(
7267 &mut self,
7268 object: &Gc<JsObject>,
7269 args: Vec<Value>,
7270 new_target: &Value,
7271 ) -> JsResult<Option<Value>> {
7272 let Some((target, handler)) = self.proxy_parts(object)? else {
7273 return Ok(None);
7274 };
7275 if !target.is_callable() {
7276 return Err(self.type_error("proxy target is not a constructor"));
7277 }
7278 let arguments = self.new_array(args.clone());
7279 let Some(result) = self.proxy_trap(
7280 &handler,
7281 "construct",
7282 vec![
7283 Value::Object(target.clone()),
7284 Value::Object(arguments),
7285 new_target.clone(),
7286 ],
7287 )?
7288 else {
7289 return Ok(Some(self.construct(
7290 Value::Object(target),
7291 new_target.clone(),
7292 args,
7293 )?));
7294 };
7295 if !matches!(result, Value::Object(_)) {
7296 return Err(self.type_error("proxy 'construct' must return an object"));
7297 }
7298 Ok(Some(result))
7299 }
7300
7301 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7302 pub(crate) fn has_own_or_inherited(
7303 &mut self,
7304 object: &Gc<JsObject>,
7305 key: &PropertyKey,
7306 ) -> JsResult<bool> {
7307 // The object itself first: it may be a proxy, and then the answer is its trap's.
7308 if let Some(answer) = self.proxy_has(object, key)? {
7309 return Ok(answer);
7310 }
7311 // An integer-indexed exotic object answers a canonical numeric index from
7312 // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7313 // prototype chain. That is observable twice: a view the buffer has been resized
7314 // away from has no indices, so `2 in view` is `false` even when
7315 // `Object.getPrototypeOf(view)[2]` exists (what
7316 // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7317 // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7318 // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7319 // goes through here, which is why the same rule is repeated in `has_property_key`
7320 // rather than living only there.
7321 if object.typed_array_parts().is_some()
7322 && let Some(numeric) = canonical_numeric_index(key)
7323 {
7324 return Ok(typed_array_index_is_valid(object, numeric));
7325 }
7326 // A host class answers `in` for its own keys, which may live nowhere in a property
7327 // table — `"x" in point` is true because the class says so, not because a property
7328 // exists.
7329 if let Some(exotic) = object.exotic()
7330 && let Some(answer) = exotic.has_property(self, object, key)?
7331 {
7332 return Ok(answer);
7333 }
7334 // `has_own` rather than `own_property_key`: an array's elements and its derived
7335 // `length` are invisible to the property table, and `Array.prototype` is an array.
7336 // A host class's `get_own_property` counts too, because the reference's
7337 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7338 // lives — a class with only `get_own_property` answers `in` through it.
7339 if self.exotic_has_own(object, key)? {
7340 return Ok(true);
7341 }
7342 // A hole is *not* the end of the search: the chain may still have the key, which
7343 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7344 for ancestor in object.chain() {
7345 // A proxy further up the chain answers for itself.
7346 if let Some(answer) = self.proxy_has(&ancestor, key)? {
7347 return Ok(answer);
7348 }
7349 // Same for a host class: a prototype may be one, and `in` reaches it.
7350 if let Some(exotic) = ancestor.exotic()
7351 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7352 {
7353 return Ok(answer);
7354 }
7355 if self.exotic_has_own(&ancestor, key)? {
7356 return Ok(true);
7357 }
7358 }
7359 Ok(false)
7360 }
7361
7362 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7363 /// trap included.
7364 ///
7365 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7366 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7367 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7368 if let Some(exotic) = object.exotic()
7369 && let Some(answer) = exotic.get_own_property(self, object, key)?
7370 {
7371 return Ok(answer.is_some());
7372 }
7373 Ok(has_own(object, key))
7374 }
7375
7376 /// `CreateListFromArrayLike`, optionally restricted to property keys.
7377 ///
7378 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7379 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7380 /// `TypeError` instead of a property named `"1.5"`.
7381 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7382 let object = self.object_from(value)?;
7383 let length = self
7384 .get_property(&object, "length")?
7385 .map(|value| value.to_number())
7386 .unwrap_or(0.0);
7387 if !length.is_finite() || length < 0.0 {
7388 return Err(self.type_error("invalid array-like length"));
7389 }
7390 let length = length as usize;
7391 let mut items = Vec::with_capacity(length.min(1024));
7392 for index in 0..length {
7393 let item = self
7394 .get_property(&object, &index.to_string())?
7395 .unwrap_or(Value::Undefined);
7396 if keys_only && matches!(&item, Value::Symbol(_)) {
7397 items.push(item);
7398 continue;
7399 }
7400 if keys_only && !matches!(&item, Value::String(_)) {
7401 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7402 }
7403 items.push(item);
7404 }
7405 Ok(items)
7406 }
7407
7408 /// A `Property` from the descriptor object a trap returned.
7409 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7410 let object = self.object_from(value)?;
7411 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7412 interp.get_property(&object, name)
7413 };
7414 let getter = field(self, "get")?;
7415 let setter = field(self, "set")?;
7416 let accessor = getter.is_some() || setter.is_some();
7417 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7418 Ok(interp
7419 .get_property(&object, name)?
7420 .is_some_and(|value| value.to_boolean()))
7421 };
7422 let enumerable = boolean(self, "enumerable")?;
7423 let configurable = boolean(self, "configurable")?;
7424 if accessor {
7425 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7426 return Err(
7427 self.type_error("a descriptor cannot be both a data property and an accessor")
7428 );
7429 }
7430 Ok(Property {
7431 getter: getter.or(Some(Value::Undefined)),
7432 setter: setter.or(Some(Value::Undefined)),
7433 enumerable,
7434 configurable,
7435 writable: false,
7436 value: None,
7437 descriptor_fields: None,
7438 })
7439 } else {
7440 Ok(Property {
7441 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7442 writable: boolean(self, "writable")?,
7443 enumerable,
7444 configurable,
7445 getter: None,
7446 setter: None,
7447 descriptor_fields: None,
7448 })
7449 }
7450 }
7451
7452 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7453 fn descriptor_from_property(&mut self, property: &Property) -> Value {
7454 let object = self.new_object(None);
7455 // A partial descriptor names only some fields, and the trap must see exactly those:
7456 // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7457 // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7458 // case, where every field is present.
7459 let fields = property.descriptor_fields;
7460 let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7461 fields.is_none_or(|fields| field(&fields))
7462 };
7463 if property.is_accessor() {
7464 let getter = property.getter.clone().unwrap_or(Value::Undefined);
7465 let setter = property.setter.clone().unwrap_or(Value::Undefined);
7466 object.define_data("get", getter);
7467 object.define_data("set", setter);
7468 } else {
7469 if names(|fields| fields.value) {
7470 let value = property.value.clone().unwrap_or(Value::Undefined);
7471 object.define_data("value", value);
7472 }
7473 if names(|fields| fields.writable) {
7474 object.define_data("writable", Value::Bool(property.writable));
7475 }
7476 }
7477 if names(|fields| fields.enumerable) {
7478 object.define_data("enumerable", Value::Bool(property.enumerable));
7479 }
7480 if names(|fields| fields.configurable) {
7481 object.define_data("configurable", Value::Bool(property.configurable));
7482 }
7483 Value::Object(object)
7484 }
7485
7486 // -- calling ------------------------------------------------------------
7487
7488 /// Call `callee` with `this` and `args`.
7489 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
7490 let Value::Object(function) = &callee else {
7491 // `typeof x === "function"` is not enough to make `x()` legal: only a
7492 // callable object is. `null` and `undefined` need no special wording
7493 // here — their `ToString` already reads the way the reference's does.
7494 let what = format!("{} is not a function", callee.to_js_string());
7495 return Err(Signal::Throw(self.make_error("TypeError", &what)));
7496 };
7497 // A proxy of a function is called through its `apply` trap. It has no
7498 // `ObjectKind::Function` of its own, so this has to come before the dispatch
7499 // below, and a proxy of a non-function has nothing to forward to.
7500 if function.proxy_state().is_some() {
7501 return match self.proxy_apply(function, this, args)? {
7502 Some(result) => Ok(result),
7503 None => Err(Signal::Throw(
7504 self.make_error("TypeError", "proxy target is not callable"),
7505 )),
7506 };
7507 }
7508 let callable = function.with(|data| match &data.kind {
7509 ObjectKind::Function(callable) => match callable {
7510 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
7511 // The `Rc` is cloned out so the borrow of this object's data is released
7512 // before the closure runs: the closure may touch the same object.
7513 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
7514 Callable::Bound {
7515 target,
7516 this,
7517 args: leading,
7518 } => Some(NativeCall::Bound {
7519 target: target.clone(),
7520 this: this.clone(),
7521 leading: leading.clone(),
7522 }),
7523 Callable::Bytecode { code, env } => {
7524 Some(NativeCall::Bytecode(code.clone(), env.clone()))
7525 }
7526 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
7527 Callable::PromiseResolve(promise) => {
7528 Some(NativeCall::PromiseResolve(promise.clone()))
7529 }
7530 Callable::PromiseReject(promise) => {
7531 Some(NativeCall::PromiseReject(promise.clone()))
7532 }
7533 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
7534 state: state.clone(),
7535 }),
7536 Callable::ThenShim {
7537 handler,
7538 resolve,
7539 reject,
7540 fulfilled,
7541 } => Some(NativeCall::ThenShim {
7542 handler: handler.clone(),
7543 resolve: resolve.clone(),
7544 reject: reject.clone(),
7545 fulfilled: *fulfilled,
7546 }),
7547 Callable::AwaitResume {
7548 coroutine,
7549 promise,
7550 kind,
7551 } => Some(NativeCall::AwaitResume {
7552 coroutine: coroutine.clone(),
7553 promise: promise.clone(),
7554 kind: *kind,
7555 }),
7556 Callable::CombinatorSettle {
7557 state,
7558 index,
7559 fulfilled,
7560 } => Some(NativeCall::CombinatorSettle {
7561 state: state.clone(),
7562 index: *index,
7563 fulfilled: *fulfilled,
7564 }),
7565 Callable::FinallyShim {
7566 callback,
7567 fulfilled,
7568 constructor,
7569 } => Some(NativeCall::FinallyShim {
7570 callback: callback.clone(),
7571 fulfilled: *fulfilled,
7572 constructor: constructor.clone(),
7573 }),
7574 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
7575 Callable::CompletedReturn {
7576 generator,
7577 promise,
7578 rejected,
7579 } => Some(NativeCall::CompletedReturn {
7580 generator: generator.clone(),
7581 promise: promise.clone(),
7582 rejected: *rejected,
7583 }),
7584 Callable::YieldResult {
7585 generator,
7586 promise,
7587 done,
7588 } => Some(NativeCall::YieldResult {
7589 generator: generator.clone(),
7590 promise: promise.clone(),
7591 done: *done,
7592 }),
7593 Callable::DisposeStep {
7594 remaining,
7595 promise,
7596 error,
7597 rejected,
7598 } => Some(NativeCall::DisposeStep {
7599 remaining: remaining.clone(),
7600 promise: promise.clone(),
7601 error: error.clone(),
7602 rejected: *rejected,
7603 }),
7604 Callable::GeneratorResume {
7605 generator,
7606 promise,
7607 kind,
7608 } => Some(NativeCall::GeneratorResume {
7609 generator: generator.clone(),
7610 promise: promise.clone(),
7611 kind: *kind,
7612 }),
7613 Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
7614 Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
7615 Callable::SettlePromise {
7616 promise,
7617 value,
7618 rejected,
7619 } => Some(NativeCall::SettlePromise {
7620 promise: promise.clone(),
7621 value: value.clone(),
7622 rejected: *rejected,
7623 }),
7624 },
7625 _ => None,
7626 });
7627 match callable {
7628 Some(NativeCall::Host(func)) => {
7629 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
7630 // function by name rather than stopping at the caller.
7631 let frame_less = function
7632 .own_property("_frame_less")
7633 .and_then(|property| property.value)
7634 .is_some_and(|value| value.to_boolean());
7635 let outer = if frame_less {
7636 None
7637 } else {
7638 self.native_frames
7639 .push((function.clone(), self.frames.len()));
7640 Some(self.current_native.replace(function.clone()))
7641 };
7642 // Same frame bookkeeping as a `Native`, plus `new.target`: a host
7643 // constructor reads it through `current_new_target` because it is handed
7644 // `undefined` for `this`. Taking the parked value here is what stops a
7645 // *plain* call made from inside a constructor body from seeing the
7646 // enclosing `new.target`.
7647 let parked = self.pending_new_target.take();
7648 let result = {
7649 let outer_new_target = std::mem::replace(
7650 &mut self.active_new_target,
7651 parked.unwrap_or(Value::Undefined),
7652 );
7653 let result = {
7654 let mut body = func.borrow_mut();
7655 body(self, this, &args)
7656 };
7657 self.active_new_target = outer_new_target;
7658 result
7659 };
7660 if !frame_less {
7661 self.native_frames.pop();
7662 self.current_native = outer.flatten();
7663 }
7664 result
7665 }
7666 Some(NativeCall::Native(func)) => {
7667 // A function marked `_frame_less` is one the reference implements
7668 // without a call frame — `eval` is the only one so far.
7669 let frame_less = function
7670 .own_property("_frame_less")
7671 .and_then(|property| property.value)
7672 .is_some_and(|value| value.to_boolean());
7673 let outer = if frame_less {
7674 None
7675 } else {
7676 self.native_frames
7677 .push((function.clone(), self.frames.len()));
7678 Some(self.current_native.replace(function.clone()))
7679 };
7680 let parked = self.pending_new_target.take();
7681 let outer_new_target = std::mem::replace(
7682 &mut self.active_new_target,
7683 parked.unwrap_or(Value::Undefined),
7684 );
7685 let result = func(self, this, &args);
7686 self.active_new_target = outer_new_target;
7687 if !frame_less {
7688 self.native_frames.pop();
7689 self.current_native = outer.flatten();
7690 }
7691 result
7692 }
7693 Some(NativeCall::Revoker(slots)) => {
7694 // Idempotent: revoking twice answers `undefined` again rather than
7695 // complaining, which is what the spec says and what a `finally` block
7696 // relies on.
7697 let mut state = slots.borrow_mut();
7698 state.target = None;
7699 state.handler = None;
7700 Ok(Value::Undefined)
7701 }
7702 Some(NativeCall::PromiseResolve(promise)) => {
7703 // One-shot: a second call is silently ignored, which
7704 // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
7705 let value = args.first().cloned().unwrap_or(Value::Undefined);
7706 self.resolve_promise_with(&promise, value)?;
7707 Ok(Value::Undefined)
7708 }
7709 Some(NativeCall::PromiseReject(promise)) => {
7710 let reason = args.first().cloned().unwrap_or(Value::Undefined);
7711 self.reject_promise(&promise, reason);
7712 Ok(Value::Undefined)
7713 }
7714 Some(NativeCall::ThenShim {
7715 handler,
7716 resolve,
7717 reject,
7718 fulfilled,
7719 }) => {
7720 // `PerformPromiseThen` with a capability: run the handler, then settle
7721 // through the capability's own pair. A throw from the handler is the
7722 // rejection, and a throw from the capability's `resolve` is not caught —
7723 // exactly the spec's `?`.
7724 let value = args.first().cloned().unwrap_or(Value::Undefined);
7725 match handler {
7726 Some(handler) => {
7727 match self.call_value(handler, Value::Undefined, vec![value]) {
7728 Ok(result) => {
7729 self.call_value(resolve, Value::Undefined, vec![result])?;
7730 }
7731 Err(Signal::Throw(reason)) => {
7732 self.call_value(reject, Value::Undefined, vec![reason])?;
7733 }
7734 Err(signal) => return Err(signal),
7735 }
7736 }
7737 None => {
7738 let handler = if fulfilled { resolve } else { reject };
7739 self.call_value(handler, Value::Undefined, vec![value])?;
7740 }
7741 }
7742 Ok(Value::Undefined)
7743 }
7744 Some(NativeCall::CapabilityExecutor { state }) => {
7745 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
7746 // slot holds a value yet. The test is on the *values*, not on a call count —
7747 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
7748 // called-twice`'s first case does exactly that), while a second call after a
7749 // real pair is the `TypeError`.
7750 let defined = |name: &str| {
7751 state
7752 .own_property(name)
7753 .and_then(|property| property.value)
7754 .is_some_and(|value| !matches!(value, Value::Undefined))
7755 };
7756 if defined("resolve") || defined("reject") {
7757 return Err(self.type_error("promise capability executor called twice"));
7758 }
7759 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
7760 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
7761 state.define_data("resolve", resolve);
7762 state.define_data("reject", reject);
7763 Ok(Value::Undefined)
7764 }
7765 Some(NativeCall::CombinatorSettle {
7766 state,
7767 index,
7768 fulfilled,
7769 }) => {
7770 let value = args.first().cloned().unwrap_or(Value::Undefined);
7771 self.settle_combinator(&state, index, fulfilled, value)?;
7772 Ok(Value::Undefined)
7773 }
7774 Some(NativeCall::AwaitResume {
7775 coroutine,
7776 promise,
7777 kind,
7778 }) => {
7779 // Resume *inline*, in the reaction that delivered the value. Deferring it
7780 // by another job inserts a tick between every `await` and its
7781 // continuation, which reorders `await` against unrelated `then` chains —
7782 // `f().then(g)` then runs before `f`'s own next statement.
7783 self.drive_async(
7784 &coroutine,
7785 &promise,
7786 kind,
7787 args.first().cloned().unwrap_or(Value::Undefined),
7788 )
7789 .map(|()| Value::Undefined)
7790 }
7791 Some(NativeCall::ReturnValue(value)) => Ok(value),
7792 Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
7793 Some(NativeCall::FinallyShim {
7794 callback,
7795 fulfilled,
7796 constructor,
7797 }) => {
7798 // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
7799 // own value is discarded; what the caller sees is the *original* outcome,
7800 // delayed until `PromiseResolve(C, result)` has settled.
7801 //
7802 // Two details are observable and both have a test:
7803 //
7804 // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
7805 // `PerformPromiseThen`. A callback that returns a thenable with its own
7806 // `then` must have that `then` called
7807 // (`resolved-observable-then-calls` counts it);
7808 // * only the **fulfil** handler is supplied. A returned promise that
7809 // *rejects* rejects the whole `finally`, rather than having its failure
7810 // swallowed and the original value passed through.
7811 let original = args.first().cloned().unwrap_or(Value::Undefined);
7812 let result = match &callback {
7813 Some(callback) => {
7814 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
7815 }
7816 None => Value::Undefined,
7817 };
7818 // `PromiseResolve(C, result)`: a `result` that is already a promise of this
7819 // constructor is reused rather than rewrapped, which is what keeps
7820 // `mp1.finally(() => mp2)` from gaining a layer.
7821 let resolved = self.promise_resolve_for(&constructor, result)?;
7822 let thunk = if fulfilled {
7823 Callable::ReturnValue(original)
7824 } else {
7825 Callable::ThrowValue(original)
7826 };
7827 // `length: 0` and `name: ""`, and **not** a constructor — the three things
7828 // `resolved-observable-then-calls-argument` reads off the thunk while it has
7829 // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
7830 // function with no `length` at all.
7831 let thunk = self.builtin_function("", 0, thunk);
7832 let then = self.read_field(&resolved, "then")?;
7833 if !matches!(&then, Value::Object(object) if object.is_callable()) {
7834 return Err(self.type_error("then is not a function"));
7835 }
7836 self.call_value(then, resolved, vec![Value::Object(thunk)])
7837 }
7838 Some(NativeCall::DisposeStep {
7839 remaining,
7840 promise,
7841 error,
7842 rejected,
7843 }) => {
7844 let error = if rejected {
7845 let reason = args.first().cloned().unwrap_or(Value::Undefined);
7846 self.merge_dispose_error(reason, error)
7847 } else {
7848 error
7849 };
7850 self.dispose_step(&remaining, &promise, error)?;
7851 Ok(Value::Undefined)
7852 }
7853 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
7854 Some(NativeCall::CompletedReturn {
7855 generator,
7856 promise,
7857 rejected,
7858 }) => {
7859 let value = args.first().cloned().unwrap_or(Value::Undefined);
7860 let outcome = if rejected {
7861 AsyncOutcome::Error(value)
7862 } else {
7863 AsyncOutcome::Value(self.iterator_result(value, true)?)
7864 };
7865 self.settle_async_request(&generator, &promise, outcome)?;
7866 Ok(Value::Undefined)
7867 }
7868 Some(NativeCall::YieldResult {
7869 generator,
7870 promise,
7871 done,
7872 }) => {
7873 let value = args.first().cloned().unwrap_or(Value::Undefined);
7874 let result = self.iterator_result(value, done)?;
7875 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
7876 Ok(Value::Undefined)
7877 }
7878 Some(NativeCall::GeneratorResume {
7879 generator,
7880 promise,
7881 kind,
7882 }) => {
7883 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
7884 // tick and reorders the generator against other chains.
7885 self.step_async_generator(
7886 &generator,
7887 &promise,
7888 kind,
7889 args.first().cloned().unwrap_or(Value::Undefined),
7890 )
7891 .map(|()| Value::Undefined)
7892 }
7893 Some(NativeCall::SettlePromise {
7894 promise,
7895 value,
7896 rejected,
7897 }) => {
7898 if rejected {
7899 self.reject_promise(&promise, value);
7900 } else {
7901 self.fulfill_promise(&promise, value);
7902 }
7903 Ok(Value::Undefined)
7904 }
7905 Some(NativeCall::Bound {
7906 target,
7907 this: bound_this,
7908 leading,
7909 }) => {
7910 let mut all = leading;
7911 all.extend(args);
7912 self.call_value(target, bound_this, all)
7913 }
7914 Some(NativeCall::Bytecode(code, env)) => {
7915 if code.code.kind.is_generator() {
7916 return self.new_generator(callee, this, args);
7917 }
7918 if code.code.kind.is_async() {
7919 // Same coroutine machinery as a generator; the difference is only in
7920 // what the completion does — see `new_async_function`.
7921 return self.new_async_function(callee, this, args);
7922 }
7923 self.execute(code, env, this, args, callee)
7924 }
7925 None => Err(Signal::Throw(
7926 self.make_error("TypeError", "not a function"),
7927 )),
7928 }
7929 }
7930
7931 /// Give a freshly built function its own `prototype` object.
7932 ///
7933 /// Every function that can be used with `new` carries one, and its
7934 /// `constructor` points back at the function — a reference cycle, which is
7935 /// exactly what the collector's cycle pass exists to reclaim.
7936 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
7937 self.install_function_prototype_with(function, None);
7938 }
7939
7940 /// [`Interp::install_function_prototype`] with an explicit parent for the new
7941 /// `prototype` object.
7942 ///
7943 /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
7944 /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
7945 /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
7946 /// `None` means `%Object.prototype%`.
7947 fn install_function_prototype_with(
7948 &mut self,
7949 function: &Gc<JsObject>,
7950 parent: Option<Gc<JsObject>>,
7951 ) {
7952 let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
7953 let prototype = self.new_object(Some(parent));
7954 let constructor = Value::Object(function.clone());
7955 prototype.define(
7956 "constructor",
7957 Property::with_attributes(constructor, true, false),
7958 );
7959 let value = Value::Object(prototype);
7960 function.define("prototype", Property::prototype_of(value, true));
7961 }
7962
7963 /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
7964 /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
7965 /// [`Interp::install_function_prototype`] — **no `constructor` property**.
7966 ///
7967 /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
7968 /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
7969 /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
7970 /// is `[]` there.
7971 fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
7972 let prototype = self.new_object(Some(parent));
7973 let value = Value::Object(prototype);
7974 function.define("prototype", Property::prototype_of(value, true));
7975 }
7976
7977 /// The `[[Prototype]]` a newly created generator object gets:
7978 /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
7979 ///
7980 /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
7981 /// function's `prototype` is writable, so a script can replace it with anything, and
7982 /// only an *object* is consulted.
7983 fn generator_instance_proto(
7984 &mut self,
7985 function: &Gc<JsObject>,
7986 default: Gc<JsObject>,
7987 ) -> JsResult<Gc<JsObject>> {
7988 match self.get_property(function, "prototype")? {
7989 Some(Value::Object(prototype)) => Ok(prototype),
7990 _ => Ok(default),
7991 }
7992 }
7993
7994 /// A getter or setter that reads or writes the reference cell behind a mapped
7995 /// `arguments` index.
7996 ///
7997 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
7998 /// count — which is what the collector treats as "a reference from outside the
7999 /// heap". The closure therefore keeps the cell alive for exactly as long as the
8000 /// accessor is reachable, which is the same lifetime the arguments object has.
8001 ///
8002 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8003 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8004 /// parameter value and the arguments object reaches the closure, never the other
8005 /// way round. Nothing the collector has to see is hidden.
8006 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8007 let name = if is_setter { "set" } else { "get" };
8008 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8009 if is_setter {
8010 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8011 Ok(Value::Undefined)
8012 } else {
8013 Ok(cell.get())
8014 }
8015 };
8016 self.new_host_function(name, 1, Box::new(func))
8017 }
8018
8019 /// The object `special_object` builds.
8020 ///
8021 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8022 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8023 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8024 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8025 /// write through `arguments` does not reach the parameter.
8026 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8027 match magic {
8028 0 | 1 => {
8029 let args = self.frame().passed().to_vec();
8030 let proto = self.realm.object_proto.clone();
8031 let object = self.new_object(Some(proto));
8032 // The marker `Object.prototype.toString` needs: an arguments object is an
8033 // ordinary object apart from reporting `[object Arguments]`, and that has
8034 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8035 // show up ahead of them in a key listing anyway — it is non-enumerable.
8036 self.internal_set(&object, "_class", self.string("Arguments"));
8037 // `length` is writable and configurable but neither enumerable nor a
8038 // plain data property: `Object.keys(arguments)` lists the indices only,
8039 // which is how `{...arguments}` copies them without the length.
8040 object.define(
8041 "length",
8042 Property::with_attributes(Value::Int(args.len() as i32), true, false),
8043 );
8044 // `magic == 1` is sloppy mode, where each index is *mapped* to the
8045 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8046 // change `a`, and assigning `a` has to change `arguments[0]`.
8047 //
8048 // The shared storage is the parameter's reference cell. The compiler
8049 // gives every parameter of such a function one (see
8050 // `provide_body_arguments`), and the cell outlives the frame, so this
8051 // keeps working after the arguments object escapes.
8052 //
8053 // The index becomes an accessor rather than a data property. A mapped
8054 // index reports as a plain writable/enumerable data property through
8055 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8056 // the getter/setter pair is only the plumbing underneath.
8057 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8058 let frame = self.frame();
8059 frame
8060 .code
8061 .arg_cell
8062 .iter()
8063 .map(|cell| {
8064 (*cell >= 0)
8065 .then(|| frame.cells.get(*cell as usize).cloned())
8066 .flatten()
8067 })
8068 .collect()
8069 } else {
8070 Vec::new()
8071 };
8072 // Tell the object which indices are mapped, so
8073 // `Object.getOwnPropertyDescriptor` can report them as the data
8074 // properties the spec describes instead of the accessors that
8075 // implement the aliasing.
8076 if magic == 1 {
8077 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8078 for cell in &mapped_cells {
8079 table.push(cell.clone());
8080 }
8081 object.set_mapped_arguments(table);
8082 }
8083 for (index, value) in args.into_iter().enumerate() {
8084 match mapped_cells.get(index).cloned().flatten() {
8085 Some(cell) => {
8086 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8087 let setter = self.new_mapped_arguments_accessor(cell, true);
8088 object.define(
8089 &index.to_string(),
8090 Property::accessor_with(
8091 Some(Value::Object(getter)),
8092 Some(Value::Object(setter)),
8093 true,
8094 ),
8095 );
8096 }
8097 None => object.define_data(&index.to_string(), value),
8098 }
8099 }
8100 // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8101 // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8102 // non-enumerable and non-configurable. It is not a nicety — it is the only
8103 // documented way to reach `%ThrowTypeError%`:
8104 //
8105 // Object.getOwnPropertyDescriptor(function(){"use strict";
8106 // return arguments;}(), "callee").get
8107 //
8108 // and the whole `ThrowTypeError/` directory is written against that
8109 // expression. Without it 13 cases failed with `cannot read property 'get'
8110 // of undefined`, which reads like a test harness bug rather than a missing
8111 // accessor.
8112 //
8113 // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8114 // writable data property holding the function being called, and
8115 // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8116 // `hasOwnProperty("callee")` hold there.
8117 if magic == 1 {
8118 let callee = self.frame().callee.clone();
8119 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8120 object.define("callee", Property::with_attributes(callee, true, false));
8121 } else if let Some(thrower) = self.realm.throw_type_error.clone()
8122 && object.own_property("callee").is_none()
8123 {
8124 object.define(
8125 "callee",
8126 Property {
8127 getter: Some(Value::Object(thrower.clone())),
8128 setter: Some(Value::Object(thrower)),
8129 enumerable: false,
8130 configurable: false,
8131 ..Property::default()
8132 },
8133 );
8134 }
8135 // An arguments object is iterable: `[...arguments]` and
8136 // `for (const a of arguments)` both work, through the *array* iterator
8137 // because the object is array-like. Without this the whole spread form
8138 // reported "not iterable".
8139 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8140 let values = self
8141 .realm
8142 .array_proto
8143 .own_property("values")
8144 .and_then(|property| property.value);
8145 if let Some(values) = values {
8146 object.define_key(
8147 &iterator_key,
8148 Property::with_attributes(values, true, false),
8149 );
8150 }
8151 Ok(Value::Object(object))
8152 }
8153 // `this.active_func`: the constructor `super()` resolves against.
8154 //
8155 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8156 // own, so it inherits this from the function it was written in along with `this`
8157 // — and that is a lexical relationship, not a stack one: an arrow that escaped
8158 // the constructor and is called back later (`iter.return = () => super()`) has
8159 // the constructor nowhere on the stack. The compiler therefore reads it out of
8160 // a closure variable of the enclosing function, exactly as the reference does
8161 // with its `this_active_func` local.
8162 2 => Ok(self
8163 .current_callee()
8164 .map_or(Value::Undefined, Value::Object)),
8165 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8166 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8167 // its own either, so the lookup walks out to the nearest non-arrow frame for
8168 // the same reason as `this.active_func` above — without that, `super()` inside
8169 // an arrow passed `undefined` as the new target and the parent constructor was
8170 // then rejected for being invoked without `new`.
8171 3 => Ok(self
8172 .eval_new_target
8173 .clone()
8174 .unwrap_or_else(|| self.frame().new_target.clone())),
8175 // `[[HomeObject]]` of the function being run: what `super` is relative to.
8176 // An arrow has none of its own, so the lookup walks out to the enclosing
8177 // method — which is why `super` works inside an arrow inside a method.
8178 4 => Ok(self
8179 .frames
8180 .iter()
8181 .rev()
8182 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8183 .map_or(Value::Undefined, Value::Object)),
8184 // `import.meta`: the innermost module body's meta object. Outside a module
8185 // the compiler never emits this, so an empty fallback is unreachable rather
8186 // than permissive.
8187 6 => {
8188 let name = self.module_stack.last().cloned();
8189 let meta = name
8190 .and_then(|name| self.modules.get(&name).cloned())
8191 .and_then(|module| module.with(|r| r.import_meta.clone()));
8192 Ok(meta.map_or(Value::Undefined, Value::Object))
8193 }
8194 other => Err(Signal::Throw(self.make_error(
8195 "InternalError",
8196 &format!("special_object {other} is not implemented yet"),
8197 ))),
8198 }
8199 }
8200
8201 /// `[[HomeObject]]` of the innermost function that has one, if any.
8202 ///
8203 /// An arrow has none, so the search walks out to the enclosing method — the same
8204 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8205 /// inside a method.
8206 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8207 self.frames
8208 .iter()
8209 .rev()
8210 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8211 }
8212
8213 /// The dispose method a `using` declaration should snapshot, or an error.
8214 ///
8215 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8216 /// is what makes a resource that only knows the synchronous protocol usable in both
8217 /// forms.
8218 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8219 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8220 if value.is_nullish() {
8221 return Ok(Value::Undefined);
8222 }
8223 let Some(object) = value.as_object() else {
8224 return Err(self.type_error("not an object"));
8225 };
8226 let mut method = if await_form {
8227 let found = self.get_property_key(
8228 object,
8229 &self.realm.well_known_key(WellKnown::AsyncDisposable),
8230 )?;
8231 match found {
8232 Some(found) if !found.is_nullish() => Some(found),
8233 _ => self
8234 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8235 }
8236 } else {
8237 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8238 };
8239 let Some(found) = method.take() else {
8240 return Err(self.type_error("value is not disposable"));
8241 };
8242 if found.is_nullish() {
8243 return Err(self.type_error("value is not disposable"));
8244 }
8245 let callable = found.as_object().is_some_and(|object| object.is_callable());
8246 if !callable {
8247 return Err(self.type_error("dispose method is not a function"));
8248 }
8249 Ok(found)
8250 }
8251
8252 /// Call one resource's disposer, folding a failure into `error_state`.
8253 ///
8254 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8255 /// because a captured `using` binding lives in its reference cell and the local slot is
8256 /// stale — a closure over the resource is legal and must not change what is disposed.
8257 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8258 let value = self.get_loc(slot);
8259 let method = self.get_loc(slot + 1);
8260 // A resource that was never initialised — its declaration threw — or that is
8261 // `null`/`undefined` has nothing to dispose.
8262 if value.is_nullish() || matches!(value, Value::Uninitialized) {
8263 return Ok(error_state);
8264 }
8265 if matches!(method, Value::Undefined | Value::Uninitialized) {
8266 return Ok(error_state);
8267 }
8268 match self.call_value(method, value, Vec::new()) {
8269 Ok(_) => Ok(error_state),
8270 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8271 Err(other) => Err(other),
8272 }
8273 }
8274
8275 /// Combine a disposal failure with whatever was already going wrong.
8276 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8277 if matches!(error_state, Value::Uninitialized) {
8278 return new_error;
8279 }
8280 self.new_suppressed_error(new_error, error_state)
8281 }
8282
8283 /// A `SuppressedError` instance built straight from its prototype.
8284 ///
8285 /// Not through the constructor: a script that rewrites
8286 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8287 /// error wrapping.
8288 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8289 let proto = self
8290 .realm
8291 .suppressed_error_proto
8292 .clone()
8293 .unwrap_or_else(|| self.realm.error_proto.clone());
8294 let object = self.new_object(Some(proto));
8295 object.define("error", Property::with_attributes(error, true, true));
8296 object.define(
8297 "suppressed",
8298 Property::with_attributes(suppressed, true, true),
8299 );
8300 object.define(
8301 "message",
8302 Property::with_attributes(self.string("SuppressedError"), true, true),
8303 );
8304 self.internal_set(&object, "_class", self.string("Error"));
8305 self.add_stack(&object);
8306 Value::Object(object)
8307 }
8308
8309 /// Call `callee`, or push its frame and let the main loop run it.
8310 ///
8311 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8312 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8313 /// continues, so `function f(){ return f() }` costs heap and stops at
8314 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8315 /// is entered directly, and natives do not re-enter JavaScript in this
8316 /// milestone.
8317 ///
8318 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8319 /// because the returning frame will.
8320 /// The elements of an array-like value, as a call argument list.
8321 ///
8322 /// `apply` accepts any array-like, not only a real array: the reference reads
8323 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8324 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8325 let Some(object) = value.as_object().cloned() else {
8326 if value.is_nullish() {
8327 // `f.apply(this, null)` passes no arguments at all.
8328 return Ok(Vec::new());
8329 }
8330 return Err(self.type_error("createListFromArrayLike called on non-object"));
8331 };
8332 let length = match self.get_property(&object, "length")? {
8333 Some(length) => length.to_number(),
8334 None => 0.0,
8335 };
8336 if !length.is_finite() || length <= 0.0 {
8337 return Ok(Vec::new());
8338 }
8339 let length = (length as usize).min(1_000_000);
8340 let mut args = Vec::with_capacity(length);
8341 for index in 0..length {
8342 let element = self.get_property(&object, &index.to_string())?;
8343 args.push(element.unwrap_or(Value::Undefined));
8344 }
8345 Ok(args)
8346 }
8347
8348 /// Turn a call to a generator function into a generator object.
8349 ///
8350 /// The frame is built exactly as an ordinary call would build it, then detached and
8351 /// stored in the generator before any body instruction runs — which is what makes
8352 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8353 /// is `initial_yield`, the first instruction of every suspending body.
8354 pub fn new_generator(
8355 &mut self,
8356 function: Value,
8357 this: Value,
8358 args: Vec<Value>,
8359 ) -> JsResult<Value> {
8360 let Some(object) = function.as_object().cloned() else {
8361 return Err(self.type_error("not a generator function"));
8362 };
8363 let Some((code, env)) = bytecode_of(&object) else {
8364 return Err(self.type_error("not a generator function"));
8365 };
8366 let is_async = code.code.kind.is_async();
8367 self.push_frame(code, env, this, args, function)?;
8368 let frame = self.frames.pop().expect("push_frame just pushed it");
8369 // A fresh generator is *suspended at start*: the body has not run, so a
8370 // `return`/`throw` on it finishes without executing anything.
8371 let mut state = GeneratorState {
8372 frame: Some(frame),
8373 phase: GeneratorPhase::SuspendedStart,
8374 parked_on_await: false,
8375 parked_on_yield_star: false,
8376 requests: std::collections::VecDeque::new(),
8377 async_busy: false,
8378 is_async,
8379 };
8380 // Run to the first suspension. For a generator that is `initial_yield`, so no
8381 // body code runs; for a malformed body it would be the first `yield`.
8382 // An `async function*` answers an async generator: same coroutine, but its
8383 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8384 let default_proto = if is_async {
8385 self.realm
8386 .async_generator_proto
8387 .clone()
8388 .unwrap_or_else(|| self.realm.generator_proto.clone())
8389 } else {
8390 self.realm.generator_proto.clone()
8391 };
8392 // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
8393 // `prototype` object when it is one, the intrinsic otherwise. Every generator having
8394 // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
8395 // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
8396 let proto = self.generator_instance_proto(&object, default_proto)?;
8397 let generator = self.new_object(Some(proto));
8398 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8399 Ok(_) => {}
8400 Err(error) => return Err(error),
8401 }
8402 generator.with_mut(|data| {
8403 data.kind = ObjectKind::Generator(Box::new(state));
8404 });
8405 Ok(Value::Object(generator))
8406 }
8407
8408 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8409 ///
8410 /// Returns the `{value, done}` object itself rather than the pair, because a
8411 /// `yield*` suspension already has one — the inner iterator's own result — and the
8412 /// protocol says to hand that straight through rather than nest it.
8413 /// Advance a generator and report *why* it parked.
8414 ///
8415 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
8416 /// "hand this value to the caller" — but an async generator does: an `await` has to
8417 /// settle before it can answer, while a `yield` is the answer.
8418 fn resume_generator_detailed(
8419 &mut self,
8420 generator: &Gc<JsObject>,
8421 kind: ResumeKind,
8422 value: Value,
8423 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8424 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
8425 ObjectKind::Generator(state) => {
8426 let is_async = state.is_async;
8427 Some(std::mem::replace(
8428 state.as_mut(),
8429 GeneratorState {
8430 frame: None,
8431 phase: GeneratorPhase::Executing,
8432 parked_on_await: false,
8433 parked_on_yield_star: false,
8434 requests: std::collections::VecDeque::new(),
8435 // **Busy while the body runs**, so a `next()` called *from inside*
8436 // the body queues instead of being served. §27.6.3.7
8437 // `AsyncGeneratorResumeNext` returns immediately for the state
8438 // "executing", and the request is served once the body suspends;
8439 // with `false` here the re-entrant call found an empty frame and
8440 // rejected (`request-queue-order-state-executing`).
8441 async_busy: is_async,
8442 is_async,
8443 },
8444 ))
8445 }
8446 _ => None,
8447 }) else {
8448 return Err(self.type_error("not a generator"));
8449 };
8450 let result = self.step_generator(&mut state, kind, value);
8451 // Requests queued *while* the body ran live on the placeholder, because the real
8452 // state is out of the object for the duration. They have to be folded back in
8453 // before the placeholder is overwritten, or the promise they carry never settles.
8454 let queued = generator.with_mut(|data| match &mut data.kind {
8455 ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
8456 _ => std::collections::VecDeque::new(),
8457 });
8458 state.requests.extend(queued);
8459 generator.with_mut(|data| {
8460 data.kind = ObjectKind::Generator(Box::new(state));
8461 });
8462 result
8463 }
8464
8465 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8466 ///
8467 /// Returns the `{value, done}` object itself rather than the pair, because a
8468 /// `yield*` suspension already has one — the inner iterator's own result — and the
8469 /// protocol says to hand that straight through rather than nest it.
8470 pub fn resume_generator(
8471 &mut self,
8472 generator: &Gc<JsObject>,
8473 kind: ResumeKind,
8474 value: Value,
8475 ) -> JsResult<Value> {
8476 let (value, done, ready, _reason) =
8477 self.resume_generator_detailed(generator, kind, value)?;
8478 if ready {
8479 return Ok(value);
8480 }
8481 self.iterator_result(value, done)
8482 }
8483
8484 /// `next`/`return`/`throw` on an async generator, which answer a promise.
8485 ///
8486 /// The body is the same coroutine a sync generator runs; what changes is that an
8487 /// `await` inside it has to settle before the method can answer, so the step is
8488 /// driven off the job queue rather than returning inline.
8489 pub fn resume_async_generator(
8490 &mut self,
8491 generator: &Gc<JsObject>,
8492 kind: ResumeKind,
8493 value: Value,
8494 ) -> JsResult<Value> {
8495 let promise = self.new_promise();
8496 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
8497 // that order, and the second value must reach the *second* `yield`.
8498 let idle = generator.with_mut(|data| match &mut data.kind {
8499 ObjectKind::Generator(state) => {
8500 state.requests.push_back(AsyncRequest {
8501 kind,
8502 value,
8503 promise: promise.clone(),
8504 });
8505 !state.async_busy
8506 }
8507 _ => false,
8508 });
8509 if idle {
8510 self.next_async_request(generator)?;
8511 }
8512 Ok(Value::Object(promise))
8513 }
8514
8515 /// Serve the front queued request, if the generator is free to run one.
8516 ///
8517 /// A finished generator answers from the queue without running anything:
8518 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
8519 /// first, and `throw(e)` rejects.
8520 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
8521 enum Front {
8522 Idle,
8523 Run(ResumeKind, Value, Gc<JsObject>),
8524 Finished(ResumeKind, Value, Gc<JsObject>),
8525 }
8526 let front = generator.with_mut(|data| match &mut data.kind {
8527 ObjectKind::Generator(state) => {
8528 let Some(request) = state.requests.front() else {
8529 return Front::Idle;
8530 };
8531 // Busy means a request is still in flight — awaiting inside the body, not
8532 // finished. Serving another now would interleave two requests.
8533 if state.async_busy && state.phase != GeneratorPhase::Completed {
8534 return Front::Idle;
8535 }
8536 let kind = request.kind;
8537 let value = request.value.clone();
8538 let promise = request.promise.clone();
8539 state.async_busy = true;
8540 if state.phase == GeneratorPhase::Completed {
8541 Front::Finished(kind, value, promise)
8542 } else {
8543 Front::Run(kind, value, promise)
8544 }
8545 }
8546 _ => Front::Idle,
8547 });
8548 match front {
8549 Front::Idle => Ok(()),
8550 Front::Run(kind, value, promise) => {
8551 self.step_async_generator(generator, &promise, kind, value)
8552 }
8553 Front::Finished(kind, value, promise) => match kind {
8554 ResumeKind::Throw => {
8555 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
8556 }
8557 ResumeKind::Next | ResumeKind::Start => {
8558 let result = self.iterator_result(Value::Undefined, true)?;
8559 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
8560 }
8561 ResumeKind::Return => {
8562 // `js_async_generator_completed_return`: the value is awaited before it
8563 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
8564 // finished generator answers `1`, not a promise.
8565 let resolved = match self.promise_resolve_intrinsic(value) {
8566 Ok(resolved) => resolved,
8567 Err(Signal::Throw(reason)) => {
8568 return self.settle_async_request(
8569 generator,
8570 &promise,
8571 AsyncOutcome::Error(reason),
8572 );
8573 }
8574 Err(other) => return Err(other),
8575 };
8576 let done = JsObject::function(
8577 self.heap,
8578 Some(self.realm.function_proto.clone()),
8579 Callable::CompletedReturn {
8580 generator: generator.clone(),
8581 promise: promise.clone(),
8582 rejected: false,
8583 },
8584 );
8585 let failed = JsObject::function(
8586 self.heap,
8587 Some(self.realm.function_proto.clone()),
8588 Callable::CompletedReturn {
8589 generator: generator.clone(),
8590 promise: promise.clone(),
8591 rejected: true,
8592 },
8593 );
8594 let Value::Object(resolved) = resolved else {
8595 return self.settle_async_request(
8596 generator,
8597 &promise,
8598 AsyncOutcome::Error(Value::Undefined),
8599 );
8600 };
8601 self.perform_then(
8602 &resolved,
8603 Some(Value::Object(done)),
8604 Some(Value::Object(failed)),
8605 )?;
8606 Ok(())
8607 }
8608 },
8609 }
8610 }
8611
8612 /// Settle the front request and start the next one.
8613 ///
8614 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
8615 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
8616 /// generator would strand every later request.
8617 fn settle_async_request(
8618 &mut self,
8619 generator: &Gc<JsObject>,
8620 promise: &Gc<JsObject>,
8621 outcome: AsyncOutcome,
8622 ) -> JsResult<()> {
8623 let settled = generator.with_mut(|data| match &mut data.kind {
8624 ObjectKind::Generator(state) => {
8625 let front = state.requests.front();
8626 debug_assert!(
8627 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
8628 "a request settled outside its turn"
8629 );
8630 state.requests.pop_front();
8631 state.async_busy = false;
8632 true
8633 }
8634 _ => false,
8635 });
8636 if settled {
8637 match outcome {
8638 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
8639 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
8640 }
8641 }
8642 self.next_async_request(generator)
8643 }
8644
8645 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
8646 ///
8647 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
8648 /// disposer runs **synchronously** — the reference starts it before returning, which
8649 /// a test can observe by logging after the call — and the rest follow once their
8650 /// predecessor settles.
8651 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
8652 let promise = self.new_promise();
8653 let mut pairs = Vec::with_capacity(resources.len());
8654 for (value, method) in resources {
8655 let pair = self.new_array(vec![value, method]);
8656 pairs.push(Value::Object(pair));
8657 }
8658 let remaining = self.new_array(pairs);
8659 self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
8660 Ok(Value::Object(promise))
8661 }
8662
8663 /// One link of the `disposeAsync` chain.
8664 ///
8665 /// Loops while the disposers finish synchronously, and parks on the first thenable it
8666 /// meets — pushing itself back in as the continuation, with the accumulated error
8667 /// carried along so a later failure can still be folded into the `SuppressedError`.
8668 fn dispose_step(
8669 &mut self,
8670 remaining: &Gc<JsObject>,
8671 promise: &Gc<JsObject>,
8672 mut error: Value,
8673 ) -> JsResult<()> {
8674 loop {
8675 let length = remaining.array_length().unwrap_or(0);
8676 if length == 0 {
8677 if matches!(error, Value::Uninitialized) {
8678 self.fulfill_promise(promise, Value::Undefined);
8679 } else {
8680 self.reject_promise(promise, error);
8681 }
8682 return Ok(());
8683 }
8684 let Some(Value::Object(pair)) = remaining
8685 .array_get(length - 1)
8686 .filter(|v| !matches!(v, Value::Hole))
8687 else {
8688 remaining.array_truncate(self.heap, length - 1);
8689 continue;
8690 };
8691 remaining.array_truncate(self.heap, length - 1);
8692 let value = pair.array_get(0).unwrap_or(Value::Undefined);
8693 let Some(Value::Object(method)) = pair.array_get(1) else {
8694 continue;
8695 };
8696 if !method.is_callable() {
8697 continue;
8698 }
8699 match self.call_value(Value::Object(method), value, Vec::new()) {
8700 Ok(result) => {
8701 if !self.is_thenable(&result)? {
8702 // Finished synchronously; the next disposer is the next iteration.
8703 continue;
8704 }
8705 let awaited = match self.promise_resolve_value(result) {
8706 Ok(awaited) => awaited,
8707 Err(Signal::Throw(reason)) => {
8708 self.reject_promise(promise, reason);
8709 return Ok(());
8710 }
8711 Err(other) => return Err(other),
8712 };
8713 let Value::Object(awaited) = awaited else {
8714 continue;
8715 };
8716 let ok = JsObject::function(
8717 self.heap,
8718 Some(self.realm.function_proto.clone()),
8719 Callable::DisposeStep {
8720 remaining: remaining.clone(),
8721 promise: promise.clone(),
8722 error: error.clone(),
8723 rejected: false,
8724 },
8725 );
8726 let failed = JsObject::function(
8727 self.heap,
8728 Some(self.realm.function_proto.clone()),
8729 Callable::DisposeStep {
8730 remaining: remaining.clone(),
8731 promise: promise.clone(),
8732 error,
8733 rejected: true,
8734 },
8735 );
8736 self.perform_then(
8737 &awaited,
8738 Some(Value::Object(ok)),
8739 Some(Value::Object(failed)),
8740 )?;
8741 return Ok(());
8742 }
8743 Err(Signal::Throw(thrown)) => {
8744 error = self.merge_dispose_error(thrown, error);
8745 }
8746 Err(other) => return Err(other),
8747 }
8748 }
8749 }
8750
8751 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
8752 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
8753 let Value::Object(object) = value else {
8754 return Ok(false);
8755 };
8756 Ok(matches!(
8757 self.get_property(object, "then")?,
8758 Some(Value::Object(then)) if then.is_callable()
8759 ))
8760 }
8761
8762 /// One step of an async generator, settling `promise` with an `{value, done}` result.
8763 fn step_async_generator(
8764 &mut self,
8765 generator: &Gc<JsObject>,
8766 promise: &Gc<JsObject>,
8767 kind: ResumeKind,
8768 value: Value,
8769 ) -> JsResult<()> {
8770 // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
8771 // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
8772 // is abrupt — a `constructor` getter that throws — the generator is resumed with a
8773 // *throw* completion instead, so the body's own `try { yield } catch` sees it:
8774 // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
8775 // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
8776 // out of the same read, one as a rejection and one as a rethrow.
8777 //
8778 // Narrow on purpose: only a value that is *already a promise* is inspected, so
8779 // nothing changes for `return 1` and the extra read is a plain data-property
8780 // lookup on the intrinsic case.
8781 if kind == ResumeKind::Return
8782 && let Value::Object(object) = &value
8783 && self.promise_state(object).is_some()
8784 && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
8785 {
8786 return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
8787 }
8788 let stepped = self.resume_generator_detailed(generator, kind, value);
8789 let (value, done, ready, reason) = match stepped {
8790 Ok(stepped) => stepped,
8791 Err(Signal::Throw(reason)) => {
8792 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
8793 }
8794 Err(other) => return Err(other),
8795 };
8796 // Only an `await` has to wait before the method can answer.
8797 if !done && reason == Some(SuspendKind::Await) {
8798 let awaited = match self.promise_resolve_value(value) {
8799 Ok(awaited) => awaited,
8800 Err(Signal::Throw(reason)) => {
8801 return self.settle_async_request(
8802 generator,
8803 promise,
8804 AsyncOutcome::Error(reason),
8805 );
8806 }
8807 Err(other) => return Err(other),
8808 };
8809 let Value::Object(awaited) = awaited else {
8810 return Ok(());
8811 };
8812 let resumed = JsObject::function(
8813 self.heap,
8814 Some(self.realm.function_proto.clone()),
8815 Callable::GeneratorResume {
8816 generator: generator.clone(),
8817 promise: promise.clone(),
8818 kind: ResumeKind::Next,
8819 },
8820 );
8821 let raised = JsObject::function(
8822 self.heap,
8823 Some(self.realm.function_proto.clone()),
8824 Callable::GeneratorResume {
8825 generator: generator.clone(),
8826 promise: promise.clone(),
8827 kind: ResumeKind::Throw,
8828 },
8829 );
8830 self.perform_then(
8831 &awaited,
8832 Some(Value::Object(resumed)),
8833 Some(Value::Object(raised)),
8834 )?;
8835 return Ok(());
8836 }
8837 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
8838 // completes it — both arrive as the settled value rather than as the promise
8839 // object. A plain value skips the round trip, which is also what keeps `yield 1`
8840 // from costing an extra tick.
8841 let awaits_value = self.is_thenable(&value)?;
8842 if awaits_value {
8843 // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
8844 // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
8845 // value that merely gets `yield`ed is awaited by the body's own `Await`, where
8846 // no `PromiseResolve` appears, so that path keeps the shortcut.
8847 let awaited = match if done {
8848 self.promise_resolve_intrinsic(value)
8849 } else {
8850 self.promise_resolve_value(value)
8851 } {
8852 Ok(awaited) => awaited,
8853 Err(Signal::Throw(reason)) => {
8854 return self.settle_async_request(
8855 generator,
8856 promise,
8857 AsyncOutcome::Error(reason),
8858 );
8859 }
8860 Err(other) => return Err(other),
8861 };
8862 let Value::Object(awaited) = awaited else {
8863 return Ok(());
8864 };
8865 // A rejected yield throws *at the yield* inside the body, so the rejection
8866 // resumes the generator rather than the method's promise.
8867 let answer = JsObject::function(
8868 self.heap,
8869 Some(self.realm.function_proto.clone()),
8870 Callable::YieldResult {
8871 generator: generator.clone(),
8872 promise: promise.clone(),
8873 done,
8874 },
8875 );
8876 let raise = JsObject::function(
8877 self.heap,
8878 Some(self.realm.function_proto.clone()),
8879 Callable::GeneratorResume {
8880 generator: generator.clone(),
8881 promise: promise.clone(),
8882 kind: ResumeKind::Throw,
8883 },
8884 );
8885 self.perform_then(
8886 &awaited,
8887 Some(Value::Object(answer)),
8888 Some(Value::Object(raise)),
8889 )?;
8890 return Ok(());
8891 }
8892 let result = if ready {
8893 // `yield*` handed back the inner iterator's own result object.
8894 value
8895 } else {
8896 self.iterator_result(value, done)?
8897 };
8898 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
8899 }
8900
8901 /// The `{value, done}` object an iterator method answers with.
8902 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
8903 let result = self.new_object(Some(self.realm.object_proto.clone()));
8904 result.define_data("value", value);
8905 result.define_data("done", Value::Bool(done));
8906 Ok(Value::Object(result))
8907 }
8908
8909 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
8910 fn step_generator(
8911 &mut self,
8912 state: &mut GeneratorState,
8913 kind: ResumeKind,
8914 value: Value,
8915 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8916 match state.phase {
8917 GeneratorPhase::Executing => {
8918 return Err(self.type_error("cannot invoke a running generator"));
8919 }
8920 GeneratorPhase::Completed => {
8921 // A finished generator answers every resumption without running.
8922 return Ok(match kind {
8923 ResumeKind::Throw => return Err(Signal::Throw(value)),
8924 ResumeKind::Return => (value, true, false, None),
8925 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
8926 });
8927 }
8928 GeneratorPhase::SuspendedStart => {
8929 if kind != ResumeKind::Next && kind != ResumeKind::Start {
8930 // The body never started, so there is nothing to unwind or return
8931 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
8932 state.frame = None;
8933 state.phase = GeneratorPhase::Completed;
8934 return Ok(match kind {
8935 ResumeKind::Throw => return Err(Signal::Throw(value)),
8936 _ => (value, true, false, None),
8937 });
8938 }
8939 }
8940 GeneratorPhase::SuspendedYield => {}
8941 }
8942
8943 let Some(mut frame) = state.frame.take() else {
8944 return Ok((Value::Undefined, true, false, None));
8945 };
8946 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
8947 // number that says which method resumed it; the emitted `if_false` branches on
8948 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
8949 let mut raised = None;
8950 match kind {
8951 ResumeKind::Next | ResumeKind::Start => {
8952 if state.phase == GeneratorPhase::SuspendedYield {
8953 frame.stack.push(value);
8954 // An `await` resumes with its value alone; only a `yield` gets the
8955 // magic number that says which of `next`/`return` resumed it.
8956 if !state.parked_on_await {
8957 frame.stack.push(Value::Int(RESUME_NEXT));
8958 }
8959 }
8960 }
8961 ResumeKind::Return => {
8962 // A `return` on a not-yet-started generator is handled above, so this is
8963 // always a real resumption.
8964 frame.stack.push(value);
8965 frame.stack.push(Value::Int(RESUME_RETURN));
8966 }
8967 ResumeKind::Throw => {
8968 // At a `yield*` the exception is *data* for the delegation: the compiled
8969 // code resumes with the value and magic `2` and calls the inner iterator's
8970 // `throw`. Everywhere else it is raised at the suspension point, so the
8971 // body's own handler sees it.
8972 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
8973 frame.stack.push(value);
8974 frame.stack.push(Value::Int(RESUME_THROW));
8975 } else {
8976 raised = Some(value);
8977 }
8978 }
8979 }
8980 state.phase = GeneratorPhase::Executing;
8981
8982 let depth = self.frames.len();
8983 self.frames.push(frame);
8984 // A `throw` unwinds from where the frame parked, exactly as if the exception had
8985 // happened at the `yield`.
8986 if let Some(exception) = raised {
8987 if self.catch_here(exception.clone()).is_none() {
8988 self.pop_frame();
8989 state.phase = GeneratorPhase::Completed;
8990 return Err(Signal::Throw(exception));
8991 }
8992 }
8993
8994 // Only the generator's *own* frame ends the generator. The body may call ordinary
8995 // functions, and those push frames of their own: a `Step::Return` from one of them
8996 // is a nested call finishing, not the generator completing. Miscounting that is
8997 // silent — the generator reports the callee's value as its own result and marks
8998 // itself done — so the depth comparison is load-bearing, not defensive.
8999 let own_frame = depth + 1;
9000 loop {
9001 match self.step() {
9002 Ok(Step::Continue) => {}
9003 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9004 let mut frame = self.frames.pop().expect("a frame is live");
9005 // `yield` left the value on the stack; `initial_yield` left nothing.
9006 let yielded = if reason == SuspendKind::Initial {
9007 Value::Undefined
9008 } else {
9009 frame.stack.pop().unwrap_or(Value::Undefined)
9010 };
9011 state.frame = Some(frame);
9012 state.parked_on_await = reason == SuspendKind::Await;
9013 state.parked_on_yield_star =
9014 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9015 state.phase = if reason == SuspendKind::Initial {
9016 GeneratorPhase::SuspendedStart
9017 } else {
9018 GeneratorPhase::SuspendedYield
9019 };
9020 // `yield*` hands the inner iterator's own result object straight
9021 // back, so the caller sees one `{value, done}` rather than a nested
9022 // one — which is why the third field says "already a result".
9023 return Ok((
9024 yielded,
9025 false,
9026 reason == SuspendKind::YieldStar,
9027 Some(reason),
9028 ));
9029 }
9030 Ok(Step::Suspend(_)) => {
9031 // A `yield` in a frame other than the generator's would mean a
9032 // generator body entered as an ordinary call, which
9033 // `call_or_push` prevents.
9034 self.unwind_to(depth);
9035 state.phase = GeneratorPhase::Completed;
9036 return Err(Signal::Throw(self.make_error(
9037 "InternalError",
9038 "a generator body ran as an ordinary call",
9039 )));
9040 }
9041 Ok(Step::Return(value)) => {
9042 self.pop_frame();
9043 if self.frames.len() > depth {
9044 // A nested call finished: hand the value back to its caller and
9045 // keep running the generator body.
9046 self.frames
9047 .last_mut()
9048 .expect("a caller is live")
9049 .stack
9050 .push(value);
9051 continue;
9052 }
9053 state.phase = GeneratorPhase::Completed;
9054 // The reference closes the generator's closure variables here; ours
9055 // live in cells the frame owned, which the drop below releases.
9056 return Ok((value, true, false, None));
9057 }
9058 Err(Signal::Throw(exception)) => {
9059 // The frame that threw gets the first chance to catch, exactly as in
9060 // the ordinary call loop; a frame above the generator's is popped and
9061 // the exception carries on down.
9062 let exception = exception;
9063 loop {
9064 if self.frames.len() <= depth {
9065 // The generator's own frame is gone, so nothing here caught it.
9066 state.phase = GeneratorPhase::Completed;
9067 return Err(Signal::Throw(exception));
9068 }
9069 if self.catch_here(exception.clone()).is_some() {
9070 break;
9071 }
9072 self.pop_frame();
9073 }
9074 }
9075 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9076 }
9077 }
9078 }
9079
9080 /// Pop frames until `depth` are left, keeping their buffers.
9081 fn unwind_to(&mut self, depth: usize) {
9082 while self.frames.len() > depth {
9083 self.pop_frame();
9084 }
9085 }
9086 fn call_or_push(
9087 &mut self,
9088 callee: Value,
9089 this: Value,
9090 args: Vec<Value>,
9091 ) -> JsResult<Option<Value>> {
9092 if let Value::Object(function) = &callee
9093 && let Some((code, env)) = bytecode_of(function)
9094 {
9095 // Calling a generator function does not run anything: it captures the
9096 // arguments in a frame and hands back the generator object.
9097 if code.code.kind.is_generator() {
9098 return self.new_generator(callee, this, args).map(Some);
9099 }
9100 // An async function answers a promise and runs its body as a coroutine, so it
9101 // takes the same path as a plain call into it.
9102 if code.code.kind.is_async() {
9103 return self.new_async_function(callee, this, args).map(Some);
9104 }
9105 self.push_frame(code, env, this, args, callee)?;
9106 return Ok(None);
9107 }
9108 self.call_value(callee, this, args).map(Some)
9109 }
9110
9111 /// `new callee(args)`.
9112 ///
9113 /// A constructor differs from a plain call in three ways: it gets a fresh object
9114 /// as `this` whose prototype is the constructor's `prototype` property, its
9115 /// return value is *replaced* by that object unless it returns an object itself,
9116 /// and a native constructor is expected to initialise the object it is given
9117 /// rather than build one.
9118 pub fn construct(
9119 &mut self,
9120 callee: Value,
9121 new_target: Value,
9122 args: Vec<Value>,
9123 ) -> JsResult<Value> {
9124 // `new` on a bound function constructs its *target*, prepending the arguments
9125 // the bind fixed and ignoring the bound `this` — a bound function is a
9126 // constructor only when its target is one, and `new` always makes a fresh
9127 // object of the target's prototype rather than reusing the bound receiver.
9128 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9129 // ran the body with `this === null` and threw on `this.x = a`.
9130 let mut callee = callee;
9131 let mut new_target = new_target;
9132 let mut args = args;
9133 loop {
9134 let Some(object) = callee.as_object().cloned() else {
9135 return Err(Signal::Throw(
9136 self.make_error("TypeError", "not a constructor"),
9137 ));
9138 };
9139 // A proxy of a function constructs through its `construct` trap, and the
9140 // trap's answer is the result directly — no fresh object is made here.
9141 if object.proxy_state().is_some() {
9142 return match self.proxy_construct(&object, args, &new_target)? {
9143 Some(result) => Ok(result),
9144 None => Err(Signal::Throw(
9145 self.make_error("TypeError", "proxy target is not a constructor"),
9146 )),
9147 };
9148 }
9149 // A generator function has no `[[Construct]]`, and the reference names it in
9150 // the message: `new (function* G(){})()` reports "G is not a constructor".
9151 if object.with(|data| match &data.kind {
9152 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9153 code.code.kind.is_generator()
9154 }
9155 _ => false,
9156 }) {
9157 let name = object
9158 .own_property("name")
9159 .and_then(|property| property.value)
9160 .map(|value| value.to_js_string())
9161 .unwrap_or_default();
9162 return Err(Signal::Throw(
9163 self.make_error("TypeError", &format!("{name} is not a constructor")),
9164 ));
9165 }
9166 let bound = object.with(|data| match &data.kind {
9167 ObjectKind::Function(Callable::Bound {
9168 target,
9169 args: leading,
9170 ..
9171 }) => Some((target.clone(), leading.clone())),
9172 _ => None,
9173 });
9174 let Some((target, leading)) = bound else {
9175 // Not a bound function, so this object is the callee. §7.2.4
9176 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9177 // refusals above cover only the built-ins the reference also refuses by
9178 // name. Everything else — a method, an arrow, an async function — has no
9179 // `[[Construct]]` either, and answering "yes" here made
9180 // `new (Array.prototype.map)` build an object instead of throwing.
9181 if !object.is_constructor() {
9182 let name = object
9183 .own_property("name")
9184 .and_then(|property| property.value)
9185 .map(|value| value.to_js_string())
9186 .unwrap_or_default();
9187 return Err(Signal::Throw(
9188 self.make_error("TypeError", &format!("{name} is not a constructor")),
9189 ));
9190 }
9191 break;
9192 };
9193 let mut all = leading;
9194 all.extend(args);
9195 args = all;
9196 // A bound function that is its own `new.target` stands in for its target:
9197 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9198 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9199 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9200 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9201 _ => false,
9202 };
9203 if same_wrapper {
9204 new_target = target.clone();
9205 }
9206 callee = target;
9207 }
9208 let Value::Object(function) = &callee else {
9209 unreachable!("the loop above only breaks on an object");
9210 };
9211 // The fresh object's prototype comes from `new.target`, not from the callee: a
9212 // derived constructor reaches here through `super()`, and the instance must be a
9213 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9214 // an object inheriting `D.prototype` rather than `C.prototype`.
9215 let prototype_source = match new_target.as_object() {
9216 Some(target) => target.clone(),
9217 None => function.clone(),
9218 };
9219 // A native constructor builds its own instance, through `new_ctor_instance`, once it
9220 // has validated its arguments. Pre-building one here would read
9221 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9222 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9223 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9224 let is_native = function.native_creates_own_instance();
9225 let this = if is_native {
9226 Value::Undefined
9227 } else {
9228 let prototype = self.get_property(&prototype_source, "prototype")?;
9229 let prototype = match prototype {
9230 Some(Value::Object(proto)) => Some(proto),
9231 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
9232 // object, the answer is the realm's *intrinsic* prototype for this
9233 // constructor, not `%Object.prototype%`.
9234 _ => {
9235 let fallback = self.get_property(function, "prototype")?;
9236 match fallback {
9237 Some(Value::Object(proto)) => Some(proto),
9238 _ => Some(self.realm.object_proto.clone()),
9239 }
9240 }
9241 };
9242 Value::Object(self.new_object(prototype))
9243 };
9244 // `new.target` inside the body is the constructor that was written, so a bound
9245 // function's target sees itself rather than the bound wrapper.
9246 //
9247 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
9248 // `?`, so assigning `None` after the call would be skipped and the failed
9249 // `new.target` would stay visible to every later native call. The symptom was a
9250 // native constructor refusing a plain call — `var s = Symbol(); new
9251 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
9252 // "FinalizationRegistry is not a constructor".
9253 let outer_new_target = self.pending_new_target.replace(new_target);
9254 let callee = callee.clone();
9255 let result = self.call_value(callee, this.clone(), args);
9256 self.pending_new_target = outer_new_target;
9257 let result = result?;
9258 // A constructor that returns an object overrides `this`; any other return value
9259 // (including `undefined`) is ignored — **except** in a derived constructor, where
9260 // §15.7.1 step 12 makes a non-object return a `TypeError`
9261 // (`Function/internals/Construct/derived-return-val`).
9262 let derived = function.with(|data| match &data.kind {
9263 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9264 code.code.is_derived_constructor
9265 }
9266 _ => false,
9267 });
9268 Ok(match result {
9269 Value::Object(_) => result,
9270 // A bare `return;` answers `undefined`, which is **legal** even in a derived
9271 // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
9272 Value::Undefined => this,
9273 _ if derived => {
9274 return Err(Signal::Throw(self.make_error(
9275 "TypeError",
9276 "derived constructor may only return an object or undefined",
9277 )));
9278 }
9279 _ => this,
9280 })
9281 }
9282
9283 /// `new.target` for the call currently being made.
9284 ///
9285 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9286 /// it as `this`), but a *host* constructor that builds its own instance is handed
9287 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9288 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9289 /// it here.
9290 ///
9291 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9292 /// receives for a plain call.
9293 pub fn current_new_target(&self) -> Value {
9294 self.active_new_target.clone()
9295 }
9296
9297 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9298 ///
9299 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9300 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9301 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9302 let constructor = self.realm.errors.get("AggregateError").cloned();
9303 let Some(constructor) = constructor else {
9304 return self.make_error("AggregateError", message);
9305 };
9306 let list = self.new_array(errors);
9307 match self.construct(
9308 Value::Object(constructor.clone()),
9309 Value::Object(constructor),
9310 vec![Value::Object(list), self.string(message)],
9311 ) {
9312 Ok(value) => value,
9313 // A user could have replaced `AggregateError` with something that throws; the
9314 // engine still owes the caller a rejection, so it falls back rather than
9315 // turning `Promise.any`'s rejection into a throw.
9316 Err(_) => self.make_error("AggregateError", message),
9317 }
9318 }
9319
9320 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9321 ///
9322 /// The error classes themselves arrive with the builtins milestone; what
9323 /// matters here is that the thrown value stringifies the way a script printing
9324 /// the caught value expects.
9325 ///
9326 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9327 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9328 /// rely on when they print a caught value.
9329 pub fn make_error(&self, name: &str, message: &str) -> Value {
9330 let proto = self
9331 .realm
9332 .errors
9333 .get(name)
9334 .map(|constructor| self.prototype_of(constructor))
9335 .unwrap_or_else(|| self.realm.error_proto.clone());
9336 let error = self.new_object(Some(proto));
9337 // `name` and `message` are own properties of the instance, which is what
9338 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9339 // `Error`.
9340 error.define(
9341 "name",
9342 Property::with_attributes(self.string(name), true, false),
9343 );
9344 error.define(
9345 "message",
9346 Property::with_attributes(self.string(message), true, false),
9347 );
9348 // The internal class, which is what tells a printer this is an error rather than a
9349 // plain object with `name` and `message` properties. The constructor path sets it
9350 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9351 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
9352 // literally `"Error"` in both places — the *name* is read from `name`, which is why
9353 // a `RangeError` still prints as `RangeError`.
9354 self.internal_set(&error, "_class", self.string("Error"));
9355 // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
9356 // answered `false` from `Error.isError` while a constructed one answered `true`,
9357 // because only the constructor set the slot. The reference answers `true` for both
9358 // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
9359 // accessor gated on this slot the omission stopped being cosmetic: `print_error`
9360 // tests `typeof stack === "string"` to decide on a trailing newline, so every
9361 // engine-thrown error lost its blank line.
9362 self.internal_set(&error, "_error_data", Value::Bool(true));
9363 // The trace is captured where the error is *made*, which is where the reference
9364 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
9365 // way out, so a caught engine error already has its stack even if the handler
9366 // never rethrows it.
9367 self.add_stack(&error);
9368 Value::Object(error)
9369 }
9370
9371 /// Give an error object its `stack` property, from the current frame stack.
9372 ///
9373 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
9374 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
9375 /// `stack` a script set, is not rewritten.
9376 pub fn add_stack(&self, object: &Gc<JsObject>) {
9377 self.add_stack_skipping(object, 0);
9378 }
9379
9380 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
9381 ///
9382 /// An `Error` constructor passes 1: the reference builds those traces with
9383 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
9384 /// constructor itself, while a `RangeError` raised inside `toISOString` does
9385 /// report `at toISOString (native)`.
9386 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
9387 if object.has_own("stack") {
9388 return;
9389 }
9390 // The trace is *captured* here but not installed as a property: `stack` is an
9391 // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
9392 // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
9393 // is kept in a hidden slot and the getter materialises it on first read.
9394 //
9395 // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
9396 // shows it — this is the same discipline `_error_data` and `_class` follow.
9397 let trace = self.stack_trace_skipping(skip);
9398 let text = self.string(trace);
9399 self.internal_set(object, "_stack_trace", text);
9400 }
9401
9402 /// The function object currently being called, if any.
9403 ///
9404 /// A native function is a bare `fn` pointer, so it cannot capture which class
9405 /// it belongs to; it reads that from the callee instead. This is also what a
9406 /// stack trace would use.
9407 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
9408 match &self.frames.last()?.callee {
9409 Value::Object(object) => Some(object.clone()),
9410 _ => None,
9411 }
9412 }
9413
9414 /// The `prototype` property of a constructor, falling back to
9415 /// `Object.prototype` for anything that is not shaped like one.
9416 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
9417 constructor
9418 .own_property("prototype")
9419 .and_then(|property| property.value)
9420 .and_then(|value| value.as_object().cloned())
9421 .unwrap_or_else(|| self.realm.object_proto.clone())
9422 }
9423
9424 /// Throw a `TypeError` carrying `message`.
9425 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
9426 Signal::Throw(self.make_error("TypeError", message.as_ref()))
9427 }
9428
9429 /// Throw a `RangeError` carrying `message`.
9430 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
9431 Signal::Throw(self.make_error("RangeError", message.as_ref()))
9432 }
9433
9434 /// The `ReferenceError` a read of an uninitialised binding raises.
9435 /// The name of the binding `slot` refers to, for an error message.
9436 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
9437 match kind {
9438 VarSlot::Loc => self
9439 .frame()
9440 .code
9441 .code
9442 .vars
9443 .get(slot)
9444 .map(|v| v.name.clone()),
9445 VarSlot::Closure => self
9446 .frame()
9447 .code
9448 .code
9449 .closure_vars
9450 .get(slot)
9451 .map(|c| c.name.clone()),
9452 }
9453 .unwrap_or_default()
9454 }
9455
9456 /// Whether `slot` names a `const` binding, which rejects every store after its
9457 /// initialiser.
9458 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
9459 match kind {
9460 VarSlot::Loc => self
9461 .frame()
9462 .code
9463 .code
9464 .vars
9465 .get(slot)
9466 .is_some_and(|v| v.is_const),
9467 VarSlot::Closure => self
9468 .frame()
9469 .code
9470 .code
9471 .closure_vars
9472 .get(slot)
9473 .is_some_and(|c| c.is_const),
9474 }
9475 }
9476
9477 /// The `TypeError` a store to a `const` binding raises.
9478 ///
9479 /// `const` is enforced here rather than at compile time because the binding can be
9480 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
9481 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
9482 /// both halves of what "checked store" means: the dead zone is over, and the
9483 /// binding is writable.
9484 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
9485 let name = self.binding_name(slot, kind);
9486 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
9487 }
9488
9489 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
9490 let name = match kind {
9491 VarSlot::Loc => self
9492 .frame()
9493 .code
9494 .code
9495 .vars
9496 .get(slot)
9497 .map(|v| v.name.clone()),
9498 VarSlot::Closure => self
9499 .frame()
9500 .code
9501 .code
9502 .closure_vars
9503 .get(slot)
9504 .map(|c| c.name.clone()),
9505 }
9506 .unwrap_or_default();
9507 Signal::Throw(self.make_error(
9508 "ReferenceError",
9509 &format!("cannot access '{name}' before initialization"),
9510 ))
9511 }
9512
9513 fn throw_reference(&self, name: &str) -> Signal {
9514 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
9515 }
9516
9517 // -- the instruction loop -----------------------------------------------
9518
9519 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
9520 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
9521 // measured at 16% of a tight arithmetic loop's total time.
9522 #[inline(always)]
9523 fn step(&mut self) -> JsResult<Step> {
9524 // The instruction is already decoded (see [`crate::insn`]), so this is an index
9525 // and a `Copy` read rather than a table lookup plus a width switch. Only the
9526 // borrow lives across the boundary; nothing is cloned.
9527 // **One** borrow of the frame: fetch the record, then advance in the same scope.
9528 // The obvious version borrowed it three times (`last` to read, `last_mut` to
9529 // write, and once more inside the handler), and each is a bounds check plus an
9530 // `Option` unwrap — on the one path every instruction takes.
9531 let Some((insn, next)) = ({
9532 let frame = self
9533 .frames
9534 .last_mut()
9535 .expect("step() is only called with a live frame");
9536 // Past the last instruction is a normal return: the compiler ends a function
9537 // with `return`, and a jump to the end of a block lands here.
9538 let insn = frame.insns().get(frame.pc).copied();
9539 match insn {
9540 None => None,
9541 Some(insn) => {
9542 // A fused record stands for the next few instructions, so the next
9543 // `pc` is its width ahead — the instructions it replaces are never
9544 // dispatched. `at` is the byte offset a stack trace reports; it stays
9545 // an offset because the line table is keyed by bytes.
9546 frame.at = insn.offset as usize;
9547 frame.pc += insn.width();
9548 Some((insn, frame.pc))
9549 }
9550 }
9551 }) else {
9552 return Ok(Step::Return(Value::Undefined));
9553 };
9554 self.check_memory()?;
9555 self.check_interrupt()?;
9556 if insn.fused == crate::insn::Fused::None {
9557 self.execute_instruction(insn.op, insn.a, insn.b, next)
9558 } else {
9559 self.execute_fused(insn)
9560 }
9561 }
9562
9563 /// Run a fused instruction: several bytecode instructions in one dispatch.
9564 ///
9565 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
9566 /// it cannot throw and cannot allocate — and anything else falls back to the real
9567 /// instructions, in their real order, so an exception leaves the operand stack
9568 /// exactly as it would have been.
9569 #[inline]
9570 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
9571 use crate::insn::Fused;
9572 let slot = insn.a as usize;
9573 match insn.fused {
9574 // `x = k`: `push k; put_loc x`.
9575 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
9576 // `x += k`: `get_loc x; push k; add; put_loc x`.
9577 Fused::AddImmLoc => {
9578 let delta = insn.b as i32;
9579 match self.get_loc(slot) {
9580 Value::Int(left) => {
9581 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
9582 // that built two `Value`s, called a function, and matched on them
9583 // again to reach this same `checked_add`. It is the innermost
9584 // operation of every accumulator in every program.
9585 let answer = match left.checked_add(delta) {
9586 Some(sum) => Value::Int(sum),
9587 None => Value::Float(left as f64 + delta as f64),
9588 };
9589 self.put_loc(slot, answer);
9590 }
9591 other => {
9592 self.push(other);
9593 self.push(Value::Int(delta));
9594 self.binary_add()?;
9595 let value = self.pop();
9596 self.put_loc(slot, value);
9597 }
9598 }
9599 }
9600 // `x += "literal"` and `x += y`: the two shapes that can append in place.
9601 Fused::AddAtomLoc => {
9602 let text = self.atom_wtf8(insn.b as usize);
9603 let right = self.string_wtf8(text);
9604 self.add_into_loc(slot, right)?;
9605 }
9606 Fused::AddLocLoc => {
9607 let source = (insn.a & 0xFFFF) as usize;
9608 let target = (insn.a >> 16) as usize;
9609 let right = self.get_loc(source);
9610 self.add_into_loc(target, right)?;
9611 }
9612 Fused::AddArgLoc => {
9613 let source = (insn.a & 0xFFFF) as usize;
9614 let target = (insn.a >> 16) as usize;
9615 let right = self.get_arg(source);
9616 self.add_into_loc(target, right)?;
9617 }
9618 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
9619 Fused::PostIncLoc => match self.get_loc(slot) {
9620 Value::Int(left) => {
9621 let answer = match left.checked_add(1) {
9622 Some(sum) => Value::Int(sum),
9623 None => Value::Float(left as f64 + 1.0),
9624 };
9625 self.put_loc(slot, answer);
9626 }
9627 other => {
9628 self.push(other);
9629 let raw = self.pop();
9630 let (old, updated) = self.advance_numeric(raw, true)?;
9631 self.push(old);
9632 self.push(updated);
9633 let value = self.pop();
9634 self.put_loc(slot, value);
9635 self.pop();
9636 }
9637 },
9638 // `if (!(x < arg)) goto target`: a loop header.
9639 //
9640 // The comparison is computed rather than replayed on the operand stack. That
9641 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
9642 // that throws: the effects happen in the same order, and a handler truncates
9643 // the stack down to its marker, so the intermediate values are unobservable.
9644 Fused::LtLocArgJump => {
9645 let loc = (insn.a >> 16) as usize;
9646 let arg = (insn.a & 0xFFFF) as usize;
9647 let left = self.get_loc(loc);
9648 let right = self.get_arg(arg);
9649 let taken = match (&left, &right) {
9650 (Value::Int(left), Value::Int(right)) => !(left < right),
9651 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9652 };
9653 if taken {
9654 self.frame_mut().pc = insn.b as usize;
9655 }
9656 }
9657 // `i < k` in a loop header, where `k` is an integer literal.
9658 Fused::LtLocImmJump => {
9659 let left = self.get_loc(insn.a as usize);
9660 let right = Value::Int(insn.imm as i32);
9661 let taken = match &left {
9662 Value::Int(left) => !(*left < insn.imm as i32),
9663 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9664 };
9665 if taken {
9666 self.frame_mut().pc = insn.b as usize;
9667 }
9668 }
9669 Fused::None => unreachable!("only called for a fused record"),
9670 }
9671 Ok(Step::Continue)
9672 }
9673
9674 /// Run records that cannot call script, cannot throw and cannot change frames.
9675 ///
9676 /// Returns `Some(value)` when the function ran off the end of its instructions (a
9677 /// normal return), and `None` when it stopped in front of an instruction the slow path
9678 /// has to handle — `pc` is written back either way, so `step` resumes at the right
9679 /// place.
9680 ///
9681 /// **The invariant is the whole point.** Every arm here is restricted to work that
9682 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
9683 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
9684 /// that the memory limit has to see. An opcode whose operands turn out to need any of
9685 /// that **stops the loop** instead of trying, so the slow path gets the instruction
9686 /// untouched and with its operands still on the stack. That is why the fallback is a
9687 /// `break` and not a duplicated slow arm: a second implementation of the same
9688 /// semantics is how a wrong answer gets in with no test noticing.
9689 ///
9690 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
9691 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
9692 fn run_fast(&mut self) -> JsResult<Option<Value>> {
9693 use crate::insn::Fused;
9694 // The outer loop exists only so a `Call` can come back through here: once a
9695 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
9696 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
9697 // frame. Re-entering re-reads both from whichever frame is now on top. Every
9698 // other exit from the inner loop returns, so this costs one loop per call.
9699 'outer: loop {
9700 // One reference-count bump per *slow* instruction (a call, an allocation, a
9701 // property access), never one per instruction — that distinction is worth
9702 // two orders of magnitude and was measured as such.
9703 let (code, mut pc) = {
9704 let frame = self.frame();
9705 (frame.code.clone(), frame.pc)
9706 };
9707 let insns = &code.insns;
9708 loop {
9709 let Some(insn) = insns.get(pc).copied() else {
9710 self.frame_mut().pc = pc;
9711 return Ok(Some(Value::Undefined));
9712 };
9713 match insn.fused {
9714 // `x = k`
9715 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
9716 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
9717 // object — stops the loop so `binary_add` can decide.
9718 Fused::AddImmLoc => {
9719 let slot = insn.a as usize;
9720 let delta = insn.b as i32;
9721 let Value::Int(left) = self.get_loc(slot) else {
9722 return Ok(self.stop(pc));
9723 };
9724 let sum = match left.checked_add(delta) {
9725 Some(sum) => Value::Int(sum),
9726 None => Value::Float(left as f64 + delta as f64),
9727 };
9728 self.put_loc(slot, sum);
9729 }
9730 // `x += "literal"` / `x += y`: the operand is a string, so the append
9731 // either allocates one or grows one. Both are the slow path's business;
9732 // the fusion's job is only to make the *slot* the sole owner, which is what
9733 // `execute_fused` needs and what `get_loc` alone destroys.
9734 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
9735 return Ok(self.stop(pc));
9736 }
9737 // `x++` on an integer, old value dropped.
9738 Fused::PostIncLoc => {
9739 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
9740 // value is read in place and overwritten in place, so the reference
9741 // count it held is released by the same assignment that stores the
9742 // new one. `get_loc` plus `put_loc` did two borrows, two table
9743 // lookups and a clone, and this arm is the whole body of a counting
9744 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
9745 let slot = insn.a as usize;
9746 let frame = self.frames.last_mut().expect("a frame is live");
9747 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
9748 let target = if cell < 0 {
9749 frame.locals.get_mut(slot)
9750 } else {
9751 None
9752 };
9753 let Some(target) = target else {
9754 return Ok(self.stop(pc));
9755 };
9756 let Value::Int(left) = *target else {
9757 return Ok(self.stop(pc));
9758 };
9759 *target = match left.checked_add(1) {
9760 Some(sum) => Value::Int(sum),
9761 None => Value::Float(left as f64 + 1.0),
9762 };
9763 }
9764 // A loop header, `if (!(x < arg)) goto target`, with both sides already
9765 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
9766 // bound stayed small integers.
9767 Fused::LtLocArgJump => {
9768 let loc = (insn.a >> 16) as usize;
9769 let arg = (insn.a & 0xFFFF) as usize;
9770 // One borrow for both slots: this arm *is* the whole loop of a
9771 // `for (i = 0; i < n; i++)` with an argument bound, so a second
9772 // `frames.last()` here is paid on every iteration. Measured 7.5% on
9773 // `dispatch:empty-loop`.
9774 let (left, right) = {
9775 let frame = self.frame();
9776 (frame.read_loc(loc), frame.read_arg(arg))
9777 };
9778 // Heavily measured: the bound is very often a `Float` even when the
9779 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
9780 // `JSON.parse` or a division is one — so requiring both sides to be
9781 // `Int` sent every iteration of those loops down the slow path. The
9782 // comparison below is the same one `relational` makes for two numbers.
9783 if !is_number(&left) || !is_number(&right) {
9784 return Ok(self.stop(pc));
9785 }
9786 // `if_false` branches on the comparison being false, which is **not**
9787 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
9788 // `>=` is also false and would keep it running forever. Clippy wants the
9789 // negation folded; that would be a wrong answer.
9790 let ordered = left.to_number() < right.to_number();
9791 let take_branch = !ordered;
9792 if take_branch {
9793 pc = insn.b as usize;
9794 continue;
9795 }
9796 }
9797 // The same header with a literal bound: `if (!(x < k)) goto target`.
9798 // The bound is an immediate, so only the counter needs a type test.
9799 #[allow(clippy::neg_cmp_op_on_partial_ord)]
9800 Fused::LtLocImmJump => {
9801 let left = self.get_loc(insn.a as usize);
9802 if !is_number(&left) {
9803 return Ok(self.stop(pc));
9804 }
9805 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
9806 if take_branch {
9807 pc = insn.b as usize;
9808 continue;
9809 }
9810 }
9811 Fused::None => match insn.op {
9812 // -- branches ---------------------------------------------------
9813 // A jump is an assignment now, because the target is an instruction
9814 // index. No arithmetic, no resolution table.
9815 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9816 let target = insn.a as usize;
9817 // A **back-edge** is a loop, and it is the only place an
9818 // instruction-level checkpoint can stop one: `for(;;){}` compiles
9819 // to a jump to itself and never leaves this loop, so the
9820 // per-instruction checks in `step` never run. That is exactly the
9821 // hole this arm closes — a host's `JS_SetInterruptHandler` did
9822 // nothing to a `for(;;){}` until it did, which is what
9823 // `tests/c/embed.c` is for.
9824 //
9825 // Polling here rather than on every instruction in this loop is
9826 // also the reference's choice (`OP_goto` calls
9827 // `js_poll_interrupts`), and it costs one compare per branch
9828 // instead of one decrement per instruction.
9829 if target <= pc {
9830 self.frame_mut().pc = target;
9831 self.check_memory()?;
9832 self.check_interrupt()?;
9833 }
9834 pc = target;
9835 continue;
9836 }
9837 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
9838 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
9839 let taken = self.pop().to_boolean();
9840 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
9841 if taken == want {
9842 pc = insn.a as usize;
9843 continue;
9844 }
9845 }
9846 // -- slot access -------------------------------------------------
9847 // A load's slot is already an operand (see `insn::implicit_operand`);
9848 // a captured one goes through its cell, which runs no script.
9849 Opcode::GetLoc
9850 | Opcode::GetLoc8
9851 | Opcode::GetLoc0
9852 | Opcode::GetLoc1
9853 | Opcode::GetLoc2
9854 | Opcode::GetLoc3 => {
9855 let value = self.get_loc(insn.a as usize);
9856 self.push(value);
9857 }
9858 Opcode::PutLoc
9859 | Opcode::PutLoc8
9860 | Opcode::PutLoc0
9861 | Opcode::PutLoc1
9862 | Opcode::PutLoc2
9863 | Opcode::PutLoc3 => {
9864 let value = self.pop();
9865 self.put_loc(insn.a as usize, value);
9866 }
9867 Opcode::GetArg
9868 | Opcode::GetArg0
9869 | Opcode::GetArg1
9870 | Opcode::GetArg2
9871 | Opcode::GetArg3 => {
9872 let value = self.get_arg(insn.a as usize);
9873 self.push(value);
9874 }
9875 Opcode::PutArg
9876 | Opcode::PutArg0
9877 | Opcode::PutArg1
9878 | Opcode::PutArg2
9879 | Opcode::PutArg3 => {
9880 let value = self.pop();
9881 self.put_arg(insn.a as usize, value);
9882 }
9883 // `a[i]` with an integer index on a dense array: see `fast_array_get`
9884 // for why a non-hole own element is exactly the slow path's answer.
9885 // The two operands are *peeked*, so a miss leaves the stack as the
9886 // slow path expects to find it.
9887 Opcode::GetArrayEl => {
9888 // One lookup, not two. The guard used `if …is_some()` and the arm
9889 // then called it again to get the value — two `peek`s, two
9890 // `array_get`s and two `Value` clones for one element.
9891 // `fast_array_get` was 13.1% of `array:indexed`, and the same
9892 // double call was the first version of the `get_field` fast path.
9893 let Some(value) = self.fast_array_get() else {
9894 return Ok(self.stop(pc));
9895 };
9896 // `a[i]` consumes both operands and leaves the element in their
9897 // place: one `truncate` and one write, no `pop`/`push` pair.
9898 let frame = self.frame_mut();
9899 frame.stack.truncate(frame.stack.len() - 2);
9900 frame.stack.push(value);
9901 }
9902 // `a[i] = v` on a dense array with an integer index: see
9903 // `fast_array_set` for why the whole store is one step.
9904 Opcode::PutArrayEl if self.fast_array_set() => {}
9905 // `o.x` resolved from the inline cache without leaving the loop.
9906 //
9907 // The cache is keyed by `(receiver identity, atom, site)` and a
9908 // monomorphic read re-validates the same chain every iteration, so
9909 // each one used to cost a `stop(pc)` — a write of `pc` into the
9910 // frame, a return out of this loop, a re-dispatch through `step` and
9911 // a re-entry. `property:monomorphic` spent 18% in
9912 // `read_field_cached` and 21% in `push`, both across that boundary.
9913 //
9914 // The site is `pc + width`, which is exactly the `next` the slow arm
9915 // passes — the two must agree or every fast lookup misses and
9916 // re-records the same entry forever.
9917 //
9918 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
9919 // slow arm finds the receiver where it expects it.
9920 // `name` resolved from the global-variable cache inside the loop.
9921 //
9922 // Same shape as `get_field` above and for the same reason: `get_var`
9923 // was not in the fast loop, so reading a global — which `fib` does
9924 // once per recursive call, for its own name — cost a `stop(pc)`, a
9925 // return out of the loop, a `step` re-dispatch and a re-entry, before
9926 // `get_global` even started its `scopes_are_plain` checks.
9927 //
9928 // Everything here is exactly `get_global`'s first branch: not lexical,
9929 // no `eval` scope, cache hit. Anything else leaves the stack untouched
9930 // and lets the slow arm decide.
9931 Opcode::GetVar => {
9932 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
9933 return Ok(self.stop(pc));
9934 };
9935 self.push(value);
9936 }
9937 Opcode::GetField | Opcode::GetField2 => {
9938 let Some(value) =
9939 self.fast_field_get(insn.a as usize, pc + insn.width())
9940 else {
9941 return Ok(self.stop(pc));
9942 };
9943 if insn.op == Opcode::GetField2 {
9944 // `get_field2` keeps the receiver for the `call_method` that
9945 // follows.
9946 self.push(value);
9947 } else {
9948 // `get_field` replaces the receiver, so this is one store over
9949 // the top slot rather than a `pop` and a `push`: the length
9950 // never changes, so neither `Vec` arm has a capacity check or a
9951 // drop to run beyond the one the overwrite itself does.
9952 let frame = self.frame_mut();
9953 match frame.stack.last_mut() {
9954 Some(slot) => *slot = value,
9955 None => return Ok(self.stop(pc)),
9956 }
9957 }
9958 }
9959 // -- constants ---------------------------------------------------
9960 Opcode::PushMinus1
9961 | Opcode::Push0
9962 | Opcode::Push1
9963 | Opcode::Push2
9964 | Opcode::Push3
9965 | Opcode::Push4
9966 | Opcode::Push5
9967 | Opcode::Push6
9968 | Opcode::Push7
9969 | Opcode::PushI8
9970 | Opcode::PushI16
9971 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
9972 // -- stack shuffling ---------------------------------------------
9973 Opcode::Drop => {
9974 self.pop();
9975 }
9976 // -- arithmetic on two integers ----------------------------------
9977 //
9978 // The operands are *looked at* before they are popped, so a non-integer
9979 // pair leaves the stack exactly as the slow path expects to find it.
9980 Opcode::Add if self.numeric_pair() => {
9981 let right = self.pop();
9982 let left = self.pop();
9983 // Exactly [`add_numbers`], which is what the slow arm reaches.
9984 let answer = match (&left, &right) {
9985 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
9986 Some(sum) => Value::Int(sum),
9987 None => Value::Float(*a as f64 + *b as f64),
9988 },
9989 _ => Value::Float(left.to_number() + right.to_number()),
9990 };
9991 self.push(answer);
9992 }
9993 Opcode::Sub
9994 | Opcode::And
9995 | Opcode::Or
9996 | Opcode::Xor
9997 | Opcode::Shl
9998 | Opcode::Sar
9999 | Opcode::Shr
10000 if self.numeric_pair() =>
10001 {
10002 let right = self.pop();
10003 let left = self.pop();
10004 let answer =
10005 arithmetic(insn.op, left, right).expect("numbers cannot throw");
10006 self.push(answer);
10007 }
10008 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10009 if self.numeric_pair() =>
10010 {
10011 let right = self.pop();
10012 let left = self.pop();
10013 let answer = self
10014 .relational(insn.op, left, right)
10015 .expect("numbers cannot throw");
10016 self.push(answer);
10017 }
10018 // -- calls -------------------------------------------------------
10019 //
10020 // A plain call: `callee(arg0, …, argN) -> result`.
10021 //
10022 // This arm exists because of one measurement. `call:recursion` had
10023 // **20.4% of its profile in `execute_instruction`** — the *slow*
10024 // executor — and `fib`'s recursive call is the only thing in that
10025 // function which is not a fast arm. Every call therefore left this
10026 // loop via `stop()`, went through `step()`'s dispatch and
10027 // `execute_instruction`'s match over every opcode, and came back here
10028 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
10029 //
10030 // Two things make it safe to do here rather than only in the slow path:
10031 //
10032 // * the caller's `pc` is stored *before* the call, which is what
10033 // `step` does too — so when the callee returns, the caller resumes
10034 // after the call and not at it;
10035 // * `check_memory` runs, because `step` calls it once per instruction
10036 // and a call allocates a frame, its locals and its cells. Skipping
10037 // the checkpoint here would let a `--memory-limit` script overshoot
10038 // by one call per instruction.
10039 Opcode::Call
10040 | Opcode::Call0
10041 | Opcode::Call1
10042 | Opcode::Call2
10043 | Opcode::Call3 => {
10044 let argc = self.argc_operand(insn.op, insn.a);
10045 let next = pc + insn.width();
10046 {
10047 let frame = self
10048 .frames
10049 .last_mut()
10050 .expect("run_fast() is only called with a live frame");
10051 // `at` is what a stack trace reports for this frame, so a throw
10052 // inside the callee has to see the call site and not whatever
10053 // the last `stop()` left there.
10054 frame.at = insn.offset as usize;
10055 frame.pc = next;
10056 }
10057 self.check_memory()?;
10058 self.check_interrupt()?;
10059 let args = self.pop_n(argc);
10060 let callee = self.pop();
10061 // A plain call has no receiver; the callee decides what to do with
10062 // `undefined` (a sloppy function substitutes the global object).
10063 if let Some(result) =
10064 self.call_or_push(callee, Value::Undefined, args)?
10065 {
10066 // Native, host, generator, async, bound — no frame was pushed,
10067 // so this loop is still describing the right function. `pc`
10068 // is advanced by the loop tail like every other arm; only the
10069 // frame's copy had to be written here, and it already was.
10070 self.push(result);
10071 } else {
10072 // A bytecode callee: its frame is on top now, and `insns` and
10073 // `pc` both belong to the caller. Start over on the new frame.
10074 continue 'outer;
10075 }
10076 }
10077 // -- return ------------------------------------------------------
10078 Opcode::Return => {
10079 let value = self.pop();
10080 self.frame_mut().pc = pc + insn.width();
10081 return Ok(Some(value));
10082 }
10083 Opcode::ReturnUndef => {
10084 self.frame_mut().pc = pc + insn.width();
10085 return Ok(Some(Value::Undefined));
10086 }
10087 // Everything else needs the slow path.
10088 _ => return Ok(self.stop(pc)),
10089 },
10090 }
10091 pc += insn.width();
10092 }
10093 }
10094 }
10095
10096 /// Whether the top two operand-stack values are both numbers.
10097 ///
10098 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
10099 /// cannot run script, so the arm may not throw and may not change frames.
10100 fn numeric_pair(&self) -> bool {
10101 is_number(&self.peek(0)) && is_number(&self.peek(1))
10102 }
10103
10104 /// `a[i]` for a dense array and an integer index, without the string round trip.
10105 ///
10106 /// The slow path answers this by turning `i` into a string (`propkey` →
10107 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
10108 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
10109 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
10110 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
10111 /// without even the cheap `Int` formatting.
10112 ///
10113 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
10114 /// unambiguously the one the slow path would give:
10115 ///
10116 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
10117 /// `2^32-1` is the length, not an index),
10118 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
10119 /// typed array or an ordinary object, all of which have their own rules),
10120 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
10121 /// starts walking the prototype chain, and `a[i]` on a hole must find
10122 /// `Array.prototype[i]` if it exists rather than `undefined`.
10123 ///
10124 /// The last condition is the one that makes this safe rather than merely fast: an own
10125 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
10126 /// `get_var` answered from the global-variable cache, or `None`.
10127 ///
10128 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10129 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10130 /// records nothing — the slow arm is about to walk the chain and record it.
10131 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10132 let frame = self.frame();
10133 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10134 // "Lexical" is presence in the realm's table, not the closure var's flag: a
10135 // `GlobalRef` forwarded through a nested function has its flags cleared.
10136 if self.realm.globals.contains_key(name) {
10137 return None;
10138 }
10139 if !self.scopes_are_plain() {
10140 return None;
10141 }
10142 let object = &self.realm.global;
10143 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10144 let cached = self.global_cache[site].as_ref()?;
10145 if !object.upgrades_to(&cached.object) {
10146 return None;
10147 }
10148 object.data_property_at(cached.index, name)
10149 }
10150
10151 /// `o.x` answered entirely from the inline cache, or `None`.
10152 ///
10153 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
10154 /// about to do exactly that and recording it twice would rebuild the chain for every
10155 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
10156 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
10157 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
10158 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
10159 // an object receiver is a reference-count bump that the answer never needs.
10160 let frame = self.frame();
10161 let object = frame.stack.last()?;
10162 let Value::Object(target) = object else {
10163 return None;
10164 };
10165 // A proxy traps the lookup, so no cache entry ever describes it.
10166 if target.proxy_state().is_some() {
10167 return None;
10168 }
10169 let key = frame.code.atom_keys.get(atom)?;
10170 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
10171 if cached.key != *key {
10172 return None;
10173 }
10174 Self::cached_hit(target, cached)
10175 }
10176
10177 fn fast_array_get(&self) -> Option<Value> {
10178 let Value::Int(index) = self.peek(0) else {
10179 return None;
10180 };
10181 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
10182 // set for an `i32`.
10183 if index < 0 {
10184 return None;
10185 }
10186 let Value::Object(object) = self.peek(1) else {
10187 return None;
10188 };
10189 match object.array_get(index as usize) {
10190 Some(value) if !matches!(value, Value::Hole) => Some(value),
10191 _ => None,
10192 }
10193 }
10194
10195 /// `a[i] = v` on a dense array with an integer index, as one store.
10196 ///
10197 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
10198 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
10199 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
10200 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
10201 /// reference at the time it was measured (14.7x).
10202 ///
10203 /// Every condition here is one the slow path would also have to satisfy before
10204 /// storing into the element vector:
10205 ///
10206 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
10207 /// accepts as an index;
10208 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
10209 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
10210 /// one inside a recorded descriptor, reports `false` and the caller stops.
10211 ///
10212 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
10213 /// writes the own element too once `array_set` says it did.
10214 fn fast_array_set(&mut self) -> bool {
10215 // Every test runs *before* anything is popped: a refusal has to leave the stack
10216 // exactly as the slow path expects to find it. Popping first and reporting the
10217 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
10218 // then ran the slow path with nothing to write.
10219 let Value::Int(index) = self.peek(1) else {
10220 return false;
10221 };
10222 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
10223 if index < 0 {
10224 return false;
10225 }
10226 // Only a real array: a typed array's elements live in its buffer, a string-like
10227 // object has no element vector, and `array_set` on either does nothing.
10228 let Value::Object(object) = self.peek(2) else {
10229 return false;
10230 };
10231 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
10232 return false;
10233 }
10234 // A non-extensible array reports `false` here, but the *slow* path has to decide
10235 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
10236 // that with the key and the stack still intact.
10237 if !object.is_extensible() {
10238 return false;
10239 }
10240 // Inside the logical length, so the store cannot change `length`. Combined with
10241 // extensibility above, the only growth left for `array_set` is filling a hole in
10242 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
10243 // shape this fast path exists for. A store past the length would grow the array,
10244 // and whether that is allowed is the slow path's question.
10245 if index as usize >= object.array_length().unwrap_or(0) {
10246 return false;
10247 }
10248 // Only an *own element* can take the inline store. A hole is not an own property,
10249 // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
10250 // trap or a setter decides, and where `new Array(1)` with a proxy above it must
10251 // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
10252 // the one case this path used to swallow.
10253 //
10254 // The cost is small: `array:indexed` only reads after a 64-element fill, and
10255 // `array:push` appends past the length, which this path already refused.
10256 if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
10257 {
10258 return false;
10259 }
10260 // The bound `array_set` refuses past. Checking it here keeps that arm from having
10261 // to report a failure after the operands are gone.
10262 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
10263 return false;
10264 }
10265 let value = self.pop();
10266 self.pop();
10267 self.pop();
10268 object.array_store(self.heap, index as usize, value)
10269 }
10270
10271 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
10272 fn stop(&mut self, pc: usize) -> Option<Value> {
10273 self.frame_mut().pc = pc;
10274 None
10275 }
10276
10277 fn push(&mut self, value: Value) {
10278 self.frame_mut().stack.push(value);
10279 }
10280
10281 fn pop(&mut self) -> Value {
10282 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10283 }
10284
10285 fn pop_n(&mut self, count: usize) -> Vec<Value> {
10286 let frame = self.frame_mut();
10287 let start = frame.stack.len().saturating_sub(count);
10288 frame.stack.split_off(start)
10289 }
10290
10291 fn peek(&self, back: usize) -> Value {
10292 let frame = self.frame();
10293 frame
10294 .stack
10295 .get(frame.stack.len().wrapping_sub(1 + back))
10296 .cloned()
10297 .unwrap_or(Value::Undefined)
10298 }
10299
10300 #[allow(clippy::too_many_lines)]
10301 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10302 use Opcode::*;
10303 match op {
10304 // -- constants and stack shuffling -----------------------------
10305 Nop => {}
10306 PushMinus1 => self.push(Value::Int(-1)),
10307 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10308 let value = match op {
10309 Push0 => 0,
10310 Push1 => 1,
10311 Push2 => 2,
10312 Push3 => 3,
10313 Push4 => 4,
10314 Push5 => 5,
10315 Push6 => 6,
10316 _ => 7,
10317 };
10318 self.push(Value::Int(value));
10319 }
10320 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
10321 PushBigintI32 => {
10322 // The immediate form of a `BigInt` literal; the reference has the same
10323 // split between this and a constant-pool entry.
10324 let value = crate::bigint::BigInt::from_i64(a as i64);
10325 self.push(self.bigint(value));
10326 }
10327 PushTrue => self.push(Value::Bool(true)),
10328 PushFalse => self.push(Value::Bool(false)),
10329 PushEmptyString => self.push(self.string("")),
10330 Undefined => self.push(Value::Undefined),
10331 Null => self.push(Value::Null),
10332 Object => {
10333 let proto = self.realm.object_proto.clone();
10334 self.push(Value::Object(self.new_object(Some(proto))));
10335 }
10336 PushThis => {
10337 let this = self.frame().this.clone();
10338 self.push(this);
10339 }
10340 PushConst | PushConst8 => {
10341 let value = self.constant(a as usize)?;
10342 self.push(value);
10343 }
10344 PushAtomValue => {
10345 let text = self.atom_wtf8(a as usize);
10346 self.push(self.string_wtf8(text));
10347 }
10348 Dup => {
10349 let value = self.peek(0);
10350 self.push(value);
10351 }
10352 Dup2 => {
10353 // `a b -> a b a b`
10354 let b = self.peek(0);
10355 let a = self.peek(1);
10356 self.push(a);
10357 self.push(b);
10358 }
10359 Dup3 => {
10360 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
10361 // prototype and key while reading the current value through them.
10362 let c = self.peek(0);
10363 let b = self.peek(1);
10364 let a = self.peek(2);
10365 self.push(a);
10366 self.push(b);
10367 self.push(c);
10368 }
10369 Swap => {
10370 // `a b -> b a`
10371 let bottom = self.pop();
10372 let top = self.pop();
10373 self.push(bottom);
10374 self.push(top);
10375 }
10376 Perm3 => {
10377 // `a b c -> b a c`, the reference's reordering for a spread method
10378 // call: `obj func array` becomes the `func this array` that `apply`
10379 // takes.
10380 let c = self.pop();
10381 let b = self.pop();
10382 let a = self.pop();
10383 self.push(b);
10384 self.push(a);
10385 self.push(c);
10386 }
10387 Dup1 => {
10388 let value = self.peek(1);
10389 self.push(value);
10390 }
10391 Drop => {
10392 self.pop();
10393 }
10394 Nip => {
10395 // `a b -> b`
10396 let top = self.pop();
10397 self.pop();
10398 self.push(top);
10399 }
10400 Perm4 => {
10401 // `obj prop a b -> a obj prop b`, the reference's reordering for a
10402 // postfix update of a computed element: it puts the *old* value
10403 // underneath the receiver and key so `put_array_el` can consume them
10404 // and leave the old value as the expression's result.
10405 let d = self.pop();
10406 let c = self.pop();
10407 let b = self.pop();
10408 let a = self.pop();
10409 self.push(c);
10410 self.push(a);
10411 self.push(b);
10412 self.push(d);
10413 }
10414 Insert2 => {
10415 // `obj a -> a obj a`
10416 let value = self.pop();
10417 let object = self.pop();
10418 self.push(value.clone());
10419 self.push(object);
10420 self.push(value);
10421 }
10422 Insert3 => {
10423 // `obj prop a -> a obj prop a`
10424 let value = self.pop();
10425 let key = self.pop();
10426 let object = self.pop();
10427 self.push(value.clone());
10428 self.push(object);
10429 self.push(key);
10430 self.push(value);
10431 }
10432 Insert4 => {
10433 // `this obj prop a -> a this obj prop a`
10434 //
10435 // `put_super_value` consumes all four and yields nothing, so the copy
10436 // underneath is what leaves the assignment an expression value.
10437 let value = self.pop();
10438 let key = self.pop();
10439 let object = self.pop();
10440 let receiver = self.pop();
10441 self.push(value.clone());
10442 self.push(receiver);
10443 self.push(object);
10444 self.push(key);
10445 self.push(value);
10446 }
10447 Swap2 => {
10448 // `a b c d -> c d a b`
10449 let d = self.pop();
10450 let c = self.pop();
10451 let b = self.pop();
10452 let a = self.pop();
10453 self.push(c);
10454 self.push(d);
10455 self.push(a);
10456 self.push(b);
10457 }
10458 Rot3l => {
10459 // `x a b -> a b x`
10460 let b = self.pop();
10461 let a = self.pop();
10462 let x = self.pop();
10463 self.push(a);
10464 self.push(b);
10465 self.push(x);
10466 }
10467 Rot3r => {
10468 // `a b c -> c a b`
10469 let c = self.pop();
10470 let b = self.pop();
10471 let a_value = self.pop();
10472 self.push(c);
10473 self.push(a_value);
10474 self.push(b);
10475 }
10476
10477 Rest => {
10478 // `...rest` in a parameter list: the arguments from index `a` on, as a
10479 // real array. It takes nothing off the stack — the arguments are in the
10480 // frame, not on it.
10481 let frame = self.frame();
10482 let from = a as usize;
10483 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
10484 let array = self.new_array(collected);
10485 self.push(Value::Object(array));
10486 }
10487
10488 // -- slots ------------------------------------------------------
10489 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
10490 let slot = self.slot_operand(op, a);
10491 let value = self.get_loc(slot);
10492 self.push(value);
10493 }
10494 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
10495 let slot = self.slot_operand(op, a);
10496 let value = self.pop();
10497 self.put_loc(slot, value);
10498 }
10499 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
10500 let slot = self.slot_operand(op, a);
10501 let value = self.pop();
10502 self.put_loc(slot, value.clone());
10503 self.push(value);
10504 }
10505 // The `_check` forms are the temporal dead zone: they throw when the
10506 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
10507 // *reads*, so only the two writes may pop — mishandling that quietly
10508 // consumes the value the caller pushed just before.
10509 GetLocCheck => {
10510 let slot = self.slot_operand(op, a);
10511 let value = self.get_loc(slot);
10512 if matches!(value, Value::Uninitialized) {
10513 return Err(self.dead_zone(slot, VarSlot::Loc));
10514 }
10515 self.push(value);
10516 }
10517 PutLocCheck | SetLocCheck => {
10518 let slot = self.slot_operand(op, a);
10519 let value = self.pop();
10520 if matches!(value, Value::Uninitialized) {
10521 return Err(self.dead_zone(slot, VarSlot::Loc));
10522 }
10523 // The initialiser goes through `put_loc`, not this, so any store that
10524 // reaches here is a later assignment — which a `const` refuses.
10525 if self.is_read_only(slot, VarSlot::Loc) {
10526 return Err(self.read_only(slot, VarSlot::Loc));
10527 }
10528 if op == SetLocCheck {
10529 self.put_loc(slot, value.clone());
10530 self.push(value);
10531 } else {
10532 self.put_loc(slot, value);
10533 }
10534 }
10535 PutLocCheckInit => {
10536 // The one store that *initialises* a lexical slot: `this` in a derived
10537 // constructor, which only exists after `super()` has run. A second
10538 // initialisation is the error the reference reports as
10539 // "'this' can be initialized only once".
10540 let slot = self.slot_operand(op, a);
10541 let value = self.pop();
10542 if !matches!(self.get_loc(slot), Value::Uninitialized) {
10543 return Err(Signal::Throw(self.make_error(
10544 "ReferenceError",
10545 "'this' can be initialized only once",
10546 )));
10547 }
10548 self.put_loc(slot, value);
10549 }
10550 CheckCtor => {
10551 // A class constructor may only run under `new`, which is what makes
10552 // `class A {}; A()` a TypeError.
10553 if matches!(self.frame().new_target, Value::Undefined) {
10554 return Err(Signal::Throw(self.make_error(
10555 "TypeError",
10556 "class constructors must be invoked with 'new'",
10557 )));
10558 }
10559 }
10560 InitCtor => {
10561 // The body a derived class gets when it declares no constructor:
10562 // forward every argument to the parent constructor, keeping `new.target`.
10563 if matches!(self.frame().new_target, Value::Undefined) {
10564 return Err(Signal::Throw(self.make_error(
10565 "TypeError",
10566 "class constructors must be invoked with 'new'",
10567 )));
10568 }
10569 let Some(callee) = self.current_callee() else {
10570 return Err(Signal::Throw(
10571 self.make_error("TypeError", "no constructor to inherit from"),
10572 ));
10573 };
10574 let parent = callee.proto().map_or(Value::Null, Value::Object);
10575 let new_target = self.frame().new_target.clone();
10576 let args = self.frame().passed().to_vec();
10577 let result = self.construct(parent, new_target, args)?;
10578 self.push(result);
10579 }
10580 SetLocUninitialized => {
10581 let slot = self.slot_operand(op, a);
10582 self.put_loc(slot, Value::Uninitialized);
10583 }
10584 CloseLoc => {
10585 // "Close" a binding: give it a *fresh* cell holding the current
10586 // value. Closures created before this point keep the old cell and the
10587 // ones created after see the new one, which is what makes every
10588 // iteration of `for (let i ...)` capture its own `i`, and what freezes
10589 // a block-scoped binding when the block ends.
10590 //
10591 // Clearing the slot instead (which this used to do) broke both: a
10592 // closure over a captured block variable read `undefined`, and a loop
10593 // terminated after one iteration.
10594 let slot = self.slot_operand(op, a);
10595 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
10596 if index >= 0 {
10597 let current = self.frame().cells[index as usize].get();
10598 let fresh = self.new_cell(current);
10599 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
10600 *cell = fresh;
10601 }
10602 }
10603 }
10604 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
10605 let slot = self.slot_operand(op, a);
10606 let value = self.get_arg(slot);
10607 self.push(value);
10608 }
10609 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
10610 let slot = self.slot_operand(op, a);
10611 let value = self.pop();
10612 self.put_arg(slot, value);
10613 }
10614 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
10615 let slot = self.slot_operand(op, a);
10616 let value = self.pop();
10617 self.put_arg(slot, value.clone());
10618 self.push(value);
10619 }
10620
10621 // -- closure variables ------------------------------------------
10622 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
10623 let slot = self.slot_operand(op, a);
10624 // A name a direct `eval` created shadows the binding the compiler chose.
10625 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
10626 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
10627 // and only a runtime lookup can know that.
10628 if let Some(cell) = self.eval_created_local(slot) {
10629 self.push(cell.get());
10630 return self.step();
10631 }
10632 let value = self.cell_value(slot)?;
10633 self.push(value);
10634 }
10635 GetVarRefCheck => {
10636 let slot = self.slot_operand(op, a);
10637 let value = self.cell_value(slot)?;
10638 if matches!(value, Value::Uninitialized) {
10639 return Err(self.dead_zone(slot, VarSlot::Closure));
10640 }
10641 self.push(value);
10642 }
10643 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
10644 let slot = self.slot_operand(op, a);
10645 let value = self.pop();
10646 if let Some(cell) = self.eval_created_local(slot) {
10647 cell.set(value);
10648 return self.step();
10649 }
10650 // Same rule as `PutLocCheck`: a checked store to a captured binding
10651 // refuses a `const` once its initialiser has run.
10652 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
10653 return Err(self.read_only(slot, VarSlot::Closure));
10654 }
10655 self.set_cell(slot, value)?;
10656 }
10657 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
10658 let slot = self.slot_operand(op, a);
10659 let value = self.pop();
10660 if let Some(cell) = self.eval_created_local(slot) {
10661 cell.set(value.clone());
10662 self.push(value);
10663 return self.step();
10664 }
10665 self.set_cell(slot, value.clone())?;
10666 self.push(value);
10667 }
10668
10669 // -- globals ----------------------------------------------------
10670 GetVar => {
10671 let value = self.get_global(a as usize)?;
10672 self.push(value);
10673 }
10674 GetVarUndef => {
10675 let value = self
10676 .get_global(a as usize)
10677 .or_else(|_| Ok(Value::Undefined))?;
10678 self.push(value);
10679 }
10680 DeleteVar => {
10681 // `delete name` for a name that is not a declared binding. A lexical
10682 // global lives in the reference table and cannot be deleted; anything
10683 // reachable only as a property of the global object is *implicit* —
10684 // `x = 1` with no declaration — and goes away if it is configurable,
10685 // which is what `delete` on an implicit global answers.
10686 let name = self.atom_text(a as usize);
10687 let global = self.realm.global.clone();
10688 let deleted = if self.realm.globals.contains_key(&name) {
10689 false
10690 } else if global.own_property(&name).is_some() {
10691 self.delete_property(&global, &name)?
10692 } else {
10693 true
10694 };
10695 self.push(Value::Bool(deleted));
10696 }
10697 PutVar => {
10698 let value = self.pop();
10699 self.put_global(a as usize, value)?;
10700 }
10701 PutVarInit => {
10702 let slot = a as usize;
10703 let value = self.pop();
10704 self.init_global(slot, value)?;
10705 }
10706
10707 // -- arithmetic -------------------------------------------------
10708 Add => self.binary_add()?,
10709 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
10710 let raw_right = self.pop();
10711 let raw_left = self.pop();
10712 // BigInt arithmetic is a separate path, and not only for the type of the
10713 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
10714 // rather than a silent conversion.
10715 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
10716 let left = self.primitive_of(raw_left)?;
10717 let right = self.primitive_of(raw_right)?;
10718 let value = self.bigint_arithmetic(op, left, right)?;
10719 self.push(value);
10720 } else {
10721 let right = self.numeric(raw_right)?;
10722 let left = self.numeric(raw_left)?;
10723 self.push(arithmetic(op, left, right)?);
10724 }
10725 }
10726 Neg => {
10727 let raw = self.pop();
10728 match raw {
10729 // A bigint negates exactly, however wide it is.
10730 Value::BigInt(big) => {
10731 let negated = big.negate();
10732 self.push(self.bigint(negated));
10733 }
10734 other => {
10735 let value = self.numeric(other)?;
10736 self.push(negate(value));
10737 }
10738 }
10739 }
10740 Plus => {
10741 let value = self.pop();
10742 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
10743 // unary plus is defined to produce a *number*, which a bigint cannot
10744 // become without loss. It used to fall through to `NaN`.
10745 if matches!(value, Value::BigInt(_)) {
10746 return Err(self.type_error("cannot convert bigint to number"));
10747 }
10748 let numeric = self.numeric_of(value)?;
10749 self.push(numeric);
10750 }
10751 Inc => {
10752 let raw = self.pop();
10753 let (_, updated) = self.advance_numeric(raw, true)?;
10754 self.push(updated);
10755 }
10756 Dec => {
10757 let raw = self.pop();
10758 let (_, updated) = self.advance_numeric(raw, false)?;
10759 self.push(updated);
10760 }
10761 PostInc | PostDec => {
10762 // `x -> x x+1`: the *new* value ends up on top, so the store the
10763 // compiler emits right after (`put_var`) writes the incremented
10764 // one, while the old value stays underneath for the expression's
10765 // own result. Getting this backwards makes `i++` a no-op, which
10766 // turns `while (i < 3)` into an infinite loop.
10767 let raw = self.pop();
10768 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
10769 self.push(old);
10770 self.push(updated);
10771 }
10772 Not => {
10773 let raw = self.pop();
10774 match raw {
10775 // `~x` on a bigint is `-x - 1`, exact at any width.
10776 Value::BigInt(big) => {
10777 let inverted = big.bitnot();
10778 self.push(self.bigint(inverted));
10779 }
10780 other => {
10781 let value = self.numeric(other)?;
10782 self.push(Value::Int(!value.to_int32()));
10783 }
10784 }
10785 }
10786 Lnot => {
10787 let value = self.pop();
10788 self.push(Value::Bool(!value.to_boolean()));
10789 }
10790
10791 // -- comparison -------------------------------------------------
10792 Lt | Lte | Gt | Gte => {
10793 let right = self.pop();
10794 let left = self.pop();
10795 let answer = self.relational(op, left, right)?;
10796 self.push(answer);
10797 }
10798 Eq | Neq => {
10799 let right = self.pop();
10800 let left = self.pop();
10801 let equal = self.abstract_equals(left, right)?;
10802 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
10803 }
10804 StrictEq => {
10805 let right = self.pop();
10806 let left = self.pop();
10807 self.push(Value::Bool(left.strict_equals(&right)));
10808 }
10809 StrictNeq => {
10810 let right = self.pop();
10811 let left = self.pop();
10812 self.push(Value::Bool(!left.strict_equals(&right)));
10813 }
10814 IsUndefined => {
10815 // `=== undefined`, which is what a destructuring default tests. It is
10816 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
10817 let value = self.pop();
10818 self.push(Value::Bool(matches!(value, Value::Undefined)));
10819 }
10820 IsUndefinedOrNull => {
10821 let value = self.pop();
10822 self.push(Value::Bool(value.is_nullish()));
10823 }
10824 Typeof => {
10825 let value = self.pop();
10826 self.push(self.string(value.type_of()));
10827 }
10828 ToObject => {
10829 // A destructuring *object* pattern starts here, which is why
10830 // `var {} = null` throws. Only `undefined` and `null` are refused; a
10831 // primitive is boxed.
10832 let value = self.pop();
10833 let object = self.object_from(&value)?;
10834 self.push(Value::Object(object));
10835 }
10836 Instanceof => {
10837 let constructor = self.pop();
10838 let object = self.pop();
10839 let answer = self.instance_of(&object, &constructor)?;
10840 self.push(Value::Bool(answer));
10841 }
10842 In => {
10843 let object = self.pop();
10844 let key = self.pop();
10845 let answer = self.has_property(&key, &object)?;
10846 self.push(Value::Bool(answer));
10847 }
10848
10849 // -- control flow -----------------------------------------------
10850 Goto | Goto8 | Goto16 => {
10851 self.frame_mut().pc = a as usize;
10852 }
10853 IfTrue | IfTrue8 => {
10854 let value = self.pop();
10855 if value.to_boolean() {
10856 self.frame_mut().pc = a as usize;
10857 }
10858 }
10859 IfFalse | IfFalse8 => {
10860 let value = self.pop();
10861 if !value.to_boolean() {
10862 self.frame_mut().pc = a as usize;
10863 }
10864 }
10865 Catch => {
10866 // Pushes the handler target onto the value stack; `unwind` finds it.
10867 self.push(Value::CatchOffset(a));
10868 }
10869 Gosub => {
10870 self.push(Value::ReturnAddress(next as u32));
10871 self.frame_mut().pc = a as usize;
10872 }
10873 Ret => {
10874 let value = self.pop();
10875 match value {
10876 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
10877 _ => {
10878 return Err(Signal::Throw(
10879 self.make_error("InternalError", "invalid return address"),
10880 ));
10881 }
10882 }
10883 }
10884 NipCatch => {
10885 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
10886 // including the marker, keeping the top value.
10887 let top = self.pop();
10888 loop {
10889 match self.pop() {
10890 Value::CatchOffset(_) | Value::Undefined => break,
10891 _ => {}
10892 }
10893 if self.frame().stack.is_empty() {
10894 break;
10895 }
10896 }
10897 self.push(top);
10898 }
10899 Throw => {
10900 let value = self.pop();
10901 return Err(Signal::Throw(value));
10902 }
10903 ThrowError => {
10904 let name = self.atom_text(a as usize);
10905 let (class, message) = match b {
10906 0 => ("TypeError", format!("'{name}' is read-only")),
10907 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
10908 2 => ("ReferenceError", format!("'{name}' is not initialized")),
10909 // `delete super.x` is a syntax-level mistake the reference reports
10910 // with this wording, not a property-access failure.
10911 3 => (
10912 "ReferenceError",
10913 "unsupported reference to 'super'".to_string(),
10914 ),
10915 4 => (
10916 "TypeError",
10917 "iterator does not have a throw method".to_string(),
10918 ),
10919 5 => (
10920 "ReferenceError",
10921 "invalid assignment left-hand side".to_string(),
10922 ),
10923 _ => ("TypeError", format!("invalid operation on '{name}'")),
10924 };
10925 return Err(Signal::Throw(self.make_error(class, &message)));
10926 }
10927 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
10928 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
10929 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
10930 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
10931 Await => return Ok(Step::Suspend(SuspendKind::Await)),
10932 ReturnAsync => {
10933 // The reference's `return_async` returns `undefined` and lets the resume
10934 // machinery pick the real value off `sp[-1]`, which is how it tells a
10935 // completion from a suspension. Carrying the value explicitly says the
10936 // same thing without the implicit stack slot.
10937 let value = self.pop();
10938 return Ok(Step::Return(value));
10939 }
10940 Return => {
10941 let value = self.pop();
10942 return Ok(Step::Return(value));
10943 }
10944 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
10945
10946 // -- calls ------------------------------------------------------
10947 Call | Call0 | Call1 | Call2 | Call3 => {
10948 let argc = self.argc_operand(op, a);
10949 let args = self.pop_n(argc);
10950 let callee = self.pop();
10951 // A plain call has no receiver; the callee decides what to do with
10952 // `undefined` (a sloppy function substitutes the global object).
10953 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
10954 self.push(result);
10955 }
10956 }
10957 CallConstructor => {
10958 // `constructor this_obj args… -> object`. The duplicated
10959 // constructor is `new.target`; this milestone does not expose it,
10960 // so the extra copy is simply consumed here.
10961 let argc = a as usize;
10962 let args = self.pop_n(argc);
10963 let new_target = self.pop();
10964 let callee = self.pop();
10965 let result = self.construct(callee, new_target, args)?;
10966 self.push(result);
10967 }
10968 CallMethod => {
10969 let argc = a as usize;
10970 let args = self.pop_n(argc);
10971 let callee = self.pop();
10972 let this = self.pop();
10973 if let Some(result) = self.call_or_push(callee, this, args)? {
10974 self.push(result);
10975 }
10976 }
10977 Apply => {
10978 // `func this array -> result`, the spread-call form: the compiler
10979 // builds one array of arguments, and all that is left here is to
10980 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
10981 let array = self.pop();
10982 let this = self.pop();
10983 let callee = self.pop();
10984 let args = self.array_like_to_args(&array)?;
10985 if a & 1 != 0 {
10986 let result = self.construct(callee, this, args)?;
10987 self.push(result);
10988 } else if let Some(result) = self.call_or_push(callee, this, args)? {
10989 self.push(result);
10990 }
10991 }
10992 TailCall | TailCallMethod => {
10993 // `tail_call` is `call` whose result is returned immediately — the
10994 // reference jumps straight to `done` instead of storing the value and
10995 // running on. The callee still gets its own frame, so deep tail
10996 // recursion hits the stack limit exactly like plain recursion does;
10997 // marking this frame lets the return path unwind without needing
10998 // instructions after the call.
10999 let argc = if op == TailCallMethod {
11000 a as usize
11001 } else {
11002 self.argc_operand(op, a)
11003 };
11004 let args = self.pop_n(argc);
11005 let callee = self.pop();
11006 let this = if op == TailCallMethod {
11007 self.pop()
11008 } else {
11009 Value::Undefined
11010 };
11011 if let Value::Object(function) = &callee
11012 && let Some((code, env)) = bytecode_of(function)
11013 {
11014 // A generator or async body is not run here at all: calling it only
11015 // *creates* the generator/coroutine, so it must not inherit this
11016 // frame. Doing so made `function f(){ return g() }` push `g`'s body
11017 // onto `f`'s frame, and the first `yield`/`await` then reported
11018 // "a generator body ran as an ordinary call".
11019 if code.code.kind.is_generator() || code.code.kind.is_async() {
11020 let value = self.call_value(callee, this, args)?;
11021 return Ok(Step::Return(value));
11022 }
11023 self.frame_mut().tail = true;
11024 self.push_frame(code, env, this, args, callee)?;
11025 return Ok(Step::Continue);
11026 }
11027 // A native callee has no frame to reuse, so its value is simply
11028 // returned.
11029 let value = self.call_value(callee, this, args)?;
11030 return Ok(Step::Return(value));
11031 }
11032
11033 // -- objects ----------------------------------------------------
11034 SpecialObject => {
11035 let value = self.special_object(a)?;
11036 self.push(value);
11037 }
11038 PrivateSymbol => {
11039 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
11040 // symbol each time it is evaluated, which is why the compiler evaluates it
11041 // once (at class definition) and stores it in a class-scope binding.
11042 let name = self.atom_text(a as usize);
11043 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
11044 self.push(Value::Symbol(symbol));
11045 }
11046 GetPrivateField => {
11047 // `obj symbol -> value`. A missing private field is a TypeError, which is what
11048 // makes `#x` inaccessible on any object not built by this class.
11049 let symbol = self.pop();
11050 let object = self.pop();
11051 let value = self.read_private_field(&object, &symbol)?;
11052 self.push(value);
11053 }
11054 PutPrivateField => {
11055 // `obj value symbol ->`, and the store is a plain assignment to a property the
11056 // class already created, so there is no setter to consult.
11057 let symbol = self.pop();
11058 let value = self.pop();
11059 let object = self.pop();
11060 self.write_private_field(&object, &symbol, value)?;
11061 }
11062 DefinePrivateField => {
11063 // `obj symbol value -> obj`: a field initialiser creates the property, and
11064 // redefining one is a TypeError ("already exists").
11065 let value = self.pop();
11066 let symbol = self.pop();
11067 let object = self.pop();
11068 self.define_private_field(&object, &symbol, value)?;
11069 self.push(object);
11070 }
11071 PrivateIn => {
11072 // `obj key -> bool`: `#x in o`. The second operand decides which question is
11073 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
11074 // is a field, so this is an own-property test; a *function* is a method or
11075 // accessor, so this is a brand check.
11076 let key = self.pop();
11077 let object = self.pop();
11078 let Some(target) = object.as_object() else {
11079 return Err(Signal::Throw(
11080 self.make_error("TypeError", "invalid 'in' operand"),
11081 ));
11082 };
11083 let present = match &key {
11084 Value::Object(_) => self.check_brand(target, &key)?,
11085 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
11086 };
11087 self.push(Value::Bool(present));
11088 }
11089 AddBrand => {
11090 // `obj home ->`: create the class brand on `home` if it has none, then give
11091 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
11092 // class definition: only the prototype's copy of the symbol is wanted.
11093 let home = self.pop();
11094 let object = self.pop();
11095 self.add_brand(&object, &home)?;
11096 }
11097 CheckBrand => {
11098 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
11099 // Both stay, because the caller needs them — `nip` halves a read into its
11100 // value and `call_method` uses the pair as receiver and callee.
11101 let function = self.peek(0);
11102 let object = self.peek(1);
11103 let Some(target) = object.as_object() else {
11104 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11105 };
11106 if !self.check_brand(target, &function)? {
11107 return Err(Signal::Throw(
11108 self.make_error("TypeError", "invalid brand on object"),
11109 ));
11110 }
11111 }
11112 GetLength => {
11113 // `get_length` is the `.length` read; an array and a string answer
11114 // from their own length, anything else from the property.
11115 let target = self.pop();
11116 let value = match &target {
11117 Value::Object(object) => match object.array_length() {
11118 Some(length) => crate::object::length_value(length),
11119 None => self.read_field(&target, "length")?,
11120 },
11121 Value::String(text) => Value::Int(text.utf16_len() as i32),
11122 _ => self.read_field(&target, "length")?,
11123 };
11124 self.push(value);
11125 }
11126 GetField | GetField2 => {
11127 let object = self.pop();
11128 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
11129 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
11130 // just below is what lets the borrow outlive the `&mut self` the lookup
11131 // needs — one refcount bump instead of a key clone plus its drop, on the
11132 // hottest property path there is: every `o.x` and every `o.m()` receiver.
11133 let code = self.frame().code.clone();
11134 let key = &code.atom_keys[a as usize];
11135 let value = self.read_field_cached(&object, key, next)?;
11136 if op == GetField2 {
11137 self.push(object);
11138 }
11139 self.push(value);
11140 }
11141 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
11142 let key = self.pop();
11143 let object = self.pop();
11144 let key = self.propkey(&key)?;
11145 let value = self.read_field_key(&object, &key)?;
11146 if matches!(op, GetArrayEl2 | GetArrayEl3) {
11147 self.push(object);
11148 }
11149 if op == GetArrayEl3 {
11150 // The key goes back in its *value* form, which the compiler stores
11151 // into the target of a destructuring assignment.
11152 self.push(match &key {
11153 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11154 PropertyKey::String(text) => self.string_wtf8(text.clone()),
11155 });
11156 }
11157 self.push(value);
11158 }
11159 PutField => {
11160 let value = self.pop();
11161 let object = self.pop();
11162 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
11163 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
11164 // only reads. `this.value = …` is the write half of the hottest loop in
11165 // `property:method-call`, and `own_property_key` was 4.8% of the case.
11166 let code = self.frame().code.clone();
11167 let key = &code.atom_keys[a as usize];
11168 self.write_field_key(&object, key, value)?;
11169 }
11170 PutArrayEl => {
11171 let value = self.pop();
11172 let key = self.pop();
11173 let object = self.pop();
11174 let key = self.propkey(&key)?;
11175 self.write_field_key(&object, &key, value)?;
11176 }
11177 DefineField => {
11178 let value = self.pop();
11179 let object = self.pop();
11180 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
11181 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
11182 // three U+FFFD — a property under a different name from the one
11183 // `o["\uD800"]` reads.
11184 let code = self.frame().code.clone();
11185 let key = code.atom_keys[a as usize].clone();
11186 // No naming here. `{m: function(){}}` is named by the *compiler*, which
11187 // emits `set_name` — and only where `NamedEvaluation` applies, so
11188 // `{m: (0, function(){})}` stays anonymous. Naming every function that
11189 // reaches a property definition got that case wrong, and the compiler is
11190 // the only place that can tell the two apart.
11191 if let Some(target) = object.as_object() {
11192 // Only an *array* stores into the element vector. A numeric key
11193 // on an ordinary object is an ordinary property, which is what
11194 // makes `{1: 'a'}` iterate as a key rather than disappear.
11195 let stored = target.is_array()
11196 && key.as_str().and_then(array_index).is_some_and(|index| {
11197 target.array_set(self.heap, index as usize, value.clone())
11198 });
11199 if !stored {
11200 target.define_data_key(&key, value);
11201 }
11202 }
11203 self.push(object);
11204 }
11205 DefineArrayEl => {
11206 // `obj key value -> obj key`. The *value* form of the key is what goes
11207 // back on the stack — the compiler stores it into the pattern's binding —
11208 // so the symbol is not stringified on the way through.
11209 let value = self.pop();
11210 let key_value = self.pop();
11211 let object = self.peek(0);
11212 let key = self.propkey(&key_value)?;
11213 self.write_field_key(&object, &key, value)?;
11214 self.push(key_value);
11215 }
11216 SetHomeObject => {
11217 // `obj func -> obj func`: records the object a method was defined on so
11218 // `super` inside it resolves against that object's prototype.
11219 let function = self.peek(0);
11220 let home = self.peek(1);
11221 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
11222 function.set_home_object(Some(home.clone()));
11223 }
11224 }
11225 Regexp => {
11226 // `pattern flags -> regexp`. A literal compiles here rather than through the
11227 // constructor, which is both what the reference's dedicated opcode is for
11228 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
11229 let flags = self.pop();
11230 let pattern = self.pop();
11231 let pattern = self.to_js_string(&pattern)?;
11232 let flags = self.to_js_string(&flags)?;
11233 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
11234 self.push(Value::Object(object));
11235 }
11236 UsingDisposeInit => {
11237 // The error state a disposal accumulates into. Uninitialised means "no
11238 // failure yet"; anything else is the exception being propagated.
11239 self.push(Value::Uninitialized);
11240 }
11241 UsingCheck => {
11242 // `value -> value, method`: validate and snapshot the disposer now, so a
11243 // later change to `Symbol.dispose` cannot change what gets called, and so a
11244 // value that is not disposable fails before the body runs.
11245 let value = self.pop();
11246 let method = self.using_method_for(&value, a as u8 == 1)?;
11247 self.push(value);
11248 self.push(method);
11249 }
11250 UsingDispose => {
11251 // `error_state -> error_state'`: dispose the variable at `slot` — its value
11252 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
11253 // the pending error.
11254 let slot = self.slot_operand(op, a);
11255 let error_state = self.pop();
11256 let merged = self.using_dispose_once(slot, error_state)?;
11257 self.push(merged);
11258 }
11259 UsingDisposeMerge => {
11260 let new_error = self.pop();
11261 let error_state = self.pop();
11262 let merged = self.merge_dispose_error(new_error, error_state);
11263 self.push(merged);
11264 }
11265 UsingDisposeEnd => {
11266 // A disposal that failed replaces the block's normal completion, so the
11267 // error state becomes a real throw here rather than at the call site.
11268 let error_state = self.pop();
11269 if !matches!(error_state, Value::Uninitialized) {
11270 return Err(Signal::Throw(error_state));
11271 }
11272 }
11273 UsingDisposeAsync => {
11274 // `await using` needs a promise to await and this runtime has no
11275 // `Promise` builtin, so the disposer is called synchronously and its result
11276 // discarded. That is correct for a disposer that returns nothing and is
11277 // reported as a gap rather than silently skipped.
11278 let slot = self.slot_operand(op, a);
11279 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
11280 self.push(error_state);
11281 }
11282 GetSuper => {
11283 // `obj -> obj's prototype`: the starting point of a `super` lookup.
11284 let object = self.pop();
11285 let proto = match &object {
11286 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
11287 _ => Value::Null,
11288 };
11289 self.push(proto);
11290 }
11291 GetSuperValue => {
11292 // `receiver proto key -> value`, searching from `proto` but reporting to
11293 // `receiver`, which is what `super.g` must do for a getter to see `this`.
11294 //
11295 // Three values in, one out: the receiver is *consumed*, not left under the
11296 // result. Leaving it there was invisible for `super.x` in `return` or
11297 // statement position (the result is what gets popped) and corrupted the
11298 // frame everywhere else — `print(super.x)` left the class where the call
11299 // opcode looks for the receiver and called the class itself.
11300 let key = self.pop();
11301 let proto = self.pop();
11302 let receiver = self.pop();
11303 let value = self.super_read(&receiver, &proto, &key)?;
11304 self.push(value);
11305 }
11306 PutSuperValue => {
11307 // `receiver proto key value ->`: a store that starts at `proto` but
11308 // assigns to `receiver`.
11309 let value = self.pop();
11310 let key = self.pop();
11311 let proto = self.pop();
11312 let receiver = self.pop();
11313 self.super_write(&receiver, &proto, &key, value)?;
11314 }
11315 DefineClass => {
11316 // `parent ctor -> ctor proto`: the constructor becomes the class and a
11317 // fresh prototype object lands on top for the methods to go on.
11318 let name = self.atom_text(a as usize);
11319 let (ctor, proto) = self.define_class(&name, b)?;
11320 self.push(ctor);
11321 self.push(Value::Object(proto));
11322 }
11323 DefineClassComputed => {
11324 // `parent ctor key -> ctor proto key`: the computed name stays put so
11325 // `define_field`-style consumers can still read it.
11326 let key = self.pop();
11327 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11328 let (ctor, proto) = self.define_class(&name, b)?;
11329 self.push(ctor);
11330 self.push(Value::Object(proto));
11331 self.push(key);
11332 }
11333 DefineMethod => {
11334 let function = self.pop();
11335 let object = self.pop();
11336 // The exact key, like `define_field`: a quoted method key may hold an
11337 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
11338 // that `o["\uD800"]` finds.
11339 let code = self.frame().code.clone();
11340 let key = code.atom_keys[a as usize].clone();
11341 // A method's `[[HomeObject]]` is the object it was defined on, which is
11342 // what `super` inside it resolves against.
11343 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11344 function.set_home_object(Some(object.clone()));
11345 }
11346 if let Some(text) = key.as_wtf8() {
11347 self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
11348 } else {
11349 self.set_function_name(
11350 &function,
11351 &key_with_accessor_prefix(&key.to_string(), b),
11352 );
11353 }
11354 if let Some(array) = object.as_object() {
11355 define_function_property(array, &key, function, b);
11356 }
11357 self.push(object);
11358 }
11359 DefineMethodComputed => {
11360 let function = self.pop();
11361 let key = self.pop();
11362 let object = self.pop();
11363 let key = self.propkey(&key)?;
11364 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
11365 // the name: `super` inside a computed method resolves through it. Without
11366 // this, `class B extends A { [k]() { return super.m() } }` read the
11367 // home object as null and threw.
11368 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11369 function.set_home_object(Some(object.clone()));
11370 }
11371 match key.as_wtf8() {
11372 Some(text) => {
11373 let name = accessor_prefixed(text, a);
11374 self.set_function_name_wtf8(&function, &name);
11375 }
11376 None => self.set_function_name(
11377 &function,
11378 &key_with_accessor_prefix(&key.to_string(), a),
11379 ),
11380 }
11381 if let Some(array) = object.as_object() {
11382 define_function_property(array, &key, function, a);
11383 }
11384 self.push(object);
11385 }
11386 SetProto => {
11387 let proto = self.pop();
11388 let object = self.pop();
11389 if let Some(target) = object.as_object() {
11390 target.set_proto(proto.as_object().cloned());
11391 }
11392 self.push(object);
11393 }
11394 CopyDataProperties => {
11395 let exclusion = self.pop();
11396 let source = self.pop();
11397 let target = self.peek(0);
11398 self.copy_properties(&target, &source, &exclusion)?;
11399 self.push(source);
11400 self.push(exclusion);
11401 }
11402 ToPropkey => {
11403 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
11404 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
11405 // ordinary `"Symbol(b)"` property.
11406 let value = self.pop();
11407 let key = match self.propkey(&value)? {
11408 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
11409 PropertyKey::String(text) => self.string_wtf8(text),
11410 };
11411 self.push(key);
11412 }
11413 SetName => {
11414 let function = self.peek(0);
11415 let name = self.atom_wtf8(a as usize);
11416 self.set_function_name_wtf8(&function, &name);
11417 }
11418 SetNameComputed => {
11419 let key = self.peek(1);
11420 let function = self.peek(0);
11421 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11422 self.set_function_name(&function, &name);
11423 }
11424
11425 // -- arrays -----------------------------------------------------
11426 ArrayFrom => {
11427 let count = a as usize;
11428 let elements = self.pop_n(count);
11429 let array = self.new_array(elements);
11430 self.push(Value::Object(array));
11431 }
11432 Append => {
11433 // `array index iterable -> array new_index`
11434 let iterable = self.pop();
11435 self.pop();
11436 let array = self.peek(0);
11437 let added = self.append_enumerate(&array, &iterable)?;
11438 self.push(Value::Int(added));
11439 }
11440
11441 // -- iteration --------------------------------------------------
11442 ForInStart => {
11443 let value = self.pop();
11444 let record = self.for_in_record(&value)?;
11445 self.push(Value::Object(record));
11446 }
11447 ForInNext => {
11448 // `record -> record key done`. The flag is *done*, not "found":
11449 // the compiler tests it with `if_false` to jump back into the body,
11450 // so reporting `true` while keys remain would end the loop at once.
11451 let record = self.peek(0);
11452 match self.for_in_advance(&record)? {
11453 Some(key) => {
11454 let text = self.string(key);
11455 self.push(text);
11456 self.push(Value::Bool(false));
11457 }
11458 None => {
11459 self.push(Value::Undefined);
11460 self.push(Value::Bool(true));
11461 }
11462 }
11463 }
11464 ForOfStart => {
11465 let value = self.pop();
11466 let iterator = self.get_iterator(&value)?;
11467 self.push(iterator.object);
11468 self.push(iterator.next);
11469 self.push(Value::CatchOffset(0));
11470 }
11471 ForOfNext => {
11472 // `iter next catch_offset -> iter next catch_offset value done`.
11473 //
11474 // The operand is how many values sit *above* the iterator triple: a
11475 // destructuring rest element keeps its target array and running index
11476 // there while draining the iterator, so the triple is not at the top.
11477 let extra = a as usize;
11478 let iterator_slot = 2 + extra;
11479 // An exhausted iterator is replaced by `undefined` (see below), so a
11480 // second step must not call `next` again — `Array.from` and a
11481 // destructuring pattern both keep stepping past the end.
11482 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
11483 (Value::Undefined, true)
11484 } else {
11485 let iterator = Iterator {
11486 object: self.peek(iterator_slot),
11487 next: self.peek(1 + extra),
11488 };
11489 self.iterator_step(&iterator)?
11490 };
11491 if done {
11492 // The result's `value` is meaningless once the iterator is done:
11493 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
11494 // rather than binding the generator's return value.
11495 let top = self.frame().stack.len() - 1 - iterator_slot;
11496 self.frame_mut().stack[top] = Value::Undefined;
11497 self.push(Value::Undefined);
11498 self.push(Value::Bool(true));
11499 } else {
11500 self.push(value);
11501 self.push(Value::Bool(false));
11502 }
11503 }
11504 IteratorNext => {
11505 // `iter next catch val -> iter next catch val'`: replace the argument with
11506 // the result of `next(val)`. The triple below stays put, which is why the
11507 // three instructions of the `yield*` loop all address the stack the same way.
11508 let value = self.pop();
11509 let object = self.peek(2);
11510 let next = self.peek(1);
11511 let result = self.call_value(next, object, vec![value])?;
11512 self.push(result);
11513 }
11514 IteratorCall => {
11515 // `iter next catch val -> iter next catch val' flag`.
11516 //
11517 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
11518 // The flag is `true` when the method was missing, which is how the
11519 // caller learns that the inner iterator cannot take part in the
11520 // unwinding.
11521 let value = self.pop();
11522 let object = self.peek(2);
11523 let key = if a & 1 != 0 { "throw" } else { "return" };
11524 let method = self.read_field(&object, key)?;
11525 if matches!(method, Value::Undefined | Value::Null) {
11526 self.push(value);
11527 self.push(Value::Bool(true));
11528 } else {
11529 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
11530 let result = self.call_value(method, object, argument)?;
11531 self.push(result);
11532 self.push(Value::Bool(false));
11533 }
11534 }
11535 IteratorCheckObject => {
11536 if !matches!(self.peek(0), Value::Object(_)) {
11537 return Err(Signal::Throw(
11538 self.make_error("TypeError", "iterator must return an object"),
11539 ));
11540 }
11541 }
11542 IteratorClose => {
11543 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
11544 // calling the iterator's `return` so it can release whatever it holds.
11545 //
11546 // The catch offset goes first, so an exception from `return` is not caught
11547 // by the loop being abandoned. This used to pop the three operands and call
11548 // nothing at all, which made `break` out of a `for of` invisible to an
11549 // iterator with a `return` method.
11550 self.pop();
11551 self.pop();
11552 let iterator = self.pop();
11553 if !matches!(iterator, Value::Undefined) {
11554 let method = self.read_field(&iterator, "return")?;
11555 if !matches!(method, Value::Undefined | Value::Null) {
11556 let result = self.call_value(method, iterator.clone(), Vec::new())?;
11557 // §7.4.6: a `return` that answers a non-object is a TypeError.
11558 if !matches!(result, Value::Object(_)) {
11559 return Err(Signal::Throw(
11560 self.make_error("TypeError", "iterator must return an object"),
11561 ));
11562 }
11563 }
11564 }
11565 }
11566 Import => {
11567 // `import(specifier)`: the options slot is on top and is not read yet.
11568 let _options = self.pop();
11569 let specifier = self.pop();
11570 let promise = self.dynamic_import(specifier)?;
11571 self.push(promise);
11572 }
11573 ForAwaitOfStart => {
11574 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
11575 // `Symbol.iterator` fallback.
11576 let value = self.pop();
11577 let iterator = self.get_async_iterator(&value)?;
11578 self.push(iterator.object);
11579 self.push(iterator.next);
11580 self.push(Value::CatchOffset(0));
11581 }
11582 ForAwaitOfNext => {
11583 // `for await` steps the iterator and leaves the *result* wrapped in a
11584 // promise, so the `await` the compiler emits right after this can suspend
11585 // on it. Unwrapping happens in `iterator_get_value_done`.
11586 let extra = a as usize;
11587 let iterator_slot = 2 + extra;
11588 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
11589 Value::Undefined
11590 } else {
11591 let iterator = Iterator {
11592 object: self.peek(iterator_slot),
11593 next: self.peek(1 + extra),
11594 };
11595 let next = iterator.next.clone();
11596 self.call_value(next, iterator.object, Vec::new())?
11597 };
11598 let promise = self.promise_resolve_value(result)?;
11599 self.push(promise);
11600 }
11601 IteratorGetValueDone => {
11602 // `result -> value done`. A missing result object means the iterator was
11603 // already exhausted, which the loop treats as `done`.
11604 let result = self.pop();
11605 let done = match &result {
11606 Value::Object(object) => self
11607 .get_property(object, "done")?
11608 .is_some_and(|value| value.to_boolean()),
11609 _ => true,
11610 };
11611 if done {
11612 // Clear the iterator object so the `iterator_close` the loop emits on
11613 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
11614 // on normal completion, and this is where a normal completion is
11615 // recognised — the same trick `for_of_next` uses, which also replaces
11616 // the slot with `undefined`.
11617 //
11618 // The layout is fixed because only `for await` emits this opcode:
11619 // `iter next catch [result]`, so the iterator is three below the top.
11620 let depth = self.frame().stack.len();
11621 if depth >= 3 {
11622 self.frame_mut().stack[depth - 3] = Value::Undefined;
11623 }
11624 self.push(Value::Undefined);
11625 self.push(Value::Bool(true));
11626 } else {
11627 let Value::Object(object) = &result else {
11628 self.push(Value::Undefined);
11629 self.push(Value::Bool(true));
11630 return Ok(Step::Continue);
11631 };
11632 let value = self
11633 .get_property(object, "value")?
11634 .unwrap_or(Value::Undefined);
11635 self.push(value);
11636 self.push(Value::Bool(false));
11637 }
11638 }
11639
11640 Delete => {
11641 // `delete obj[key]`, where the key was just pushed. Deleting an array
11642 // index leaves a *hole* rather than closing the gap, and a
11643 // non-configurable property answers `false` and stays.
11644 let key = self.pop();
11645 let target = self.pop();
11646 let key = self.propkey(&key)?;
11647 let text_label = key.as_str().unwrap_or("").to_string();
11648 let deleted = match &target {
11649 Value::Object(object) => {
11650 let object = object.clone();
11651 self.delete_property_key(&object, &key)?
11652 }
11653 // A string's `length` and its index properties are
11654 // non-configurable, so deleting one answers `false`.
11655 Value::String(text) => {
11656 !(text_label == "length"
11657 || array_index(&text_label)
11658 .is_some_and(|index| (index as usize) < text.utf16_len()))
11659 }
11660 // "delete null.a" is a TypeError, not a no-op: the operator needs an
11661 // object to delete from, and only a *boxable* primitive has one.
11662 Value::Undefined | Value::Null => {
11663 return Err(Signal::Throw(
11664 self.make_error("TypeError", "cannot convert to object"),
11665 ));
11666 }
11667 // Any other primitive has no own properties; deleting nothing
11668 // succeeds.
11669 _ => true,
11670 };
11671 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
11672 // `TypeError` rather than a `false` result. Sloppy mode silently reports
11673 // the refusal, which is why the same statement throws here but not there.
11674 if !deleted && self.current_strict() {
11675 return Err(Signal::Throw(
11676 self.make_error("TypeError", "cannot delete property"),
11677 ));
11678 }
11679 self.push(Value::Bool(deleted));
11680 }
11681
11682 // -- exceptions and bookkeeping ---------------------------------
11683 Fclosure | Fclosure8 => {
11684 let value = self.closure(a as usize)?;
11685 self.push(value);
11686 }
11687
11688 other => {
11689 let name = other.info().name;
11690 return Err(Signal::Throw(self.make_error(
11691 "InternalError",
11692 &format!("{name} is not implemented yet"),
11693 )));
11694 }
11695 }
11696 Ok(Step::Continue)
11697 }
11698
11699 // -- operand helpers ----------------------------------------------------
11700
11701 /// The slot index an operand names, taking short forms into account.
11702 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
11703 use Opcode::*;
11704 match op {
11705 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
11706 | SetVarRef0 => 0,
11707 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
11708 | SetVarRef1 => 1,
11709 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
11710 | SetVarRef2 => 2,
11711 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
11712 | SetVarRef3 => 3,
11713 _ => a as usize,
11714 }
11715 }
11716
11717 /// The argument count of a call, taking `call0`…`call3` into account.
11718 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
11719 use Opcode::*;
11720 match op {
11721 Call0 => 0,
11722 Call1 => 1,
11723 Call2 => 2,
11724 Call3 => 3,
11725 _ => a as usize,
11726 }
11727 }
11728
11729 /// The atom's name as a property key.
11730 ///
11731 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
11732 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
11733 /// `String::clone` was a heap allocation and a copy — per property access.
11734 /// The atom at `index`, as a property key.
11735 ///
11736 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
11737 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
11738 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
11739 /// 5.3% of `property:monomorphic`.
11740 /// The atom's text, exactly — including an unpaired surrogate.
11741 ///
11742 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
11743 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
11744 /// `atom_text` below is for the other kind of use, where the atom is a key in the
11745 /// engine's own tables.
11746 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
11747 self.frame()
11748 .code
11749 .code
11750 .atoms
11751 .get(index)
11752 .map(|atom| match atom {
11753 Atom::Str(text) => text.clone(),
11754 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
11755 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
11756 Atom::Null => crate::value::Wtf8::new(String::new()),
11757 })
11758 .unwrap_or_default()
11759 }
11760
11761 fn atom_text(&self, index: usize) -> String {
11762 self.frame()
11763 .code
11764 .code
11765 .atoms
11766 .get(index)
11767 .map(|atom| match atom {
11768 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
11769 // compare it to an identifier, and a surrogate-bearing name is reachable
11770 // through `atom_wtf8` where it matters.
11771 Atom::Str(text) => text.to_string_lossy().into_owned(),
11772 Atom::Index(value) => value.to_string(),
11773 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
11774 // `throw_error`, `delete super.x`) never read it.
11775 Atom::Null => String::new(),
11776 })
11777 .unwrap_or_default()
11778 }
11779
11780 fn constant(&mut self, index: usize) -> JsResult<Value> {
11781 let constant = self.frame().code.code.cpool.get(index).cloned();
11782 Ok(match &constant {
11783 Some(Constant::Number(number)) => Value::Float(*number),
11784 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
11785 Some(Constant::BigInt { digits, radix }) => {
11786 match crate::bigint::BigInt::from_radix(digits, *radix) {
11787 Some(big) => self.bigint(big),
11788 // A literal the parser accepted is always parseable; a failure here
11789 // would be a compiler bug, so it reads as an `InternalError`.
11790 None => {
11791 return Err(Signal::Throw(
11792 self.make_error("InternalError", "unparseable bigint literal"),
11793 ));
11794 }
11795 }
11796 }
11797 Some(Constant::Function(_)) => {
11798 return Err(Signal::Throw(
11799 self.make_error("InternalError", "a bare function constant"),
11800 ));
11801 }
11802 // A tagged template's call site: a frozen array of the cooked chunks with a
11803 // frozen `raw` array beside it, which is what `String.raw` reads back.
11804 Some(Constant::Template { cooked, raw }) => {
11805 let cooked_values: Vec<Value> = cooked
11806 .iter()
11807 .map(|chunk| match chunk {
11808 Some(text) => self.string_wtf8(text.clone()),
11809 None => Value::Undefined,
11810 })
11811 .collect();
11812 let raw_values: Vec<Value> =
11813 raw.iter().map(|text| self.string(text.clone())).collect();
11814 let raw_array = self.new_array(raw_values);
11815 raw_array.set_extensible(false);
11816 let template = self.new_array(cooked_values);
11817 template.define(
11818 "raw",
11819 Property::with_attributes(Value::Object(raw_array), false, false),
11820 );
11821 template.set_extensible(false);
11822 Value::Object(template)
11823 }
11824 _ => Value::Undefined,
11825 })
11826 }
11827
11828 /// The reference cell a closure-variable slot names.
11829 ///
11830 /// Two kinds of binding share this addressing: a genuine closure variable
11831 /// (captured from an enclosing function) lives in this frame's environment,
11832 /// while a *declared global* lives in the realm so that a script, a function
11833 /// declaration and their uses all see one binding. A plain `Global` — an
11834 /// undeclared name that may be satisfied by the global object — has no cell at
11835 /// all, which is how `typeof x` still works for a name that does not exist.
11836 /// The reference cell a closure-variable slot names.
11837 ///
11838 /// The environment is resolved once, when the closure is built, and this is
11839 /// just the lookup afterwards. A *declared global* is in there too, pointing at
11840 /// the realm's cell, so a script, a hoisted function declaration and their uses
11841 /// all share one binding. A plain `Global` — a name the script never declared —
11842 /// is read and written through `get_var`/`put_var` by name instead, which is
11843 /// what lets the global object satisfy it.
11844 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
11845 self.frame().env.cells.get(slot).cloned()
11846 }
11847
11848 /// Whether `slot` refers to a global binding through the reference table.
11849 ///
11850 /// A global's cell in the closure environment only exists so the slot has
11851 /// something to point at; the binding itself lives on the global object (a `var`)
11852 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
11853 /// be routed, not performed on the placeholder.
11854 fn is_global_slot(&self, slot: usize) -> bool {
11855 self.frame()
11856 .code
11857 .code
11858 .closure_vars
11859 .get(slot)
11860 .is_some_and(|c| {
11861 // A module's declarations and imports are *not* globals: their cells are
11862 // the module environment's, filled by the host, so the placeholder routing
11863 // must not apply to them.
11864 matches!(
11865 c.closure_type,
11866 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
11867 )
11868 })
11869 }
11870
11871 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
11872 if self.is_global_slot(slot) {
11873 return self.get_global(slot);
11874 }
11875 Ok(self
11876 .var_ref_cell(slot)
11877 .map(|cell| cell.get())
11878 .unwrap_or(Value::Undefined))
11879 }
11880
11881 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
11882 // A function declaration is hoisted by storing into a global reference before
11883 // the body runs, so this path is also what puts it on the global object.
11884 if self.is_global_slot(slot) {
11885 return self.put_global(slot, value);
11886 }
11887 if let Some(cell) = self.var_ref_cell(slot) {
11888 cell.set(value);
11889 }
11890 Ok(())
11891 }
11892
11893 // -- closures -----------------------------------------------------------
11894
11895 /// Build the closure for the function constant `index`.
11896 ///
11897 /// Every entry in the child's closure table names where its binding lives in
11898 /// *this* frame: a local or argument slot that was marked captured, or a cell
11899 /// this frame is itself holding. That is how a variable three functions deep
11900 /// stays one binding.
11901 fn closure(&mut self, index: usize) -> JsResult<Value> {
11902 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
11903 else {
11904 return Err(Signal::Throw(
11905 self.make_error("InternalError", "fclosure of a non-function"),
11906 ));
11907 };
11908 let mut cells = Vec::with_capacity(function.closure_vars.len());
11909 for closure_var in &function.closure_vars {
11910 let cell = match closure_var.closure_type {
11911 ClosureType::Arg => {
11912 let slot = closure_var.var_idx as usize;
11913 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
11914 }
11915 ClosureType::Local => {
11916 let slot = closure_var.var_idx as usize;
11917 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
11918 }
11919 ClosureType::Ref | ClosureType::GlobalRef => {
11920 // A `Ref` names a cell in this frame's own closure table; a
11921 // `GlobalRef` also starts there, then resolves by name below.
11922 let slot = closure_var.var_idx as usize;
11923 if let Some(cell) = self.frame().env.cells.get(slot) {
11924 cells.push(cell.clone());
11925 continue;
11926 }
11927 -1
11928 }
11929 _ => -1,
11930 };
11931 if cell >= 0 {
11932 let cell = self.frame().cells[cell as usize].clone();
11933 cells.push(cell);
11934 continue;
11935 }
11936 // A global: the cell is created on demand and shared through the realm,
11937 // so every function sees one binding.
11938 let name = closure_var.name.clone();
11939 let cell = match self.realm.globals.get(&name) {
11940 Some(cell) => cell.clone(),
11941 None => {
11942 let cell = self.new_cell(Value::Undefined);
11943 self.realm.globals.insert(name.clone(), cell.clone());
11944 cell
11945 }
11946 };
11947 cells.push(cell);
11948 }
11949 let name = function.name.clone();
11950 // `.length` is the arity before any default or rest parameter, not the number
11951 // of slots a pattern parameter needs.
11952 let length = function.defined_args;
11953 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
11954 // function and an arrow function do not. A *method* also does not, but that is not
11955 // known here — the method is marked when the `[[HomeObject]]` is attached (see
11956 // `set_home_object`), which is the moment it becomes a method.
11957 let function_kind = function.kind;
11958 let constructible =
11959 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
11960 let code = Gc::new(self.heap, CompiledCode::new(*function));
11961 // A closure built inside an `eval` inherits the eval's view of the enclosing
11962 // bindings, so it can still read them once the eval has returned.
11963 let eval_scope = self
11964 .active_eval_scope
11965 .clone()
11966 .or_else(|| self.frame().env.eval_scope.clone());
11967 // A closure sees the variables a direct `eval` declared in the frame it was
11968 // created in — the ones declared before *and after* it, so the same object is
11969 // shared; only the phase bounds which of them are visible.
11970 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
11971 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
11972 let env = Gc::new(
11973 self.heap,
11974 ClosureEnv {
11975 cells,
11976 eval_scope,
11977 local_vars,
11978 local_phase,
11979 },
11980 );
11981 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
11982 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
11983 // the only thing that carries `Symbol.toStringTag`, so without it
11984 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
11985 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
11986 let proto = match function_kind {
11987 js_compile::bytecode::FunctionKind::AsyncGenerator => self
11988 .realm
11989 .async_generator_function_proto
11990 .clone()
11991 .or_else(|| self.realm.function_proto.clone().into()),
11992 js_compile::bytecode::FunctionKind::Generator => self
11993 .realm
11994 .generator_function_proto
11995 .clone()
11996 .or_else(|| self.realm.function_proto.clone().into()),
11997 js_compile::bytecode::FunctionKind::Async => self
11998 .realm
11999 .async_function_proto
12000 .clone()
12001 .or_else(|| self.realm.function_proto.clone().into()),
12002 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
12003 };
12004 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
12005 object.set_constructible(constructible);
12006 object.define(
12007 "length",
12008 Property::name_or_length(Value::Int(length as i32)),
12009 );
12010 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
12011 // that checks the own-property descriptor fails if the property is missing.
12012 object.define("name", Property::name_or_length(self.string(name)));
12013 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
12014 // when `[[Construct]]` is created, so an async function and an arrow function have
12015 // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
12016 // function) an own `prototype` property, which `builtin.js` checks for absence.
12017 //
12018 // A **generator** function is the exception that is not constructible: it still
12019 // gets a `prototype` field, because that object is what a generator *instance*
12020 // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
12021 // made `function* g(){}; g.prototype` `undefined` and every generator share
12022 // `%GeneratorPrototype%` as its direct prototype.
12023 if constructible {
12024 self.install_function_prototype(&object);
12025 } else if matches!(
12026 function_kind,
12027 js_compile::bytecode::FunctionKind::Generator
12028 | js_compile::bytecode::FunctionKind::AsyncGenerator
12029 ) {
12030 let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
12031 self.realm.generator_proto.clone()
12032 } else {
12033 self.realm
12034 .async_generator_proto
12035 .clone()
12036 .unwrap_or_else(|| self.realm.generator_proto.clone())
12037 };
12038 self.install_generator_prototype(&object, parent);
12039 }
12040 Ok(Value::Object(object))
12041 }
12042
12043 // -- conversions used by the operators ----------------------------------
12044
12045 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
12046 // `+x` is `ToNumber`, which for a string parses it and for an object runs
12047 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
12048 // string, which then behaves differently in every later comparison.
12049 match value {
12050 Value::Int(_) | Value::Float(_) => Ok(value),
12051 other => Ok(Value::Float(self.to_js_number(&other)?)),
12052 }
12053 }
12054
12055 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
12056 ///
12057 /// Returns the *converted* old value and the new one, because the two callers need
12058 /// different halves: `++x` yields the new value, while `x++` yields the old one and
12059 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
12060 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
12061 /// boolean.
12062 ///
12063 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
12064 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
12065 /// a bigint algorithm then ran exactly once.
12066 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
12067 if let Value::BigInt(big) = &value {
12068 let one = crate::bigint::BigInt::from_i64(1);
12069 let next = if up { big.add(&one) } else { big.sub(&one) };
12070 return Ok((value, self.bigint(next)));
12071 }
12072 let old = self.numeric(value)?;
12073 let new = if up {
12074 increment(old.clone())
12075 } else {
12076 decrement(old.clone())
12077 };
12078 Ok((old, new))
12079 }
12080
12081 fn numeric(&mut self, value: Value) -> JsResult<Value> {
12082 // `ToNumber` on an object runs `ToPrimitive` first, which is how
12083 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
12084 // heard at all. Reading the object's own tag instead (`other.to_number()`)
12085 // turned the whole operand into `NaN` and swallowed the exception.
12086 match value {
12087 Value::Int(_) | Value::Float(_) => Ok(value),
12088 other => Ok(Value::Float(self.to_js_number(&other)?)),
12089 }
12090 }
12091
12092 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
12093 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
12094 match value {
12095 Value::BigInt(big) => Ok((**big).clone()),
12096 // The reference words this the same way for every operator, so a failing
12097 // script reads identically; the operator itself adds nothing a caller can use.
12098 _ => Err(Signal::Throw(
12099 self.make_error("TypeError", "cannot convert bigint to number"),
12100 )),
12101 }
12102 }
12103
12104 /// Arithmetic where at least one operand is a `BigInt`.
12105 ///
12106 /// The two numeric types never mix, so a bigint paired with anything else is an error
12107 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
12108 /// that the relational operators handle it separately.
12109 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12110 use Opcode::*;
12111 let a = self.bigint_operand(&left)?;
12112 let b = self.bigint_operand(&right)?;
12113 let result = match op {
12114 Add => a.add(&b),
12115 Sub => a.sub(&b),
12116 Mul => a.mul(&b),
12117 Div | Mod => {
12118 let Some((quotient, remainder)) = a.div_rem(&b) else {
12119 return Err(Signal::Throw(
12120 self.make_error("RangeError", "division by zero"),
12121 ));
12122 };
12123 if op == Div { quotient } else { remainder }
12124 }
12125 Pow => {
12126 let Some(value) = a.pow(&b) else {
12127 return Err(Signal::Throw(self.make_error(
12128 "RangeError",
12129 "BigInt exponent must be non-negative and not absurdly large",
12130 )));
12131 };
12132 value
12133 }
12134 And => a.bitand(&b),
12135 Or => a.bitor(&b),
12136 Xor => a.bitxor(&b),
12137 Shl | Sar => {
12138 // A shift count is a `BigInt` here, and both directions are exact; a
12139 // negative count would be the other direction, which the spec forbids.
12140 let Some(count) = b.to_i64() else {
12141 return Err(Signal::Throw(
12142 self.make_error("RangeError", "BigInt shift count is too large"),
12143 ));
12144 };
12145 if count < 0 {
12146 return Err(Signal::Throw(self.make_error(
12147 "RangeError",
12148 "BigInt shift count must be non-negative",
12149 )));
12150 }
12151 if op == Shl {
12152 a.shl(count as u64)
12153 } else {
12154 a.shr(count as u64)
12155 }
12156 }
12157 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
12158 _ => {
12159 return Err(Signal::Throw(self.make_error(
12160 "TypeError",
12161 "BigInts have no unsigned right shift, use >> instead",
12162 )));
12163 }
12164 };
12165 Ok(self.bigint(result))
12166 }
12167
12168 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
12169 ///
12170 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
12171 /// is on the mathematical values, and nothing is rounded first.
12172 /// `<`, `<=`, `>`, `>=`.
12173 ///
12174 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
12175 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
12176 /// It is a `?`-returning function for exactly that reason: an object operand can run
12177 /// script, and script can throw. The old version compared `to_number` of the raw
12178 /// values, which answered `false` for every object instead of calling `valueOf` —
12179 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
12180 /// never ran.
12181 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12182 // The hot arm first: `i < n` with both sides already integers. No conversion, no
12183 // call, nothing that can throw.
12184 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12185 let ordering = Some(left.cmp(right));
12186 return Ok(ordering_answer(op, ordering));
12187 }
12188 // Anything that can run script has to be converted first, in this order.
12189 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
12190 {
12191 (
12192 self.to_primitive(left, Hint::Number)?,
12193 self.to_primitive(right, Hint::Number)?,
12194 )
12195 } else {
12196 (left, right)
12197 };
12198 let ordering = match (&left, &right) {
12199 // The loop condition `i < n` is integer against integer, and it runs once
12200 // per iteration of every loop in every program. Without this arm it took the
12201 // `to_number` path twice, which is a `match` plus a conversion each.
12202 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
12203 (Value::String(a), Value::String(b)) => {
12204 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
12205 }
12206 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
12207 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
12208 // is true even though `2.5` has no bigint form.
12209 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
12210 let b = other.to_number();
12211 if b.is_nan() {
12212 None
12213 } else {
12214 compare_bigint_and_f64(a, b)
12215 }
12216 }
12217 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
12218 let a = other.to_number();
12219 if a.is_nan() {
12220 None
12221 } else {
12222 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
12223 }
12224 }
12225 _ => left.to_number().partial_cmp(&right.to_number()),
12226 };
12227 Ok(ordering_answer(op, ordering))
12228 }
12229
12230 fn binary_add(&mut self) -> JsResult<()> {
12231 let right = self.pop();
12232 let left = self.pop();
12233 // Two integers add without any of the machinery below: no `ToPrimitive` (an
12234 // `Int` is already primitive), no string check, no bigint check, no allocation.
12235 // `x += 1` in a loop is the single most common instruction sequence in real
12236 // script, and it used to walk every one of those checks before reaching the
12237 // same `checked_add`.
12238 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12239 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
12240 return Ok(());
12241 }
12242 let left = self.primitive_of(left)?;
12243 let right = self.primitive_of(right)?;
12244 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
12245 // that check comes before the bigint one: `"" + 1n` is a string, not a
12246 // mixed-type error.
12247 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
12248 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
12249 // `TypeError`, the one place a symbol and a string do not mix.
12250 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
12251 // between a copy and a rope from their lengths, and a rope is what turns
12252 // `text += "abc"` in a loop from quadratic into linear.
12253 if let (Value::String(left), Value::String(right)) = (&left, &right) {
12254 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
12255 // reports as `InternalError: string too long`.
12256 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
12257 return Err(Signal::Throw(
12258 self.make_error("InternalError", "string too long"),
12259 ));
12260 };
12261 self.push(Value::String(Gc::new(self.heap, joined)));
12262 return Ok(());
12263 }
12264 // At least one operand was not a string, so `ToString` it. This rejects a
12265 // symbol, which is the one place a symbol and a string do not mix.
12266 let left = self.checked_to_wtf8(&left)?;
12267 let right = self.checked_to_wtf8(&right)?;
12268 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
12269 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
12270 let text = left.concat(&right);
12271 self.push(self.string_wtf8(text));
12272 return Ok(());
12273 }
12274 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
12275 // not a conversion.
12276 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
12277 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
12278 self.push(value);
12279 return Ok(());
12280 }
12281 let left = self.numeric(left)?;
12282 let right = self.numeric(right)?;
12283 self.push(add_numbers(left, right));
12284 Ok(())
12285 }
12286
12287 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
12288 self.to_primitive(value, Hint::Default)
12289 }
12290
12291 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
12292 ///
12293 /// The order depends on the hint: the "number" order tries `valueOf` first and
12294 /// `toString` second, the "string" order the other way round, and the default
12295 /// hint uses the number order. A result that is still an object is a `TypeError`,
12296 /// because no built-in `valueOf`/`toString` returns one.
12297 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
12298 let Value::Object(object) = &value else {
12299 return Ok(value);
12300 };
12301 // A Date overrides the default hint to mean "string", which is what
12302 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
12303 // this, `"" + new Date()` would print the milliseconds, not the date.
12304 let hint = if hint == Hint::Default && is_date_object(self, object) {
12305 Hint::String
12306 } else {
12307 hint
12308 };
12309 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
12310 // handed the hint as a string. This is the hook a Date uses for its default hint
12311 // and a script uses to take over conversion entirely.
12312 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
12313 // `GetMethod`, not "is it a callable object": the property has to be read and then
12314 // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
12315 // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
12316 // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
12317 // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
12318 // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
12319 // callable.
12320 match self.get_property_key(object, &key)? {
12321 None | Some(Value::Undefined) | Some(Value::Null) => {}
12322 Some(Value::Object(function)) if function.is_callable() => {
12323 let hint = match hint {
12324 Hint::String => "string",
12325 Hint::Number => "number",
12326 Hint::Default => "default",
12327 };
12328 let hint = self.string(hint);
12329 let result = self.call_value(
12330 Value::Object(function),
12331 Value::Object(object.clone()),
12332 vec![hint],
12333 )?;
12334 if !matches!(result, Value::Object(_)) {
12335 return Ok(result);
12336 }
12337 return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
12338 }
12339 Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
12340 }
12341 let order: [&str; 2] = match hint {
12342 Hint::String => ["toString", "valueOf"],
12343 Hint::Number | Hint::Default => ["valueOf", "toString"],
12344 };
12345 let receiver = object.clone();
12346 for method in order {
12347 if let Some(function) = self.get_property(&receiver, method)?
12348 && matches!(&function, Value::Object(object) if object.is_callable())
12349 {
12350 let result =
12351 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
12352 if !matches!(result, Value::Object(_)) {
12353 return Ok(result);
12354 }
12355 }
12356 }
12357 Err(self.type_error("cannot convert object to primitive value"))
12358 }
12359
12360 /// `ToString` with the object case going through `ToPrimitive`.
12361 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
12362 if matches!(value, Value::Object(_)) {
12363 let primitive = self.to_primitive(value.clone(), Hint::String)?;
12364 return Ok(primitive.to_js_string());
12365 }
12366 // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
12367 // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
12368 // callers that want that strictness call [`Interp::to_string_strict`] — putting the
12369 // check here broke `String(Symbol())` and 45 cases that print a symbol.
12370 Ok(value.to_js_string())
12371 }
12372
12373 /// `ToString(value)`, with §7.1.19's symbol refusal.
12374 ///
12375 /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
12376 /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
12377 /// operations and conflating them cost 45 cases in one direction and 6 in the other.
12378 pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
12379 if matches!(value, Value::Symbol(_)) {
12380 return Err(self.type_error("cannot convert a Symbol to a string"));
12381 }
12382 if matches!(value, Value::Object(_)) {
12383 let primitive = self.to_primitive(value.clone(), Hint::String)?;
12384 if matches!(primitive, Value::Symbol(_)) {
12385 return Err(self.type_error("cannot convert a Symbol to a string"));
12386 }
12387 return Ok(primitive.to_js_string());
12388 }
12389 Ok(value.to_js_string())
12390 }
12391
12392 /// `ToString` that keeps the string's code units instead of flattening them.
12393 ///
12394 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
12395 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
12396 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12397 if matches!(value, Value::Symbol(_)) {
12398 return Err(Signal::Throw(
12399 self.make_error("TypeError", "cannot convert symbol to string"),
12400 ));
12401 }
12402 // An object runs `ToPrimitive` first, which may itself produce a symbol.
12403 let value = self.to_primitive(value.clone(), Hint::String)?;
12404 match value {
12405 Value::Symbol(_) => Err(Signal::Throw(
12406 self.make_error("TypeError", "cannot convert symbol to string"),
12407 )),
12408 Value::String(text) => Ok(text.wtf8().clone()),
12409 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
12410 }
12411 }
12412
12413 /// `ToNumber` with the object case going through `ToPrimitive`.
12414 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
12415 let value = if matches!(value, Value::Object(_)) {
12416 self.to_primitive(value.clone(), Hint::Number)?
12417 } else {
12418 value.clone()
12419 };
12420 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
12421 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
12422 // `NaN` to stay total, and the operators check for the bigint themselves — but
12423 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
12424 // refuse, and answering `NaN` made them silently wrong instead.
12425 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
12426 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
12427 match value {
12428 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
12429 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
12430 other => Ok(other.to_number()),
12431 }
12432 }
12433
12434 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
12435 /// [`ElementType::write`].
12436 ///
12437 /// This is separated from the write because both conversions are observable script —
12438 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
12439 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
12440 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
12441 /// setters, and a plain `a[i] = v`.
12442 pub(crate) fn element_value(
12443 &mut self,
12444 element: crate::builtins::typedarray::ElementType,
12445 value: Value,
12446 ) -> JsResult<Value> {
12447 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
12448 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
12449 let primitive = match &value {
12450 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
12451 _ => value,
12452 };
12453 if element.is_bigint() {
12454 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
12455 Ok(Value::BigInt(Gc::new(self.heap, big)))
12456 } else {
12457 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
12458 Ok(Value::Float(self.to_js_number(&primitive)?))
12459 }
12460 }
12461
12462 /// `ToPropertyKey`: what a computed member access uses as its key.
12463 ///
12464 /// A symbol is returned as itself, never stringified — that is what keeps
12465 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
12466 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
12467 match value {
12468 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
12469 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
12470 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
12471 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
12472 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12473 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
12474 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
12475 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
12476 other.to_js_string(),
12477 ))),
12478 },
12479 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
12480 }
12481 }
12482
12483 /// `ToPropertyKey` for the callers that can only use a string key.
12484 ///
12485 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
12486 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
12487 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
12488 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
12489 /// program continues with a value nobody asked for.
12490 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12491 use crate::value::Wtf8;
12492 Ok(match value {
12493 // A string key keeps its code units. Going through a lossy `String` would make
12494 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
12495 Value::String(text) => text.wtf8().clone(),
12496 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
12497 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
12498 // falling back to its `ToString` would print `[object Object]`.
12499 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12500 Value::String(text) => text.wtf8().clone(),
12501 other => Wtf8::new(other.to_js_string()),
12502 },
12503 other => Wtf8::new(other.to_js_string()),
12504 })
12505 }
12506
12507 // -- object operations used by instructions -----------------------------
12508
12509 /// Read `object[key]`, returning `undefined` when the property is missing.
12510 ///
12511 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
12512 /// primitive (looking through its prototype) as well as an object — which is what
12513 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
12514 /// argument needs too.
12515 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
12516 self.read_field_key(object, &PropertyKey::from(key))
12517 }
12518
12519 /// [`Interp::read_field`] with a key that may be a symbol.
12520 ///
12521 /// A symbol key never reaches the string shortcuts: a string's `length` and its
12522 /// indices are string properties, and a symbol named `length` is a different
12523 /// property that a string primitive cannot have.
12524 /// [`Interp::read_field_key`], with an inline cache in front of it.
12525 ///
12526 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
12527 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
12528 /// without this the engine walked the chain and compared ~40 property names on each
12529 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
12530 ///
12531 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
12532 /// missing property. Those answers depend on running code or on state the guard below
12533 /// does not cover, and a wrong answer here is far more expensive than a lookup.
12534 ///
12535 /// A hit is re-validated against the *whole* walked chain, not just the level that
12536 /// answered: the receiver and every prototype down to that level must still be the same
12537 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
12538 /// property-table *lengths* — which is what catches a property appearing on an
12539 /// intermediate prototype and shadowing the cached one.
12540 pub fn read_field_cached(
12541 &mut self,
12542 object: &Value,
12543 key: &PropertyKey,
12544 slot: usize,
12545 ) -> JsResult<Value> {
12546 let index = Self::field_cache_slot(object, key, slot);
12547 let Value::Object(target) = object else {
12548 return self.read_field_key(object, key);
12549 };
12550 if target.proxy_state().is_some() {
12551 return self.read_field_key(object, key);
12552 }
12553 if let Some(cached) = &self.field_cache[index]
12554 && cached.key == *key
12555 && let Some(value) = Self::cached_hit(target, cached)
12556 {
12557 return Ok(value);
12558 }
12559 let value = self.read_field_key(object, key)?;
12560 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
12561 Ok(value)
12562 }
12563
12564 /// Whether a cache entry still describes this lookup, and if so the value.
12565 ///
12566 /// The guard is the whole point of the entry: identity plus property-table length for
12567 /// every level walked. Re-checked per level rather than once at the receiving end,
12568 /// because a shadowing property can appear anywhere along the chain.
12569 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
12570 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
12571 // starts with: a clone is a reference-count bump and a drop, and for
12572 // `property:monomorphic` every single hit takes only this arm.
12573 let (weak, len) = cached.chain[0].as_ref()?;
12574 if !target.upgrades_to(weak) {
12575 return None;
12576 }
12577 if cached.level == 0 {
12578 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
12579 return target.cached_property_at(cached.index, &cached.key, *len);
12580 }
12581 if target.props_len() != *len {
12582 return None;
12583 }
12584 let mut level = 1;
12585 let mut current = target.proto()?;
12586 loop {
12587 let (weak, len) = cached.chain[level].as_ref()?;
12588 if !current.upgrades_to(weak) || current.props_len() != *len {
12589 return None;
12590 }
12591 if level == cached.level as usize {
12592 // The level that answered: the value is only reusable while the key is
12593 // still there and still a plain data property.
12594 return current.cached_data_property(cached.index, &cached.key);
12595 }
12596 current = current.proto()?;
12597 level += 1;
12598 }
12599 }
12600
12601 /// Build a cache entry for a lookup that just went through the slow path.
12602 ///
12603 /// Records the chain only when the answer came from a plain data property at a level
12604 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
12605 /// costs the next lookup the walk it would have cost anyway.
12606 fn record_field_lookup(
12607 target: &Gc<JsObject>,
12608 key: &PropertyKey,
12609 _value: Value,
12610 ) -> Option<FieldCache> {
12611 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
12612 [None, None, None];
12613 let mut current = target.clone();
12614 for level in 0..MAX_CACHED_CHAIN {
12615 chain[level] = Some((current.downgrade(), current.props_len()));
12616 if let Some((found, _)) = current.own_property_index(key) {
12617 // `own_property_index` declines an accessor and a hole, which is exactly
12618 // the set that must not be cached.
12619 return Some(FieldCache {
12620 key: key.clone(),
12621 index: found,
12622 level: level as u8,
12623 chain,
12624 });
12625 }
12626 current = current.proto()?;
12627 }
12628 None
12629 }
12630
12631 /// Which cache slot a lookup uses.
12632 ///
12633 /// Mixes the object's address, the name and the site, so that two properties of one
12634 /// object, and one property of two objects, land in different slots — which is what lets
12635 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
12636 /// other iteration.
12637 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
12638 let mut hash = match object {
12639 Value::Object(object) => object.address(),
12640 _ => 0,
12641 };
12642 hash = hash
12643 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
12644 .rotate_left(17)
12645 .wrapping_add(key.hash_code());
12646 hash = hash.wrapping_add(site.wrapping_mul(31));
12647 // The table is a power of two, so the low bits are the slot.
12648 hash & (FIELD_CACHE_SLOTS - 1)
12649 }
12650
12651 /// Read `key` from `object`, without the inline cache.
12652 ///
12653 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
12654 /// prototype chain, while the cached form answers an own data property from memory.
12655 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
12656 let text = key.as_str().unwrap_or("");
12657 let Value::Object(object) = object else {
12658 // Reading a property of `undefined`/`null` is the classic TypeError.
12659 if object.is_nullish() {
12660 return Err(Signal::Throw(self.make_error(
12661 "TypeError",
12662 &format!("cannot read property '{key}' of {}", object.to_js_string()),
12663 )));
12664 }
12665 // A string has `length` and index access without being boxed.
12666 if let Value::String(value) = object {
12667 if text == "length" {
12668 return Ok(Value::Int(value.utf16_len() as i32));
12669 }
12670 if let Some(index) = array_index(text) {
12671 return Ok(match value.wtf8().unit_at(index as usize) {
12672 Some(unit) => self.string_wtf8(unit),
12673 None => Value::Undefined,
12674 });
12675 }
12676 }
12677 // A property of a primitive is looked up on its prototype: this is what
12678 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
12679 let prototype = match object {
12680 Value::String(_) => self.realm.string_proto.clone(),
12681 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
12682 Value::Bool(_) => self.realm.boolean_proto.clone(),
12683 // A symbol's methods live on `Symbol.prototype`, reached the same way —
12684 // `sym.description` reads through the prototype, not off the symbol.
12685 Value::Symbol(_) => self.realm.symbol_proto.clone(),
12686 // …and a bigint's on `BigInt.prototype`, which is how
12687 // `(255n).toString(16)` reaches its method.
12688 Value::BigInt(_) => self.realm.bigint_proto.clone(),
12689 _ => None,
12690 };
12691 if let Some(prototype) = prototype
12692 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
12693 {
12694 return Ok(value);
12695 }
12696 return Ok(Value::Undefined);
12697 };
12698 Ok(self
12699 .get_property_key(object, key)?
12700 .unwrap_or(Value::Undefined))
12701 }
12702
12703 /// The `#name` a private symbol stands for, for error messages.
12704 ///
12705 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
12706 /// was made from.
12707 fn private_name(symbol: &Value) -> Option<String> {
12708 match symbol {
12709 Value::Symbol(symbol) if symbol.is_private() => Some(
12710 symbol
12711 .description()
12712 .map(|text| text.to_string())
12713 .unwrap_or_default(),
12714 ),
12715 _ => None,
12716 }
12717 }
12718
12719 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
12720 ///
12721 /// Every private-field opcode takes the symbol the class stored in its own scope; a
12722 /// non-symbol here would be a compiler bug, and the reference guards it with
12723 /// `JS_ThrowTypeErrorNotASymbol`.
12724 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
12725 match symbol {
12726 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
12727 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
12728 }
12729 }
12730
12731 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
12732 ///
12733 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
12734 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
12735 /// would hit if the parser did not reject it first.
12736 fn define_private_field(
12737 &mut self,
12738 object: &Value,
12739 symbol: &Value,
12740 value: Value,
12741 ) -> JsResult<()> {
12742 let key = self.private_key(symbol)?;
12743 let Some(target) = object.as_object() else {
12744 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12745 };
12746 if !target.is_extensible() {
12747 return Err(Signal::Throw(
12748 self.make_error("TypeError", "object is not extensible"),
12749 ));
12750 }
12751 if target.own_property_key(&key).is_some() {
12752 let name = Self::private_name(symbol).unwrap_or_default();
12753 return Err(Signal::Throw(self.make_error(
12754 "TypeError",
12755 &format!("private class field '{name}' already exists"),
12756 )));
12757 }
12758 target.define_data_key(&key, value);
12759 Ok(())
12760 }
12761
12762 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
12763 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
12764 let key = self.private_key(symbol)?;
12765 let Some(target) = object.as_object() else {
12766 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12767 };
12768 match target.own_property_key(&key) {
12769 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
12770 None => {
12771 let name = Self::private_name(symbol).unwrap_or_default();
12772 Err(Signal::Throw(self.make_error(
12773 "TypeError",
12774 &format!("private class field '{name}' does not exist"),
12775 )))
12776 }
12777 }
12778 }
12779
12780 /// `JS_SetPrivateField`: the store half of the same rule.
12781 fn write_private_field(
12782 &mut self,
12783 object: &Value,
12784 symbol: &Value,
12785 value: Value,
12786 ) -> JsResult<()> {
12787 let key = self.private_key(symbol)?;
12788 let Some(target) = object.as_object() else {
12789 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12790 };
12791 if target.write_value_key(&key, value) {
12792 return Ok(());
12793 }
12794 let name = Self::private_name(symbol).unwrap_or_default();
12795 Err(Signal::Throw(self.make_error(
12796 "TypeError",
12797 &format!("private class field '{name}' does not exist"),
12798 )))
12799 }
12800
12801 /// The `in` half: does `object` have this private field?
12802 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
12803 ///
12804 /// The symbol is created once per class — the first `add_brand` on a given home object
12805 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
12806 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
12807 /// emit for the *instance* brand passes null because all it wants is the symbol.
12808 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
12809 let Some(home_object) = home.as_object() else {
12810 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12811 };
12812 let symbol = match home_object.private_brand() {
12813 Some(symbol) => symbol,
12814 None => {
12815 let symbol = Gc::new(
12816 self.heap,
12817 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
12818 );
12819 home_object.set_private_brand(symbol.clone());
12820 symbol
12821 }
12822 };
12823 let Some(target) = object.as_object() else {
12824 // Not an object: nothing to brand. The reference does the same, and `undefined`
12825 // here would otherwise turn a field initialiser into a TypeError.
12826 return Ok(());
12827 };
12828 if !target.is_extensible() {
12829 return Err(Signal::Throw(
12830 self.make_error("TypeError", "object is not extensible"),
12831 ));
12832 }
12833 if target.carries_brand(&symbol) {
12834 return Err(Signal::Throw(
12835 self.make_error("TypeError", "private method is already present"),
12836 ));
12837 }
12838 target.add_brand(symbol);
12839 Ok(())
12840 }
12841
12842 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
12843 ///
12844 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
12845 /// decides whether to throw.
12846 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
12847 let Some(function) = function.as_object() else {
12848 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12849 };
12850 let Some(home) = function.home_object() else {
12851 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12852 };
12853 let Some(brand) = home.private_brand() else {
12854 return Err(Signal::Throw(
12855 self.make_error("TypeError", "expecting <brand> private field"),
12856 ));
12857 };
12858 Ok(object.carries_brand(&brand))
12859 }
12860
12861 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
12862 let Value::Object(object) = object else {
12863 return Err(Signal::Throw(self.make_error(
12864 "TypeError",
12865 &format!("cannot set property '{key}' of {}", object.to_js_string()),
12866 )));
12867 };
12868 // The write half of the property inline cache, in effect: an own, writable,
12869 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
12870 // decide — no prototype walk (an own property shadows the chain before a setter
12871 // there could matter), no extensibility check (the object already has the key),
12872 // and no `[[DefineOwnProperty]]`.
12873 //
12874 // `this.value = …` inside a method is the whole write side of
12875 // `property:method-call`, and it was reaching `set_property_with_key` with its
12876 // proxy test, its typed-array test, its array-index test and finally a linear
12877 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
12878 //
12879 // Every disqualifier is checked here: a proxy traps the set, an array index and
12880 // `length` live outside the property table, and a typed array's element is stored
12881 // through its view's element type.
12882 if object.proxy_state().is_none()
12883 && !object.is_array()
12884 && object.typed_array_element_type().is_none()
12885 && object.write_value_key(key, value.clone())
12886 {
12887 return Ok(());
12888 }
12889 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
12890 let on_failure = if self.frame().code.code.strict {
12891 DeleteFailure::Throw
12892 } else {
12893 DeleteFailure::Ignore
12894 };
12895 self.set_property_with_key(object, key, value, on_failure)
12896 }
12897
12898 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
12899 ///
12900 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
12901 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
12902 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
12903 /// `Number.parseInt(sym)` — so those callers use this instead.
12904 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
12905 if matches!(value, Value::Symbol(_)) {
12906 return Err(Signal::Throw(
12907 self.make_error("TypeError", "cannot convert symbol to string"),
12908 ));
12909 }
12910 // An object runs `ToPrimitive` first, which may itself produce a symbol —
12911 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
12912 let value = self.to_primitive(value.clone(), Hint::String)?;
12913 if matches!(value, Value::Symbol(_)) {
12914 return Err(Signal::Throw(
12915 self.make_error("TypeError", "cannot convert symbol to string"),
12916 ));
12917 }
12918 Ok(value.to_js_string())
12919 }
12920
12921 /// `ToPropertyKey` for a builtin that takes a key argument.
12922 ///
12923 /// Fallible: a key whose `toString` throws has to propagate that error, both for
12924 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
12925 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
12926 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
12927 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
12928 self.propkey(value)
12929 }
12930
12931 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
12932 ///
12933 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
12934 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
12935 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
12936 /// `RangeError` — and why this cannot be a plain `ToNumber`.
12937 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
12938 let number = match value {
12939 Value::Int(number) => *number as f64,
12940 Value::Float(number) => *number,
12941 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
12942 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
12943 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
12944 // reference answers 0.
12945 Value::Null | Value::Bool(_) => value.to_number(),
12946 _ => {
12947 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
12948 match primitive {
12949 Value::Int(number) => number as f64,
12950 Value::Float(number) => number,
12951 other => {
12952 // `ToString` then `ToNumber`, so a string length goes through the
12953 // full numeric-literal grammar: `"0x00B"` is 11 and `" 5 "` is 5.
12954 // `Value::to_number` on the string already implements exactly that.
12955 let text = self.to_js_string(&other)?;
12956 crate::value::string_to_number(&text)
12957 }
12958 }
12959 }
12960 };
12961 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
12962 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
12963 // is a `RangeError`, not `0`.
12964 if !number.is_finite()
12965 || number.fract() != 0.0
12966 || !(0.0..=u32::MAX as f64).contains(&number)
12967 {
12968 return Err(self.range_error("invalid array length"));
12969 }
12970 Ok(number as u32)
12971 }
12972
12973 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
12974 /// `Object.getOwnPropertySymbols` put in their result array.
12975 pub fn key_value(&self, key: &PropertyKey) -> Value {
12976 match key {
12977 PropertyKey::String(text) => self.string_wtf8(text.clone()),
12978 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
12979 }
12980 }
12981
12982 /// Fill in a String exotic object: `_value`, `length` and the index properties.
12983 ///
12984 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
12985 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
12986 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
12987 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
12988 /// the two paths had drifted; this is the one both now use.
12989 ///
12990 /// The indices are *code units*, so an astral character occupies two of them — the
12991 /// same rule `s.length` and `s[i]` follow.
12992 /// Give an already-created object the internal slot that makes it a wrapper of
12993 /// `value`, so the primitive's prototype methods work on it.
12994 ///
12995 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
12996 /// which are wrappers of their own type holding the empty value.
12997 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
12998 self.internal_set(object, "_value", value);
12999 }
13000
13001 pub(crate) fn init_string_wrapper(
13002 &mut self,
13003 object: &Gc<JsObject>,
13004 text: &Gc<crate::value::JsString>,
13005 ) {
13006 object.define(
13007 "length",
13008 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
13009 );
13010 for index in 0..text.utf16_len() {
13011 if let Some(unit) = text.wtf8().unit_at(index) {
13012 object.define(
13013 &index.to_string(),
13014 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
13015 Property::with_attributes(self.string_wtf8(unit), false, true),
13016 );
13017 }
13018 }
13019 object.define_key(
13020 &self.internal_slot("_value"),
13021 Property::with_attributes(Value::String(text.clone()), false, false),
13022 );
13023 }
13024
13025 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
13026 ///
13027 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
13028 /// throws. The wrapper carries its primitive in `_value` — the same slot
13029 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
13030 /// on a boxed value no constructor ever built.
13031 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13032 let (prototype, primitive) = match value {
13033 Value::Object(object) => return Ok(object.clone()),
13034 Value::String(text) => {
13035 let object = self.new_object(self.realm.string_proto.clone());
13036 self.init_string_wrapper(&object, text);
13037 return Ok(object);
13038 }
13039 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
13040 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
13041 // A symbol and a bigint box into wrappers whose methods live on
13042 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
13043 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
13044 // branch below instead produced an object with *no* prototype, so those
13045 // methods were unreachable on a box.
13046 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
13047 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
13048 Value::Undefined | Value::Null => {
13049 return Err(Signal::Throw(self.make_error(
13050 "TypeError",
13051 &format!("cannot convert {} to object", value.to_js_string()),
13052 )));
13053 }
13054 _ => (None, value.clone()),
13055 };
13056 let object = self.new_object(prototype);
13057 self.internal_set(&object, "_value", primitive);
13058 Ok(object)
13059 }
13060
13061 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
13062 ///
13063 /// Split out for a reader that has to create the object *before* it knows what it wraps:
13064 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
13065 /// written before its primitive, so the placeholder has to exist first and be filled in
13066 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
13067 /// than a second in the deserialiser.
13068 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
13069 let prototype = match value {
13070 Value::String(_) => self.realm.string_proto.clone(),
13071 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13072 Value::Bool(_) => self.realm.boolean_proto.clone(),
13073 Value::Symbol(_) => self.realm.symbol_proto.clone(),
13074 Value::BigInt(_) => self.realm.bigint_proto.clone(),
13075 _ => {
13076 return Err(Signal::Throw(self.make_error(
13077 "TypeError",
13078 &format!("cannot box {}", value.to_js_string()),
13079 )));
13080 }
13081 };
13082 object.set_proto(prototype);
13083 if let Value::String(text) = value {
13084 self.init_string_wrapper(object, text);
13085 return Ok(());
13086 }
13087 self.internal_set(object, "_value", value.clone());
13088 Ok(())
13089 }
13090
13091 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
13092 ///
13093 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
13094 /// through the `Symbol` function object, so the registry is reachable as a method rather
13095 /// than only from `builtins::symbol`.
13096 pub fn symbol_for(&mut self, key: &str) -> Value {
13097 if let Some(existing) = self.realm.symbol_registry.get(key) {
13098 return existing.clone();
13099 }
13100 let symbol = crate::builtins::symbol::symbol_value(
13101 self,
13102 crate::value::JsSymbol::registered(key.to_string()),
13103 );
13104 self.realm
13105 .symbol_registry
13106 .insert(key.to_string(), symbol.clone());
13107 symbol
13108 }
13109
13110 /// `a == b`, the coercing comparison.
13111 ///
13112 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
13113 /// which is what makes `[] == ""` true: `[]` becomes `""` via
13114 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
13115 /// because the conversion is allowed to call script code, so the two primitive
13116 /// operands are handed back to it.
13117 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
13118 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
13119 return Ok(left.loose_equals(&right));
13120 }
13121 // `null == undefined` holds even though neither is an object.
13122 if matches!(left, Value::Undefined | Value::Null)
13123 && matches!(right, Value::Undefined | Value::Null)
13124 {
13125 return Ok(true);
13126 }
13127 if matches!(left, Value::Undefined | Value::Null)
13128 || matches!(right, Value::Undefined | Value::Null)
13129 {
13130 return Ok(false);
13131 }
13132 // Two objects compare by identity. Only an object *against a primitive* is
13133 // converted, which is why `{} == {}` is false while `[] == ""` is true.
13134 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
13135 return Ok(a.ptr_eq(b));
13136 }
13137 let left = self.to_primitive(left, Hint::Default)?;
13138 let right = self.to_primitive(right, Hint::Default)?;
13139 Ok(left.loose_equals(&right))
13140 }
13141
13142 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
13143 let Value::Object(object) = object else {
13144 return Err(Signal::Throw(
13145 self.make_error("TypeError", "cannot use 'in' on a non-object"),
13146 ));
13147 };
13148 let key = self.propkey(key)?;
13149 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
13150 // trap. One implementation, so an array's derived `length` and its inherited holes
13151 // cannot be right in one caller and wrong in another.
13152 self.has_own_or_inherited(object, &key)
13153 }
13154
13155 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
13156 ///
13157 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
13158 /// whole reason the operator is a hook rather than a prototype walk.
13159 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13160 if let Value::Object(function) = constructor {
13161 let key = self.realm.well_known_key(WellKnown::HasInstance);
13162 let method = self.get_property_key(function, &key)?;
13163 if let Some(method) = method
13164 && !matches!(method, Value::Undefined)
13165 {
13166 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
13167 return Ok(answer.to_boolean());
13168 }
13169 }
13170 self.instance_of(object, constructor)
13171 }
13172
13173 /// `OrdinaryHasInstance`: the prototype walk on its own.
13174 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13175 self.instance_of(object, constructor)
13176 }
13177
13178 /// `IsArray`: an array, or a proxy whose target is one.
13179 ///
13180 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
13181 /// makes `Array.isArray(new Proxy([], {}))` true.
13182 pub fn is_array_value(&self, value: &Value) -> bool {
13183 match value {
13184 Value::Object(object) => {
13185 if let Some(state) = object.proxy_state() {
13186 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
13187 }
13188 object.is_array()
13189 }
13190 _ => false,
13191 }
13192 }
13193
13194 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
13195 ///
13196 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
13197 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
13198 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
13199 /// see [`Interp::enqueue_job_function`].
13200 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
13201 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
13202 // the handler is reported rather than lost — the same reason a `then` reaction needs a
13203 // promise to settle.
13204 let promise = self.new_promise();
13205 self.fulfill_promise(&promise, Value::Undefined);
13206 self.jobs.push_back(Job::Reaction {
13207 handler: Some(function),
13208 argument: Value::Undefined,
13209 rejected: false,
13210 promise,
13211 });
13212 Ok(())
13213 }
13214
13215 /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
13216 ///
13217 /// Four of its steps were missing or wrong, and each one is a test262 case in
13218 /// `Function/prototype/Symbol.hasInstance/`:
13219 ///
13220 /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
13221 /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
13222 /// `[[BoundThis]]` standing in for the object when that is an object), which is why
13223 /// `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
13224 /// `prototype` of its own, so without this step the walk below gives `false`;
13225 /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
13226 /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
13227 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13228 let Value::Object(function) = constructor else {
13229 return Ok(false);
13230 };
13231 if !function.is_callable() {
13232 return Ok(false);
13233 }
13234 // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
13235 // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
13236 // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
13237 if let Some((target, this)) = function.bound_target_and_this() {
13238 let object = if this.as_object().is_some() {
13239 this
13240 } else {
13241 object.clone()
13242 };
13243 return self.instance_of(&object, &target);
13244 }
13245 let Value::Object(target) = object else {
13246 return Ok(false);
13247 };
13248 let prototype = self.get_property(function, "prototype")?;
13249 let Some(Value::Object(prototype)) = prototype else {
13250 return Err(Signal::Throw(self.make_error(
13251 "TypeError",
13252 "function has non-object prototype in instanceof check",
13253 )));
13254 };
13255 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
13256 // which is also what makes `proxyOfInstance instanceof C` work.
13257 let mut current = Some(target.clone());
13258 while let Some(object) = current {
13259 if object.ptr_eq(&prototype) {
13260 return Ok(true);
13261 }
13262 current = self.object_prototype_of(&object)?;
13263 }
13264 Ok(false)
13265 }
13266
13267 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
13268 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
13269 if let Some(proto) = self.proxy_get_prototype_of(object)? {
13270 return Ok(proto);
13271 }
13272 if let Some(exotic) = object.exotic()
13273 && let Some(proto) = exotic.get_prototype(self, object)?
13274 {
13275 return Ok(proto);
13276 }
13277 Ok(object.proto())
13278 }
13279
13280 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
13281 pub fn object_set_prototype_of(
13282 &mut self,
13283 object: &Gc<JsObject>,
13284 proto: Option<Gc<JsObject>>,
13285 ) -> JsResult<bool> {
13286 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
13287 return Ok(answer);
13288 }
13289 if let Some(exotic) = object.exotic()
13290 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
13291 {
13292 return Ok(answer);
13293 }
13294 // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
13295 // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
13296 // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
13297 // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
13298 if self
13299 .internal_get(object, "_immutable_proto")
13300 .is_some_and(|flag| flag.to_boolean())
13301 && !same_proto(object.proto().as_ref(), proto.as_ref())
13302 {
13303 return Ok(false);
13304 }
13305 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
13306 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
13307 // inheriting from itself, which every later prototype walk then had to defend
13308 // against — and `Reflect.setPrototypeOf` reported success for an operation the
13309 // language says is impossible.
13310 if let Some(proto) = &proto {
13311 let mut current = Some(proto.clone());
13312 let mut guard = 0;
13313 while let Some(node) = current {
13314 if node.ptr_eq(object) {
13315 return Err(Signal::Throw(
13316 self.make_error("TypeError", "circular prototype chain"),
13317 ));
13318 }
13319 guard += 1;
13320 if guard > 1000 {
13321 break;
13322 }
13323 current = node.proto();
13324 }
13325 }
13326 // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
13327 // re-setting it to the *same* one is a no-op `true`. Missing this made
13328 // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
13329 // actually reparent the object — and it is what
13330 // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
13331 // forwarding path has nothing else left to refuse it.
13332 if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
13333 return Ok(false);
13334 }
13335 object.set_proto(proto);
13336 Ok(true)
13337 }
13338
13339 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
13340 ///
13341 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
13342 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
13343 /// already one.
13344 /// `HasProperty(O, P)`.
13345 ///
13346 /// One implementation, shared with the `in` operator. It used to be a second copy that
13347 /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
13348 /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
13349 /// proxy ran the wrong hook and could even disagree with `in`. The
13350 /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
13351 /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
13352 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
13353 self.has_own_or_inherited(object, key)
13354 }
13355
13356 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
13357 ///
13358 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
13359 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
13360 /// boolean as well, and it needs the receiver to be the one the caller named.
13361 pub fn set_property_with_key_receiver(
13362 &mut self,
13363 object: &Gc<JsObject>,
13364 key: &PropertyKey,
13365 value: Value,
13366 receiver: Option<&Value>,
13367 on_failure: DeleteFailure,
13368 ) -> JsResult<bool> {
13369 let receiver = receiver
13370 .cloned()
13371 .unwrap_or_else(|| Value::Object(object.clone()));
13372 if object.proxy_state().is_some() {
13373 return match self.proxy_set(object, key, value, &receiver)? {
13374 Some(accepted) => Ok(accepted),
13375 None => Ok(true),
13376 };
13377 }
13378 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
13379 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
13380 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
13381 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
13382 //
13383 // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
13384 //
13385 // * `SameValue(O, Receiver)` stores into the buffer, converting first;
13386 // * an *invalid* index with a different receiver answers `true` and does nothing,
13387 // not even converting `V` (`valueOfCalls` stays 0);
13388 // * a valid index with a different receiver falls through to
13389 // `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
13390 // value lands on the **receiver**, unconverted, and can be refused by a
13391 // non-extensible receiver, an accessor, or a read-only index there.
13392 //
13393 // The last one used to write into the view itself, which left `target[0]` changed
13394 // and `receiver[0]` untouched — backwards.
13395 if object.typed_array_element_type().is_some()
13396 && let Some(numeric) = canonical_numeric_index(key)
13397 {
13398 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13399 if same {
13400 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13401 return Ok(true);
13402 }
13403 if !typed_array_index_is_valid(object, numeric) {
13404 return Ok(true);
13405 }
13406 let Some(receiver) = receiver.as_object().cloned() else {
13407 return Ok(false);
13408 };
13409 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
13410 if existing.is_accessor() || !existing.writable {
13411 return Ok(false);
13412 }
13413 let property = Property {
13414 value: Some(value),
13415 ..existing
13416 };
13417 return self.object_define_own_property(&receiver, key, property);
13418 }
13419 return self.object_define_own_property(&receiver, key, Property::data(value));
13420 }
13421 // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
13422 // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
13423 // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
13424 // `Reflect.set` to *report* the refusal instead of raising.
13425 //
13426 // A receiver that is not the object turns the whole operation into
13427 // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
13428 // `[[Set]]` rather than a lookup — that is what makes
13429 // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
13430 // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
13431 // writes to `object`, so it cannot express that and is only used when the two are
13432 // the same.
13433 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13434 if !same {
13435 return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
13436 }
13437 // Same receiver: the plain path below writes into `object`, which is right, but it
13438 // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
13439 // boolean, so the two step-1 refusals have to be read off the own descriptor here.
13440 if let Some(existing) = self.object_get_own_property(object, key)? {
13441 if existing.is_accessor() {
13442 return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
13443 Some(setter) => {
13444 self.call_value(setter, receiver, vec![value])?;
13445 Ok(true)
13446 }
13447 None => Ok(false),
13448 };
13449 }
13450 if !existing.writable {
13451 return Ok(false);
13452 }
13453 }
13454 // Otherwise it is an ordinary create-or-write into `object` itself.
13455 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13456 Ok(true)
13457 }
13458
13459 /// `[[IsExtensible]]`, with the proxy trap when there is one.
13460 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13461 if let Some(answer) = self.proxy_is_extensible(object)? {
13462 return Ok(answer);
13463 }
13464 if let Some(exotic) = object.exotic()
13465 && let Some(answer) = exotic.is_extensible(self, object)?
13466 {
13467 return Ok(answer);
13468 }
13469 Ok(object.is_extensible())
13470 }
13471
13472 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
13473 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13474 if let Some(answer) = self.proxy_prevent_extensions(object)? {
13475 return Ok(answer);
13476 }
13477 // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
13478 //
13479 // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
13480 //
13481 // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
13482 // created with an explicit length, because the buffer can still move it. That is
13483 // what makes `Object.freeze` refuse every such view, including a zero-length one
13484 // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
13485 // plain buffer is allowed.
13486 if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
13487 && buffer
13488 .array_buffer_storage()
13489 .is_some_and(|storage| storage.borrow().is_resizable())
13490 {
13491 return Err(
13492 self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
13493 );
13494 }
13495 if let Some(exotic) = object.exotic()
13496 && let Some(answer) = exotic.prevent_extensions(self, object)?
13497 {
13498 return Ok(answer);
13499 }
13500 object.set_extensible(false);
13501 Ok(true)
13502 }
13503
13504 fn copy_properties(
13505 &mut self,
13506 target: &Value,
13507 source: &Value,
13508 exclusion: &Value,
13509 ) -> JsResult<()> {
13510 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
13511 // does contribute: its index properties are own, enumerable and writable, which
13512 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
13513 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
13514 // is a no-op.
13515 let Some(target) = target.as_object() else {
13516 return Ok(());
13517 };
13518 let source_object = match source {
13519 Value::Object(object) => object.clone(),
13520 Value::String(text) => {
13521 // Untaken keys are the string's indices, which are code units.
13522 for index in 0..text.utf16_len() {
13523 if let Some(unit) = text.wtf8().unit_at(index) {
13524 target.define_data(&index.to_string(), self.string_wtf8(unit));
13525 }
13526 }
13527 return Ok(());
13528 }
13529 _ => return Ok(()),
13530 };
13531 // An object *rest* element passes the keys already taken by the literal part as
13532 // an array of strings; a spread passes `null`, which excludes nothing. Only the
13533 // string keys of the exclusion array are meaningful, so an array is read by its
13534 // elements rather than by its own property names.
13535 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
13536 if let Value::Object(list) = exclusion
13537 && let Some(length) = list.array_length()
13538 {
13539 for index in 0..length {
13540 if let Some(value) = list.array_get(index) {
13541 excluded.push(self.propkey_of(&value)?);
13542 }
13543 }
13544 }
13545 let source = &source_object;
13546 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
13547 // Reading the property table directly made every spread of a proxy empty.
13548 let keys = self.object_own_property_keys(source)?;
13549 for as_key in keys {
13550 if as_key.is_symbol() {
13551 // A spread copies string-keyed properties only.
13552 continue;
13553 }
13554 if excluded.contains(&crate::value::Wtf8::new(
13555 as_key.as_str().unwrap_or_default(),
13556 )) {
13557 continue;
13558 }
13559 let enumerable = self
13560 .object_get_own_property(source, &as_key)?
13561 .is_some_and(|property| property.enumerable);
13562 if !enumerable {
13563 continue;
13564 }
13565 let value = self
13566 .get_property_key(source, &as_key)?
13567 .unwrap_or(Value::Undefined);
13568 target.define_data_key(&as_key, value);
13569 }
13570 Ok(())
13571 }
13572
13573 // -- iteration ---------------------------------------------------------
13574
13575 /// One object's own keys in enumeration order: array indices ascending, then the
13576 /// rest in insertion order.
13577 ///
13578 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
13579 /// whether the key is enumerable, which the caller resolves per key because an
13580 /// array's elements are not in the same store as its named properties.
13581 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
13582 // An index can arrive twice, once from the array's element store and once from
13583 // its property map, so the numeric keys go through a map that keeps the
13584 // enumerable answer if either source gave one.
13585 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
13586 for (key, enumerable) in &own {
13587 if let Some(index) = key.as_str().and_then(array_index) {
13588 let entry = numeric.entry(index).or_insert(false);
13589 *entry = *entry || *enumerable;
13590 }
13591 }
13592 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
13593 .into_iter()
13594 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
13595 .collect();
13596 ordered.extend(
13597 own.into_iter()
13598 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
13599 );
13600 ordered
13601 }
13602
13603 /// Build the key list a `for-in` loop walks.
13604 ///
13605 /// The order is the specification's: own properties before inherited ones, and
13606 /// within one object the integer-like keys in ascending numeric order ahead of the
13607 /// string keys in insertion order. A shadowed key only appears once, and a key that
13608 /// is a non-enumerable own property anywhere nearer is skipped entirely.
13609 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13610 let record = self.new_object(None);
13611 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
13612 // A proxy supplies its own key list, and — the reason this is not just another
13613 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
13614 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
13615 // descriptor there.
13616 if let Value::Object(object) = value
13617 && object.proxy_state().is_some()
13618 {
13619 let own = self
13620 .proxy_own_keys(object)?
13621 .unwrap_or_else(|| object.own_property_keys());
13622 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
13623 let mut numeric: Vec<u32> = Vec::new();
13624 let mut rest: Vec<PropertyKey> = Vec::new();
13625 for key in own {
13626 match key.as_str().and_then(array_index) {
13627 Some(index) => numeric.push(index),
13628 None => rest.push(key),
13629 }
13630 }
13631 numeric.sort_unstable();
13632 ordered.extend(
13633 numeric
13634 .into_iter()
13635 .map(|index| PropertyKey::from(index.to_string())),
13636 );
13637 ordered.extend(rest);
13638 for (index, key) in ordered.into_iter().enumerate() {
13639 record.define_data(&index.to_string(), self.key_value(&key));
13640 }
13641 record.define_data("__index", Value::Int(0));
13642 // The mark that makes `for_in_advance` re-ask the proxy per key.
13643 record.define_data("__proxy", Value::Object(object.clone()));
13644 return Ok(record);
13645 }
13646 if let Value::Object(object) = value {
13647 let mut chain = vec![object.clone()];
13648 chain.extend(object.chain());
13649 // Every own string key the walk has seen, enumerable or not. A
13650 // non-enumerable own property still hides a same-named enumerable one
13651 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
13652 // keeps `x` out of the loop even when the prototype has one.
13653 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
13654 for object in chain {
13655 let mut own: Vec<(crate::value::Wtf8, bool)> = object
13656 .own_property_keys()
13657 .iter()
13658 .filter_map(|key| key.as_wtf8().cloned())
13659 .map(|key| {
13660 let enumerable = object
13661 .own_property(&key.to_string_lossy())
13662 .map(|property| property.enumerable)
13663 .unwrap_or(false);
13664 (key, enumerable)
13665 })
13666 .collect();
13667 if let Some(length) = object.array_length() {
13668 own.retain(|(key, _)| key.as_str() != Some("length"));
13669 for index in 0..length {
13670 // A dense element is enumerable; a **hole** is not there at all —
13671 // and a hole is also what an index with a recorded descriptor
13672 // leaves behind, in which case the table entry above already
13673 // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
13674 // defines index 0 non-enumerable and `for…in` must skip it).
13675 if let Some(value) = object.array_get(index)
13676 && !matches!(value, Value::Hole)
13677 {
13678 own.push((crate::value::Wtf8::new(index.to_string()), true));
13679 }
13680 }
13681 }
13682 // Integer-like keys come first in ascending order, then the rest in
13683 // insertion order — and the ordering is *per object*, not for the chain
13684 // as a whole: one pass over every collected key lifted a prototype's
13685 // `"4"` above the target's own `x`/`y`, which is not the order
13686 // `for…in` reports.
13687 for (key, enumerable) in Self::order_own_keys(own) {
13688 if visited.contains(&key) {
13689 continue;
13690 }
13691 visited.push(key.clone());
13692 if enumerable {
13693 keys.push(key);
13694 }
13695 }
13696 }
13697 }
13698 for (index, key) in keys.into_iter().enumerate() {
13699 record.define_data(&index.to_string(), self.string_wtf8(key));
13700 }
13701 record.define_data("__index", Value::Int(0));
13702 Ok(record)
13703 }
13704
13705 /// The next key of a `for…in` record, `None` when the loop is done.
13706 ///
13707 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
13708 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
13709 /// the loop reaches it, so a handler that stops reporting a key partway through drops
13710 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
13711 /// key the handler had already withdrawn.
13712 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
13713 let Value::Object(record) = record else {
13714 return Ok(None);
13715 };
13716 let proxy = record
13717 .own_property("__proxy")
13718 .and_then(|property| property.value);
13719 loop {
13720 let index = record
13721 .own_property("__index")
13722 .and_then(|property| property.value)
13723 .map(|value| value.to_int32())
13724 .unwrap_or(0);
13725 let Some(candidate) = record
13726 .own_property(&index.to_string())
13727 .and_then(|property| property.value)
13728 else {
13729 return Ok(None);
13730 };
13731 record.define_data("__index", Value::Int(index + 1));
13732 let text = candidate.to_js_string();
13733 let Some(Value::Object(proxy)) = &proxy else {
13734 return Ok(Some(text));
13735 };
13736 // The candidate is already a key string here, so the lookup does not need a
13737 // second `ToPropertyKey` conversion.
13738 let key = PropertyKey::from(text.as_str());
13739 let live = match self.proxy_get_own_property(proxy, &key)? {
13740 Some(descriptor) => descriptor,
13741 // Not a proxy after all, or it lost its state: fall back to the target.
13742 None => proxy.own_property_key(&key),
13743 };
13744 if live.is_some_and(|property| property.enumerable) {
13745 return Ok(Some(text));
13746 }
13747 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
13748 // next one.
13749 }
13750 }
13751
13752 /// The iterator for `for-of`: the object and its `next` method.
13753 ///
13754 /// An object that already carries a `next` method is used as it is — that is what
13755 /// `arr.values()` returns — and only arrays and strings get the built-in
13756 /// sequence iterator.
13757 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
13758 ///
13759 /// Callers that must choose between the iterable and the array-like protocol — the
13760 /// typed-array constructor is the main one — need to ask *before* committing to one.
13761 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
13762 let key = self.realm.well_known_key(WellKnown::Iterator);
13763 let method = self.read_field_key(value, &key)?;
13764 if matches!(method, Value::Undefined | Value::Null) {
13765 return Ok(false);
13766 }
13767 if !matches!(&method, Value::Object(object) if object.is_callable()) {
13768 return Err(Signal::Throw(
13769 self.make_error("TypeError", "Symbol.iterator is not callable"),
13770 ));
13771 }
13772 Ok(true)
13773 }
13774
13775 /// Collect everything an iterable yields.
13776 ///
13777 /// The cap is a guard against a generator that never ends: an unbounded collect would
13778 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
13779 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
13780 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
13781 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
13782 const MAX_ITEMS: usize = 1 << 24;
13783 let iterator = self.get_iterator(value)?;
13784 let mut out = Vec::new();
13785 loop {
13786 let (element, done) = self.iterator_step(&iterator)?;
13787 if done {
13788 return Ok(out);
13789 }
13790 out.push(element);
13791 if out.len() > MAX_ITEMS {
13792 // Close before refusing: the walk is being abandoned, so the iterator's
13793 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
13794 // unrun and a locked resource unreleased.
13795 self.close_iterator_after_throw(&iterator)?;
13796 return Err(self.range_error("iterable is too long to collect"));
13797 }
13798 }
13799 }
13800
13801 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
13802 ///
13803 /// A native constructor calls this once it has validated its arguments, which is the
13804 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
13805 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
13806 /// never reached. The prototype comes from `new.target` when it is an object, and from
13807 /// `default_proto` otherwise.
13808 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
13809 let proto = self.ctor_prototype(default_proto)?;
13810 Ok(self.new_object(Some(proto)))
13811 }
13812
13813 /// An **array** whose prototype comes from `new.target`.
13814 ///
13815 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
13816 /// instance from `new.target.prototype`, and building a plain array instead made every
13817 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
13818 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
13819 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
13820 Ok(JsObject::array(self.heap, Some(proto), 0))
13821 }
13822
13823 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
13824 ///
13825 /// The `Option` form is for the constructors that build their instance in a helper which
13826 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
13827 /// from `await`'s internal promise, and only the first has a `new.target`.
13828 fn ctor_prototype_opt(
13829 &mut self,
13830 default_proto: Option<Gc<JsObject>>,
13831 ) -> JsResult<Option<Gc<JsObject>>> {
13832 // `active_new_target`: by the time a native constructor runs, `call_value` has
13833 // already consumed the parked value.
13834 let Some(target) = self
13835 .active_new_target
13836 .as_object()
13837 .cloned()
13838 .map(Value::Object)
13839 else {
13840 return Ok(default_proto);
13841 };
13842 let Some(target) = target.as_object().cloned() else {
13843 return Ok(default_proto);
13844 };
13845 match self.get_property(&target, "prototype")? {
13846 Some(Value::Object(proto)) => Ok(Some(proto)),
13847 _ => Ok(default_proto),
13848 }
13849 }
13850
13851 /// `new.target.prototype`, or `default_proto` when this is a plain call.
13852 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
13853 let Some(target) = self.active_new_target.as_object().cloned() else {
13854 return Ok(default_proto);
13855 };
13856 match self.get_property(&target, "prototype")? {
13857 Some(Value::Object(proto)) => Ok(proto),
13858 _ => Ok(default_proto),
13859 }
13860 }
13861
13862 /// `CreateDataPropertyOrThrow(O, key, value)`.
13863 ///
13864 /// A *definition*, not an assignment. The difference is visible the moment the target
13865 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
13866 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
13867 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
13868 /// refused (`configurable: false`).
13869 ///
13870 /// The fast path exists because this is called once per element by `map`, `filter`,
13871 /// `slice` and friends: a plain array with no custom element descriptors and a writable
13872 /// `length` can store straight into its element vector.
13873 pub fn create_data_property_or_throw(
13874 &mut self,
13875 object: &Gc<JsObject>,
13876 index: usize,
13877 value: Value,
13878 ) -> JsResult<()> {
13879 // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
13880 // an array (that is what `Array.isArray` must say), so the element fast path would
13881 // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
13882 // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
13883 // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
13884 // records the exact trap sequence.
13885 if object.proxy_state().is_none()
13886 && object.is_array()
13887 && object.elements_writable()
13888 && !object.has_element_descriptors()
13889 && object.is_extensible()
13890 && object.array_set(self.heap, index, value.clone())
13891 {
13892 return Ok(());
13893 }
13894 let key = PropertyKey::from(index.to_string());
13895 let property = Property {
13896 value: Some(value),
13897 writable: true,
13898 enumerable: true,
13899 configurable: true,
13900 ..Property::default()
13901 };
13902 // `CreateDataProperty` always asks for the default attributes, so it can only ever
13903 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
13904 // the rest. Checking here rather than inside `object_define_own_property` is
13905 // deliberate: that function receives a fully-populated `Property` and cannot tell
13906 // an omitted attribute from an explicit `false`, so the generic check it would need
13907 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
13908 // writable property (that cost eight `Object/defineProperty` tests).
13909 if object.proxy_state().is_none()
13910 && let Some(existing) = self.object_get_own_property(object, &key)?
13911 && !existing.configurable
13912 {
13913 return Err(self.type_error("cannot create the property"));
13914 }
13915 if self.object_define_own_property(object, &key, property)? {
13916 return Ok(());
13917 }
13918 Err(self.type_error("cannot create the property"))
13919 }
13920
13921 /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
13922 ///
13923 /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
13924 /// its callers have; this is the same operation for the named properties a built-in
13925 /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
13926 /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
13927 /// `Array.prototype` cannot see it — while `Set` would run that accessor.
13928 pub fn create_named_data_property_or_throw(
13929 &mut self,
13930 object: &Gc<JsObject>,
13931 key: &str,
13932 value: Value,
13933 ) -> JsResult<()> {
13934 let key = PropertyKey::from(key);
13935 let property = Property {
13936 value: Some(value),
13937 writable: true,
13938 enumerable: true,
13939 configurable: true,
13940 ..Property::default()
13941 };
13942 if object.proxy_state().is_none()
13943 && let Some(existing) = self.object_get_own_property(object, &key)?
13944 && !existing.configurable
13945 {
13946 return Err(self.type_error("cannot create the property"));
13947 }
13948 if self.object_define_own_property(object, &key, property)? {
13949 return Ok(());
13950 }
13951 Err(self.type_error("cannot create the property"))
13952 }
13953
13954 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
13955 ///
13956 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
13957 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
13958 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
13959 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
13960 /// run user code and both can throw.
13961 pub fn species_constructor(
13962 &mut self,
13963 object: &Gc<JsObject>,
13964 default: Value,
13965 ) -> JsResult<Value> {
13966 let Some(constructor) = self.get_property(object, "constructor")? else {
13967 return Ok(default);
13968 };
13969 let constructor = match constructor {
13970 Value::Undefined => return Ok(default),
13971 Value::Object(constructor) => constructor,
13972 _ => return Err(self.type_error("constructor is not an object")),
13973 };
13974 let key = self.realm.well_known_key(WellKnown::Species);
13975 let species = self.get_property_key(&constructor, &key)?;
13976 match species {
13977 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
13978 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
13979 Some(_) => Err(self.type_error("species is not a constructor")),
13980 }
13981 }
13982
13983 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
13984 ///
13985 /// The result is an array of `length` holes whose prototype comes from
13986 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
13987 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
13988 /// is why the `IsArray` check is the first step and not an optimisation.
13989 pub fn array_species_create(
13990 &mut self,
13991 original: &Value,
13992 length: usize,
13993 ) -> JsResult<Gc<JsObject>> {
13994 // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
13995 // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
13996 // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
13997 // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
13998 // `new_array_of_length` (`slice/create-non-array-invalid-len`).
13999 // `ArrayCreate(length)` is only reached when the result is a **plain array of this
14000 // realm** — the species may be a user function that ignores the length entirely, and
14001 // then `2**53 - 1` is not its problem
14002 // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
14003 // a short proxy and expects the copy loop to run).
14004 let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
14005 if length > ARRAY_CREATE_LIMIT {
14006 return Err(interp.range_error("invalid array length"));
14007 }
14008 Ok(interp.new_array_of_length(length))
14009 };
14010 let Some(object) = original.as_object().cloned() else {
14011 return default(self);
14012 };
14013 if !object.is_array() {
14014 return default(self);
14015 }
14016 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
14017 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
14018 let Some(constructor) = self.get_property(&object, "constructor")? else {
14019 return default(self);
14020 };
14021 let species = match constructor {
14022 Value::Undefined => return Ok(self.new_array_of_length(length)),
14023 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
14024 return default(self);
14025 }
14026 Value::Object(constructor) => {
14027 let key = self.realm.well_known_key(WellKnown::Species);
14028 match self.get_property_key(&constructor, &key)? {
14029 None | Some(Value::Undefined) | Some(Value::Null) => {
14030 return default(self);
14031 }
14032 Some(species) => species,
14033 }
14034 }
14035 // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
14036 // is a `TypeError`, not "the default". Treating it as the default made
14037 // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
14038 // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
14039 // `concat/create-ctor-non-object` are the same rule three times.
14040 _ => return Err(self.type_error("constructor is not an object")),
14041 };
14042 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
14043 // that is merely callable is the `create-species-non-ctor` case.
14044 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
14045 return Err(self.type_error("species is not a constructor"));
14046 }
14047 // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
14048 // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
14049 // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
14050 let created = self.construct(
14051 species.clone(),
14052 species,
14053 vec![crate::object::length_value(length)],
14054 )?;
14055 let Some(created) = created.as_object().cloned() else {
14056 return Err(self.type_error("species constructor did not answer an object"));
14057 };
14058 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
14059 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
14060 // object, and `create-species-with-non-writable-property` asserts exactly that.
14061 // The length is set for the array case; the generic case is the caller's
14062 // `Set(A, "length", …)`.
14063 if created.is_array() {
14064 created.array_set_length(self.heap, length);
14065 }
14066 Ok(created)
14067 }
14068
14069 /// Whether `object` is this realm's `%Array%`.
14070 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
14071 self.realm
14072 .array_constructor
14073 .as_ref()
14074 .is_some_and(|array| array.ptr_eq(object))
14075 }
14076
14077 /// A fresh `length`-hole array with the intrinsic prototype.
14078 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
14079 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
14080 array.array_set_length(self.heap, length);
14081 array
14082 }
14083
14084 /// Whether this call is a construction, i.e. `new.target` is defined.
14085 ///
14086 /// A native constructor receives `this = undefined` (it builds its own instance), so it
14087 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
14088 /// The native function currently executing, if any.
14089 pub fn current_native(&self) -> Option<Gc<JsObject>> {
14090 self.current_native.clone()
14091 }
14092
14093 /// Whether this call is a construction, i.e. `new.target` is defined.
14094 pub fn is_constructing(&self) -> bool {
14095 // `active_new_target`, not `pending_new_target`: the parked value is consumed by
14096 // `call_value` before a native runs, so by the time a constructor body asks, the
14097 // answer is only in the active slot.
14098 matches!(self.active_new_target, Value::Object(_))
14099 }
14100
14101 /// The `TypeError` a constructor too primitive to have a wrapper raises.
14102 ///
14103 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
14104 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
14105 /// happens inside the native function, which is why the trace carries an
14106 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
14107 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
14108 /// constructor`, and an unnamed one reports the leading space of `" is not a
14109 /// constructor"` because the reference formats the empty name as it is.
14110 ///
14111 /// It is also the answer for a `new.target` that cannot be named at all — not a
14112 /// function, or a throwing `name` getter — where the reference falls back to the bare
14113 /// `not a constructor`.
14114 pub fn not_a_constructor_error(&mut self) -> Signal {
14115 let target = self.active_new_target.clone();
14116 self.not_a_constructor_error_for(target)
14117 }
14118
14119 /// The same `TypeError` for an explicit target, for the callers that check
14120 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
14121 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
14122 let target = match target {
14123 Value::Object(target) if target.is_callable() => target,
14124 _ => return self.type_error("not a constructor"),
14125 };
14126 let name = match self.get_property(&target, "name") {
14127 Ok(Some(value)) => value.to_js_string(),
14128 _ => return self.type_error("not a constructor"),
14129 };
14130 self.type_error(format!("{name} is not a constructor"))
14131 }
14132
14133 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
14134 ///
14135 /// True whenever `new.target` is not the callee itself, or when it has no usable
14136 /// `prototype` — the cases where reading the property is observable at all.
14137 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
14138 match &self.active_new_target {
14139 Value::Object(target) => !target.ptr_eq(callee),
14140 Value::Undefined => false,
14141 _ => true,
14142 }
14143 }
14144
14145 /// The symbol key for one of the engine's own hidden slots.
14146 ///
14147 /// Cached on the realm, so every object of a kind shares one key and a slot can be
14148 /// read back by name.
14149 /// Whether any object on `object`'s **prototype chain** owns an array index.
14150 ///
14151 /// The one question the array methods' dense fast paths have to ask before touching the
14152 /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
14153 /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
14154 /// vector an unreliable answer. Walking the chain once per call is cheap because a
14155 /// prototype almost never holds an index.
14156 pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
14157 let mut current = object.proto();
14158 // Bounded, like every other prototype walk here: a proxy can answer a cycle.
14159 for _ in 0..10_000 {
14160 let Some(proto) = current else {
14161 return false;
14162 };
14163 if proto.has_indexed_own_property() {
14164 return true;
14165 }
14166 current = proto.proto();
14167 }
14168 false
14169 }
14170
14171 /// The hidden symbol a named internal slot is keyed by, created on first use.
14172 ///
14173 /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
14174 /// either keeping a table of its own.
14175 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
14176 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
14177 return PropertyKey::Symbol(symbol.clone());
14178 }
14179 let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
14180 self.realm
14181 .internal_slots
14182 .borrow_mut()
14183 .insert(name, Value::Symbol(symbol.clone()));
14184 PropertyKey::Symbol(symbol)
14185 }
14186
14187 /// Read a hidden slot, or `None` when the object has none of that name.
14188 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
14189 let slots = self.realm.internal_slots.borrow();
14190 let Value::Symbol(symbol) = slots.get(name)? else {
14191 return None;
14192 };
14193 object
14194 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
14195 .and_then(|property| property.value)
14196 }
14197
14198 /// Define a hidden slot.
14199 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
14200 let key = self.internal_slot(name);
14201 object.define_key(&key, Property::with_attributes(value, false, false));
14202 }
14203
14204 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
14205 ///
14206 /// The method is looked up on the value (through its prototype), called with no
14207 /// arguments, and its result becomes the iterator. A generator gets here through
14208 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
14209 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
14210 ///
14211 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
14212 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
14213 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
14214 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
14215 /// does, and a user-defined iterable works without a special case.
14216 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
14217 /// `Symbol.iterator`.
14218 ///
14219 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
14220 /// iterable is legal there, and each value it produces is simply already settled by
14221 /// the time the `await` around it runs.
14222 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14223 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
14224 let method = self.read_field_key(value, &async_key)?;
14225 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
14226 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
14227 // is *present but not callable* is a TypeError — it does not mean "try the other
14228 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
14229 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
14230 // guard is there to catch.
14231 let absent = matches!(method, Value::Undefined | Value::Null);
14232 if !absent {
14233 let Value::Object(object) = &method else {
14234 return Err(Signal::Throw(
14235 self.make_error("TypeError", "value is not iterable"),
14236 ));
14237 };
14238 if !object.is_callable() {
14239 return Err(Signal::Throw(
14240 self.make_error("TypeError", "value is not iterable"),
14241 ));
14242 }
14243 }
14244 if absent {
14245 return self.get_iterator(value);
14246 }
14247 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14248 if !matches!(iterator, Value::Object(_)) {
14249 return Err(Signal::Throw(
14250 self.make_error("TypeError", "iterator is not an object"),
14251 ));
14252 }
14253 // §7.4.2 `GetIteratorFromMethod` step 3.b: `GetIteratorDirect` reads `next` and
14254 // §7.4.1 requires it to be **callable** straight away — a throwing `return` must
14255 // not be reached, because the `TypeError` comes before any stepping
14256 // (`fromEntries/iterator-not-closed-for-uncallable-next`).
14257 let next = self.read_field(&iterator, "next")?;
14258 if !matches!(&next, Value::Object(function) if function.is_callable()) {
14259 return Err(Signal::Throw(
14260 self.make_error("TypeError", "iterator's next method is not callable"),
14261 ));
14262 }
14263 Ok(Iterator {
14264 object: iterator,
14265 next,
14266 })
14267 }
14268
14269 /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
14270 /// read — `@@iterator` is **not** consulted.
14271 ///
14272 /// The distinction is observable and test262 exercises it: a set-like object's `keys`
14273 /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
14274 /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
14275 /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
14276 /// refused it with "[object Object] is not iterable".
14277 pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
14278 if !matches!(value, Value::Object(_)) {
14279 return Err(self.type_error("iterator is not an object"));
14280 }
14281 let next = self.read_field(&value, "next")?;
14282 Ok(Iterator {
14283 object: value,
14284 next,
14285 })
14286 }
14287
14288 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14289 let key = self.realm.well_known_key(WellKnown::Iterator);
14290 let method = self.read_field_key(value, &key)?;
14291 let Value::Object(function) = &method else {
14292 return Err(Signal::Throw(self.make_error(
14293 "TypeError",
14294 &format!("{} is not iterable", value.to_js_string()),
14295 )));
14296 };
14297 if !function.is_callable() {
14298 return Err(Signal::Throw(self.make_error(
14299 "TypeError",
14300 &format!("{} is not iterable", value.to_js_string()),
14301 )));
14302 }
14303 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14304 // The spec requires an object here; a primitive iterator has no `next` to call
14305 // and would fail one step later with a confusing message.
14306 if !matches!(iterator, Value::Object(_)) {
14307 return Err(Signal::Throw(
14308 self.make_error("TypeError", "iterator is not an object"),
14309 ));
14310 }
14311 // `GetIteratorDirect` requires `next` to be **callable** right away, before any
14312 // stepping and therefore before any `return` can be reached
14313 // (`fromEntries/iterator-not-closed-for-uncallable-next`).
14314 let next = self.read_field(&iterator, "next")?;
14315 if !matches!(&next, Value::Object(function) if function.is_callable()) {
14316 return Err(Signal::Throw(
14317 self.make_error("TypeError", "iterator's next method is not callable"),
14318 ));
14319 }
14320 Ok(Iterator {
14321 object: iterator,
14322 next,
14323 })
14324 }
14325
14326 /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
14327 /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
14328 /// exception from `return` propagates normally instead of being swallowed. That is the
14329 /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
14330 /// because confusing them is exactly the bug both exist to avoid.
14331 pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
14332 let method = self.read_field(&iterator.object, "return")?;
14333 if matches!(method, Value::Undefined | Value::Null) {
14334 return Ok(());
14335 }
14336 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14337 return Err(self.type_error("iterator return is not a function"));
14338 }
14339 self.call_value(method, iterator.object.clone(), Vec::new())?;
14340 Ok(())
14341 }
14342
14343 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
14344 /// cannot replace it.
14345 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
14346 let method = self.read_field(&iterator.object, "return")?;
14347 if matches!(method, Value::Undefined | Value::Null) {
14348 return Ok(());
14349 }
14350 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14351 return Err(self.type_error("iterator return is not a function"));
14352 }
14353 self.call_value(method, iterator.object.clone(), Vec::new())?;
14354 Ok(())
14355 }
14356
14357 /// One step of an internal iterator: the value and whether it is exhausted.
14358 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
14359 // A real iterator (`next` is a function) answers with a result object.
14360 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
14361 let result =
14362 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
14363 let Some(result) = result.as_object().cloned() else {
14364 return Err(self.type_error("iterator result is not an object"));
14365 };
14366 let done = self
14367 .get_property(&result, "done")?
14368 .is_some_and(|value| value.to_boolean());
14369 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
14370 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
14371 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
14372 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
14373 // made an unrelated `value` getter observable after the loop was over.
14374 if done {
14375 return Ok((Value::Undefined, true));
14376 }
14377 let value = self
14378 .get_property(&result, "value")?
14379 .unwrap_or(Value::Undefined);
14380 return Ok((value, false));
14381 }
14382 // An iterator whose `next` is not callable is treated as exhausted, which is
14383 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
14384 // that are not iterable at all.
14385 Ok((Value::Undefined, true))
14386 }
14387
14388 /// `[...iterable]`: append everything the iterator yields, and answer the next
14389 /// index.
14390 ///
14391 /// This goes through the same iterator machinery `for-of` uses rather than copying
14392 /// an array's elements, because a spread source is any iterable: a string spreads
14393 /// into its characters and an array iterator spreads into its results. Handling
14394 /// only arrays made `[..."ab"]` come out empty with no error at all.
14395 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
14396 let Some(target) = array.as_object().cloned() else {
14397 return Ok(0);
14398 };
14399 let start = target.array_length().unwrap_or(0);
14400 let mut added = 0;
14401 let iterator = self.get_iterator(iterable)?;
14402 loop {
14403 let (value, done) = self.iterator_step(&iterator)?;
14404 if done {
14405 break;
14406 }
14407 target.array_set(self.heap, start + added, value);
14408 added += 1;
14409 }
14410 Ok((start + added) as i32)
14411 }
14412
14413 /// How an uncaught exception is reported.
14414 ///
14415 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
14416 /// with `ToString` — `js_std_dump_error` is three lines that end in
14417 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
14418 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
14419 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
14420 ///
14421 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
14422 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
14423 /// `toString`"; it does call it, but only for objects of a class it does not know how
14424 /// to walk, and never for errors, arrays or plain objects.
14425 ///
14426 /// A printer that fails must not take the reporter down with it, so that case falls
14427 /// back to the `ToString` rendering.
14428 pub fn describe_exception(&mut self, value: &Value) -> String {
14429 match crate::print::sprint(self, value) {
14430 Ok(text) => text,
14431 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
14432 }
14433 }
14434
14435 /// The file name of whatever is running, innermost frame first.
14436 ///
14437 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
14438 /// innermost frame's file name, without distinguishing a module body from a plain
14439 /// script. `import()` uses it as the base for a relative specifier, which is why
14440 /// `import('./x.js')` inside a script resolves next to the script and not next to the
14441 /// process's working directory.
14442 pub fn script_or_module_name(&self) -> Option<String> {
14443 self.script_or_module_name_at(0)
14444 }
14445
14446 /// [`Interp::script_or_module_name`] `level` frames further out.
14447 ///
14448 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
14449 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
14450 /// frame without a file name is skipped rather than counted, because a native call
14451 /// pushes no frame of its own and so cannot be a level.
14452 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
14453 self.frames
14454 .iter()
14455 .rev()
14456 .filter_map(|frame| frame.code.code.filename.clone())
14457 .nth(level)
14458 }
14459
14460 /// The current call stack, formatted the way `qjs` prints `error.stack`.
14461 ///
14462 /// One ` at name (file:line:col)` line per active frame, innermost first. The
14463 /// position is the one recorded for the instruction each frame is stopped on, which
14464 /// is why the compiler builds a pc-to-position table per function: without it a
14465 /// trace could only name the function, not the line inside it.
14466 ///
14467 /// A frame whose code has no positions prints just `(file)`, matching the
14468 /// reference's output for stripped bytecode.
14469 pub fn stack_trace(&self) -> String {
14470 self.stack_trace_skipping(0)
14471 }
14472
14473 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
14474 fn stack_trace_skipping(&self, skip: usize) -> String {
14475 // One ordered list, innermost first, so `skip` counts the same thing whether the
14476 // frames it leaves out are native or bytecode. Indices rather than references: a
14477 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
14478 let depth = self.frames.len();
14479 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
14480 // A native entered while `at` bytecode frames were live was called *from* the
14481 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
14482 // entered at the current depth are therefore innermost of all.
14483 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
14484 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
14485 if *at == wanted {
14486 order.push((true, index));
14487 }
14488 }
14489 };
14490 push_natives(&mut order, depth);
14491 for index in (0..depth).rev() {
14492 order.push((false, index));
14493 push_natives(&mut order, index);
14494 }
14495 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
14496 // barrier. Natives entered at exactly the barrier depth are the eval entry point
14497 // itself (`evalScript (native)`), and the reference leaves those out too.
14498 if let Some(barrier) = self.trace_barriers.last().copied() {
14499 order.retain(|(is_native, index)| match is_native {
14500 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
14501 false => *index >= barrier,
14502 });
14503 }
14504
14505 let mut out = String::new();
14506 for (is_native, index) in order.into_iter().skip(skip) {
14507 match is_native {
14508 true => {
14509 out.push_str(" at ");
14510 let (native, _) = &self.native_frames[index];
14511 let name = native
14512 .own_property("name")
14513 .and_then(|property| property.value)
14514 .map(|value| value.to_js_string())
14515 .unwrap_or_default();
14516 out.push_str(&name);
14517 out.push_str(" (native)\n");
14518 }
14519 false => {
14520 let frame = &self.frames[index];
14521 let code = &frame.code.code;
14522 let file = code.filename.as_deref().unwrap_or("<input>");
14523 // The name comes from the function *object*, not from the compiled code:
14524 // an anonymous function expression is named by the property it is stored
14525 // in (`{valueOf: function(){}}`), which only the object knows.
14526 let bound_name = match &frame.callee {
14527 Value::Object(object) => {
14528 object
14529 .own_property("name")
14530 .and_then(|property| match property.value {
14531 Some(Value::String(text)) if !text.wtf8().is_empty() => {
14532 Some(text.to_string_lossy().into_owned())
14533 }
14534 _ => None,
14535 })
14536 }
14537 _ => None,
14538 };
14539 // No callee object means the body was entered by the host, so the
14540 // name has to come from the compiled code. Two cases differ:
14541 //
14542 // * an *unnamed* function of any kind — the reference reads the
14543 // `name` property, finds it empty, and prints `<anonymous>`;
14544 // * a *module* body, which has no `name` property at all: the
14545 // reference builds that function object with `js_closure2` and
14546 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
14547 // so a trace reaching it also prints `<anonymous>` — while a
14548 // *script* body prints `<eval>`, its `name`.
14549 let unnamed = code.name.is_empty() || code.module.is_some();
14550 out.push_str(" at ");
14551 match bound_name.as_deref() {
14552 Some(name) => out.push_str(name),
14553 None if unnamed => out.push_str("<anonymous>"),
14554 None => out.push_str(&code.name),
14555 }
14556 match code.position_at(frame.at as u32) {
14557 Some((line, column)) => {
14558 out.push_str(&format!(" ({file}:{line}:{column})\n"));
14559 }
14560 None => out.push_str(&format!(" ({file})\n")),
14561 }
14562 }
14563 }
14564 }
14565 out
14566 }
14567
14568 /// Give an anonymous function the name of the property it is stored in.
14569 ///
14570 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
14571 /// enumerable and not configurable, and a function that already has a real name
14572 /// keeps it.
14573 ///
14574 /// "Already named" means a *non-empty* name: every function object is created with
14575 /// a `name` of `""` so the property exists on all of them, and treating that empty
14576 /// string as a name left every anonymous function nameless — which is how a stack
14577 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
14578 /// `SetFunctionName`, for a name that came from source text.
14579 fn set_function_name(&mut self, function: &Value, name: &str) {
14580 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
14581 }
14582
14583 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
14584 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
14585 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
14586 let Value::Object(object) = function else {
14587 return;
14588 };
14589 // `SetFunctionName` applies to *functions* and classes only, and only when they are
14590 // anonymous. Without the callability guard, `{value: someObject}` renamed
14591 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
14592 // on the right-hand side of a property. That is how a `zipKeyed` result object
14593 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
14594 // has no `NamedEvaluation` at all.
14595 if !object.is_callable() {
14596 return;
14597 }
14598 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
14599 && !existing.wtf8().is_empty()
14600 {
14601 return;
14602 }
14603 let text = self.string_wtf8(name.clone());
14604 object.define("name", Property::name_or_length(text));
14605 }
14606
14607 // -- global declarations -----------------------------------------------
14608
14609 /// Declare a global binding, creating its reference cell.
14610 /// Declare a `var` or function global, whose home is the global object.
14611 ///
14612 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
14613 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
14614 /// such as `print`, or a redeclaration — is left alone.
14615 pub fn declare_var_global(&mut self, name: &str) {
14616 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
14617 // global object is exactly the leak `typeof my_var === "undefined"` after
14618 // `eval("var my_var=2")` rules out.
14619 if let Some(scope) = self.eval_scope.as_mut() {
14620 scope.entry(name.to_string()).or_insert(Value::Undefined);
14621 return;
14622 }
14623 // A sloppy direct eval declares into its *caller's* variable environment. Doing
14624 // this on the global object instead made `eval("var c = 1")` inside a parameter
14625 // list overwrite a global `c`, and made two calls to the same function share one
14626 // binding.
14627 if let Some(cell) = self.declare_eval_local(name) {
14628 cell.set(Value::Undefined);
14629 return;
14630 }
14631 let global = self.realm.global.clone();
14632 if global.own_property(name).is_some() {
14633 return;
14634 }
14635 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
14636 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
14637 // whole point of that trick and what lets `Object.defineProperty` reshape it
14638 // afterwards. `eval_scope` is `Some` while an eval is running.
14639 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
14640 global.define(
14641 name,
14642 Property {
14643 value: Some(Value::Undefined),
14644 writable: true,
14645 enumerable: true,
14646 configurable: from_eval,
14647 ..Property::default()
14648 },
14649 );
14650 }
14651
14652 /// Declare a *lexical* global binding, which starts in its dead zone.
14653 ///
14654 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
14655 /// global object and is created when its initialiser runs.
14656 pub fn declare_global(&mut self, name: &str, is_const: bool) {
14657 if is_const {
14658 self.realm.lexical_consts.insert(name.to_string());
14659 }
14660 if !self.realm.globals.contains_key(name) {
14661 // `Uninitialized` rather than `Undefined`: the binding exists but is not
14662 // readable until its initialiser runs, and that is what `let x` before
14663 // `x = 1` has to observe.
14664 let cell = self.new_cell(Value::Uninitialized);
14665 self.realm.globals.insert(name.to_string(), cell);
14666 self.realm.declared.push(name.to_string());
14667 }
14668 }
14669}
14670
14671/// The bytecode and environment of a function object, if it is a bytecode function.
14672///
14673/// Extracted before a call so no borrow of the object is held across it.
14674fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
14675 function.with(|data| match &data.kind {
14676 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
14677 _ => None,
14678 })
14679}
14680
14681/// A native call target, extracted before the call so no borrow is held.
14682enum NativeCall {
14683 Native(NativeFn),
14684 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
14685 /// not hold that object's `RefCell` borrow.
14686 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
14687 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
14688 Bound {
14689 target: Value,
14690 this: Value,
14691 leading: Vec<Value>,
14692 },
14693 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
14694 Revoker(crate::object::ProxyRef),
14695 /// A promise's `resolve`.
14696 PromiseResolve(Gc<JsObject>),
14697 /// A promise's `reject`.
14698 PromiseReject(Gc<JsObject>),
14699 /// The executor `NewPromiseCapability(C)` hands a user constructor.
14700 CapabilityExecutor {
14701 state: Gc<JsObject>,
14702 },
14703 /// One leg of a `then` that settles through a user capability.
14704 ThenShim {
14705 handler: Option<Value>,
14706 resolve: Value,
14707 reject: Value,
14708 fulfilled: bool,
14709 },
14710 /// One continuation of an `await`.
14711 AwaitResume {
14712 coroutine: Gc<JsObject>,
14713 promise: Gc<JsObject>,
14714 kind: ResumeKind,
14715 },
14716 /// One element of a `Promise` combinator settling.
14717 CombinatorSettle {
14718 state: Gc<JsObject>,
14719 index: usize,
14720 fulfilled: bool,
14721 },
14722 /// One of `Promise.prototype.finally`'s two shims.
14723 FinallyShim {
14724 callback: Option<Value>,
14725 fulfilled: bool,
14726 constructor: Value,
14727 },
14728 /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
14729 ReturnValue(Value),
14730 /// A thunk that throws a fixed value, for `finally`'s `thrower`.
14731 ThrowValue(Value),
14732 /// Settle a promise with a fixed outcome.
14733 SettlePromise {
14734 promise: Gc<JsObject>,
14735 value: Value,
14736 rejected: bool,
14737 },
14738 /// Continue an async generator after its `await` settled.
14739 GeneratorResume {
14740 generator: Gc<JsObject>,
14741 promise: Gc<JsObject>,
14742 kind: ResumeKind,
14743 },
14744 /// Read a module namespace's binding out of its cell.
14745 ModuleBinding(Gc<Cell>),
14746 /// Finish a completed async generator's `return(v)` once `v` has settled.
14747 CompletedReturn {
14748 generator: Gc<JsObject>,
14749 promise: Gc<JsObject>,
14750 rejected: bool,
14751 },
14752 /// Answer a pending async-generator method with `{value, done}`.
14753 YieldResult {
14754 generator: Gc<JsObject>,
14755 promise: Gc<JsObject>,
14756 done: bool,
14757 },
14758 /// One step of `AsyncDisposableStack.disposeAsync`.
14759 DisposeStep {
14760 remaining: Gc<JsObject>,
14761 promise: Gc<JsObject>,
14762 error: Value,
14763 rejected: bool,
14764 },
14765}
14766
14767/// What a store does when the object refuses the write.
14768#[derive(Clone, Copy, PartialEq, Eq)]
14769pub enum DeleteFailure {
14770 /// Raise a `TypeError`, which is what strict mode and every built-in does.
14771 Throw,
14772 /// Ignore the write, which is what a sloppy-mode assignment does.
14773 Ignore,
14774}
14775
14776/// Whether `object` is a `Date` instance, by the class tag it carries.
14777///
14778/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
14779/// builtins module depending on the interpreter's conversion order.
14780fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
14781 interp
14782 .internal_get(object, "_class")
14783 .is_some_and(|value| value.to_js_string() == "Date")
14784}
14785
14786/// Which type `ToPrimitive` prefers when it converts an object.
14787#[derive(Clone, Copy, PartialEq, Eq)]
14788pub enum Hint {
14789 /// The default hint, which behaves like [`Hint::Number`].
14790 Default,
14791 /// `Number(obj)` and the arithmetic operators.
14792 Number,
14793 /// `String(obj)` and `ToPropertyKey`.
14794 String,
14795}
14796
14797/// Which table a binding slot indexes, for the messages that name it.
14798#[derive(Clone, Copy)]
14799enum VarSlot {
14800 Loc,
14801 Closure,
14802}
14803
14804/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
14805fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
14806 Ok(this)
14807}
14808
14809/// An internal iterator: the sequence plus a cursor.
14810pub(crate) struct Iterator {
14811 pub(crate) object: Value,
14812 pub(crate) next: Value,
14813}
14814
14815/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
14816/// and plain `a` for a method.
14817///
14818/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
14819/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
14820/// reads `at get a (file:1:2)`.
14821/// The same prefixing, for a name that may hold an unpaired surrogate.
14822fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
14823 let prefix = match flags & 3 {
14824 1 => "get ",
14825 2 => "set ",
14826 _ => return key.clone(),
14827 };
14828 let mut units: Vec<u16> = prefix.encode_utf16().collect();
14829 units.extend_from_slice(&key.to_units());
14830 crate::value::Wtf8::from_units(&units)
14831}
14832
14833fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
14834 match flags & 3 {
14835 1 => format!("get {key}"),
14836 2 => format!("set {key}"),
14837 _ => key.to_string(),
14838 }
14839}
14840
14841/// Define a method or accessor property, per the `define_method` flag byte.
14842///
14843/// The low two bits pick value/getter/setter and bit 2 marks the property
14844/// enumerable.
14845///
14846/// A getter and a setter arrive as two separate `define_method` instructions, and the
14847/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
14848/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
14849/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
14850/// `JS_DefineProperty`, which leaves the other half alone.
14851fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
14852 let enumerable = flags & 4 != 0;
14853 let kind = flags & 3;
14854 let existing = object.own_property_key(key);
14855 let property = match kind {
14856 1 => Property {
14857 getter: Some(function),
14858 // The setter half, if this literal already defined one.
14859 setter: existing
14860 .filter(Property::is_accessor)
14861 .and_then(|p| p.setter),
14862 enumerable,
14863 configurable: true,
14864 ..Property::default()
14865 },
14866 2 => Property {
14867 getter: existing
14868 .filter(Property::is_accessor)
14869 .and_then(|p| p.getter),
14870 setter: Some(function),
14871 enumerable,
14872 configurable: true,
14873 ..Property::default()
14874 },
14875 _ => Property {
14876 value: Some(function),
14877 writable: true,
14878 enumerable,
14879 configurable: true,
14880 ..Property::default()
14881 },
14882 };
14883 object.define_key(key, property);
14884}
14885
14886// ---------------------------------------------------------------------------
14887// Operand decoding
14888// ---------------------------------------------------------------------------
14889
14890/// How `print` renders a value: the reference's `JS_PrintValue`.
14891///
14892/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
14893/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
14894/// The format is reproduced closely because the test suite compares output text:
14895///
14896/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
14897/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
14898/// * a cycle prints `[circular N]` with `N` the stack index of the object;
14899/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
14900/// end print as `<N empty item(s)>`;
14901/// * a string is quoted inside a container but raw at the top level, which is why
14902/// `print("x")` and `print(["x"])` differ.
14903pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
14904 // A string argument is printed raw: `js_print` converts it with `ToString`
14905 // instead of dumping it, and the quoting only appears inside a container.
14906 if let Value::String(text) = value {
14907 return text.to_string_lossy().into_owned();
14908 }
14909 let mut printer = Printer {
14910 interp,
14911 out: String::new(),
14912 stack: Vec::new(),
14913 };
14914 printer.value(value, 0);
14915 printer.out
14916}
14917
14918/// The internal class name an object carries, when it has one.
14919fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
14920 interp
14921 .internal_get(object, "_class")
14922 .map(|value| value.to_js_string())
14923}
14924
14925/// A string property, looked up the way `GetProperty` does: own first, then the
14926/// prototype chain. Needed because the print formatter holds the interpreter
14927/// immutably and so cannot run getters.
14928fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
14929 let mut current = Some(object.clone());
14930 // Bounded, because a prototype cycle would otherwise loop forever.
14931 for _ in 0..100 {
14932 let node = current?;
14933 if let Some(property) = node.own_property(name)
14934 && let Some(value) = property.value
14935 {
14936 return Some(value.to_js_string());
14937 }
14938 current = node.with(|data| data.proto.clone());
14939 }
14940 None
14941}
14942
14943/// The `JS_PrintValue` state: output, and the objects currently being printed.
14944struct Printer<'a, 'rt> {
14945 /// Kept for the class-name lookups that typed arrays and `Date` will need.
14946 #[allow(dead_code)]
14947 interp: &'a Interp<'rt>,
14948 out: String,
14949 stack: Vec<Gc<JsObject>>,
14950}
14951
14952impl Printer<'_, '_> {
14953 /// Depth past which a container is summarised by its class name.
14954 const MAX_DEPTH: usize = 2;
14955
14956 fn value(&mut self, value: &Value, level: usize) {
14957 match value {
14958 Value::Undefined
14959 | Value::Uninitialized
14960 | Value::Hole
14961 | Value::CatchOffset(_)
14962 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
14963 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
14964 // The printer writes a bigint the way the language spells one, so a dump is
14965 // unambiguous about which kind of number it is showing.
14966 Value::BigInt(big) => {
14967 self.out.push_str(&big.to_decimal_string());
14968 self.out.push('n');
14969 }
14970 Value::Null => self.out.push_str("null"),
14971 Value::Bool(true) => self.out.push_str("true"),
14972 Value::Bool(false) => self.out.push_str("false"),
14973 Value::Int(number) => self.out.push_str(&number.to_string()),
14974 Value::Float(number) => {
14975 self.out
14976 .push_str(&crate::value::number_to_string_for_print(*number));
14977 }
14978 Value::String(text) => self.print_string(&text.to_string_lossy()),
14979 Value::Object(object) => self.object(object, level),
14980 }
14981 }
14982
14983 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
14984 // A cycle is reported rather than followed; the index is where the object
14985 // already sits in the print stack, which is what the reference shows.
14986 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
14987 self.out.push_str(&format!("[circular {index}]"));
14988 return;
14989 }
14990 if object.is_callable() {
14991 let name = object
14992 .own_property("name")
14993 .and_then(|property| property.value)
14994 .map(|value| value.to_js_string())
14995 .unwrap_or_default();
14996 if name.is_empty() {
14997 self.out.push_str("[Function (anonymous)]");
14998 } else {
14999 self.out.push_str(&format!("[Function {name}]"));
15000 }
15001 return;
15002 }
15003 if level >= Self::MAX_DEPTH {
15004 let class = if object.is_array() { "Array" } else { "Object" };
15005 self.out.push_str(&format!("[{class}]"));
15006 return;
15007 }
15008 // `Date` and `Error` print as themselves rather than as bags of properties:
15009 // the ISO string, and `Name: message` followed by the trace.
15010 if let Some(class) = class_of(self.interp, object) {
15011 if class == "Date" {
15012 self.date(object);
15013 return;
15014 }
15015 if class == "Error" {
15016 self.error(object);
15017 return;
15018 }
15019 }
15020 self.stack.push(object.clone());
15021 if object.is_array() {
15022 self.array(object, level);
15023 } else {
15024 self.plain_object(object, level);
15025 }
15026 self.stack.pop();
15027 }
15028
15029 /// A Date prints as its ISO string; an invalid one falls through to the plain
15030 /// object form, the way the reference falls back when `toISOString` throws.
15031 fn date(&mut self, object: &Gc<JsObject>) {
15032 let value = self
15033 .interp
15034 .internal_get(object, "_date_value")
15035 .map(|value| value.to_number());
15036 match value.and_then(crate::builtins::date::iso_string) {
15037 Some(text) => self.out.push_str(&text),
15038 None => self.plain_object(object, 0),
15039 }
15040 }
15041
15042 /// `Name: message`, then the trace with its trailing newline removed.
15043 fn error(&mut self, object: &Gc<JsObject>) {
15044 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
15045 self.out.push_str(&name);
15046 if let Some(message) = inherited(object, "message")
15047 && !message.is_empty()
15048 {
15049 self.out.push_str(": ");
15050 self.out.push_str(&message);
15051 }
15052 if let Some(stack) = inherited(object, "stack") {
15053 self.out.push('\n');
15054 self.out.push_str(stack.trim_end_matches('\n'));
15055 }
15056 }
15057
15058 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
15059 let elements = object.array_elements().unwrap_or_default();
15060 self.out.push_str("[ ");
15061 // An interior hole means the array is "sparse": the reference prints those
15062 // as `index: value` pairs and says nothing about the holes themselves, while
15063 // a hole run at the end becomes a single `<N empty items>` note.
15064 let last_present = elements
15065 .iter()
15066 .rposition(|value| !matches!(value, Value::Hole));
15067 let has_interior_hole = match last_present {
15068 Some(last) => elements[..last]
15069 .iter()
15070 .any(|value| matches!(value, Value::Hole)),
15071 None => false,
15072 };
15073 let mut first = true;
15074 if has_interior_hole {
15075 let mut index = 0;
15076 while index < elements.len() {
15077 let value = &elements[index];
15078 if matches!(value, Value::Hole) {
15079 index += 1;
15080 continue;
15081 }
15082 if !first {
15083 self.out.push_str(", ");
15084 }
15085 first = false;
15086 self.out.push_str(&format!("{index}: "));
15087 self.value(value, level + 1);
15088 index += 1;
15089 }
15090 } else {
15091 for (index, value) in elements.iter().enumerate() {
15092 if matches!(value, Value::Hole) {
15093 continue;
15094 }
15095 if !first {
15096 self.out.push_str(", ");
15097 }
15098 first = false;
15099 let _ = index;
15100 self.value(value, level + 1);
15101 }
15102 if let Some(last) = last_present {
15103 let trailing = elements.len() - last - 1;
15104 if trailing > 0 {
15105 if !first {
15106 self.out.push_str(", ");
15107 }
15108 self.out.push_str(&format!(
15109 "<{trailing} empty item{}>",
15110 if trailing > 1 { "s" } else { "" }
15111 ));
15112 }
15113 } else if !elements.is_empty() {
15114 let count = elements.len();
15115 self.out.push_str(&format!(
15116 "<{count} empty item{}>",
15117 if count > 1 { "s" } else { "" }
15118 ));
15119 }
15120 }
15121 self.out.push_str(" ]");
15122 }
15123
15124 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
15125 self.out.push_str("{ ");
15126 let mut first = true;
15127 for key in object.own_keys() {
15128 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
15129 continue;
15130 };
15131 if !property.enumerable {
15132 continue;
15133 }
15134 if !first {
15135 self.out.push_str(", ");
15136 }
15137 first = false;
15138 self.out
15139 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
15140 &key.to_string_lossy(),
15141 )));
15142 self.out.push_str(": ");
15143 // An accessor has no value to dump; the reference names the half that
15144 // exists instead of calling it.
15145 if property.is_accessor() {
15146 let text = match (property.getter.is_some(), property.setter.is_some()) {
15147 (true, true) => "[Getter/Setter]",
15148 (false, true) => "[Setter]",
15149 _ => "[Getter]",
15150 };
15151 self.out.push_str(text);
15152 } else {
15153 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
15154 }
15155 }
15156 self.out.push_str(" }");
15157 }
15158
15159 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
15160 fn print_string(&mut self, text: &str) {
15161 self.out.push('"');
15162 for character in text.chars() {
15163 match character {
15164 '"' => self.out.push_str("\\\""),
15165 '\\' => self.out.push_str("\\\\"),
15166 '\n' => self.out.push_str("\\n"),
15167 '\r' => self.out.push_str("\\r"),
15168 '\t' => self.out.push_str("\\t"),
15169 c if (c as u32) < 0x20 => {
15170 self.out.push_str(&format!("\\u{:04x}", c as u32));
15171 }
15172 c => self.out.push(c),
15173 }
15174 }
15175 self.out.push('"');
15176 }
15177}
15178
15179/// How `print` renders a value.
15180///
15181/// `ToString`, except that negative zero keeps its sign — the reference's host
15182/// printer does that while `String(-0)` is `"0"`.
15183pub fn display(value: &Value) -> String {
15184 match value {
15185 Value::Float(number) => crate::value::number_to_string_for_print(*number),
15186 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
15187 "undefined".to_string()
15188 }
15189 other => other.to_js_string(),
15190 }
15191}
15192
15193// ---------------------------------------------------------------------------
15194// Numeric operators
15195// ---------------------------------------------------------------------------
15196
15197/// `a + b` keeping the `Int` representation when it fits.
15198fn add_numbers(left: Value, right: Value) -> Value {
15199 match (&left, &right) {
15200 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
15201 Some(sum) => Value::Int(sum),
15202 None => Value::Float(*a as f64 + *b as f64),
15203 },
15204 _ => Value::Float(left.to_number() + right.to_number()),
15205 }
15206}
15207
15208/// The arithmetic operators other than `+`, which needs string concatenation.
15209fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15210 use Opcode::*;
15211 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
15212 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
15213 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
15214 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
15215 return Ok(match op {
15216 And => Value::Int(x & y),
15217 Or => Value::Int(x | y),
15218 Xor => Value::Int(x ^ y),
15219 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
15220 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
15221 Shr => match (*x as u32) >> ((*y as u32) & 31) {
15222 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
15223 shifted => Value::Float(shifted as f64),
15224 },
15225 Sub => match x.checked_sub(*y) {
15226 Some(value) => Value::Int(value),
15227 None => Value::Float(*x as f64 - *y as f64),
15228 },
15229 _ => return arithmetic_slow(op, left, right),
15230 });
15231 }
15232 arithmetic_slow(op, left, right)
15233}
15234
15235/// [`arithmetic`] for everything the integer fast path above does not take.
15236fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15237 use Opcode::*;
15238 let (a, b) = (left.to_number(), right.to_number());
15239 Ok(match op {
15240 Sub => match (&left, &right) {
15241 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
15242 Some(value) => Value::Int(value),
15243 None => Value::Float(a - b),
15244 },
15245 _ => Value::Float(a - b),
15246 },
15247 Mul => Value::Float(a * b),
15248 Div => Value::Float(a / b),
15249 Mod => Value::Float(js_mod(a, b)),
15250 Pow => Value::Float(a.powf(b)),
15251 And => Value::Int(left.to_int32() & right.to_int32()),
15252 Or => Value::Int(left.to_int32() | right.to_int32()),
15253 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
15254 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
15255 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
15256 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
15257 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
15258 // fits the small-integer representation stays an `Int`; the rest become a
15259 // float, which is how the reference keeps `n >>> 0` non-negative.
15260 Shr => {
15261 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
15262 match i32::try_from(shifted) {
15263 Ok(value) => Value::Int(value),
15264 Err(_) => Value::Float(shifted as f64),
15265 }
15266 }
15267 _ => Value::Float(a),
15268 })
15269}
15270
15271/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
15272///
15273/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
15274/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
15275/// slow path where the rules live.
15276fn is_number(value: &Value) -> bool {
15277 matches!(value, Value::Int(_) | Value::Float(_))
15278}
15279
15280/// The `Value::Bool` a comparison operator answers for `ordering`.
15281///
15282/// `None` is the unordered case — a `NaN` on either side — and every operator answers
15283/// false for it, including `<=` and `>=`.
15284fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
15285 use Opcode::*;
15286 let answer = match (op, ordering) {
15287 (_, None) => false,
15288 (Lt, Some(ordering)) => ordering.is_lt(),
15289 (Lte, Some(ordering)) => ordering.is_le(),
15290 (Gt, Some(ordering)) => ordering.is_gt(),
15291 (Gte, Some(ordering)) => ordering.is_ge(),
15292 _ => false,
15293 };
15294 Value::Bool(answer)
15295}
15296
15297/// `%`, which follows the sign of the dividend rather than Rust's.
15298fn js_mod(left: f64, right: f64) -> f64 {
15299 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
15300 return f64::NAN;
15301 }
15302 if right.is_infinite() {
15303 return left;
15304 }
15305 let remainder = left % right;
15306 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
15307 // the spec makes the sign match the dividend.
15308 if remainder == 0.0 {
15309 0.0f64.copysign(left)
15310 } else {
15311 remainder
15312 }
15313}
15314
15315fn negate(value: Value) -> Value {
15316 match value {
15317 Value::Int(0) => Value::Float(-0.0),
15318 Value::Int(i) => Value::Int(-i),
15319 other => Value::Float(-other.to_number()),
15320 }
15321}
15322
15323fn increment(value: Value) -> Value {
15324 match value {
15325 Value::Int(i) => match i.checked_add(1) {
15326 Some(next) => Value::Int(next),
15327 None => Value::Float(i as f64 + 1.0),
15328 },
15329 other => Value::Float(other.to_number() + 1.0),
15330 }
15331}
15332
15333fn decrement(value: Value) -> Value {
15334 match value {
15335 Value::Int(i) => match i.checked_sub(1) {
15336 Some(next) => Value::Int(next),
15337 None => Value::Float(i as f64 - 1.0),
15338 },
15339 other => Value::Float(other.to_number() - 1.0),
15340 }
15341}
15342
15343/// Compare a `BigInt` with an `f64` on their mathematical values.
15344///
15345/// Neither side is rounded to the other's precision: the number is split into its integer
15346/// part (compared as an exact bigint) and its fraction, which is what decides the answer
15347/// when the integer parts are equal. An infinite value is larger than every bigint.
15348fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
15349 use std::cmp::Ordering;
15350 if number.is_nan() {
15351 return None;
15352 }
15353 if number.is_infinite() {
15354 return Some(if number > 0.0 {
15355 Ordering::Less
15356 } else {
15357 Ordering::Greater
15358 });
15359 }
15360 let truncated = number.trunc();
15361 // A number wider than `i128` still has an exact integer part, but no bigint form we can
15362 // build cheaply; the sign of the difference is all that is needed, so compare against
15363 // the bigint's own magnitude instead.
15364 if truncated.abs() >= 1.7e38 {
15365 let big_as_f64 = big.to_f64();
15366 return big_as_f64.partial_cmp(&number);
15367 }
15368 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
15369 match big.cmp(&integer) {
15370 Ordering::Equal => {
15371 // Same integer part: the fraction decides, and a negative number's fraction is
15372 // below the integer (`-1.5` truncates to `-1`).
15373 if number > truncated {
15374 Some(Ordering::Less)
15375 } else if number < truncated {
15376 Some(Ordering::Greater)
15377 } else {
15378 Some(Ordering::Equal)
15379 }
15380 }
15381 other => Some(other),
15382 }
15383}
15384
15385/// `CanonicalNumericIndexString(argument)` (§7.1.21).
15386///
15387/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
15388/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
15389/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
15390/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
15391/// rather than treating it as `0`.
15392fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
15393 let PropertyKey::String(text) = key else {
15394 // A symbol is never an index.
15395 return None;
15396 };
15397 let text = text.to_string_lossy();
15398 if text == "-0" {
15399 return Some(-0.0);
15400 }
15401 let number: f64 = text.parse().ok()?;
15402 // The round-trip test *is* the definition: only the canonical spelling qualifies.
15403 // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
15404 // `"0.10"` does not.
15405 let rendered = Value::Float(number).to_js_string();
15406 (rendered == text).then_some(number)
15407}
15408
15409/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
15410///
15411/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
15412/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
15413/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
15414/// numeric and invalid, which is why they stop the prototype chain instead of falling
15415/// through it.
15416///
15417/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
15418/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
15419/// `in`, `delete` and `defineProperty` separately to make sure it does not.
15420fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
15421 numeric.is_finite()
15422 && numeric.fract() == 0.0
15423 && !(numeric == 0.0 && numeric.is_sign_negative())
15424 && numeric >= 0.0
15425 && object
15426 .typed_array_length()
15427 .is_some_and(|length| (numeric as usize) < length)
15428}
15429
15430/// `ArrayCreate`'s length bound, `2**32 - 1`.
15431///
15432/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
15433/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
15434/// through — can enforce it without depending on a builtin module.
15435const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;