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 // §27.2.4.6 step 5: `? Call(resolve, undefined, «x»)` — an exception from a
1855 // *user* resolve function propagates (`resolve/capability-invocation-error`), while
1856 // the intrinsic one swallows its own self-resolution error.
1857 self.call_value(resolve, Value::Undefined, vec![value])?;
1858 Ok(promise)
1859 }
1860
1861 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1862 /// promise, as `{ value: completion }`.
1863 ///
1864 /// The three cases are the reference's, and they differ on purpose:
1865 ///
1866 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1867 /// exception before any promise exists;
1868 /// * a **runtime** error rejects the returned promise;
1869 /// * success resolves it with `{ value }`, where the value is the script's completion
1870 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1871 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1872 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1873 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1874 ///
1875 /// # What this does not do
1876 ///
1877 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1878 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1879 /// the parser and the suspension machinery to accept a suspended top-level script, and
1880 /// is not implemented — such source is a syntax error here. Everything else about the
1881 /// flag is reproduced.
1882 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1883 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1884 // too, and the reference truncates that one at the same place as a runtime failure.
1885 if barrier {
1886 let depth = self.frames.len();
1887 self.trace_barriers.push(depth);
1888 }
1889 // Compiled before the promise exists, so a parse failure propagates as a throw
1890 // instead of being folded into a rejection.
1891 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1892 Ok(compiled) => compiled,
1893 Err(error) => {
1894 if barrier {
1895 self.trace_barriers.pop();
1896 }
1897 return Err(error);
1898 }
1899 };
1900 // An async body answers its own promise, and that promise is what the reference
1901 // hands back — the same object, not a wrapper around it. Its resolution value is
1902 // the `{value}` object the compiled epilogue built.
1903 if compiled.kind.is_async() {
1904 let strict = compiled.strict;
1905 let promise = self.run_eval_script(compiled, strict)?;
1906 if barrier {
1907 self.trace_barriers.pop();
1908 }
1909 return Ok(promise);
1910 }
1911 let (promise, resolve, reject) = self.new_promise_capability();
1912 let strict = compiled.strict;
1913 match self.run_eval_script(compiled, strict) {
1914 Ok(value) => {
1915 // `{ value }` is a plain object, so resolving with it adopts nothing even
1916 // when the completion value is itself a promise.
1917 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1918 self.set_property(&wrapped, "value", value)?;
1919 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1920 }
1921 Err(Signal::Throw(error)) => {
1922 self.call_value(reject, Value::Undefined, vec![error])?;
1923 }
1924 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1925 }
1926 if barrier {
1927 self.trace_barriers.pop();
1928 }
1929 Ok(Value::Object(promise))
1930 }
1931
1932 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1933 ///
1934 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1935 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1936 /// timer table, where the collector already scans it.
1937 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1938 let (promise, resolve, _reject) = self.new_promise_capability();
1939 let resolve = self.new_host_function(
1940 "resolve",
1941 1,
1942 Box::new(
1943 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1944 let value = args.first().cloned().unwrap_or(Value::Undefined);
1945 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1946 },
1947 ),
1948 );
1949 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1950 // timer table is part of what the collector walks.
1951 self.schedule_timer(Value::Object(resolve), delay_ms);
1952 Ok(Value::Object(promise))
1953 }
1954
1955 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1956 /// new promise resolved with it.
1957 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1958 if let Value::Object(object) = &value
1959 && self.promise_state(object).is_some()
1960 {
1961 return Ok(value);
1962 }
1963 let promise = self.new_promise();
1964 self.resolve_promise_with(&promise, value)?;
1965 Ok(Value::Object(promise))
1966 }
1967
1968 /// §27.2.4.7 `PromiseResolve(%Promise%, value)`.
1969 ///
1970 /// The difference from [`Interp::promise_resolve_value`] is step 1.a: when `value` is
1971 /// already a promise, its **`constructor` is read**, and only if that is the intrinsic
1972 /// `%Promise%` is `value` returned unchanged. A getter placed on `constructor` is
1973 /// therefore observable — which is exactly what
1974 /// `AsyncGeneratorPrototype/return/return-*-broken-promise*.js` use to check that the
1975 /// `AsyncGeneratorAwaitReturn` path goes through `PromiseResolve` rather than a private
1976 /// shortcut.
1977 pub fn promise_resolve_intrinsic(&mut self, value: Value) -> JsResult<Value> {
1978 if let Value::Object(object) = &value
1979 && self.promise_state(object).is_some()
1980 {
1981 let constructor = self.get_property(object, "constructor")?;
1982 let same = match (&constructor, &self.realm.promise_constructor) {
1983 (Some(Value::Object(found)), Some(intrinsic)) => found.ptr_eq(intrinsic),
1984 _ => false,
1985 };
1986 if same {
1987 return Ok(value);
1988 }
1989 }
1990 let promise = self.new_promise();
1991 self.resolve_promise_with(&promise, value)?;
1992 Ok(Value::Object(promise))
1993 }
1994
1995 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
1996 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
1997 // Resolving a promise with itself is a `TypeError`. The check exists because the
1998 // alternative is a chain of self-reactions that never settles.
1999 if let Value::Object(object) = &value
2000 && object.ptr_eq(promise)
2001 {
2002 // The spec rejects *and* throws, so both the promise and the caller see it.
2003 let thrown = self.type_error("cannot resolve a promise with itself");
2004 let Signal::Throw(error) = thrown.clone() else {
2005 unreachable!("type_error always throws")
2006 };
2007 self.reject_promise(promise, error);
2008 return Err(thrown);
2009 }
2010 // §27.2.1.3.1 `NewPromiseResolveThenableJob` step 3: `Get(resolution, "then")` is a
2011 // `Completion`, and an abrupt one **rejects** the promise rather than throwing to
2012 // whoever resolved it — a poisoned `then` getter is the case every
2013 // `*-poisoned-then` test is written against.
2014 let then = match &value {
2015 Value::Object(object) => match self.get_property(object, "then") {
2016 Ok(then) => then,
2017 Err(signal) => {
2018 if let Signal::Throw(reason) = signal {
2019 self.reject_promise(promise, reason);
2020 return Ok(());
2021 }
2022 return Err(signal);
2023 }
2024 },
2025 _ => None,
2026 };
2027 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
2028 if !callable_then {
2029 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
2030 self.fulfill_promise(promise, value);
2031 return Ok(());
2032 }
2033 // Adopting a thenable is asynchronous — `then` is called from a job, never from
2034 // inside `resolve`, so a script cannot make a promise settle synchronously.
2035 self.jobs.push_back(Job::Thenable {
2036 then: then.expect("checked callable"),
2037 value,
2038 promise: promise.clone(),
2039 });
2040 Ok(())
2041 }
2042
2043 /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
2044 ///
2045 /// `C.resolve` is user code and may answer a plain thenable rather than one of this
2046 /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
2047 ///
2048 /// The property read is **not** short-circuitable even for a real promise: the spec says
2049 /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
2050 /// expects it to run. Skipping the read for promises not only lost the throw, it made
2051 /// the combinator's loop infinite — the test's iterator never sets `done`.
2052 pub fn invoke_then(
2053 &mut self,
2054 thenable: Value,
2055 on_fulfilled: Value,
2056 on_rejected: Value,
2057 ) -> JsResult<()> {
2058 let then = match &thenable {
2059 Value::Object(object) => self.get_property(object, "then")?,
2060 primitive => {
2061 let boxed = self.object_from(primitive)?;
2062 self.get_property(&boxed, "then")?
2063 }
2064 };
2065 let Some(then) = then else {
2066 return Err(self.type_error("thenable has no then method"));
2067 };
2068 if !matches!(&then, Value::Object(object) if object.is_callable()) {
2069 return Err(self.type_error("then is not a function"));
2070 }
2071 self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
2072 Ok(())
2073 }
2074
2075 /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
2076 ///
2077 /// `Promise.prototype.then` in one step: register a reaction and answer the derived
2078 /// promise.
2079 pub fn perform_then(
2080 &mut self,
2081 promise: &Gc<JsObject>,
2082 on_fulfilled: Option<Value>,
2083 on_rejected: Option<Value>,
2084 ) -> JsResult<Value> {
2085 let Some(state) = self.promise_state(promise) else {
2086 return Err(self.type_error("not a promise"));
2087 };
2088 // Whether a rejection handler is being attached decides whether a recorded
2089 // rejection stops being unhandled, so it is read before the values are moved.
2090 let has_rejection_handler = on_rejected.is_some();
2091 let derived = self.new_promise();
2092 let reaction = crate::object::PromiseReaction {
2093 on_fulfilled,
2094 on_rejected,
2095 promise: derived.clone(),
2096 };
2097 let settled = {
2098 let mut state = state.borrow_mut();
2099 // A rejection somebody reacts to is no longer unhandled.
2100 state.handled = true;
2101 match &state.status {
2102 crate::object::PromiseStatus::Pending => {
2103 state.reactions.push(reaction.clone());
2104 None
2105 }
2106 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2107 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2108 }
2109 };
2110 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2111 // later, means somebody is listening after all.
2112 if has_rejection_handler {
2113 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2114 }
2115 if let Some((argument, rejected)) = settled {
2116 let handler = if rejected {
2117 reaction.on_rejected
2118 } else {
2119 reaction.on_fulfilled
2120 };
2121 self.jobs.push_back(Job::Reaction {
2122 handler,
2123 argument,
2124 rejected,
2125 promise: reaction.promise,
2126 });
2127 }
2128 Ok(Value::Object(derived))
2129 }
2130
2131 /// The rejections nobody listened to, formatted the way the reference reports them.
2132 ///
2133 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2134 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2135 /// unhandled at the point the queue drains, because a `then` may still be attached
2136 /// before the host acts on it.
2137 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2138 let entries = std::mem::take(&mut self.unhandled);
2139 // Somebody may have attached a handler after the rejection was recorded, so the
2140 // promise is the authority rather than the list.
2141 let still_unhandled: Vec<Value> = entries
2142 .into_iter()
2143 .filter_map(|(promise, reason)| {
2144 let handled = self
2145 .promise_state(&promise)
2146 .map(|state| state.borrow().handled)
2147 .unwrap_or(true);
2148 (!handled).then_some(reason)
2149 })
2150 .collect();
2151 still_unhandled
2152 .into_iter()
2153 .map(|reason| {
2154 let text = self.describe_exception(&reason);
2155 let stack = match &reason {
2156 Value::Object(object) => self
2157 .get_property(object, "stack")
2158 .ok()
2159 .flatten()
2160 .map(|value| value.to_js_string())
2161 // `stack` carries a trailing newline of its own, which would leave
2162 // a blank line between two reported rejections.
2163 .map(|text| text.trim_end().to_string())
2164 .unwrap_or_default(),
2165 _ => String::new(),
2166 };
2167 if stack.is_empty() {
2168 format!("Possibly unhandled promise rejection: {text}")
2169 } else {
2170 format!("Possibly unhandled promise rejection: {text}\n{stack}")
2171 }
2172 })
2173 .collect()
2174 }
2175
2176 /// Run the microtask queue to exhaustion.
2177 ///
2178 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2179 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2180 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2181 ///
2182 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2183 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2184 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2185 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2186 crate::builtins::json::parse_text(self, text, true)
2187 }
2188
2189 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2190 ///
2191 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2192 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2193 /// immediately, and `setTimeout(f, -1)` is ordinary code.
2194 ///
2195 /// The callback is called with **no arguments**. The reference stores only the function
2196 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2197 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2198 /// extra arguments arrive as `undefined`.
2199 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2200 let id = self.next_timer_id;
2201 // Wrap rather than grow: the id reaches the script as an `Int32`.
2202 self.next_timer_id = if self.next_timer_id == i32::MAX {
2203 1
2204 } else {
2205 self.next_timer_id + 1
2206 };
2207 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2208 self.tasks.push(Task::Timer {
2209 id,
2210 callback,
2211 due_at,
2212 });
2213 id
2214 }
2215
2216 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2217 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2218 pub fn cancel_timer(&mut self, id: i32) -> bool {
2219 let before = self.tasks.len();
2220 self.tasks.retain(|task| match task {
2221 Task::Timer { id: task_id, .. } => *task_id != id,
2222 });
2223 self.tasks.len() != before
2224 }
2225
2226 /// How long until the earliest pending timer, or `None` when none is pending.
2227 pub fn next_timeout(&self) -> Option<std::time::Duration> {
2228 let now = std::time::Instant::now();
2229 self.tasks
2230 .iter()
2231 .map(|task| match task {
2232 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2233 })
2234 .min()
2235 }
2236
2237 /// Run one turn of the event loop.
2238 ///
2239 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2240 /// run at most one due timer, then drain again. The blocking belongs to the caller
2241 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2242 /// is how it asks.
2243 ///
2244 /// One timer per turn rather than all of them: a timer callback may schedule another
2245 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2246 /// starve the microtask queue.
2247 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2248 self.drain_jobs()?;
2249 let now = std::time::Instant::now();
2250 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2251 // followed by `setTimeout(g, 1)` must run `g` first.
2252 let due = self
2253 .tasks
2254 .iter()
2255 .enumerate()
2256 .filter(|(_, task)| match task {
2257 Task::Timer { due_at, .. } => *due_at <= now,
2258 })
2259 .min_by_key(|(_, task)| match task {
2260 Task::Timer { due_at, .. } => *due_at,
2261 })
2262 .map(|(index, _)| index);
2263 let Some(index) = due else {
2264 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2265 // descriptor is registered but no timer is closer, so a script that never
2266 // touches the descriptor still gets control back. Without a cap a handler on a
2267 // descriptor that is never ready would block for as long as the host allows.
2268 let timeout = self
2269 .next_timeout()
2270 .unwrap_or(std::time::Duration::from_secs(10))
2271 .min(std::time::Duration::from_secs(10));
2272 if !self.fd_handlers.is_empty() {
2273 // Blocking on a timer while descriptors are registered would starve them,
2274 // and blocking on the descriptors while a timer is due would delay it; the
2275 // host polls with the earlier of the two deadlines, which this timeout is.
2276 return Ok(Turn::Poll(timeout));
2277 }
2278 return Ok(match self.next_timeout() {
2279 Some(wait) => Turn::Wait(wait),
2280 None => Turn::Done,
2281 });
2282 };
2283 let Task::Timer { callback, .. } = self.tasks.remove(index);
2284 let this = Value::Undefined;
2285 // A throwing timer callback must not stop the loop: the reference reports it and
2286 // keeps going, because the alternative is that one bad timer silently stops every
2287 // later one.
2288 // No arguments: see `schedule_timer` — the reference calls the callback bare.
2289 match self.call_value(callback, this, Vec::new()) {
2290 Ok(_) => {}
2291 Err(Signal::Throw(value)) => {
2292 let text = self.describe_exception(&value);
2293 self.timer_errors.push(text);
2294 }
2295 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2296 }
2297 self.drain_jobs()?;
2298 Ok(Turn::Ran)
2299 }
2300
2301 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2302 ///
2303 /// `callback` of `None` unregisters that direction, and an entry with neither direction
2304 /// left is removed — the reference does the same, so a script can rely on
2305 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2306 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2307 let entry = self.fd_handlers.entry(fd).or_default();
2308 if readable {
2309 entry.read = callback;
2310 } else {
2311 entry.write = callback;
2312 }
2313 if entry.read.is_none() && entry.write.is_none() {
2314 self.fd_handlers.remove(&fd);
2315 }
2316 }
2317
2318 /// Register or clear an `os.signal` handler.
2319 ///
2320 /// `None` removes it; the host separately restores the default disposition or sets
2321 /// ignore, because which of those happened is the script's choice (`null` versus
2322 /// `undefined`) and not something this table can express.
2323 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2324 match handler {
2325 Some(handler) => {
2326 self.signal_handlers.insert(signal, handler);
2327 }
2328 None => {
2329 self.signal_handlers.remove(&signal);
2330 }
2331 }
2332 }
2333
2334 /// Run the handler for `signal`, reporting whether one ran.
2335 ///
2336 /// A throwing handler is reported and the loop continues, like a timer's.
2337 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2338 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2339 return Ok(false);
2340 };
2341 match self.call_value(handler, Value::Undefined, Vec::new()) {
2342 Ok(_) => {}
2343 Err(Signal::Throw(value)) => {
2344 let text = self.describe_exception(&value);
2345 self.timer_errors.push(text);
2346 }
2347 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2348 }
2349 self.drain_jobs()?;
2350 Ok(true)
2351 }
2352
2353 /// The descriptors the host has to poll, and in which direction.
2354 ///
2355 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2356 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2357 /// `os_poll` asks for.
2358 pub fn pending_fds(&self) -> Vec<FdInterest> {
2359 self.fd_handlers
2360 .iter()
2361 .map(|(fd, entry)| FdInterest {
2362 fd: *fd,
2363 read: entry.read.is_some(),
2364 write: entry.write.is_some(),
2365 })
2366 .collect()
2367 }
2368
2369 /// Call the handler registered for `fd`, reporting whether one ran.
2370 ///
2371 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2372 /// poll iteration and then restarts the loop, because the handler may have changed the
2373 /// registration list underneath it; doing the same here keeps a handler that
2374 /// unregisters itself from being called with stale state.
2375 ///
2376 /// A throwing handler is reported and the loop continues — a bad handler must not stop
2377 /// every later one, exactly as with timers.
2378 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2379 let Some(entry) = self.fd_handlers.get(&fd) else {
2380 return Ok(false);
2381 };
2382 let callback = if readable {
2383 entry.read.clone()
2384 } else if writable {
2385 entry.write.clone()
2386 } else {
2387 None
2388 };
2389 let Some(callback) = callback else {
2390 return Ok(false);
2391 };
2392 self.drain_jobs()?;
2393 match self.call_value(callback, Value::Undefined, Vec::new()) {
2394 Ok(_) => {}
2395 Err(Signal::Throw(value)) => {
2396 let text = self.describe_exception(&value);
2397 self.timer_errors.push(text);
2398 }
2399 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2400 }
2401 self.drain_jobs()?;
2402 Ok(true)
2403 }
2404
2405 /// Take the errors timer callbacks threw, leaving the list empty.
2406 pub fn take_timer_errors(&mut self) -> Vec<String> {
2407 std::mem::take(&mut self.timer_errors)
2408 }
2409
2410 /// Whether anything is still pending: a microtask or a timer.
2411 pub fn has_pending_work(&self) -> bool {
2412 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2413 }
2414
2415 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2416 pub fn has_pending_timers_or_jobs(&self) -> bool {
2417 !self.jobs.is_empty() || !self.tasks.is_empty()
2418 }
2419
2420 /// Run every queued microtask, including ones queued while draining.
2421 pub fn drain_jobs(&mut self) -> JsResult<()> {
2422 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2423 // would spin forever, so the drain is bounded the way the call stack is.
2424 let mut budget = 1_000_000usize;
2425 while let Some(job) = self.jobs.pop_front() {
2426 if budget == 0 {
2427 return Err(Signal::Throw(
2428 self.make_error("InternalError", "promise job queue did not drain"),
2429 ));
2430 }
2431 budget -= 1;
2432 self.run_job(job)?;
2433 // `FinalizationRegistry` at the job boundary: this is the safe point where the
2434 // engine may run script that the script itself did not ask for. Doing it here
2435 // rather than from a drop hook is what keeps the callback out of arbitrary
2436 // engine bookkeeping — see `builtins::weak`'s header.
2437 crate::builtins::weak::drain_finalizers(self)?;
2438 }
2439 // A script that queued no jobs may still have dropped targets, so the checkpoint
2440 // runs once more after the queue empties.
2441 crate::builtins::weak::drain_finalizers(self)?;
2442 Ok(())
2443 }
2444
2445 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2446 ///
2447 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2448 /// `None` and is swept out here. This is also where the realm learns that a registry
2449 /// died, which is why it is a mutation rather than a read.
2450 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2451 let handles = std::mem::take(&mut self.realm.finalization_registries);
2452 let mut live = Vec::with_capacity(handles.len());
2453 for handle in handles {
2454 let Some(object) = handle.upgrade() else {
2455 continue;
2456 };
2457 let Some(state) = object.finalization_state() else {
2458 continue;
2459 };
2460 live.push((object.clone(), *state));
2461 self.realm.finalization_registries.push(object.downgrade());
2462 }
2463 live
2464 }
2465
2466 /// Run one microtask.
2467 fn run_job(&mut self, job: Job) -> JsResult<()> {
2468 match job {
2469 Job::Reaction {
2470 handler: None,
2471 argument,
2472 rejected,
2473 promise,
2474 } => {
2475 // No handler: the settlement passes straight through to the derived
2476 // promise, which is why `p.catch(f)` ignores fulfilments.
2477 if rejected {
2478 self.reject_promise(&promise, argument);
2479 } else {
2480 self.fulfill_promise(&promise, argument);
2481 }
2482 Ok(())
2483 }
2484 Job::Reaction {
2485 handler: Some(handler),
2486 argument,
2487 promise,
2488 ..
2489 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2490 Ok(answer) => {
2491 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2492 self.reject_promise(&promise, error);
2493 }
2494 Ok(())
2495 }
2496 Err(Signal::Throw(reason)) => {
2497 self.reject_promise(&promise, reason);
2498 Ok(())
2499 }
2500 Err(other) => Err(other),
2501 },
2502 Job::Thenable {
2503 then,
2504 value,
2505 promise,
2506 } => {
2507 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2508 // the value it produces settles `promise`.
2509 // The thenable's `then` gets this promise's own pair, so whatever it
2510 // produces settles `promise`.
2511 // `length: 1`, `name: ""` — a resolve/reject function is a
2512 // `%Promise.prototype.then%`-style pair, not a bare native. Building them
2513 // with `JsObject::function` left `length` at 0, which a test reads straight
2514 // off the function (`finally/resolved-observable-then-calls-argument`
2515 // requires `resolve.length === 1` for the pair handed to a thenable).
2516 let resolve =
2517 self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
2518 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
2519 match self.call_value(
2520 then,
2521 value,
2522 vec![Value::Object(resolve), Value::Object(reject)],
2523 ) {
2524 Ok(_) => Ok(()),
2525 Err(Signal::Throw(reason)) => {
2526 self.reject_promise(&promise, reason);
2527 Ok(())
2528 }
2529 Err(other) => Err(other),
2530 }
2531 }
2532 Job::Resume {
2533 coroutine,
2534 promise,
2535 kind,
2536 value,
2537 } => self.drive_async(&coroutine, &promise, kind, value),
2538 Job::GeneratorResume {
2539 generator,
2540 promise,
2541 kind,
2542 value,
2543 } => self.step_async_generator(&generator, &promise, kind, value),
2544 Job::Import {
2545 specifier,
2546 referrer,
2547 promise,
2548 } => {
2549 self.run_dynamic_import(&specifier, &referrer, &promise);
2550 Ok(())
2551 }
2552 }
2553 }
2554
2555 /// One element of a `Promise` combinator settled.
2556 ///
2557 /// The shared state object holds the result array, the number still outstanding, and
2558 /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2559 /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2560 /// to settle, only whatever `Sub` said a capability is.
2561 ///
2562 /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2563 /// and `any` must ignore every later settlement, and `all` must not report a second
2564 /// rejection after the first.
2565 fn settle_combinator(
2566 &mut self,
2567 state: &Gc<JsObject>,
2568 index: usize,
2569 fulfilled: bool,
2570 value: Value,
2571 ) -> JsResult<()> {
2572 let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2573 // Each element settles at most once: a thenable may call `onFulfilled` twice
2574 // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2575 // call a no-op. Without it the second call decremented `remaining` again and settled
2576 // `all` with a short values array (`call-resolve-element-items`).
2577 let done = field("done");
2578 let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2579 let settled = field("settled").is_some_and(|value| value.to_boolean());
2580 if settled {
2581 return Ok(());
2582 }
2583 if let Some(Value::Object(done)) = &done {
2584 if done
2585 .array_get(index)
2586 .is_some_and(|value| value.to_boolean())
2587 {
2588 return Ok(());
2589 }
2590 done.array_set(self.heap, index, Value::Bool(true));
2591 }
2592 let resolve = field("resolve");
2593 let reject = field("reject");
2594 let keys = field("keys");
2595 let results = field("results").and_then(|value| value.as_object().cloned());
2596 // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2597 // promise: the handler is a plain function the constructor chose.
2598 let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2599 if let Some(handler) = handler {
2600 interp.call_value(handler, Value::Undefined, vec![value])?;
2601 }
2602 Ok(())
2603 };
2604 match kind {
2605 // `race`: the first settlement wins and stops the rest.
2606 3 => {
2607 state.define_data("settled", Value::Bool(true));
2608 let handler = if fulfilled { resolve } else { reject };
2609 settle_with(self, handler, value)?;
2610 return Ok(());
2611 }
2612 // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2613 // the first rejection wins outright.
2614 0 | 4 if !fulfilled => {
2615 state.define_data("settled", Value::Bool(true));
2616 settle_with(self, reject, value)?;
2617 return Ok(());
2618 }
2619 // `any`: the first fulfilment wins.
2620 2 if fulfilled => {
2621 state.define_data("settled", Value::Bool(true));
2622 settle_with(self, resolve, value)?;
2623 return Ok(());
2624 }
2625 _ => {}
2626 }
2627 let Some(results) = &results else {
2628 return Ok(());
2629 };
2630 match kind {
2631 4 => {
2632 results.array_set(self.heap, index, value);
2633 }
2634 0 => {
2635 results.array_set(self.heap, index, value);
2636 }
2637 // `allSettled` (and its keyed twin) never rejects; each slot records what
2638 // happened.
2639 1 | 5 => {
2640 let record = self.new_object(Some(self.realm.object_proto.clone()));
2641 if fulfilled {
2642 record.define_data("status", self.string("fulfilled"));
2643 record.define_data("value", value);
2644 } else {
2645 record.define_data("status", self.string("rejected"));
2646 record.define_data("reason", value);
2647 }
2648 results.array_set(self.heap, index, Value::Object(record));
2649 }
2650 // `any`: a rejection is parked in the errors array and the sweep continues.
2651 2 => {
2652 results.array_set(self.heap, index, value);
2653 }
2654 _ => {}
2655 }
2656 let remaining = field("remaining")
2657 .map(|value| value.to_int32())
2658 .unwrap_or(0);
2659 let left = remaining - 1;
2660 state.define_data("remaining", Value::Int(left));
2661 if left != 0 {
2662 return Ok(());
2663 }
2664 state.define_data("settled", Value::Bool(true));
2665 match kind {
2666 0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2667 // The keyed result: an ordinary object with a **null** prototype, holding the
2668 // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2669 4 | 5 => {
2670 let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2671 settle_with(self, resolve, keyed)?;
2672 }
2673 2 => {
2674 // The rejection is an `AggregateError` whose `errors` is the results array
2675 // itself — the slots are the reasons, in input order.
2676 let errors = results.array_elements().unwrap_or_default();
2677 let error = self.aggregate_error(errors, "all promises were rejected");
2678 settle_with(self, reject, error)?;
2679 }
2680 _ => {}
2681 }
2682 Ok(())
2683 }
2684
2685 /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2686 ///
2687 /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2688 /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2689 /// prototype is load-bearing in both directions: a key called `toString` must not
2690 /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2691 /// (`resolves-empty-object.js`).
2692 pub(crate) fn keyed_result_object(
2693 &mut self,
2694 keys: Option<&Value>,
2695 values: &Gc<JsObject>,
2696 ) -> JsResult<Value> {
2697 let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2698 return Ok(Value::Object(self.new_object(None)));
2699 };
2700 let result = self.new_object(None);
2701 let count = values.array_length().unwrap_or(0);
2702 for index in 0..count {
2703 let Some(key) = keys.array_get(index) else {
2704 continue;
2705 };
2706 let Some(value) = values.array_get(index) else {
2707 continue;
2708 };
2709 let property = Property::with_attributes(value, true, true);
2710 match &key {
2711 Value::Symbol(symbol) => {
2712 result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2713 }
2714 other => {
2715 let text = self.to_js_string(other)?;
2716 result.define_key(&PropertyKey::from(text.as_str()), property);
2717 }
2718 }
2719 }
2720 Ok(Value::Object(result))
2721 }
2722
2723 /// Build an async function's result: a promise whose body runs as a coroutine.
2724 pub fn new_async_function(
2725 &mut self,
2726 function: Value,
2727 this: Value,
2728 args: Vec<Value>,
2729 ) -> JsResult<Value> {
2730 let promise = self.new_promise();
2731 let coroutine = self.new_coroutine(function, this, args)?;
2732 if let Err(Signal::Throw(reason)) =
2733 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2734 {
2735 self.reject_promise(&promise, reason);
2736 }
2737 Ok(Value::Object(promise))
2738 }
2739
2740 /// The coroutine an async body runs in.
2741 ///
2742 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2743 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2744 /// than growing a second state machine. The difference is only in the ending — a
2745 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2746 /// Run `code` as an async function body, answering the promise it settles.
2747 ///
2748 /// Used for a module with top-level `await`: its body is an async function whose
2749 /// caller is the host, so there is no function object to pass through
2750 /// [`Interp::new_async_function`].
2751 pub fn run_async_body(
2752 &mut self,
2753 code: Gc<CompiledCode>,
2754 env: Gc<ClosureEnv>,
2755 this: Value,
2756 ) -> JsResult<Value> {
2757 let promise = self.new_promise();
2758 let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2759 if let Err(Signal::Throw(reason)) =
2760 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2761 {
2762 self.reject_promise(&promise, reason);
2763 }
2764 Ok(Value::Object(promise))
2765 }
2766
2767 fn new_coroutine(
2768 &mut self,
2769 function: Value,
2770 this: Value,
2771 args: Vec<Value>,
2772 ) -> JsResult<Gc<JsObject>> {
2773 let Some(object) = function.as_object().cloned() else {
2774 return Err(self.type_error("not a function"));
2775 };
2776 let Some((code, env)) = bytecode_of(&object) else {
2777 return Err(self.type_error("not a function"));
2778 };
2779 self.new_coroutine_from(code, env, this, args)
2780 }
2781
2782 /// Build a coroutine over an already-resolved body.
2783 fn new_coroutine_from(
2784 &mut self,
2785 code: Gc<CompiledCode>,
2786 env: Gc<ClosureEnv>,
2787 this: Value,
2788 args: Vec<Value>,
2789 ) -> JsResult<Gc<JsObject>> {
2790 let function = Value::Undefined;
2791 self.push_frame(code, env, this, args, function)?;
2792 let frame = self.frames.pop().expect("push_frame just pushed it");
2793 let state = GeneratorState {
2794 frame: Some(frame),
2795 phase: GeneratorPhase::SuspendedStart,
2796 parked_on_await: false,
2797 parked_on_yield_star: false,
2798 requests: std::collections::VecDeque::new(),
2799 async_busy: false,
2800 // An `async function` body is driven by `drive_async`, never by the generator
2801 // protocol, and the object is not reachable from script.
2802 is_async: false,
2803 };
2804 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2805 coroutine.with_mut(|data| {
2806 data.kind = ObjectKind::Generator(Box::new(state));
2807 });
2808 Ok(coroutine)
2809 }
2810
2811 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2812 /// `await` and `value` is what it awaited.
2813 fn resume_coroutine(
2814 &mut self,
2815 coroutine: &Gc<JsObject>,
2816 kind: ResumeKind,
2817 value: Value,
2818 ) -> JsResult<(Value, bool)> {
2819 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2820 ObjectKind::Generator(state) => {
2821 let is_async = state.is_async;
2822 Some(std::mem::replace(
2823 state.as_mut(),
2824 GeneratorState {
2825 frame: None,
2826 phase: GeneratorPhase::Executing,
2827 parked_on_await: false,
2828 parked_on_yield_star: false,
2829 requests: std::collections::VecDeque::new(),
2830 async_busy: false,
2831 is_async,
2832 },
2833 ))
2834 }
2835 _ => None,
2836 }) else {
2837 return Err(self.type_error("not a coroutine"));
2838 };
2839 let result = self.step_generator(&mut state, kind, value);
2840 coroutine.with_mut(|data| {
2841 data.kind = ObjectKind::Generator(Box::new(state));
2842 });
2843 let (value, done, _ready, _reason) = result?;
2844 Ok((value, done))
2845 }
2846
2847 /// Advance an async body and settle its promise with the outcome.
2848 fn drive_async(
2849 &mut self,
2850 coroutine: &Gc<JsObject>,
2851 promise: &Gc<JsObject>,
2852 kind: ResumeKind,
2853 value: Value,
2854 ) -> JsResult<()> {
2855 match self.resume_coroutine(coroutine, kind, value) {
2856 Ok((value, true)) => {
2857 // `Ok` with `done` means the body finished *normally*, even when it was
2858 // resumed by a `throw` — `try { await p } catch {}` completes by
2859 // returning. Only the `Err` arm below is a rejection.
2860 //
2861 // Resolving rather than fulfilling matters: `return promise` in an async
2862 // body adopts the inner promise, so `async function f(){ return
2863 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2864 // promise.
2865 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2866 self.reject_promise(promise, reason);
2867 }
2868 Ok(())
2869 }
2870 Ok((value, false)) => {
2871 // Parked on `await`: follow what it awaited and resume with the outcome.
2872 let awaited = match self.promise_resolve_value(value) {
2873 Ok(awaited) => awaited,
2874 Err(Signal::Throw(error)) => {
2875 self.reject_promise(promise, error);
2876 return Ok(());
2877 }
2878 Err(other) => return Err(other),
2879 };
2880 self.hook_await(awaited, coroutine, promise)
2881 }
2882 Err(Signal::Throw(reason)) => {
2883 self.reject_promise(promise, reason);
2884 Ok(())
2885 }
2886 Err(other) => Err(other),
2887 }
2888 }
2889
2890 /// Arrange for `coroutine` to resume when `awaited` settles.
2891 fn hook_await(
2892 &mut self,
2893 awaited: Value,
2894 coroutine: &Gc<JsObject>,
2895 promise: &Gc<JsObject>,
2896 ) -> JsResult<()> {
2897 let resumed = JsObject::function(
2898 self.heap,
2899 Some(self.realm.function_proto.clone()),
2900 Callable::AwaitResume {
2901 coroutine: coroutine.clone(),
2902 promise: promise.clone(),
2903 kind: ResumeKind::Next,
2904 },
2905 );
2906 let raised = JsObject::function(
2907 self.heap,
2908 Some(self.realm.function_proto.clone()),
2909 Callable::AwaitResume {
2910 coroutine: coroutine.clone(),
2911 promise: promise.clone(),
2912 kind: ResumeKind::Throw,
2913 },
2914 );
2915 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2916 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2917 let Value::Object(awaited) = &awaited else {
2918 self.jobs.push_back(Job::Resume {
2919 coroutine: coroutine.clone(),
2920 promise: promise.clone(),
2921 kind: ResumeKind::Next,
2922 value: awaited,
2923 });
2924 return Ok(());
2925 };
2926 self.perform_then(
2927 awaited,
2928 Some(Value::Object(resumed)),
2929 Some(Value::Object(raised)),
2930 )?;
2931 Ok(())
2932 }
2933
2934 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2935 /// things an engine keeps outside it — array elements and an array's `length`.
2936 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2937 if let Some(property) = object.own_property_key(key) {
2938 return Some(property);
2939 }
2940 // A typed array's indices are bytes in its buffer, so a descriptor for one has to
2941 // be synthesized too — and every one of them is a plain writable, enumerable,
2942 // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
2943 // `undefined` before this, which made `key-is-numericindex` fail on its own
2944 // side effect check.
2945 //
2946 // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
2947 // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
2948 // likewise not elements however numeric they look.
2949 if object.typed_array_element_type().is_some()
2950 && let Some(numeric) = canonical_numeric_index(key)
2951 && numeric.is_finite()
2952 && numeric.fract() == 0.0
2953 && !(numeric == 0.0 && numeric.is_sign_negative())
2954 && numeric >= 0.0
2955 && (numeric as usize) < object.typed_array_length().unwrap_or(0)
2956 {
2957 let value = object.typed_array_element(numeric as usize)?;
2958 return Some(Property::data(value));
2959 }
2960 // An array's elements live in their own vector rather than the property table, so
2961 // a descriptor for one has to be synthesized — with the attributes an element has.
2962 if let Some(index) = key.as_str().and_then(array_index)
2963 && let Some(value) = object.array_get(index as usize)
2964 && !matches!(value, Value::Hole)
2965 {
2966 return Some(Property::data(value));
2967 }
2968 // `length` is an own property of an array that is not in its property table
2969 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
2970 // and non-enumerable.
2971 if key.as_str() == Some("length")
2972 && let Some(length) = object.array_length()
2973 {
2974 return Some(Property {
2975 value: Some(crate::object::length_value(length)),
2976 writable: object.length_writable(),
2977 enumerable: false,
2978 configurable: false,
2979 getter: None,
2980 setter: None,
2981 descriptor_fields: None,
2982 });
2983 }
2984 None
2985 }
2986
2987 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
2988 pub fn object_get_own_property(
2989 &mut self,
2990 object: &Gc<JsObject>,
2991 key: &PropertyKey,
2992 ) -> JsResult<Option<Property>> {
2993 if let Some(answer) = self.proxy_get_own_property(object, key)? {
2994 return Ok(answer);
2995 }
2996 if let Some(exotic) = object.exotic()
2997 && let Some(answer) = exotic.get_own_property(self, object, key)?
2998 {
2999 return Ok(answer);
3000 }
3001 // A mapped `arguments` index is a data property as far as script can see: the
3002 // accessor pair that aliases the parameter is plumbing, and exposing it would
3003 // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
3004 // report a `get` where the spec has a `[[Value]]`.
3005 if let Some(index) = key.as_str().and_then(crate::object::array_index)
3006 && let Some(cell) = object.mapped_argument_cell(index as usize)
3007 {
3008 // Non-configurable is *not* the default: an ordinary mapped index is
3009 // configurable, and only becomes non-configurable once something
3010 // redefines it. Preserve whatever the property table currently says.
3011 // The attributes come from whatever the property table holds, because they
3012 // can be changed independently of the mapping; only the *value* and the
3013 // data-property *kind* are the accessor's secret.
3014 let flags = Self::ordinary_own_property(object, key);
3015 if let Some(existing) = &flags
3016 && !existing.is_accessor()
3017 {
3018 // Already demapped: the table entry is the answer, not the cell.
3019 return Ok(flags);
3020 }
3021 return Ok(Some(Property {
3022 value: Some(cell.get()),
3023 writable: true,
3024 enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
3025 configurable: flags.as_ref().is_some_and(|p| p.configurable),
3026 ..Property::default()
3027 }));
3028 }
3029 Ok(Self::ordinary_own_property(object, key))
3030 }
3031
3032 /// §7.3.40 `SetterThatIgnoresPrototypeProperties(thisValue, home, propertyKey, value)`.
3033 ///
3034 /// Written for `Error.prototype.stack`'s setter and the exact mechanism
3035 /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
3036 /// abstract operation here rather than a private helper in `error.rs`.
3037 ///
3038 /// The name is the whole point: the setter must behave as if the prototype were not
3039 /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3040 /// the accessor for every error object in the realm. Everything below follows from that:
3041 ///
3042 /// 1. `thisValue` must be an object — otherwise `TypeError`.
3043 /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3044 /// accessor's own home an error rather than a self-shadow.
3045 /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3046 /// either has a string or has made a mistake.
3047 /// 4. An existing *own* property decides the path — an own setter is called, an own
3048 /// non-writable data property is a `TypeError` — and only a missing own property
3049 /// falls through to defining one.
3050 /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3051 /// traps and a non-extensible receiver is a `TypeError`.
3052 ///
3053 /// The installed shape is writable + configurable, not enumerable.
3054 pub fn setter_that_ignores_prototype_properties(
3055 &mut self,
3056 this_value: Value,
3057 home: &Gc<JsObject>,
3058 property_key: &str,
3059 args: &[Value],
3060 ) -> JsResult<Value> {
3061 self.setter_that_ignores_prototype_properties_key(
3062 this_value,
3063 home,
3064 &PropertyKey::from(property_key),
3065 args,
3066 )
3067 }
3068
3069 /// [`Interp::setter_that_ignores_prototype_properties`] for a key that may be a symbol.
3070 ///
3071 /// `Iterator.prototype[@@toStringTag]`'s setter is the symbol-keyed caller.
3072 pub fn setter_that_ignores_prototype_properties_key(
3073 &mut self,
3074 this_value: Value,
3075 home: &Gc<JsObject>,
3076 key: &PropertyKey,
3077 args: &[Value],
3078 ) -> JsResult<Value> {
3079 let Some(receiver) = this_value.as_object().cloned() else {
3080 return Err(self.type_error("setter called on a non-object"));
3081 };
3082 if Gc::ptr_eq(&receiver, home) {
3083 return Err(self.type_error("cannot assign to the accessor's own home object"));
3084 }
3085 // No type check here: §7.3.40 takes an arbitrary `v`, and
3086 // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3087 // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3088 // before calling this.
3089 let value = args.first().cloned().unwrap_or(Value::Undefined);
3090 // Step 4: an own property on the receiver changes what happens, and there are three
3091 // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3092 // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3093 // `Set` with `throw = true`, and a test exists for each.
3094 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
3095 if existing.is_accessor() && existing.setter.is_none() {
3096 // A getter-only own accessor cannot be written through.
3097 return Err(self.type_error("no setter for the own property"));
3098 }
3099 // Everything else — an own data property, or an own accessor *with* a setter —
3100 // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3101 // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3102 // an own user setter receives the value (`setter-own-accessor`), because
3103 // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3104 // setter directly is the difference between one code path and two that can
3105 // disagree.
3106 self.set_property_with_key(
3107 &receiver,
3108 key,
3109 value.clone(),
3110 crate::interp::DeleteFailure::Throw,
3111 )?;
3112 return Ok(Value::Undefined);
3113 }
3114 let property = Property {
3115 value: Some(value.clone()),
3116 writable: true,
3117 // Enumerable, despite the accessor it shadows not being. The reference installs
3118 // it that way and six cases check it (`setter-creates-own-property` and friends).
3119 enumerable: true,
3120 configurable: true,
3121 ..Property::default()
3122 };
3123 if !self.object_define_own_property(&receiver, key, property)? {
3124 return Err(self.type_error("the receiver refused the definition"));
3125 }
3126 Ok(Value::Undefined)
3127 }
3128
3129 /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3130 ///
3131 /// The indices of a typed array are not properties at all — they are bytes in the
3132 /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3133 /// fly. That makes their descriptor shape fixed: every valid index is writable,
3134 /// enumerable and configurable, so a definition can only ever change the *value*, and
3135 /// every other descriptor is refused rather than applied.
3136 ///
3137 /// The order of the checks is the spec's, and two of them are load-bearing:
3138 ///
3139 /// * the index is validated **before** the value is converted, because the conversion
3140 /// itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3141 /// detaches from a `valueOf` and still expects `true` with no store, which only
3142 /// happens when the index was valid on the way in;
3143 /// * the store is attempted even when the index has gone out of bounds by the time the
3144 /// conversion finishes, because the store is a silent no-op rather than a failure —
3145 /// the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3146 /// the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3147 ///
3148 /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3149 /// the existing element, which is harmless here: every valid index is already
3150 /// writable, enumerable and configurable, so a `false` in the merged property can only
3151 /// have come from the descriptor having named `false`.
3152 fn integer_indexed_define_own_property(
3153 &mut self,
3154 object: &Gc<JsObject>,
3155 numeric: f64,
3156 property: &Property,
3157 ) -> JsResult<bool> {
3158 // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3159 // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3160 if !typed_array_index_is_valid(object, numeric) {
3161 return Ok(false);
3162 }
3163 // Step 6: the indices are data properties, so an accessor descriptor is refused
3164 // rather than converted. `Object.defineProperty` turns the `false` into a
3165 // `TypeError`; `Reflect.defineProperty` reports it.
3166 if property.is_accessor() {
3167 return Ok(false);
3168 }
3169 // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3170 // definition that asks for anything else cannot be honoured.
3171 if !property.writable || !property.enumerable || !property.configurable {
3172 return Ok(false);
3173 }
3174 // Step 10: only a descriptor that names a value stores anything.
3175 let Some(value) = property.value.clone() else {
3176 return Ok(true);
3177 };
3178 let Some(element) = object.typed_array_element_type() else {
3179 return Ok(false);
3180 };
3181 let stored = self.element_value(element, value)?;
3182 if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3183 return Err(self.type_error(reason));
3184 }
3185 Ok(true)
3186 }
3187
3188 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3189 pub fn object_define_own_property(
3190 &mut self,
3191 object: &Gc<JsObject>,
3192 key: &PropertyKey,
3193 property: Property,
3194 ) -> JsResult<bool> {
3195 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3196 return Ok(accepted);
3197 }
3198 // A proxy always answers above — with `Some` from its trap, or with `None` when
3199 // the trap is absent, and then the definition belongs to the **target**
3200 // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3201 // when there is no trap). Falling through to the ordinary path here defined the
3202 // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3203 // property the target never saw.
3204 if object.proxy_state().is_some() {
3205 let Some((target, _handler)) = self.proxy_parts(object)? else {
3206 return Err(self.type_error("cannot use a proxy that has been revoked"));
3207 };
3208 return self.object_define_own_property(&target, key, property);
3209 }
3210 // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3211 // they accept exactly one descriptor shape. This has to happen before the
3212 // ordinary path, which would happily store a data property next to the buffer —
3213 // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3214 // and `TypedArray/prototype/set` are about this section.
3215 if object.typed_array_element_type().is_some()
3216 && let Some(index) = canonical_numeric_index(key)
3217 {
3218 return self.integer_indexed_define_own_property(object, index, &property);
3219 }
3220 // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3221 // non-extensible object. The check lives here rather than in the callers because
3222 // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3223 // `Array.prototype.filter` uses to store its result, and a species object made
3224 // non-extensible by its own constructor must make that a `TypeError`
3225 // (`target-array-non-extensible`).
3226 // Note the `is_none()`: an already-present property may still be **redefined** on a
3227 // non-extensible object, and only *adding* one is refused (as Distinct from
3228 // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3229 // properties — testing extensibility before looking for the property made every
3230 // `Object.freeze` of an ordinary object refuse its own second step).
3231 if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3232 return Ok(false);
3233 }
3234 // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3235 // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3236 // an omitted field is left alone). Merging here rather than at each call site is
3237 // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3238 // the value and `enumerable` in place.
3239 //
3240 // The merge is a no-op when the property is absent: there is nothing to keep.
3241 let was_partial = property.descriptor_fields.is_some();
3242 let property = match property.descriptor_fields {
3243 None => property,
3244 Some(fields) => {
3245 let base = self.object_get_own_property(object, key)?;
3246 let mut merged = base.clone().unwrap_or_default();
3247 // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3248 // descriptor names, and switching kind discards the other half —
3249 // `{set: f}` on a data property is an accessor with no getter, not a data
3250 // property whose `get` happens to be absent.
3251 let wants_accessor = fields.get || fields.set;
3252 let wants_data = fields.value || fields.writable;
3253 if wants_accessor {
3254 merged.value = None;
3255 merged.writable = false;
3256 merged.getter = property.getter.clone();
3257 merged.setter = property.setter.clone();
3258 } else if wants_data {
3259 merged.getter = None;
3260 merged.setter = None;
3261 if fields.value {
3262 merged.value = property.value.clone();
3263 }
3264 if fields.writable {
3265 merged.writable = property.writable;
3266 }
3267 }
3268 if fields.enumerable {
3269 merged.enumerable = property.enumerable;
3270 }
3271 if fields.configurable {
3272 merged.configurable = property.configurable;
3273 }
3274 merged.descriptor_fields = None;
3275 merged
3276 }
3277 };
3278 // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3279 // descriptor. `define_property_on` runs the same check before it calls here, so an
3280 // ordinary object is already covered; what is *not* is the forwarding a proxy does
3281 // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3282 // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3283 // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3284 // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3285 // own define would have refused.
3286 //
3287 // Only partial descriptors are validated here. A whole `Property` passed by an
3288 // internal caller (`Property::data(…)`) carries attributes that say nothing about
3289 // what the descriptor "named", and those callers rely on the write landing.
3290 if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3291 // Every branch below is gated on `!existing.configurable`: a *configurable*
3292 // property may be reshaped however the descriptor likes, which is why an
3293 // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3294 // must succeed. Testing only `writable` refused that and broke
3295 // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3296 let same_kind = existing.is_accessor() == property.is_accessor();
3297 if !same_kind {
3298 // Step 4: a non-configurable property may not change kind.
3299 if !existing.configurable {
3300 return Ok(false);
3301 }
3302 } else if existing.is_accessor() {
3303 // Step 6: an accessor's halves are its value.
3304 if !existing.configurable
3305 && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3306 || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3307 {
3308 return Ok(false);
3309 }
3310 } else if !existing.configurable && !existing.writable {
3311 // Step 7: a non-configurable *and* non-writable data property's value is
3312 // fixed, and it may not become writable again.
3313 if property.writable {
3314 return Ok(false);
3315 }
3316 let current = existing.value.clone().unwrap_or(Value::Undefined);
3317 let requested = property.value.clone().unwrap_or(Value::Undefined);
3318 if !current.same_value(&requested) {
3319 return Ok(false);
3320 }
3321 }
3322 // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3323 // is frozen with it.
3324 if !existing.configurable
3325 && (property.configurable || property.enumerable != existing.enumerable)
3326 {
3327 return Ok(false);
3328 }
3329 }
3330 // A host class that intercepts definitions owns the attributes of the properties it
3331 // defines: `_class`-style storage on the native side is the usual reason.
3332 if let Some(exotic) = object.exotic()
3333 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3334 {
3335 return Ok(accepted);
3336 }
3337 // An array index is stored in the element vector, which can hold a plain value and
3338 // nothing else. An accessor — or a data property with non-default attributes —
3339 // therefore has to live in the property table, and the element slot is blanked so
3340 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3341 // {get})` stored the accessor where no read ever looked, and the array kept
3342 // answering its old value.
3343 // An array's `length` is not stored in the property table, so defining it has to
3344 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3345 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3346 // {value: 1})` reported success and changed nothing.
3347 if key.as_str() == Some("length") && object.is_array() {
3348 // `{writable: false}` on `length` does not change the length, but it does make
3349 // it read-only — after which neither a later `{writable: true}` nor a store
3350 // past the end may succeed.
3351 if property.value.is_none() {
3352 if !object.length_writable() && property.writable {
3353 return Ok(false);
3354 }
3355 object.set_length_writable(property.writable);
3356 return Ok(true);
3357 }
3358 if !object.length_writable() {
3359 return Ok(false);
3360 }
3361 }
3362 if key.as_str() == Some("length")
3363 && object.is_array()
3364 && let Some(value) = property.value.clone()
3365 {
3366 let requested = value.to_number();
3367 let valid = requested.is_finite()
3368 && requested >= 0.0
3369 && requested.fract() == 0.0
3370 && requested <= u32::MAX as f64;
3371 if !valid {
3372 return Err(self.range_error("invalid array length"));
3373 }
3374 // Truncating deletes the elements above the new length, and a non-configurable
3375 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3376 // makes `a.length = 2` fail rather than quietly drop it.
3377 let current = object.array_length().unwrap_or(0);
3378 let requested = requested as usize;
3379 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3380 // §10.4.2.4 `ArraySetLength` step 3.i.2: the refusal still applies
3381 // `[[Writable]]: false` when the descriptor asked for it — the length is
3382 // left at its old value but locked. Returning `false` alone left it
3383 // writable, which `verifyProperty` catches
3384 // (`defineProperties/15.2.3.7-6-a-164`).
3385 if property
3386 .descriptor_fields
3387 .is_some_and(|fields| fields.writable)
3388 && !property.writable
3389 && object.length_writable()
3390 {
3391 object.set_length_writable(false);
3392 }
3393 return Ok(false);
3394 }
3395 object.array_set_length(self.heap, requested);
3396 return Ok(true);
3397 }
3398 let plain = property.writable
3399 && property.enumerable
3400 && property.configurable
3401 && !property.is_accessor();
3402 if let Some(index) = key.as_str().and_then(array_index)
3403 && object.is_array()
3404 {
3405 // Growing the array needs a writable `length`: after
3406 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3407 // be added.
3408 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3409 return Ok(false);
3410 }
3411 if plain && property.value.is_some() {
3412 // An ordinary element: the vector is where a read looks first, so it has
3413 // to be the vector that changes — unless the index is too far out to be
3414 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3415 // one property, because past its own limit it stores the index as an
3416 // ordinary key. Falling through to `define_key` below is the same choice,
3417 // and the alternative was worse: the store used to be *dropped* and the
3418 // length left at 0, which is a silent wrong answer.
3419 let value = property.value.clone().unwrap_or(Value::Undefined);
3420 object.delete_key(key);
3421 if object.array_set(self.heap, index as usize, value) {
3422 return Ok(true);
3423 }
3424 // Past the dense limit the element lives in the table like any property.
3425 object.note_element_descriptor();
3426 object.define_key(key, property);
3427 // A sparse store past the dense limit still extends `length`, which is what
3428 // `a[a.length] = v` relies on — but only extends: shortening would delete
3429 // the sparse properties above the index, including this one.
3430 if index as usize + 1 > object.array_length().unwrap_or(0) {
3431 object.array_set_length(self.heap, index as usize + 1);
3432 }
3433 return Ok(true);
3434 }
3435 // A non-plain element — an accessor, or an attribute that is not the default —
3436 // lives in the table while the slot becomes a hole. Recording it keeps every
3437 // later `a[i] = v` off the dense path, where the write would have shadowed the
3438 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3439 // replace the accessor with a plain data property.
3440 object.note_element_descriptor();
3441 object.define_key(key, property);
3442 // The slot stays, so `length` does not shrink; a hole is not an element, so
3443 // the table entry is now what a read finds.
3444 object.array_set(self.heap, index as usize, Value::Hole);
3445 // `ArraySetLength` step 2 of `OrdinaryDefineOwnProperty`'s index branch —
3446 // `length = index + 1` — applies whatever the descriptor's *attributes* are,
3447 // not just to a plain one: `Object.defineProperty(a, 4294967294, {value: 100})`
3448 // makes `a.length` 4294967295 (`defineProperty/15.2.3.6-4-183`).
3449 if index as usize + 1 > object.array_length().unwrap_or(0) {
3450 object.array_set_length(self.heap, index as usize + 1);
3451 }
3452 return Ok(true);
3453 }
3454 object.define_key(key, property);
3455 Ok(true)
3456 }
3457
3458 /// Build a proxy object over `target`, with its traps read from `handler`.
3459 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3460 JsObject::proxy(self.heap, target, handler)
3461 }
3462
3463 /// The `revoke` function for a proxy's slots.
3464 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3465 let revoke = JsObject::function(
3466 self.heap,
3467 Some(self.realm.function_proto.clone()),
3468 Callable::Revoker(slots),
3469 );
3470 // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3471 // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3472 // inherited from `Function.prototype` reads the same but fails the three cases that
3473 // check the own-property list (`revocation-function-{length,name,property-order}`).
3474 revoke.define("length", Property::name_or_length(Value::Int(0)));
3475 revoke.define("name", Property::name_or_length(self.string("")));
3476 revoke
3477 }
3478
3479 /// A new array.
3480 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3481 let array = JsObject::array(
3482 self.heap,
3483 Some(self.realm.array_proto.clone()),
3484 elements.len(),
3485 );
3486 for (index, element) in elements.into_iter().enumerate() {
3487 array.array_set(self.heap, index, element);
3488 }
3489 array
3490 }
3491
3492 /// A new native function object.
3493 ///
3494 /// The observable `name` and `length` are installed as properties here, which is
3495 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3496 /// so `f.name = "x"` behaves like the writable property it is.
3497 /// A native constructor that builds its own instance after validating its arguments.
3498 ///
3499 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3500 /// check runs before `new.target.prototype` is read.
3501 pub fn new_native_ctor(
3502 &self,
3503 name: impl Into<String>,
3504 length: u32,
3505 func: NativeFn,
3506 ) -> Gc<JsObject> {
3507 let function = JsObject::function(
3508 self.heap,
3509 Some(self.realm.function_proto.clone()),
3510 Callable::Native {
3511 func,
3512 own_instance: true,
3513 },
3514 );
3515 function.set_constructible(true);
3516 function.define(
3517 "length",
3518 Property::name_or_length(Value::Int(length as i32)),
3519 );
3520 function.define("name", Property::name_or_length(self.string(name)));
3521 function
3522 }
3523
3524 /// A native constructor that lets `new` build the instance first.
3525 ///
3526 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3527 /// validation that must precede reading `new.target.prototype`, so the object can be
3528 /// created before the implementation runs. Distinct from [`Interp::new_native`],
3529 /// which makes a *method* and therefore not a constructor at all.
3530 pub fn new_native_constructor(
3531 &self,
3532 name: impl Into<String>,
3533 length: u32,
3534 func: NativeFn,
3535 ) -> Gc<JsObject> {
3536 let function = self.new_native(name, length, func);
3537 function.set_constructible(true);
3538 function
3539 }
3540
3541 /// A new host function object: a native closure that carries its own state.
3542 ///
3543 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3544 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3545 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3546 /// this safe: the closure must not capture a `Gc`.
3547 pub fn new_host_function(
3548 &self,
3549 name: impl Into<String>,
3550 length: u32,
3551 func: crate::object::HostFn,
3552 ) -> Gc<JsObject> {
3553 self.new_host_inner(name.into(), length, func, false)
3554 }
3555
3556 /// A host constructor: `new` hands it `this = undefined`, so it validates its
3557 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3558 pub fn new_host_ctor(
3559 &self,
3560 name: impl Into<String>,
3561 length: u32,
3562 func: crate::object::HostFn,
3563 ) -> Gc<JsObject> {
3564 let function = self.new_host_inner(name.into(), length, func, true);
3565 function.set_constructible(true);
3566 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3567 // installs its own methods on it, so it starts as a plain object.
3568 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3569 function.define(
3570 "prototype",
3571 Property {
3572 value: Some(Value::Object(proto)),
3573 writable: true,
3574 enumerable: false,
3575 configurable: false,
3576 ..Property::default()
3577 },
3578 );
3579 function
3580 }
3581
3582 fn new_host_inner(
3583 &self,
3584 name: String,
3585 length: u32,
3586 func: crate::object::HostFn,
3587 own_instance: bool,
3588 ) -> Gc<JsObject> {
3589 let function = JsObject::function(
3590 self.heap,
3591 Some(self.realm.function_proto.clone()),
3592 Callable::Host {
3593 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3594 own_instance,
3595 },
3596 );
3597 function.define(
3598 "length",
3599 Property::name_or_length(Value::Int(length as i32)),
3600 );
3601 function.define("name", Property::name_or_length(self.string(name)));
3602 function
3603 }
3604
3605 /// A callable object with the `length`/`name` a built-in function has, in that order.
3606 ///
3607 /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3608 /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3609 /// [`JsObject::function`] defines neither, which is why every capability helper built
3610 /// with it reported no own `length` and no own `name` at all.
3611 ///
3612 /// The attributes are the spec's for a built-in: not writable, not enumerable,
3613 /// configurable.
3614 pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3615 let function =
3616 JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3617 function.define(
3618 "length",
3619 Property::name_or_length(Value::Int(length as i32)),
3620 );
3621 function.define("name", Property::name_or_length(self.string(name)));
3622 function
3623 }
3624
3625 /// A new native function object.
3626 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3627 let function = JsObject::function(
3628 self.heap,
3629 Some(self.realm.function_proto.clone()),
3630 Callable::Native {
3631 func,
3632 own_instance: false,
3633 },
3634 );
3635 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3636 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3637 // `length,name` and this listed `name,length`. A bytecode function already gets it
3638 // the right way round; only native ones were built backwards.
3639 function.define(
3640 "length",
3641 Property::name_or_length(Value::Int(length as i32)),
3642 );
3643 function.define("name", Property::name_or_length(self.string(name)));
3644 function
3645 }
3646
3647 /// A new bound function.
3648 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3649 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3650 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3651 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3652 let constructible = target
3653 .as_object()
3654 .is_some_and(|target| target.is_constructor());
3655 let bound = JsObject::function(
3656 self.heap,
3657 Some(self.realm.function_proto.clone()),
3658 Callable::Bound { target, this, args },
3659 );
3660 bound.set_constructible(constructible);
3661 bound
3662 }
3663
3664 /// A new reference cell.
3665 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3666 Gc::new(self.heap, Cell::new(value))
3667 }
3668
3669 // -- running ------------------------------------------------------------
3670
3671 /// Evaluate `code` as a script body and return its completion value.
3672 /// Compile and run `source` for the engine's own use, returning its completion value.
3673 ///
3674 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3675 /// needs to be a real async function, and the engine already runs those as coroutines,
3676 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3677 ///
3678 /// Differences from [`Self::eval_in_global`], both deliberate:
3679 ///
3680 /// * It does **not** drain the microtask queue. Install runs while the realm is still
3681 /// being built, and the source is an IIFE that only constructs a closure, so there
3682 /// is nothing to drain — and draining here would run script-queued jobs in the
3683 /// middle of `install`.
3684 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3685 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3686 /// and it should not look like the user wrote something wrong.
3687 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3688 let program = match js_parse::parse_script(source) {
3689 Ok(program) => program,
3690 Err(error) => {
3691 let message = format!("builtin source does not parse: {error}");
3692 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3693 }
3694 };
3695 let mut code = match js_compile::compile_script_with_source(&program, source) {
3696 Ok(code) => code,
3697 Err(error) => {
3698 let message = format!("builtin source does not compile: {}", error.message);
3699 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3700 }
3701 };
3702 // The frame has to name something, and `<builtin>` is what a stack trace through
3703 // this code should say.
3704 code.set_filename("<builtin>");
3705 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3706 let closure_vars = compiled.code.closure_vars.clone();
3707 let env = self.global_env(&closure_vars);
3708 let this = Value::Object(self.realm.global.clone());
3709 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3710 }
3711
3712 /// Run an already-parsed script and drain the microtasks it queued.
3713 ///
3714 /// The drain is what lets an `async` function's body advance past its first `await`
3715 /// before the host sees the result: nothing else pumps the job queue.
3716 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3717 let this = Value::Object(self.realm.global.clone());
3718 self.run_script_with_this(code, this)
3719 }
3720
3721 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3722 ///
3723 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3724 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3725 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3726 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3727 /// state the next script evaluation tripped over.
3728 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3729 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3730 let closure_vars = compiled.code.closure_vars.clone();
3731 let env = self.global_env(&closure_vars);
3732 let callee = Value::Undefined;
3733 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3734 // The script is done, so the microtasks it queued run before the host sees the
3735 // result. Without this an `async` function's body would never advance past its
3736 // first `await`, because nothing else drains the queue.
3737 self.drain_jobs()?;
3738 Ok(result)
3739 }
3740
3741 /// Compile and run `source` in global scope, returning its completion value.
3742 ///
3743 /// This is what `eval` and `new Function` use. Running it as a script means it
3744 /// sees the global object and nothing else, which is right for `eval("1+1")` and
3745 /// for a `Function` body; a *direct* eval that reads a local variable would need
3746 /// the compiler to hand its variable environment over, which is not implemented.
3747 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3748 self.eval_in_global_named(source, EVAL_FILE, false)
3749 }
3750
3751 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3752 ///
3753 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3754 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3755 /// through the code, so they cannot share one constant.
3756 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3757 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3758 }
3759
3760 /// Evaluate `source` as a global script, reported under `file`.
3761 ///
3762 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3763 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3764 /// from inside a C callback, where the interpreter is the running one rather than a
3765 /// context's own.
3766 pub fn eval_in_global_named(
3767 &mut self,
3768 source: &str,
3769 file: &str,
3770 barrier: bool,
3771 ) -> JsResult<Value> {
3772 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3773 // eval-created global binding — configurable, unlike a script's own `var`.
3774 self.eval_depth += 1;
3775 if barrier {
3776 let depth = self.frames.len();
3777 self.trace_barriers.push(depth);
3778 }
3779 let result = self.eval_in_global_inner(source, file);
3780 if barrier {
3781 self.trace_barriers.pop();
3782 }
3783 self.eval_depth -= 1;
3784 result
3785 }
3786
3787 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3788 let compiled = self.compile_global_script(source, file, false)?;
3789 let strict = compiled.strict;
3790 self.run_eval_script(compiled, strict)
3791 }
3792
3793 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3794 ///
3795 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3796 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3797 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3798 /// direct eval's is.
3799 pub fn eval_script_with_this(
3800 &mut self,
3801 source: &str,
3802 file: &str,
3803 this: Value,
3804 ) -> JsResult<Value> {
3805 let program = match js_parse::parse_script(source) {
3806 Ok(program) => program,
3807 Err(error) => {
3808 return Err(Signal::Throw(self.syntax_error_at(
3809 file,
3810 error.span.start.line,
3811 error.span.start.column,
3812 &error.message,
3813 )));
3814 }
3815 };
3816 let mut compiled = match js_compile::compile_script(&program) {
3817 Ok(compiled) => compiled,
3818 Err(error) => {
3819 return Err(Signal::Throw(self.syntax_error_at(
3820 file,
3821 error.span.start.line,
3822 error.span.start.column,
3823 &error.message,
3824 )));
3825 }
3826 };
3827 compiled.set_filename(file);
3828 self.run_script_with_this(compiled, this)
3829 }
3830
3831 /// Parse and compile `source` as a global script, without running it.
3832 ///
3833 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3834 /// before a promise exists to reject — while still evaluating in the same eval context
3835 /// (direct-eval strictness, `new.target`, `super`).
3836 fn compile_global_script(
3837 &mut self,
3838 source: &str,
3839 file: &str,
3840 async_body: bool,
3841 ) -> JsResult<CompiledFunction> {
3842 // A *direct* eval inherits the strictness of the code that called it, which is
3843 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3844 // implicit global. The caller's frame is the innermost one here, because a
3845 // native function does not push a frame of its own.
3846 let strict = self.current_strict();
3847 // `eval` runs in the caller's function context, so `new.target` is legal here
3848 // even though the source is a bare script — and so is `super.x` when the caller
3849 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3850 // caller's, which is what `special_object 4` already does.
3851 let context = js_parse::EvalContext {
3852 in_method: self.enclosing_home_object().is_some(),
3853 // `super()` belongs to a derived constructor, and an eval'd body is not a
3854 // constructor at all: the caller frame's `this` is already built.
3855 in_derived_constructor: false,
3856 };
3857 // A *global* eval is not a function body: `new.target` and `super` are out of
3858 // reach there. Its `{async: true}` form differs in the other direction — the body
3859 // may `await` — so the two flags are independent and the reference sets both from
3860 // the eval type rather than from the caller.
3861 let parsed = if async_body {
3862 js_parse::parse_suspensible_global_eval(source, strict)
3863 } else {
3864 js_parse::parse_eval_script_in(source, strict, context)
3865 };
3866 let program = match parsed {
3867 Ok(program) => program,
3868 Err(error) => {
3869 // The message is bare: the position lives in `fileName`,
3870 // `lineNumber`, `columnNumber` and the stack frame above, which is where
3871 // the reference puts it. An `invalid source: L:C: ` prefix made
3872 // `e.message` differ from the reference while the stack already agreed.
3873 return Err(Signal::Throw(self.syntax_error_at(
3874 file,
3875 error.span.start.line,
3876 error.span.start.column,
3877 &error.message,
3878 )));
3879 }
3880 };
3881 let mut compiled = match if async_body {
3882 js_compile::compile_script_suspensible(&program)
3883 } else {
3884 js_compile::compile_script(&program)
3885 } {
3886 Ok(compiled) => compiled,
3887 // A construct the compiler does not handle yet is reported the same way a
3888 // parse error is: it happens before anything runs, so the trace is the
3889 // position in the source followed by the caller.
3890 Err(error) => {
3891 return Err(Signal::Throw(self.syntax_error_at(
3892 file,
3893 error.span.start.line,
3894 error.span.start.column,
3895 &error.message,
3896 )));
3897 }
3898 };
3899 compiled.set_filename(file);
3900 Ok(compiled)
3901 }
3902
3903 /// Run an `eval`'d script in the caller's scope.
3904 ///
3905 /// Three things have to come from the calling frame, because the eval'd code is a
3906 /// script and would otherwise see only the global object:
3907 ///
3908 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3909 /// * `arguments`, exposed as a binding of the eval's own scope, so
3910 /// `f("arguments.length", 1)` sees the caller's arguments;
3911 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3912 /// `eval("var v = 1")` into the global object.
3913 ///
3914 /// Locals of the calling function are *not* reachable: that needs the compiler to
3915 /// hand its variable environment over, which this milestone does not do.
3916 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3917 // `this` and `arguments` come from the innermost frame only — those are not
3918 // lexical — while the name bindings come from the whole chain of frames, part
3919 // of it being ordinary scope resolution.
3920 // An arrow has no `this` of its own, so an `eval` inside one inherits the
3921 // enclosing function's receiver — the lexical `this` the arrow was compiled to
3922 // read from its closure.
3923 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3924 // variable environment is the innermost frame of all: an arrow's own body is where
3925 // `var`s declared by an `eval` inside it belong.
3926 let caller_index = self
3927 .frames
3928 .iter()
3929 .rposition(|frame| !frame.code.code.is_arrow)
3930 .or_else(|| self.frames.len().checked_sub(1));
3931 let env_index = self.frames.len().checked_sub(1);
3932 let caller = caller_index.and_then(|index| self.frames.get(index));
3933 let (this, passed) = match caller {
3934 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3935 // No frame at all: the eval is running at the top level, so there is
3936 // nothing to inherit and the global receiver is right.
3937 None => (Value::Object(self.realm.global.clone()), Vec::new()),
3938 };
3939 // Innermost frame first, so the first binding found for a name is the one that
3940 // shadows the rest. A script frame (`<eval>`) contributes nothing.
3941 let mut bindings: Vec<EvalBinding> = Vec::new();
3942 // The calling function's own bindings, resolved by the compiler at the call
3943 // site. That table is the only reliable answer when a name is declared twice in
3944 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3945 // body means, and guessing by declaration order picks the wrong one as soon as
3946 // two loops in a row use the same name.
3947 // Only a *direct* eval sees the caller's scope. The compiler records a site for
3948 // every direct call — a bare `eval(...)` callee — so finding one at the current
3949 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
3950 // callee to a value first and leave no site behind.
3951 let mut direct = false;
3952 let mut resolved_here = false;
3953 if let Some(frame) = self.frames.last() {
3954 let (line, column) = frame
3955 .code
3956 .code
3957 .position_at(frame.at as u32)
3958 .unwrap_or_default();
3959 // The nearest site at or before the current position, not an exact match:
3960 // the recorded position of the `call` instruction is the callee's, which
3961 // sits a few columns inside the call expression the compiler recorded. A
3962 // site is unique per call, so "the closest one behind us" identifies it.
3963 if let Some(site) = frame
3964 .code
3965 .code
3966 .eval_sites
3967 .iter()
3968 .filter(|site| (site.line, site.column) <= (line, column))
3969 .max_by_key(|site| (site.line, site.column))
3970 {
3971 direct = true;
3972 resolved_here = true;
3973 for binding in &site.bindings {
3974 // An enclosing function's frame sits `owner` levels below the one
3975 // running the call.
3976 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
3977 else {
3978 continue;
3979 };
3980 bindings.push(EvalBinding {
3981 name: binding.name.clone(),
3982 frame,
3983 slot: if binding.is_arg {
3984 EvalSlot::Arg
3985 } else {
3986 EvalSlot::Local
3987 },
3988 index: binding.index as usize,
3989 });
3990 }
3991 }
3992 }
3993 for frame_index in (0..self.frames.len()).rev() {
3994 // Skip the innermost frame's flat scan when the compiler already answered
3995 // for it; an enclosing frame still needs one, because the eval resolves
3996 // those names dynamically.
3997 if resolved_here && frame_index == self.frames.len() - 1 {
3998 continue;
3999 }
4000 let frame = &self.frames[frame_index];
4001 for (index, arg) in frame.code.code.args.iter().enumerate() {
4002 bindings.push(EvalBinding {
4003 name: arg.name.clone(),
4004 frame: frame_index,
4005 slot: EvalSlot::Arg,
4006 index,
4007 });
4008 }
4009 for (index, local) in frame.code.code.vars.iter().enumerate() {
4010 bindings.push(EvalBinding {
4011 name: local.name.clone(),
4012 frame: frame_index,
4013 slot: EvalSlot::Local,
4014 index,
4015 });
4016 }
4017 }
4018 let mut seen = BTreeSet::new();
4019 bindings.retain(|binding| seen.insert(binding.name.clone()));
4020
4021 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4022 // elements is all the spec's ordinary uses need.
4023 //
4024 // Known divergence: this is bound for a *global* eval too, where there is no
4025 // caller and the reference throws `'arguments' is not defined`. Deciding properly
4026 // needs "does the calling frame have an `arguments` of its own", which is not
4027 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4028 // script or eval body does not, and `eval(b)` passes the callee as a value so even
4029 // the call-site detection does not answer it. Modelled as a binding in the caller's
4030 // variable environment, this would fall out; that is a larger change than the one
4031 // this comment is attached to.
4032 let arguments = Value::Object(self.new_array(passed));
4033
4034 // Only a *strict* eval gets a variable environment of its own. A sloppy one
4035 // declares its `var`s in the caller's — which for a top-level eval is the global
4036 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4037 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4038 // vanish into a scope nobody reads back from.
4039 let previous_scope = if code_strict {
4040 self.eval_scope.replace(BTreeMap::new())
4041 } else {
4042 None
4043 };
4044 let previous_arguments = self.eval_arguments.replace(arguments);
4045 let previous_with = self.eval_with.replace(self.with_objects());
4046 let inherited_new_target = self
4047 .frames
4048 .iter()
4049 .rev()
4050 .find(|frame| !frame.code.code.is_arrow)
4051 .map(|frame| frame.new_target.clone());
4052 let previous_new_target = self
4053 .eval_new_target
4054 .replace(inherited_new_target.unwrap_or(Value::Undefined));
4055 let eval_cells = self.eval_cells_for(&bindings);
4056 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4057 // A sloppy direct eval declares its `var`s in the caller's variable environment;
4058 // `declare_eval_local` needs to know which frame that is.
4059 // An indirect eval gets the global environment, so nothing of the caller's is
4060 // recorded as the place its `var`s belong.
4061 let previous_caller = self
4062 .eval_caller
4063 .replace(if direct { env_index } else { None });
4064 // The cell-based view of the same bindings, which is what a closure created
4065 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4066 // whose compiler did not put a binding in a cell simply does not appear here —
4067 // reads and writes still work through `eval_bindings`, they just cannot outlive
4068 // the eval.
4069 let previous_eval_scope = self
4070 .active_eval_scope
4071 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4072 let compiled = Gc::new(self.heap, CompiledCode::new(code));
4073 let closure_vars = compiled.code.closure_vars.clone();
4074 let env = self.global_env(&closure_vars);
4075 let callee = Value::Undefined;
4076 // An async body does not run here: it becomes a coroutine and answers a promise,
4077 // which is what makes `await` legal in it. `this` still has to be the caller's
4078 // (for a global eval, the global object), because `this` is not part of `await`.
4079 let result = if compiled.code.kind.is_async() {
4080 self.run_async_body(compiled, env, this)
4081 } else {
4082 self.execute(compiled, env, this, Vec::new(), callee)
4083 };
4084 self.eval_scope = previous_scope;
4085 self.eval_arguments = previous_arguments;
4086 self.eval_with = previous_with;
4087 self.eval_new_target = previous_new_target;
4088 self.eval_bindings = previous_bindings;
4089 self.eval_caller = previous_caller;
4090 self.active_eval_scope = previous_eval_scope;
4091 result
4092 }
4093
4094 /// The cell-backed subset of `bindings`, in the same priority order.
4095 ///
4096 /// Both lookup routes have to agree — the eval's own reads go through
4097 /// [`Interp::eval_binding_value`] and the closures it builds go through
4098 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4099 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4100 /// is not in a cell simply does not appear: reads and writes still work, they just
4101 /// cannot be handed to a closure that outlives the eval.
4102 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4103 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4104 for binding in bindings {
4105 let Some(frame) = self.frames.get(binding.frame) else {
4106 continue;
4107 };
4108 let cell = match binding.slot {
4109 EvalSlot::Arg => frame
4110 .code
4111 .arg_cell
4112 .get(binding.index)
4113 .copied()
4114 .unwrap_or(-1),
4115 EvalSlot::Local => frame
4116 .code
4117 .loc_cell
4118 .get(binding.index)
4119 .copied()
4120 .unwrap_or(-1),
4121 };
4122 if cell < 0 {
4123 continue;
4124 }
4125 if let Some(cell) = frame.cells.get(cell as usize) {
4126 names.push((binding.name.clone(), cell.clone()));
4127 }
4128 }
4129 names
4130 }
4131
4132 /// A `SyntaxError` that reports where in the source it happened.
4133 ///
4134 /// Compile-time failures never run, so they have no frame of their own; the
4135 /// reference still puts the position first in the trace, with no function name and
4136 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4137 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4138 /// reference borrows), which is how a script reads the position without parsing
4139 /// the trace.
4140 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4141 ///
4142 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4143 /// `columnNumber`, which is how the reference prints one. A positionless error
4144 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4145 /// the reference raises it from `js_resolve_module`, where there is no position.
4146 pub(crate) fn syntax_error_plain(
4147 &mut self,
4148 error: &js_parse::SyntaxError,
4149 file: &str,
4150 ) -> Value {
4151 if error.positionless {
4152 return self.make_error("SyntaxError", &error.message);
4153 }
4154 self.syntax_error_at(
4155 file,
4156 error.span.start.line,
4157 error.span.start.column,
4158 &error.message,
4159 )
4160 }
4161
4162 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4163 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
4164 let value = self.make_error("SyntaxError", message);
4165 if let Value::Object(object) = &value {
4166 let text = self.string(blamed);
4167 // `stack` is an own data property, and the reference keeps it
4168 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4169 object.define("stack", Property::with_attributes(text, true, false));
4170 let name = self.string(file);
4171 object.define("fileName", Property::with_attributes(name, true, true));
4172 object.define(
4173 "lineNumber",
4174 Property::with_attributes(Value::Int(line as i32), true, true),
4175 );
4176 object.define(
4177 "columnNumber",
4178 Property::with_attributes(Value::Int(column as i32), true, true),
4179 );
4180 }
4181 value
4182 }
4183
4184 /// Run a compiled script whose completion value is a function, returning it.
4185 ///
4186 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4187 /// get the closure out, which keeps the constant-pool plumbing in one place.
4188 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4189 self.run_script(code)
4190 }
4191
4192 /// The environment of a script or of any function compiled at global scope:
4193 /// every entry is a global binding, so each one resolves to the realm's cell.
4194 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4195 let mut cells = Vec::with_capacity(closure_vars.len());
4196 for closure_var in closure_vars {
4197 let cell = match closure_var.closure_type {
4198 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4199 if closure_var.is_lexical =>
4200 {
4201 // A lexical declaration: the cell is created here holding the
4202 // dead-zone marker, which is what makes the binding exist and
4203 // unreadable before its initialiser runs.
4204 self.declare_global(&closure_var.name, closure_var.is_const);
4205 self.realm.globals[&closure_var.name].clone()
4206 }
4207 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4208 // A `var` or function declaration becomes a property of the global
4209 // object, and it exists from here on — which is why
4210 // `print(v); var v = 1` prints `undefined` instead of raising.
4211 // Declaring it at instantiation time (rather than at the
4212 // initialiser) is also what makes it non-configurable: the store
4213 // then lands on an existing property instead of creating one.
4214 self.declare_var_global(&closure_var.name);
4215 // The cell is a placeholder that nothing indexes; it cannot be
4216 // omitted because the slot has to hold something.
4217 self.new_cell(Value::Undefined)
4218 }
4219 _ => {
4220 // An undeclared global is read by name; the cell is a
4221 // placeholder that nothing indexes.
4222 self.new_cell(Value::Undefined)
4223 }
4224 };
4225 cells.push(cell);
4226 }
4227 Gc::new(
4228 self.heap,
4229 ClosureEnv {
4230 cells,
4231 eval_scope: None,
4232 local_vars: None,
4233 local_phase: 1,
4234 },
4235 )
4236 }
4237
4238 /// Push a frame and run until it returns.
4239 pub(crate) fn execute(
4240 &mut self,
4241 code: Gc<CompiledCode>,
4242 env: Gc<ClosureEnv>,
4243 this: Value,
4244 args: Vec<Value>,
4245 callee: Value,
4246 ) -> JsResult<Value> {
4247 let depth = self.frames.len();
4248 if depth == 0 {
4249 // A throw that reached the host ends the *active* mode: the next one is catchable
4250 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4251 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4252 // for the throw that evaluation will raise.
4253 self.uncatchable = false;
4254 }
4255 self.push_frame(code, env, this, args, callee)?;
4256 loop {
4257 // The fast loop first: it runs whole runs of records with `pc` in a register.
4258 //
4259 // `step`'s `pc` lives in the frame, so every instruction writes it back and
4260 // reads it again — a store, a load and two bounds checks that a loop body does
4261 // not need, because nothing outside the loop can run in between. This is the
4262 // classic split: advance a register, and only spill it when leaving.
4263 //
4264 // `Some(value)` means the function ended by running off the end of its
4265 // instruction array, which is a normal return.
4266 let step = match self.run_fast() {
4267 Ok(Some(value)) => Ok(Step::Return(value)),
4268 Ok(None) => self.step(),
4269 Err(signal) => Err(signal),
4270 };
4271 match step {
4272 Ok(Step::Continue) => {}
4273 Ok(Step::Return(value)) => {
4274 self.pop_frame();
4275 // A frame that ended in a `tail_call` hands its value straight to
4276 // its caller: nothing after the call can run, so every frame above
4277 // the callee unwinds with the same value. See [`Frame::tail`] —
4278 // the reference does not reuse frames either, so recursion depth
4279 // and the stack-overflow limit behave the same way.
4280 while self.frames.len() > depth && self.frame().tail {
4281 self.pop_frame();
4282 }
4283 if self.frames.len() == depth {
4284 return Ok(value);
4285 }
4286 // The caller resumes with the value on its stack.
4287 self.frames
4288 .last_mut()
4289 .expect("a caller is live")
4290 .stack
4291 .push(value);
4292 }
4293 Err(Signal::Throw(value)) => {
4294 // The host's standing request becomes the active mode for this unwind,
4295 // and is consumed here so it does not leak into the next throw.
4296 if self.uncatchable_next {
4297 self.uncatchable_next = false;
4298 self.uncatchable = true;
4299 }
4300 // An uncatchable throw walks past every `catch` on the way out. The
4301 // frames are still popped, because the values they hold have to be
4302 // dropped — only the search for a handler is skipped.
4303 if self.uncatchable {
4304 while self.frames.len() > depth {
4305 self.frames.pop();
4306 }
4307 return Err(Signal::Throw(value));
4308 }
4309 // A handler lives on the stack of the frame that is throwing —
4310 // `catch` pushed it there — so this frame gets the first chance
4311 // to catch before it is popped.
4312 let value = value;
4313 loop {
4314 if self.frames.len() <= depth {
4315 return Err(Signal::Throw(value));
4316 }
4317 if self.catch_here(value.clone()).is_some() {
4318 break;
4319 }
4320 self.frames.pop();
4321 }
4322 }
4323 // A `yield` in a frame that `execute` is running directly means a
4324 // generator body was entered as an ordinary call, which only happens if
4325 // the generator check in `call_or_push` was bypassed.
4326 Ok(Step::Suspend(_)) => {
4327 return Err(Signal::Throw(self.make_error(
4328 "InternalError",
4329 "a generator body ran as an ordinary call",
4330 )));
4331 }
4332 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4333 }
4334 }
4335 }
4336
4337 /// Install a handler for `value` if this frame has one, resuming at it.
4338 ///
4339 /// The scan is the reference's: walk the frame's stack downwards looking for the
4340 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
4341 /// `0` is an enumerator marker rather than a handler — it exists so that a
4342 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
4343 /// here and the unwinding continues.
4344 fn catch_here(&mut self, value: Value) -> Option<()> {
4345 let frame = self.frames.last_mut()?;
4346 while let Some(top) = frame.stack.pop() {
4347 if let Value::CatchOffset(offset) = top {
4348 if offset == 0 {
4349 continue;
4350 }
4351 frame.stack.push(value);
4352 frame.pc = offset as usize;
4353 return Some(());
4354 }
4355 }
4356 None
4357 }
4358
4359 fn push_frame(
4360 &mut self,
4361 code: Gc<CompiledCode>,
4362 env: Gc<ClosureEnv>,
4363 this: Value,
4364 mut args: Vec<Value>,
4365 callee: Value,
4366 ) -> JsResult<()> {
4367 // Two bounds, and the byte budget is the one that decides in practice. The
4368 // reference's message is `stack overflow` on an `InternalError`, not V8's
4369 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4370 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4371 let frame_cost = Self::frame_cost(&code);
4372 let stack_base = self.stack_used();
4373 if self.frames.len() >= self.max_frames
4374 || stack_base.saturating_add(frame_cost) > self.stack_limit
4375 {
4376 return Err(Signal::Throw(
4377 self.make_error("InternalError", "stack overflow"),
4378 ));
4379 }
4380 let arg_count = code.code.args.len();
4381 // How many were actually passed, which `arguments.length` reports and
4382 // `assert(x)` depends on: a call with one argument must not look like a call
4383 // with one argument and an explicit `undefined`.
4384 let passed = args.len();
4385 // Missing arguments are `undefined` in their slots; extra ones are dropped
4386 // from the slots but still reachable through `arguments`.
4387 //
4388 // A call that passes no more than the declared parameters needs **no** copy:
4389 // after the resize below, `args[..passed]` *is* the passed values. Only the
4390 // extra ones — which `truncate` is about to drop — have to be kept, and they are
4391 // the rare case. This used to copy every call: one `Value` clone per argument
4392 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4393 let passed_overflow = (passed > arg_count).then(|| {
4394 let mut values = self.take_values(passed, Value::Undefined);
4395 values[..passed].clone_from_slice(&args[..passed]);
4396 values
4397 });
4398 // Only when the counts differ, which for the overwhelmingly common call — as many
4399 // arguments as parameters — is never. `resize` followed by `truncate` on equal
4400 // lengths is two length compares and nothing else, but this is the hottest few
4401 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4402 if passed != arg_count {
4403 args.resize(arg_count, Value::Undefined);
4404 args.truncate(arg_count);
4405 }
4406 let cell_count = code.code.var_ref_count as usize;
4407 let mut cells = Vec::with_capacity(cell_count);
4408 for _ in 0..cell_count {
4409 cells.push(self.new_cell(Value::Undefined));
4410 }
4411 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4412 // A captured argument lives in its cell, not in the argument slot, so the
4413 // incoming value has to be moved there before the body runs.
4414 for (slot, cell) in code.arg_cell.iter().enumerate() {
4415 if *cell >= 0
4416 && let Some(value) = args.get(slot).cloned()
4417 {
4418 cells[*cell as usize].set(value);
4419 }
4420 }
4421 // Sloppy mode substitutes the global object for a missing receiver and boxes a
4422 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4423 // reports `object`. Strict mode passes the value through untouched.
4424 let this = if code.code.strict {
4425 this
4426 } else if this.is_nullish() {
4427 Value::Object(self.realm.global.clone())
4428 } else if matches!(this, Value::Object(_)) {
4429 this
4430 } else {
4431 match crate::builtins::this_object(self, &this) {
4432 Ok(boxed) => Value::Object(boxed),
4433 Err(_) => this,
4434 }
4435 };
4436 let stack_depth = code.code.stack_size as usize + 1;
4437 // Taken before the `push` borrows `self.frames`, because the operand stack comes
4438 // out of the same recycle pool the locals did.
4439 let stack = self.take_values(stack_depth, Value::Undefined);
4440 self.frames.push(Frame {
4441 code,
4442 env,
4443 this,
4444 args,
4445 passed_count: passed,
4446 passed_overflow: passed_overflow.map(Box::new),
4447 locals,
4448 cells,
4449 local_vars: None,
4450 // Exactly the depth the compiler computed, so the operand stack never
4451 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4452 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4453 // the buffer between calls, so "exactly" costs nothing after the first one.
4454 stack,
4455 pc: 0,
4456 at: 0,
4457 callee,
4458 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4459 cost: frame_cost,
4460 stack_base,
4461 tail: false,
4462 });
4463 Ok(())
4464 }
4465
4466 /// A value buffer of `len` slots, from the recycle pool when there is one.
4467 ///
4468 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4469 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4470 // A frame with no locals asks for nothing, and that is most frames: taking a
4471 // buffer out of the pool, clearing it and resizing it to zero is four operations
4472 // and a pool pop for an empty `Vec`, which is free to construct.
4473 if len == 0 {
4474 return Vec::new();
4475 }
4476 let mut buffer = self.free_values.pop().unwrap_or_default();
4477 buffer.clear();
4478 buffer.resize(len, fill);
4479 buffer
4480 }
4481
4482 /// Return a finished frame's value buffers for the next call to reuse.
4483 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4484 for mut buffer in [
4485 std::mem::take(&mut frame.locals),
4486 frame
4487 .passed_overflow
4488 .take()
4489 .map(|buffer| *buffer)
4490 .unwrap_or_default(),
4491 std::mem::take(&mut frame.stack),
4492 ] {
4493 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4494 // GC root: it kept every value the frame held reachable, which is invisible
4495 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4496 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4497 // exactly that within one run — the target `{}` of a finished IIFE was still
4498 // in its operand stack, in the pool.
4499 buffer.clear();
4500 // A buffer with no capacity is what `Vec::new` is; putting it back would just
4501 // fill the pool with nothing to offer.
4502 if free_values.len() < RECYCLE_SLOTS
4503 && buffer.capacity() > 0
4504 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4505 {
4506 free_values.push(buffer);
4507 }
4508 }
4509 }
4510
4511 /// Pop a finished frame and keep its buffers.
4512 ///
4513 /// Every place that drops a frame goes through here: a recycled buffer is also where
4514 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4515 /// nothing but the reuse.
4516 fn pop_frame(&mut self) -> Option<()> {
4517 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4518 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4519 let last = self.frames.len().checked_sub(1)?;
4520 Self::recycle(&mut self.free_values, &mut self.frames[last]);
4521 self.frames.truncate(last);
4522 Some(())
4523 }
4524
4525 /// Poll the host's interrupt handler, if one is installed.
4526 ///
4527 /// The counter is what keeps this off the hot path when nobody asked: the early return is
4528 /// one `Option` test, and with no handler installed the whole function is that test —
4529 /// `check_memory` next door already costs more, so this cannot be what shows up in a
4530 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4531 #[inline]
4532 fn check_interrupt(&mut self) -> JsResult<()> {
4533 if self.interrupt.is_none() {
4534 return Ok(());
4535 }
4536 if self.interrupt_counter > 0 {
4537 self.interrupt_counter -= 1;
4538 return Ok(());
4539 }
4540 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4541 // The closure is taken out for the duration so that a handler which re-enters the
4542 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4543 let mut handler = self.interrupt.take().expect("checked above");
4544 let abort = handler();
4545 self.interrupt = Some(handler);
4546 if abort {
4547 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4548 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4549 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4550 // documentation says.
4551 self.uncatchable = true;
4552 return Err(Signal::Throw(
4553 self.make_error("InternalError", "interrupted"),
4554 ));
4555 }
4556 Ok(())
4557 }
4558
4559 /// A memory checkpoint: does the heap still fit under its limit?
4560 ///
4561 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4562 /// a `Cell` read and a predictable branch, and the point of asking that often is that
4563 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4564 /// only at calls would let it run until the machine died, which is the exact failure
4565 /// `--memory-limit` exists to prevent.
4566 ///
4567 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4568 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4569 /// script that catches it, drops the reference and carries on is legitimate: measured
4570 /// on `qjs --memory-limit 1M`, the engine recovers.
4571 fn check_memory(&mut self) -> JsResult<()> {
4572 // One `Cell` read and a predictable branch when no limit is set, and an integer
4573 // compare when one is. Containers report their own growth as it happens
4574 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4575 // walking it here was the first version and it was O(live) per 256 instructions,
4576 // which turned a 100k-element push loop into a five-minute one.
4577 let Some(limit) = self.heap.memory_limit() else {
4578 return Ok(());
4579 };
4580 let used = self.heap.used_bytes();
4581 if used <= limit {
4582 // Back under the limit — a collection or a dropped reference did it. The next
4583 // time it goes over is a new failure, not a repeat of this one.
4584 self.oom_reported_at = 0;
4585 return Ok(());
4586 }
4587 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4588 // block runs normally after `out of memory` — it allocates nothing, so nothing
4589 // fails. A check that re-fired on every instruction made the handler itself throw,
4590 // which is a dead end: the error became unobservable from script.
4591 //
4592 // Comparing against the total at the last report gives the same behaviour: the
4593 // handler runs while the total is unchanged, and the very next allocation over the
4594 // limit fails.
4595 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4596 {
4597 return Ok(());
4598 }
4599 self.oom_reported_at = used;
4600 Err(Signal::Throw(
4601 self.make_error("InternalError", "out of memory"),
4602 ))
4603 }
4604
4605 /// Fail before allocating `payload` bytes, if they would not fit.
4606 ///
4607 /// For the allocations whose size comes from script data — `new Array(n)`,
4608 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4609 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4610 /// answering NULL for the one big request.
4611 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4612 if self.heap.fits(payload) {
4613 return Ok(());
4614 }
4615 Err(Signal::Throw(
4616 self.make_error("InternalError", "out of memory"),
4617 ))
4618 }
4619
4620 /// Bytes of frame state the live call chain accounts for.
4621 pub fn stack_used(&self) -> usize {
4622 match self.frames.last() {
4623 Some(frame) => frame.stack_base + frame.cost,
4624 None => 0,
4625 }
4626 }
4627
4628 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4629 ///
4630 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4631 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4632 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4633 /// instead. That is the whole difference between the two models: it rations C stack, we
4634 /// ration frame state, and both quantities are dominated by the value slots — which is
4635 /// why the two depths come out comparable rather than merely proportional.
4636 fn frame_cost(code: &CompiledCode) -> usize {
4637 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4638 std::mem::size_of::<Frame>()
4639 + std::mem::size_of::<Value>() * slots
4640 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4641 }
4642
4643 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4644 ///
4645 /// Only names the eval created are here: a name the frame already declared statically
4646 /// is written through to its own slot instead, so this cannot shadow a real local.
4647 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4648 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4649 let (local_vars, phase) = self.visible_local_vars()?;
4650 if !local_vars.contains(name) {
4651 return None;
4652 }
4653 local_vars.get(name, phase)
4654 }
4655
4656 /// The variables a direct `eval` declared, as the code currently running sees them.
4657 ///
4658 /// Inside an eval that is the *caller's* set — the eval's own variable environment
4659 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4660 /// else it is the current frame's, falling back to the frame the closure was created
4661 /// in.
4662 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4663 ///
4664 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4665 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4666 /// refcount operations (the clone out of the frame, the drop at the end of the match)
4667 /// just to be asked `is_none`.
4668 fn has_visible_local_vars(&self) -> bool {
4669 let index = match self.eval_caller.flatten() {
4670 Some(caller) => caller,
4671 None => match self.frames.len().checked_sub(1) {
4672 Some(top) => top,
4673 None => return false,
4674 },
4675 };
4676 match self.frames.get(index) {
4677 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4678 None => false,
4679 }
4680 }
4681
4682 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4683 // While an `eval` runs, its own frame is on top but its variable environment is
4684 // the *caller's* — so the caller is what the lookup has to start from.
4685 let (index, phase) = match self.eval_caller.flatten() {
4686 Some(caller) => (
4687 caller,
4688 if self.in_parameter_list_at(caller) {
4689 0
4690 } else {
4691 1
4692 },
4693 ),
4694 None => (
4695 self.frames.len().checked_sub(1)?,
4696 if self.in_parameter_list() { 0 } else { 1 },
4697 ),
4698 };
4699 let frame = self.frames.get(index)?;
4700 // The frame's own variables, or — for an arrow, which has no variable environment
4701 // of its own — the one it was created in, which `ClosureEnv` carries.
4702 if let Some(local_vars) = frame.local_vars.clone() {
4703 return Some((local_vars, phase));
4704 }
4705 frame
4706 .env
4707 .local_vars
4708 .clone()
4709 .map(|local_vars| (local_vars, frame.env.local_phase))
4710 }
4711
4712 /// Whether the innermost frame is still evaluating its parameter list.
4713 ///
4714 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4715 /// and a closure created there may only see that much of [`LocalVars`].
4716 fn in_parameter_list(&self) -> bool {
4717 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4718 }
4719
4720 /// [`Interp::in_parameter_list`] for a specific frame.
4721 fn in_parameter_list_at(&self, frame: usize) -> bool {
4722 let Some(frame) = self.frames.get(frame) else {
4723 return false;
4724 };
4725 let code = &frame.code.code;
4726 if !code.has_parameter_expressions {
4727 return false;
4728 }
4729 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4730 // function as its body and let a direct `eval` act accordingly.
4731 if code.body_start == (0, 0) {
4732 return false;
4733 }
4734 match code.position_at(frame.at as u32) {
4735 Some(position) => position < code.body_start,
4736 None => false,
4737 }
4738 }
4739
4740 fn frame(&self) -> &Frame {
4741 self.frames.last().expect("a frame is live")
4742 }
4743
4744 fn frame_mut(&mut self) -> &mut Frame {
4745 self.frames.last_mut().expect("a frame is live")
4746 }
4747
4748 // -- slot access --------------------------------------------------------
4749
4750 /// Move a local's value out, leaving `undefined` in the slot.
4751 ///
4752 /// `None` for a captured slot: its value lives in a cell shared with every closure
4753 /// that closed over it, so it can never be exclusively ours and must not be taken.
4754 ///
4755 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4756 /// for every read and fatal for this one — a clone is exactly the second handle that
4757 /// rules out growing the string in place.
4758 fn take_loc(&mut self, slot: usize) -> Option<Value> {
4759 let frame = self.frames.last_mut()?;
4760 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4761 return None;
4762 }
4763 frame
4764 .locals
4765 .get_mut(slot)
4766 .map(|value| std::mem::replace(value, Value::Undefined))
4767 }
4768
4769 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4770 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4771 ///
4772 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4773 /// it** — the value is put back before the general path runs — so a `valueOf` that
4774 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4775 /// error as it would have without the fusion. This is why the in-place attempt is a
4776 /// `take` and not a `get`: an optimisation that changes what an exception observes is
4777 /// a wrong answer with a good excuse.
4778 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4779 // The take is `matches!`-guarded on the *right* operand only, and the taken value
4780 // is put back on every path that does not append. An earlier version wrote the two
4781 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4782 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4783 // through with its value already taken and dropped: the general path below then
4784 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4785 // A wrong answer, from an optimisation, with every test green.
4786 if matches!(right, Value::String(_))
4787 && let Some(taken) = self.take_loc(slot)
4788 {
4789 if let Value::String(mut left) = taken {
4790 let appended = match left.get_mut() {
4791 Some(string) => string.append_in_place(
4792 // The pattern is the one `matches!` just checked.
4793 match &right {
4794 Value::String(text) => text,
4795 _ => unreachable!("guarded above"),
4796 },
4797 ),
4798 None => None,
4799 };
4800 self.put_loc(slot, Value::String(left));
4801 if let Some(added) = appended {
4802 // The buffer grew where it stood, so the heap's running total has to
4803 // be told: `measure_used` would report the new length, and the two must
4804 // agree or the subtraction at free time leaves the counter wrong.
4805 self.heap.adjust_payload(added as isize);
4806 return Ok(());
4807 }
4808 } else {
4809 self.put_loc(slot, taken);
4810 }
4811 }
4812 // The two-number case, without an operand stack round trip. Everything below
4813 // this point is the *general* path: push both, call `binary_add`, pop the answer,
4814 // store it — five operations and two `Value` clones for what is one integer add.
4815 // `AddImmLoc` already answers this shape that way; the fusion above it was written
4816 // for string append and never got the numeric half, so `t += i` — a counting loop
4817 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4818 let left = self.get_loc(slot);
4819 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4820 self.put_loc(
4821 slot,
4822 match a.checked_add(*b) {
4823 Some(sum) => Value::Int(sum),
4824 None => Value::Float(*a as f64 + *b as f64),
4825 },
4826 );
4827 return Ok(());
4828 }
4829 self.push(left);
4830 self.push(right);
4831 self.binary_add()?;
4832 let value = self.pop();
4833 self.put_loc(slot, value);
4834 Ok(())
4835 }
4836
4837 fn get_arg(&self, slot: usize) -> Value {
4838 self.frame().read_arg(slot)
4839 }
4840
4841 fn put_arg(&mut self, slot: usize, value: Value) {
4842 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4843 if cell == -1 {
4844 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4845 *slot = value;
4846 }
4847 } else {
4848 self.frame().cells[cell as usize].set(value);
4849 }
4850 }
4851
4852 fn get_loc(&self, slot: usize) -> Value {
4853 // The cell mapping is `-1` for every slot that was not captured — which is all of
4854 // them in a function that creates no closure. `Frame::read_loc` tests that first,
4855 // so the common case is one array read and a clone: 20% of every loop iteration
4856 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4857 // sample of `dispatch:arith`).
4858 self.frame().read_loc(slot)
4859 }
4860
4861 fn put_loc(&mut self, slot: usize, value: Value) {
4862 // One borrow instead of three, and the cell check on the frame we already hold.
4863 let frame = self.frames.last_mut().expect("a frame is live");
4864 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4865 if cell < 0 {
4866 if let Some(slot) = frame.locals.get_mut(slot) {
4867 *slot = value;
4868 }
4869 } else if let Some(cell) = frame.cells.get(cell as usize) {
4870 cell.set(value);
4871 }
4872 }
4873
4874 // -- globals ------------------------------------------------------------
4875
4876 /// The name a global-slot operand refers to.
4877 fn global_name(&self, slot: usize) -> String {
4878 self.frame()
4879 .code
4880 .code
4881 .closure_vars
4882 .get(slot)
4883 .map(|c| c.name.clone())
4884 .unwrap_or_default()
4885 }
4886
4887 /// The facts about a global binding that decide where it lives.
4888 ///
4889 /// A script's globals split in two, and the split is observable: `var` and
4890 /// function declarations become properties of the global object (`globalThis.v`
4891 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4892 /// declarations live in the global *lexical* environment and are invisible there
4893 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4894 /// `is_lexical` flag means the answer is already in the bytecode.
4895 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4896 let name = self.global_name(slot);
4897 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4898 // while forwarding a reference through a nested function is built with the
4899 // flags cleared, so `const c` would look like an ordinary `var` from inside a
4900 // closure. Presence in the realm's lexical table is the same fact, recorded
4901 // once, and every slot sees it.
4902 let lexical = self.realm.globals.contains_key(&name);
4903 let is_const = self.realm.lexical_consts.contains(&name);
4904 (name, lexical, is_const)
4905 }
4906
4907 /// The value of `name` in the innermost active `with` object, if any.
4908 ///
4909 /// The active objects are the [`VarKind::With`] locals of every frame still running,
4910 /// innermost frame first and innermost block first within one. Walking frames rather
4911 /// than keeping a separate stack is what makes a closure called from inside a `with`
4912 /// see it, and what keeps the object alive only as long as the block is.
4913 /// The innermost active `with` object that has `name`, if any.
4914 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4915 let objects = self.eval_with.clone().unwrap_or_default();
4916 for object in objects {
4917 let key = self.string(name.to_string());
4918 if self
4919 .has_property(&key, &Value::Object(object.clone()))
4920 .ok()?
4921 {
4922 return Some(object);
4923 }
4924 }
4925 None
4926 }
4927
4928 /// Every active `with` object, innermost first.
4929 fn with_objects(&self) -> Vec<Gc<JsObject>> {
4930 let mut objects = Vec::new();
4931 for frame in self.frames.iter().rev() {
4932 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4933 if var.kind != js_compile::VarKind::With {
4934 continue;
4935 }
4936 // A captured binding lives in its cell and not in the slot list, so the
4937 // cell is consulted first — a closure created inside the block is exactly
4938 // what makes the object captured. Before the store runs the slot still
4939 // holds `undefined`, and a `with` object is always boxed, so a non-object
4940 // entry is simply not in scope yet.
4941 let value = frame
4942 .code
4943 .loc_cell
4944 .get(index)
4945 .copied()
4946 .filter(|cell| *cell >= 0)
4947 .and_then(|cell| frame.cells.get(cell as usize))
4948 .map(|cell| cell.get())
4949 .or_else(|| frame.locals.get(index).cloned());
4950 if let Some(Value::Object(object)) = value {
4951 objects.push(object);
4952 }
4953 }
4954 }
4955 objects
4956 }
4957
4958 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
4959 for object in self.eval_with.clone().unwrap_or_default() {
4960 let key = self.string(name.to_string());
4961 if self.has_property(&key, &Value::Object(object.clone()))? {
4962 return Ok(Some(self.read_field(&Value::Object(object), name)?));
4963 }
4964 }
4965 Ok(None)
4966 }
4967
4968 /// Whether every scope between here and the global object is an ordinary one.
4969 ///
4970 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
4971 /// bytecode resolved; when any is live the general path has to run in full order. When
4972 /// none is — every ordinary program — a global read is a property read and nothing
4973 /// else, and that is worth caching.
4974 fn scopes_are_plain(&self) -> bool {
4975 self.eval_caller.is_none()
4976 && self.eval_with.is_none()
4977 && self.eval_arguments.is_none()
4978 && self.eval_bindings.is_empty()
4979 && self.eval_scope.is_none()
4980 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
4981 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
4982 // its `ClosureEnv`, so the test has to be the same one the general path makes.
4983 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
4984 // upstream corpus caught and no unit test did.
4985 && !self.has_visible_local_vars()
4986 && self.frame().env.eval_scope.is_none()
4987 }
4988
4989 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
4990 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
4991 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
4992 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
4993 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
4994 // borrow outlive the `&mut self` the lookup needs.
4995 //
4996 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
4997 // forwarded through a nested function has its flags cleared, so the flag cannot
4998 // be believed.
4999 let code = self.frame().code.clone();
5000 let name = code
5001 .code
5002 .closure_vars
5003 .get(slot)
5004 .map(|c| c.name.as_str())
5005 .unwrap_or_default();
5006 let lexical = self.realm.globals.contains_key(name);
5007 // The common case, first: an ordinary global `var`, with a cache in front of the
5008 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
5009 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
5010 // cache hit and return without touching any of it.
5011 if !lexical && self.scopes_are_plain() {
5012 return self.get_plain_global(name, slot);
5013 }
5014 if name == "arguments"
5015 && let Some(arguments) = &self.eval_arguments
5016 {
5017 return Ok(arguments.clone());
5018 }
5019 // A `with` block around the *call site* is part of the scope an `eval` sees, so
5020 // the objects live when the eval started are consulted before anything else. The
5021 // snapshot is taken at entry rather than scanning the frames on every read: a
5022 // block that has already finished still leaves its object in the slot, and a
5023 // bytecode read outside the block must not see it.
5024 if let Some(value) = self.with_lookup(name)? {
5025 return Ok(value);
5026 }
5027 // A variable a direct `eval` declared shadows everything the compiler resolved,
5028 // including an enclosing function's binding: the eval put it in the caller's own
5029 // variable environment, which is nearer than any captured scope.
5030 if let Some((local_vars, phase)) = self.visible_local_vars()
5031 && let Some(cell) = local_vars.get(name, phase)
5032 {
5033 return Ok(cell.get());
5034 }
5035 // The frame that called `eval` is the innermost scope the eval'd code sees, so
5036 // its local `a` wins over a global `a`.
5037 if let Some(value) = self.eval_binding_value(name) {
5038 return Ok(value);
5039 }
5040 // A closure created by an `eval` resolves its free names against the bindings
5041 // that eval saw, even after the eval (and its frames) are gone.
5042 if let Some(cell) = self
5043 .frame()
5044 .env
5045 .eval_scope
5046 .as_ref()
5047 .and_then(|scope| scope.get(name))
5048 {
5049 let value = cell.get();
5050 if matches!(value, Value::Uninitialized) {
5051 return Err(self.throw_reference(name));
5052 }
5053 return Ok(value);
5054 }
5055 // A binding declared by the strict `eval` currently running shadows anything
5056 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5057 if let Some(scope) = &self.eval_scope
5058 && let Some(value) = scope.get(name)
5059 {
5060 return Ok(value.clone());
5061 }
5062 if lexical {
5063 // A lexical global is a binding in a side table, so the dead zone is
5064 // visible and it is nowhere on the global object.
5065 if let Some(cell) = self.realm.globals.get(name) {
5066 let value = cell.get();
5067 if matches!(value, Value::Uninitialized) {
5068 return Err(self.throw_reference(name));
5069 }
5070 return Ok(value);
5071 }
5072 return Err(self.throw_reference(name));
5073 }
5074 // A `var` global is an ordinary property, so the prototype chain and the
5075 // global object's own builtins are all reachable through it.
5076 match self.get_property(&self.realm.global.clone(), name)? {
5077 Some(value) => Ok(value),
5078 None => Err(self.throw_reference(name)),
5079 }
5080 }
5081
5082 /// Read a plain global `var`: a cached own data property, or the full lookup.
5083 ///
5084 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5085 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5086 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5087 let object = self.realm.global.clone();
5088 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5089 if let Some(cached) = &self.global_cache[site]
5090 && object.upgrades_to(&cached.object)
5091 && let Some(value) = object.data_property_at(cached.index, name)
5092 {
5093 return Ok(value);
5094 }
5095 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5096 // chain exactly as before, then remember the answer if it is worth remembering.
5097 let Some(value) = self.get_property(&object, name)? else {
5098 return Err(self.throw_reference(name));
5099 };
5100 if let Some(index) = object.own_data_index(name) {
5101 self.global_cache[site] = Some(GlobalCache {
5102 object: object.downgrade(),
5103 index,
5104 });
5105 }
5106 Ok(value)
5107 }
5108
5109 /// Store to a global binding.
5110 ///
5111 /// Returns a signal when the store is refused: a `const` global may only be
5112 /// written by its initialiser, and a non-configurable `var` global may not be
5113 /// deleted but is always writable.
5114 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5115 let (name, lexical, is_const) = self.global_binding(slot);
5116
5117 // An assignment inside a `with` writes through to the object that supplies the
5118 // name, which for an `eval` means consulting the same chain `get_global` does.
5119 if let Some(owner) = self.with_owner(&name) {
5120 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5121 return Ok(());
5122 }
5123 // A variable the running eval *declared* takes the write before any caller
5124 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5125 // environment even when an enclosing function has a `var c` of its own.
5126 if self.eval_caller.flatten().is_some()
5127 && let Some((local_vars, phase)) = self.visible_local_vars()
5128 && local_vars.contains(&name)
5129 && let Some(cell) = local_vars.get(&name, phase)
5130 {
5131 cell.set(value);
5132 return Ok(());
5133 }
5134 // A binding of the frame that called `eval` takes the write, which is what
5135 // makes `f("a = 3")` change the caller's `a`.
5136 if self.set_eval_binding(&name, &value)? {
5137 return Ok(());
5138 }
5139 // A closure that outlived its `eval` writes through to the same cell it reads.
5140 if let Some(cell) = self
5141 .frame()
5142 .env
5143 .eval_scope
5144 .as_ref()
5145 .and_then(|scope| scope.get(&name))
5146 .cloned()
5147 {
5148 cell.set(value);
5149 return Ok(());
5150 }
5151 // Inside a strict `eval`, a name it declared itself is stored there. An
5152 // *assignment* to a name nobody declared is not a declaration, so it falls
5153 // through: strict mode raises `ReferenceError` for it, which is what
5154 // `eval("1 + (@not_def = 1)")` has to do.
5155 if let Some(scope) = self.eval_scope.as_mut()
5156 && scope.contains_key(&name)
5157 {
5158 scope.insert(name, value);
5159 return Ok(());
5160 }
5161 if lexical {
5162 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5163 if is_const && !matches!(cell.get(), Value::Uninitialized) {
5164 return Err(self.read_only_global(&name));
5165 }
5166 cell.set(value);
5167 return Ok(());
5168 }
5169 // Writing an undeclared lexical global is a `ReferenceError` in strict
5170 // mode and a silent global creation otherwise; creating the cell here
5171 // keeps both paths from losing the value.
5172 let cell = self.new_cell(value);
5173 self.realm.globals.insert(name, cell);
5174 return Ok(());
5175 }
5176 // A variable a direct `eval` declared in this call shadows the global object, even
5177 // when the global already has a property of that name — `var c = "global"` at the
5178 // top level must not capture `eval("var c = 1")` inside a function.
5179 if let Some((local_vars, phase)) = self.visible_local_vars()
5180 && local_vars.contains(&name)
5181 && let Some(cell) = local_vars.get(&name, phase)
5182 {
5183 cell.set(value);
5184 return Ok(());
5185 }
5186 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5187 // remembered a global's slot index since M12b, but the *store* side never did: it
5188 // converted the name to a `PropertyKey` (two allocations) and then scanned the
5189 // global object's whole table — which holds every builtin — on every assignment to
5190 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5191 // full global lookup per iteration; measured with a counter, `s` as a global made
5192 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5193 //
5194 // Re-validated exactly like the read: same object, same index, still the name, and
5195 // — the one extra check a store needs — still writable. A global that is an
5196 // accessor, non-writable, or inherited fails here and falls through to the full
5197 // path below, which reports the failure the way it always did.
5198 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5199 let global = self.realm.global.clone();
5200 if let Some(cached) = &self.global_cache[site]
5201 && global.upgrades_to(&cached.object)
5202 && global.write_data_at(cached.index, &name, value.clone())
5203 {
5204 return Ok(());
5205 }
5206 match global.own_property(&name) {
5207 // A `var` global is writable, so the store goes straight through — but
5208 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5209 // store (a non-writable or accessor-without-setter global) is a silent
5210 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5211 // split every other assignment has.
5212 Some(_) => {
5213 let on_failure = if self.current_strict() {
5214 DeleteFailure::Throw
5215 } else {
5216 DeleteFailure::Ignore
5217 };
5218 let result = self.set_property_with(&global, &name, value, on_failure);
5219 // Teach the cache the slot for a plain writable own data property, which is
5220 // what a declared `var` is. Without this the fast path above could never
5221 // fire for a global that is only ever *written* — its entry would have to
5222 // be put there by a read of the same slot, and a write-only loop has none.
5223 if result.is_ok()
5224 && let Some(index) = global.own_data_index(&name)
5225 {
5226 self.global_cache[site] = Some(GlobalCache {
5227 object: global.downgrade(),
5228 index,
5229 });
5230 }
5231 result
5232 }
5233 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5234 // declaration creates a *configurable* property, which is what makes it
5235 // deletable and is the one way a global differs from a declared `var`.
5236 // In strict mode the same store is a `ReferenceError` instead: that is the
5237 // whole point of strict mode, and creating the global silently meant
5238 // `"use strict"; x = 1` looked like it worked.
5239 None => {
5240 if self.current_strict() {
5241 return Err(self.throw_reference(&name));
5242 }
5243 // A direct eval declares here rather than on the global object: its
5244 // `var`s belong to the caller's variable environment. `declare_eval_local`
5245 // also covers a plain assignment to a variable an earlier eval made.
5246 if let Some(cell) = self.declare_eval_local(&name) {
5247 cell.set(value);
5248 return Ok(());
5249 }
5250 global.define_data(&name, value);
5251 Ok(())
5252 }
5253 }
5254 }
5255
5256 /// The value of a binding of the frame that called `eval`, if there is one.
5257 fn eval_binding_value(&self, name: &str) -> Option<Value> {
5258 let binding = self
5259 .eval_bindings
5260 .iter()
5261 .find(|binding| binding.name == name)?;
5262 let owner = self.frames.get(binding.frame)?;
5263 let (slot, index) = (binding.slot, binding.index);
5264 Some(match slot {
5265 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5266 cell if cell >= 0 => owner
5267 .cells
5268 .get(cell as usize)
5269 .map(|cell| cell.get())
5270 .unwrap_or(Value::Undefined),
5271 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5272 },
5273 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5274 cell if cell >= 0 => owner
5275 .cells
5276 .get(cell as usize)
5277 .map(|cell| cell.get())
5278 .unwrap_or(Value::Undefined),
5279 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5280 },
5281 })
5282 }
5283
5284 /// Write to a binding of the frame that called `eval`.
5285 ///
5286 /// `Ok(false)` means no binding matched and the caller should keep looking. A
5287 /// matched binding can still refuse the store, which is why this is fallible: a
5288 /// `const` is read-only everywhere, and a named function expression's own name is
5289 /// read-only in strict mode.
5290 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5291 let Some(binding) = self
5292 .eval_bindings
5293 .iter()
5294 .find(|binding| binding.name == name)
5295 else {
5296 return Ok(false);
5297 };
5298 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5299 let strict = self.current_strict();
5300 let Some(owner) = self.frames.get_mut(frame) else {
5301 return Ok(false);
5302 };
5303 match slot {
5304 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5305 cell if cell >= 0 => {
5306 if let Some(cell) = owner.cells.get(cell as usize) {
5307 cell.set(value.clone());
5308 }
5309 }
5310 _ => {
5311 if let Some(slot) = owner.args.get_mut(index) {
5312 *slot = value.clone();
5313 }
5314 }
5315 },
5316 EvalSlot::Local => {
5317 let declared = owner.code.code.vars.get(index);
5318 // A `const` is read-only even through `eval`. The realm records this for
5319 // globals (see `lexical_consts`), but a local's `const`-ness is only in
5320 // the bytecode, so this is where it has to be enforced.
5321 if declared.is_some_and(|var| var.is_const) {
5322 return Err(self.read_only_local(name));
5323 }
5324 // The name of a named function expression is read-only too, but only
5325 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5326 // such a name is ignored, the same as a direct store would be.
5327 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5328 return if strict {
5329 Err(self.read_only_local(name))
5330 } else {
5331 Ok(true)
5332 };
5333 }
5334 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5335 cell if cell >= 0 => {
5336 if let Some(cell) = owner.cells.get(cell as usize) {
5337 cell.set(value.clone());
5338 }
5339 }
5340 _ => {
5341 if let Some(slot) = owner.locals.get_mut(index) {
5342 *slot = value.clone();
5343 }
5344 }
5345 }
5346 }
5347 }
5348 Ok(true)
5349 }
5350
5351 /// The `TypeError` an assignment to a read-only binding raises.
5352 fn read_only_local(&self, name: &str) -> Signal {
5353 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5354 }
5355
5356 /// Declare `name` as a variable of the frame that called the running `eval`.
5357 ///
5358 /// `None` when there is no direct eval in progress, or it was called from the top
5359 /// level — then the caller's variable environment *is* the global one and the
5360 /// existing path is right.
5361 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5362 let caller = self.eval_caller.flatten()?;
5363 // The bottom frame is the top-level script, whose variable environment *is* the
5364 // global one — so `eval("var x = 1")` at the top level still creates a global.
5365 if caller == 0 {
5366 return None;
5367 }
5368 // A name the eval's *own* variable environment already binds is not a new
5369 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5370 // `arguments`, and creating a second binding would leave the first — the one
5371 // closures read — untouched. A binding of an *outer* frame does not count: a
5372 // declaration shadows it rather than writing through.
5373 if self
5374 .eval_bindings
5375 .iter()
5376 .any(|binding| binding.name == name && binding.frame == caller)
5377 {
5378 return None;
5379 }
5380 let phase = if self.in_parameter_list_at(caller) {
5381 0
5382 } else {
5383 1
5384 };
5385 self.frame_local_vars(caller)?;
5386 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5387 if let Some(cell) = local_vars.get(name, 1) {
5388 return Some(cell);
5389 }
5390 let cell = self.new_cell(Value::Undefined);
5391 Some(local_vars.declare(name, phase, cell))
5392 }
5393
5394 /// Make sure `frame` has a `LocalVars`, creating it on demand.
5395 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5396 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5397 return Some(local_vars.clone());
5398 }
5399 let local_vars = Gc::new(self.heap, LocalVars::new());
5400 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5401 Some(local_vars)
5402 }
5403
5404 /// Whether the realm already has a binding for `name`, lexically or as an *own*
5405 /// property of the global object. Used to decide whether a store inside an
5406 /// `eval` writes through to the realm or declares a binding of its own.
5407 ///
5408 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5409 /// write to `Object.prototype.toString`, and must not shadow it either.
5410 fn global_knows(&mut self, name: &str) -> bool {
5411 if self.realm.globals.contains_key(name) {
5412 return true;
5413 }
5414 self.realm.global.own_property(name).is_some()
5415 }
5416
5417 /// Whether the code currently running is strict.
5418 ///
5419 /// Read off the frame's function, which is where the parser's answer ended up; a
5420 /// native function never runs strict-only checks, and there is no frame at all
5421 /// before the first script.
5422 pub fn current_strict(&self) -> bool {
5423 self.frames
5424 .last()
5425 .is_some_and(|frame| frame.code.code.strict)
5426 }
5427
5428 /// Initialise a declared global, which is what ends its dead zone.
5429 ///
5430 /// A `var` global becomes a property of the global object: writable, so a later
5431 /// assignment goes through, and non-configurable, so `delete` refuses.
5432 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5433 let (name, lexical, _) = self.global_binding(slot);
5434 // A `var` declared by the strict `eval` currently running belongs to the
5435 // eval's scope, not to the global object: `eval("var v = 1")` must not make
5436 // `typeof v` answer `"number"` afterwards. A name the realm already has is
5437 // initialised in place, which is what a re-declaration inside eval does.
5438 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5439 self.eval_scope
5440 .as_mut()
5441 .expect("checked above")
5442 .insert(name, value);
5443 return Ok(());
5444 }
5445 if let Some(scope) = self.eval_scope.as_mut()
5446 && scope.contains_key(&name)
5447 {
5448 scope.insert(name, value);
5449 return Ok(());
5450 }
5451 if lexical {
5452 // The cell exists (created at declaration time) holding the dead-zone
5453 // marker; storing the value is what makes the binding readable.
5454 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5455 cell.set(value);
5456 return Ok(());
5457 }
5458 let cell = self.new_cell(value);
5459 self.realm.globals.insert(name, cell);
5460 return Ok(());
5461 }
5462 let global = self.realm.global.clone();
5463 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5464 // to answer `false` and leave the binding in place. `with_attributes` ties
5465 // `configurable` to `writable`, so the property is built field by field.
5466 global.define(
5467 &name,
5468 Property {
5469 value: Some(value),
5470 writable: true,
5471 enumerable: true,
5472 configurable: false,
5473 ..Property::default()
5474 },
5475 );
5476 Ok(())
5477 }
5478
5479 /// The `TypeError` a store to a `const` global raises.
5480 fn read_only_global(&self, name: &str) -> Signal {
5481 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5482 }
5483
5484 // -- properties ---------------------------------------------------------
5485
5486 /// Read `object[key]`, following the prototype chain.
5487 ///
5488 /// An inherited accessor runs with the *receiver* as `this`, which is why the
5489 /// lookup returns the owner rather than just the value.
5490 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5491 self.get_property_key(object, &PropertyKey::from(key))
5492 }
5493
5494 /// [`Interp::get_property`] with a key that may be a symbol.
5495 pub fn get_property_key(
5496 &mut self,
5497 object: &Gc<JsObject>,
5498 key: &PropertyKey,
5499 ) -> JsResult<Option<Value>> {
5500 self.get_property_key_for(object, None, key)
5501 }
5502
5503 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5504 ///
5505 /// The receiver matters when the property is found on a *prototype*: a getter has to
5506 /// see the object the read started from. For a primitive that is the primitive
5507 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5508 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5509 /// the owner.
5510 pub fn get_property_key_for(
5511 &mut self,
5512 object: &Gc<JsObject>,
5513 receiver: Option<&Value>,
5514 key: &PropertyKey,
5515 ) -> JsResult<Option<Value>> {
5516 // A proxy answers for itself, before any of the shortcuts below: `new
5517 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5518 // have.
5519 if object.proxy_state().is_some() {
5520 let receiver = receiver
5521 .cloned()
5522 .unwrap_or_else(|| Value::Object(object.clone()));
5523 return self.proxy_get(object, &receiver, key);
5524 }
5525 // A host class's `get_property` trap replaces the whole read, prototype walk
5526 // included — that is what makes a native accessor free rather than a JavaScript
5527 // getter call.
5528 if let Some(exotic) = object.exotic() {
5529 let receiver_value = receiver
5530 .cloned()
5531 .unwrap_or_else(|| Value::Object(object.clone()));
5532 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5533 return Ok(Some(value));
5534 }
5535 // With no `get_property` trap, a `get_own_property` trap still answers for the
5536 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5537 // and the hook lives exactly there. A key the trap reports as absent is still
5538 // looked for on the prototype, which is why the search resumes *above*.
5539 if let Some(property) = exotic.get_own_property(self, object, key)? {
5540 return match property {
5541 Some(property) => self.read_property(property, object, receiver),
5542 None => match lookup_key_above(object, key) {
5543 Some((_, property)) => self.read_property(property, object, receiver),
5544 None => Ok(None),
5545 },
5546 };
5547 }
5548 }
5549 // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
5550 // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
5551 // The `[[Get]]` short-circuit therefore belongs to this one arm.
5552 //
5553 // Constructibility is exactly the split the reference makes: `function f(){}` and
5554 // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
5555 // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
5556 // function" — it *is* the predicate, which is why no extra marker is needed.
5557 if let Some(text) = key.as_str()
5558 && (text == "caller" || text == "arguments")
5559 && object.is_constructor()
5560 && object.is_callable()
5561 && !object.is_bound_function()
5562 // …and only when the body is **sloppy**. A strict body reaches the
5563 // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
5564 // whole `Function/15.3.5.4_2-*gs` family is written against
5565 // (`onlyStrict`, so every function in them is strict).
5566 && !object.function_is_strict()
5567 && object.own_property(text).is_none()
5568 {
5569 return Ok(Some(Value::Undefined));
5570 }
5571 // The element-vector and `length` shortcuts are string-only: an array index
5572 // has no symbol spelling.
5573 if let Some(text) = key.as_str() {
5574 if let Some(value) = self.own_element(object, text) {
5575 return Ok(Some(value));
5576 }
5577 // `length` is not stored as a property: an array's length is its element
5578 // count, and keeping one copy of it is what makes `push`/`pop` and
5579 // `a.length = n` agree.
5580 if let Some(length) = object.array_length()
5581 && text == "length"
5582 {
5583 // Not `Value::Int(length as i32)`: see [`length_value`].
5584 return Ok(Some(crate::object::length_value(length)));
5585 }
5586 }
5587 // A proxy or a hooked exotic object anywhere above `object` makes the static
5588 // table walk below wrong: a proxy's own table is *empty by design* (the properties
5589 // live on its target), so the walk skipped that link entirely and everything behind
5590 // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
5591 // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
5592 // -target-is-proxy.js` are the four.
5593 if Self::chain_needs_dispatch(object) {
5594 return self.walk_get(object, receiver, key);
5595 }
5596 match lookup_key(object, key) {
5597 Some((_, property)) => self.read_property(property, object, receiver),
5598 None => Ok(None),
5599 }
5600 }
5601
5602 /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
5603 /// answer for itself.
5604 ///
5605 /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
5606 /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
5607 /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
5608 /// an inherited getter the object the read started from.
5609 fn walk_get(
5610 &mut self,
5611 start: &Gc<JsObject>,
5612 receiver: Option<&Value>,
5613 key: &PropertyKey,
5614 ) -> JsResult<Option<Value>> {
5615 let receiver = receiver
5616 .cloned()
5617 .unwrap_or_else(|| Value::Object(start.clone()));
5618 let mut current = Some(start.clone());
5619 while let Some(holder) = current {
5620 // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
5621 // has to ask it, not read its (empty) own-property table. `Object.create(new
5622 // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
5623 // instead found nothing.
5624 if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
5625 return Ok(Some(value));
5626 }
5627 // A host class's `get_property` trap replaces the whole read for that holder,
5628 // prototype walk included — the same rule `get_property_key_for` applies to the
5629 // first object.
5630 if let Some(exotic) = holder.exotic()
5631 && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
5632 {
5633 return Ok(Some(value));
5634 }
5635 if let Some(property) = self.object_get_own_property(&holder, key)? {
5636 return self.read_property(property, &holder, Some(&receiver));
5637 }
5638 current = self.object_prototype_of(&holder)?;
5639 }
5640 Ok(None)
5641 }
5642
5643 /// Whether `object` or anything above it has properties that cannot be read out of a
5644 /// property table — a proxy, or an exotic object with a `get_own_property` hook.
5645 ///
5646 /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
5647 /// is the hot path for every property read; this is the check that decides whether it
5648 /// is safe to take it.
5649 fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
5650 object
5651 .chain()
5652 .iter()
5653 .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
5654 }
5655
5656 /// The value a property read answers.
5657 ///
5658 /// One place rather than three, because an accessor has to run with the *receiver* as
5659 /// `this` whether the descriptor came from the property table, an exotic
5660 /// `get_own_property` trap, or a prototype above one.
5661 fn read_property(
5662 &mut self,
5663 property: Property,
5664 object: &Gc<JsObject>,
5665 receiver: Option<&Value>,
5666 ) -> JsResult<Option<Value>> {
5667 if property.is_accessor() {
5668 match &property.getter {
5669 Some(getter) if !matches!(getter, Value::Undefined) => {
5670 let receiver = receiver
5671 .cloned()
5672 .unwrap_or_else(|| Value::Object(object.clone()));
5673 self.call_value(getter.clone(), receiver, Vec::new())
5674 .map(Some)
5675 }
5676 // An accessor with no getter reads as `undefined`.
5677 _ => Ok(Some(Value::Undefined)),
5678 }
5679 } else {
5680 Ok(property.value)
5681 }
5682 }
5683
5684 /// `super.key` — start the search at `proto`, but report to `receiver`.
5685 ///
5686 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5687 /// found on the prototype of a class has to see the *instance* as `this`, and a
5688 /// plain property read off `proto` would lose that.
5689 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5690 let start = self.require_object(proto)?;
5691 let key = self.propkey(key)?;
5692 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5693 if matches!(proto, Value::Null) {
5694 return Ok(Value::Undefined);
5695 }
5696 match lookup_key(&start, &key) {
5697 Some((_, property)) if property.is_accessor() => match &property.getter {
5698 Some(getter) if !matches!(getter, Value::Undefined) => {
5699 self.call_value(getter.clone(), receiver.clone(), Vec::new())
5700 }
5701 _ => Ok(Value::Undefined),
5702 },
5703 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5704 None => Ok(Value::Undefined),
5705 }
5706 }
5707
5708 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5709 ///
5710 /// A setter found on the prototype runs with `receiver` as `this`; a data property
5711 /// is shadowed by a new own property on the receiver, the same rule an ordinary
5712 /// assignment follows.
5713 fn super_write(
5714 &mut self,
5715 receiver: &Value,
5716 proto: &Value,
5717 key: &Value,
5718 value: Value,
5719 ) -> JsResult<()> {
5720 let target = self.require_object(receiver)?;
5721 let key = self.propkey(key)?;
5722 if !matches!(proto, Value::Null)
5723 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5724 {
5725 if property.is_accessor() {
5726 if let Some(setter) = &property.setter
5727 && !matches!(setter, Value::Undefined)
5728 {
5729 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5730 }
5731 return Ok(());
5732 }
5733 // A data property on the prototype is writable or not; reading `owner` at
5734 // all is only for the attribute check.
5735 if !property.writable {
5736 return Err(self.type_error(format!("'{key}' is read-only")));
5737 }
5738 let _ = owner;
5739 }
5740 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5741 }
5742
5743 /// The object a `super` operation needs, or the `TypeError` the spec raises.
5744 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5745 match value.as_object() {
5746 Some(object) => Ok(object.clone()),
5747 None => Err(Signal::Throw(
5748 self.make_error("TypeError", "value is not an object"),
5749 )),
5750 }
5751 }
5752
5753 /// Build the class object `define_class` produces.
5754 ///
5755 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5756 /// whose prototype property is a fresh object inheriting from the parent's
5757 /// prototype, and whose own prototype is the parent constructor — which is what makes
5758 /// a static method inherited too.
5759 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5760 let ctor = self.pop();
5761 let parent = self.pop();
5762 let Value::Object(function) = &ctor else {
5763 return Err(Signal::Throw(
5764 self.make_error("TypeError", "class constructor must be a function"),
5765 ));
5766 };
5767 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5768 // but gives the instances no prototype at all.
5769 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5770 match &parent {
5771 Value::Null => (Some(self.realm.function_proto.clone()), None),
5772 Value::Object(parent_class) => {
5773 if !parent_class.is_callable() {
5774 return Err(Signal::Throw(
5775 self.make_error("TypeError", "parent class must be constructor"),
5776 ));
5777 }
5778 let proto = self.get_property(parent_class, "prototype")?;
5779 match proto {
5780 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5781 Some(Value::Null) => (Some(parent_class.clone()), None),
5782 _ => {
5783 return Err(Signal::Throw(self.make_error(
5784 "TypeError",
5785 "parent prototype must be an object or null",
5786 )));
5787 }
5788 }
5789 }
5790 _ => {
5791 return Err(Signal::Throw(
5792 self.make_error("TypeError", "parent class must be constructor"),
5793 ));
5794 }
5795 }
5796 } else {
5797 (
5798 Some(self.realm.function_proto.clone()),
5799 Some(self.realm.object_proto.clone()),
5800 )
5801 };
5802 let proto = self.new_object(parent_proto);
5803 function.set_proto(parent_ctor);
5804 // A class is not callable without `new`, and its `prototype` is not writable —
5805 // both follow from being a class and are what `class A {}; A()` throws on.
5806 function.set_class_constructor(true);
5807 function.set_home_object(None);
5808 self.set_function_name(&ctor, name);
5809 self.define_class_properties(function, &ctor, &proto)?;
5810 Ok((ctor, proto))
5811 }
5812
5813 /// Give the constructor its `prototype` and `length`, and the prototype its
5814 /// `constructor` back-pointer.
5815 fn define_class_properties(
5816 &mut self,
5817 function: &Gc<JsObject>,
5818 ctor: &Value,
5819 proto: &Gc<JsObject>,
5820 ) -> JsResult<()> {
5821 proto.define(
5822 "constructor",
5823 Property::with_attributes(ctor.clone(), true, false),
5824 );
5825 function.define(
5826 "prototype",
5827 Property::prototype_of(Value::Object(proto.clone()), false),
5828 );
5829 if let Some((code, _)) = bytecode_of(function) {
5830 let length = code.code.defined_args;
5831 function.define(
5832 "length",
5833 Property::name_or_length(Value::Int(length as i32)),
5834 );
5835 }
5836 Ok(())
5837 }
5838
5839 /// The own array element `key` names, if this object has one.
5840 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5841 // A typed array's elements live in its buffer, not in a property list: reading one
5842 // goes through the view's element type so a bounds check and a detached buffer are
5843 // both handled there.
5844 //
5845 // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
5846 // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
5847 // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
5848 // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
5849 // consulted. Testing with `array_index` rejected all three, which let a throwing
5850 // getter installed on `TypedArray.prototype["-1"]` run.
5851 if object.typed_array_parts().is_some() {
5852 let property_key = PropertyKey::from(key);
5853 let numeric = canonical_numeric_index(&property_key)?;
5854 if typed_array_index_is_valid(object, numeric) {
5855 return object.typed_array_element(numeric as usize);
5856 }
5857 // Canonical, but not a valid index: `undefined`, and *final*.
5858 return Some(Value::Undefined);
5859 }
5860 let index = array_index(key)?;
5861 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5862 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5863 // search early, which is why `Array.prototype[1] = 9` could not be seen through
5864 // `[1,,3][1]`.
5865 match object.array_get(index as usize) {
5866 Some(Value::Hole) | None => None,
5867 other => other,
5868 }
5869 }
5870
5871 /// Store `object[key] = value`, honouring setters and inherited properties.
5872 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5873 self.set_property_with(object, key, value, DeleteFailure::Throw)
5874 }
5875
5876 /// Store a property, choosing what to do when the object refuses.
5877 ///
5878 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5879 /// mode, which is the one place assignment differs by mode. Native code (the array
5880 /// methods, `JSON`) always asks for the throw.
5881 pub fn set_property_with(
5882 &mut self,
5883 object: &Gc<JsObject>,
5884 key: &str,
5885 value: Value,
5886 on_failure: DeleteFailure,
5887 ) -> JsResult<()> {
5888 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5889 }
5890
5891 /// [`Interp::set_property_with`] with a key that may be a symbol.
5892 pub fn set_property_with_key(
5893 &mut self,
5894 object: &Gc<JsObject>,
5895 key: &PropertyKey,
5896 value: Value,
5897 on_failure: DeleteFailure,
5898 ) -> JsResult<()> {
5899 self.set_property_with_key_receiver_aware(object, key, value, on_failure)
5900 }
5901
5902 /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
5903 ///
5904 /// The receiver split lives one level up, in
5905 /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
5906 /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
5907 /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
5908 /// stores into `object` itself, which is why the element branch below converts `V`
5909 /// before asking whether the index is valid: `V` may put it back in bounds
5910 /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
5911 fn set_property_with_key_receiver_aware(
5912 &mut self,
5913 object: &Gc<JsObject>,
5914 key: &PropertyKey,
5915 value: Value,
5916 on_failure: DeleteFailure,
5917 ) -> JsResult<()> {
5918 // A proxy's `set` trap decides, and its `false` means the same thing an
5919 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5920 if object.proxy_state().is_some() {
5921 let receiver = Value::Object(object.clone());
5922 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5923 return match (accepted, on_failure) {
5924 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5925 (false, DeleteFailure::Throw) => {
5926 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5927 }
5928 };
5929 }
5930 }
5931 // A host class's `set_property` trap decides for itself. `Some(false)` is a
5932 // refusal and means exactly what a proxy's `false` means.
5933 if let Some(exotic) = object.exotic() {
5934 let receiver = Value::Object(object.clone());
5935 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5936 return match (accepted, on_failure) {
5937 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5938 (false, DeleteFailure::Throw) => {
5939 Err(self.type_error(format!("property '{key}' is read-only")))
5940 }
5941 };
5942 }
5943 }
5944 // The element and `length` shortcuts only exist for string keys: an array
5945 // index has no symbol spelling, and a symbol named `length` is an ordinary
5946 // property.
5947 let text = key.as_str();
5948 // A typed array's elements are a window onto its buffer: the store has to go
5949 // through the view's element type so the value is wrapped (or clamped) and so an
5950 // out-of-range or detached write is a silent no-op, as the spec says.
5951 //
5952 // The key test is `CanonicalNumericIndexString`, like every other index operation
5953 // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
5954 // does not exist, so they do nothing and leave no own property behind
5955 // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
5956 // path, which created a property named `"-0"`.
5957 //
5958 // The conversion comes **first**, before the index is checked at all, and that
5959 // order is observable twice over:
5960 //
5961 // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
5962 // has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
5963 // then store the converted value;
5964 // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
5965 // `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
5966 // run and its exception to escape.
5967 //
5968 // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
5969 // validity check, not a validity check that skips the conversion. The store itself
5970 // is a no-op when the index is invalid by then, which is why no extra guard is
5971 // needed around `typed_array_set`.
5972 if let Some(element) = object.typed_array_element_type()
5973 && let Some(numeric) = canonical_numeric_index(key)
5974 {
5975 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
5976 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
5977 // in `Interp`, because it is script-observable and the storage borrow inside
5978 // `typed_array_set` must not be held across it.
5979 let stored = self.element_value(element, value)?;
5980 if typed_array_index_is_valid(object, numeric)
5981 && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
5982 {
5983 return Err(self.type_error(reason));
5984 }
5985 return Ok(());
5986 }
5987 if let Some(text) = text
5988 && let Some(index) = array_index(text)
5989 && object.is_array()
5990 {
5991 // An accessor defined on an index lives in the property table while the
5992 // element slot is a hole, so the store has to go through the property first.
5993 // Writing the vector directly skipped the setter entirely.
5994 if let Some(existing) = object.own_property_key(key) {
5995 if existing.is_accessor() {
5996 return match existing.setter.clone() {
5997 Some(setter) if !matches!(setter, Value::Undefined) => {
5998 let receiver = Value::Object(object.clone());
5999 self.call_value(setter, receiver, vec![value]).map(|_| ())
6000 }
6001 _ => match on_failure {
6002 DeleteFailure::Throw => Err(self.type_error(format!(
6003 "cannot set property '{text}', it has only a getter"
6004 ))),
6005 DeleteFailure::Ignore => Ok(()),
6006 },
6007 };
6008 }
6009 if !existing.writable {
6010 return match on_failure {
6011 DeleteFailure::Throw => {
6012 Err(self.type_error(format!("'{text}' is read-only")))
6013 }
6014 DeleteFailure::Ignore => Ok(()),
6015 };
6016 }
6017 }
6018 {
6019 // Growing the array needs a writable `length`.
6020 if (index as usize) >= object.array_length().unwrap_or(0)
6021 && !object.length_writable()
6022 {
6023 return match on_failure {
6024 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6025 DeleteFailure::Ignore => Ok(()),
6026 };
6027 }
6028 // Adding an index past the end makes the array longer, which a
6029 // non-extensible array refuses.
6030 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6031 return match on_failure {
6032 DeleteFailure::Throw => Err(self.type_error(format!(
6033 "cannot add property '{key}', object is not extensible"
6034 ))),
6035 DeleteFailure::Ignore => Ok(()),
6036 };
6037 }
6038 if object.element_is_locked(index) {
6039 return match on_failure {
6040 DeleteFailure::Throw => {
6041 Err(self.type_error(format!("'{key}' is read-only")))
6042 }
6043 DeleteFailure::Ignore => Ok(()),
6044 };
6045 }
6046 // The element vector is only half of `[[Set]]` for an index: the
6047 // prototype chain is consulted first, and a setter there answers instead
6048 // of the element store. This branch used to write the element directly, so
6049 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6050 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6051 // the reference calls the setter and the array keeps no own index.
6052 //
6053 // An *exotic* prototype has no entry to find, because its indices live
6054 // outside the property table — `Object.setPrototypeOf([], typedArray)`
6055 // then looked like "nothing on the chain" and the store created the
6056 // element, where the view's `[[Set]]` answers `true` and does nothing for
6057 // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6058 // checks the array's `length` stays 0). So the dispatch comes first.
6059 if !object.has_own_key(key)
6060 && let Some(proto) = object.proto()
6061 && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6062 {
6063 let receiver = Value::Object(object.clone());
6064 let accepted =
6065 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6066 return if accepted {
6067 Ok(())
6068 } else {
6069 match on_failure {
6070 DeleteFailure::Throw => {
6071 Err(self.type_error(format!("'{key}' is read-only")))
6072 }
6073 DeleteFailure::Ignore => Ok(()),
6074 }
6075 };
6076 }
6077 if let Some((owner, property)) = lookup_key(object, key)
6078 && !owner.ptr_eq(object)
6079 {
6080 match &property {
6081 property if property.is_accessor() => {
6082 match &property.setter {
6083 Some(setter) if !matches!(setter, Value::Undefined) => {
6084 let receiver = Value::Object(object.clone());
6085 self.call_value(setter.clone(), receiver, vec![value])?;
6086 }
6087 _ => {
6088 return match on_failure {
6089 DeleteFailure::Throw => Err(self.type_error(format!(
6090 "cannot set property '{text}', it has only a getter"
6091 ))),
6092 DeleteFailure::Ignore => Ok(()),
6093 };
6094 }
6095 }
6096 return Ok(());
6097 }
6098 property if !property.writable => {
6099 return match on_failure {
6100 DeleteFailure::Throw => {
6101 Err(self.type_error(format!("'{text}' is read-only")))
6102 }
6103 DeleteFailure::Ignore => Ok(()),
6104 };
6105 }
6106 _ => {}
6107 }
6108 }
6109 if object.array_set(self.heap, index as usize, value.clone()) {
6110 return Ok(());
6111 }
6112 // Past the dense limit the slot is too far out to be worth one `Value`
6113 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6114 // constant time by keeping the index as an ordinary property. The store
6115 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6116 // to a legal program.
6117 object.define_key(key, Property::with_attributes(value, true, true));
6118 // Extend, never shorten: the index may be *inside* the current length (a
6119 // huge `length` with a sparse store), and shortening would delete the
6120 // sparse properties above it — including the one just stored.
6121 if index as usize + 1 > object.array_length().unwrap_or(0) {
6122 object.array_set_length(self.heap, index as usize + 1);
6123 }
6124 return Ok(());
6125 }
6126 }
6127 if text == Some("length") && object.is_array() {
6128 // §10.4.2.4 steps 3–5: **two** `ToNumber` conversions, then the writability
6129 // test. A `valueOf` that locks `length` on its second call therefore turns the
6130 // store into a refused write rather than a silent success
6131 // (`length/define-own-prop-length-coercion-order-set`).
6132 let rounded = self.coerce_array_length_twice(&value)?;
6133 if !object.length_writable() {
6134 return match on_failure {
6135 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6136 DeleteFailure::Ignore => Ok(()),
6137 };
6138 }
6139 // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6140 // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6141 // answered `NaN`, which left the assignment silently ignored
6142 // (`S15.4.5.2_A3_T2`).
6143 let _ = rounded;
6144 let length = self.to_js_number(&value)?;
6145 // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6146 // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6147 // `RangeError`s; the old code only tested "finite and non-negative" and then
6148 // truncated, so `[].length = 4294967297` quietly produced a length no array can
6149 // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6150 let valid = length.is_finite()
6151 && length >= 0.0
6152 && length.fract() == 0.0
6153 && length <= u32::MAX as f64;
6154 if !valid {
6155 return Err(self.range_error("invalid array length"));
6156 }
6157 {
6158 let length = length as usize;
6159 // `a.length = n` with `n` below a non-configurable element cannot
6160 // drop that element, so the whole assignment fails. The spec makes
6161 // this a `TypeError` rather than a silent no-op, in any mode.
6162 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6163 // Sloppy mode stops the truncation at the blocking element
6164 // instead of failing; strict mode raises.
6165 // Both modes stop at the blocking element; they differ in
6166 // whether that is reported. The reference truncates *then*
6167 // throws, so the array is left in the shortened state.
6168 object.array_truncate(self.heap, blocked + 1);
6169 return match on_failure {
6170 DeleteFailure::Throw => {
6171 Err(self.type_error(format!("cannot delete property '{blocked}'")))
6172 }
6173 DeleteFailure::Ignore => Ok(()),
6174 };
6175 }
6176 object.array_set_length(self.heap, length);
6177 return Ok(());
6178 }
6179 }
6180 // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6181 // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6182 // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6183 //
6184 // The prototype step is a dispatch, not a lookup. Walking the chain here and
6185 // applying whatever came back is the same thing for an ordinary prototype and
6186 // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6187 // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6188 // answers "not mine, the receiver is not me" without touching the buffer. This
6189 // code used to find nothing owned by `o`, find no property on the view either,
6190 // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6191 // object and never converted (`key-is-valid-index-prototype-chain-set`,
6192 // `key-is-canonical-invalid-index-prototype-chain-set`).
6193 //
6194 // The read-only and accessor rules of step 1 are what make
6195 // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6196 // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6197 let own = match self.lookup_for_write(object, key)? {
6198 Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6199 _ => None,
6200 };
6201 if let Some(property) = own {
6202 if property.is_accessor() {
6203 return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6204 Some(setter) => {
6205 let receiver = Value::Object(object.clone());
6206 self.call_value(setter, receiver, vec![value])?;
6207 Ok(())
6208 }
6209 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6210 // Sloppy code swallows that refusal, strict code raises — the same
6211 // rule the read-only *data* property below follows, and skipping it
6212 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6213 // return silently. The reference answers `TypeError: 'x' is
6214 // read-only`.
6215 None => match on_failure {
6216 DeleteFailure::Throw => {
6217 Err(self.type_error(format!("'{key}' is read-only")))
6218 }
6219 DeleteFailure::Ignore => Ok(()),
6220 },
6221 };
6222 }
6223 // An own non-writable data property stops here: nothing may change it.
6224 if !property.writable {
6225 return match on_failure {
6226 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6227 DeleteFailure::Ignore => Ok(()),
6228 };
6229 }
6230 // An existing writable own property keeps its attributes: only the value
6231 // moves. Redefining instead would reset them, which is how a
6232 // non-configurable global `var` used to become deletable.
6233 if object.write_value_key(key, value.clone()) {
6234 return Ok(());
6235 }
6236 }
6237 // Step 2: hand the store to the prototype, with `object` as the receiver.
6238 if let Some(proto) = object.proto() {
6239 let receiver = Value::Object(object.clone());
6240 let accepted =
6241 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6242 return if accepted {
6243 Ok(())
6244 } else {
6245 match on_failure {
6246 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6247 DeleteFailure::Ignore => Ok(()),
6248 }
6249 };
6250 }
6251 // Step 3: create one, and a non-extensible object cannot.
6252 if !object.is_extensible() {
6253 return match on_failure {
6254 DeleteFailure::Throw => Err(self.type_error(format!(
6255 "cannot add property {key}, object is not extensible"
6256 ))),
6257 DeleteFailure::Ignore => Ok(()),
6258 };
6259 }
6260 object.define_data_key(key, value);
6261 Ok(())
6262 }
6263
6264 /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6265 ///
6266 /// The distinction the fast path above does not need: it is called with the store's
6267 /// receiver already being the object it writes to. Here `object` is the one whose
6268 /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6269 /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6270 /// and not a write to `object`.
6271 ///
6272 /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6273 /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6274 /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6275 /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6276 /// descriptor on the prototype refuses instead, which is the same rule that keeps
6277 /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6278 ///
6279 /// Answers `false` where the spec says `false`; the caller turns that into the
6280 /// strict-mode `TypeError` or the sloppy-mode silence.
6281 fn ordinary_set_with_receiver(
6282 &mut self,
6283 object: &Gc<JsObject>,
6284 receiver: &Value,
6285 key: &PropertyKey,
6286 value: Value,
6287 on_failure: DeleteFailure,
6288 ) -> JsResult<bool> {
6289 // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6290 if object.proxy_state().is_some() {
6291 return Ok(self
6292 .proxy_set(object, key, value, receiver)?
6293 .unwrap_or(true));
6294 }
6295 // A host class decides for itself, with the receiver the caller named.
6296 if let Some(exotic) = object.exotic()
6297 && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6298 {
6299 return Ok(accepted);
6300 }
6301 // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6302 // rather than the receiver, but the receiver may still *be* the view:
6303 // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6304 // itself as receiver, and then the first half applies — convert `V` once, store
6305 // if the index is valid, answer `true` either way. The conversion is the observable
6306 // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6307 //
6308 // Only the second half, a view that is *not* the receiver, skips the conversion
6309 // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6310 // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6311 // below with the value still unconverted.
6312 if object.typed_array_element_type().is_some()
6313 && let Some(numeric) = canonical_numeric_index(key)
6314 {
6315 if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6316 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6317 return Ok(true);
6318 }
6319 if !typed_array_index_is_valid(object, numeric) {
6320 return Ok(true);
6321 }
6322 }
6323 let own = self.object_get_own_property(object, key)?;
6324 if let Some(own) = own {
6325 if own.is_accessor() {
6326 return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6327 Some(setter) => {
6328 self.call_value(setter, receiver.clone(), vec![value])?;
6329 Ok(true)
6330 }
6331 None => Ok(false),
6332 };
6333 }
6334 // A non-writable data descriptor refuses, own or inherited. Either way the
6335 // receiver must not gain a shadowing property.
6336 if !own.writable {
6337 return Ok(false);
6338 }
6339 // Step 1.d: the *receiver's* own descriptor decides whether it can be
6340 // created or written, and it is created as an ordinary data property.
6341 let Some(receiver_object) = receiver.as_object().cloned() else {
6342 return Ok(false);
6343 };
6344 return match self.object_get_own_property(&receiver_object, key)? {
6345 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6346 Some(existing) => self.object_define_own_property(
6347 &receiver_object,
6348 key,
6349 Property {
6350 value: Some(value),
6351 ..existing
6352 },
6353 ),
6354 None => {
6355 self.object_define_own_property(&receiver_object, key, Property::data(value))
6356 }
6357 };
6358 }
6359 // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6360 if let Some(proto) = object.proto() {
6361 return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6362 }
6363 // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6364 // *default* data descriptor here, so control falls into step 2 exactly as if the
6365 // target had owned a writable property — which means the **receiver's** own
6366 // descriptor is asked for before the write. Skipping that question went straight to
6367 // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6368 // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6369 // exactly those calls).
6370 let Some(receiver_object) = receiver.as_object().cloned() else {
6371 return Ok(false);
6372 };
6373 match self.object_get_own_property(&receiver_object, key)? {
6374 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6375 Some(existing) => self.object_define_own_property(
6376 &receiver_object,
6377 key,
6378 Property {
6379 value: Some(value),
6380 ..existing
6381 },
6382 ),
6383 None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6384 }
6385 }
6386
6387 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6388 ///
6389 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6390 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6391 /// a virtual accessor gets its setter run without implementing `set_property` at all.
6392 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6393 /// the prototype, so the walk resumes above the object.
6394 fn lookup_for_write(
6395 &mut self,
6396 object: &Gc<JsObject>,
6397 key: &PropertyKey,
6398 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6399 let Some(exotic) = object.exotic() else {
6400 return Ok(lookup_key(object, key));
6401 };
6402 Ok(match exotic.get_own_property(self, object, key)? {
6403 Some(Some(property)) => Some((object.clone(), property)),
6404 Some(None) => lookup_key_above(object, key),
6405 None => lookup_key(object, key),
6406 })
6407 }
6408
6409 /// Delete `object[key]`.
6410 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6411 self.delete_property_key(object, &PropertyKey::from(key))
6412 }
6413
6414 /// [`Interp::delete_property`] with a key that may be a symbol.
6415 pub fn delete_property_key(
6416 &mut self,
6417 object: &Gc<JsObject>,
6418 key: &PropertyKey,
6419 ) -> JsResult<bool> {
6420 // A proxy decides for itself, and may even throw; the invariant checks live in
6421 // `proxy_delete`.
6422 if let Some(answer) = self.proxy_delete(object, key)? {
6423 return Ok(answer);
6424 }
6425 // A host class's `delete_property` trap decides; `false` is a refusal, which the
6426 // caller reports as a failed delete.
6427 if let Some(exotic) = object.exotic()
6428 && let Some(answer) = exotic.delete_property(self, object, key)?
6429 {
6430 return Ok(answer);
6431 }
6432 // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6433 // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6434 // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6435 // one answers `false` because the elements are non-configurable. The prototype
6436 // chain is not consulted either, which is what makes a throwing getter on
6437 // `TypedArray.prototype["-1"]` stay unrun.
6438 if object.typed_array_parts().is_some()
6439 && object.proxy_state().is_none()
6440 && let Some(numeric) = canonical_numeric_index(key)
6441 {
6442 return Ok(!typed_array_index_is_valid(object, numeric));
6443 }
6444 let mapped_index = key.as_str().and_then(array_index);
6445 if let Some(index) = mapped_index
6446 && let Some(length) = object.array_length()
6447 && (index as usize) < length
6448 {
6449 // An accessor defined on an index lives in the property table rather than the
6450 // element vector, so both have to be cleared: `delete` after
6451 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6452 object.delete_key(key);
6453 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6454 // index stops answering `in`.
6455 if object.element_is_undeletable(index) {
6456 return Ok(false);
6457 }
6458 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6459 // so a later `defineProperty(arguments, "0", {value})` writes to the object
6460 // and no longer through to the parameter. A refused delete leaves the
6461 // mapping alone.
6462 object.drop_mapped_argument(index as usize);
6463 object.array_set(self.heap, index as usize, Value::Hole);
6464 return Ok(true);
6465 }
6466 // An array's `length` is a non-configurable own property that lives outside the
6467 // property table, so `delete_key` finds nothing and reports success — `Reflect
6468 // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6469 // §10.4.4.1 step 3 refuses it.
6470 if key.as_str() == Some("length") && object.array_length().is_some() {
6471 return Ok(false);
6472 }
6473 // The same for an object that is not an array: only a delete that actually
6474 // removed the property ends the alias.
6475 let deleted = object.delete_key(key);
6476 if deleted && let Some(index) = mapped_index {
6477 object.drop_mapped_argument(index as usize);
6478 }
6479 Ok(deleted)
6480 }
6481
6482 // -- proxy traps --------------------------------------------------------
6483 //
6484 // A proxy's internal methods all look the same: ask the handler for the trap, call it
6485 // with the target and the operation's own arguments, then check the answer against
6486 // the target. The checks are not decoration — they are what stops a proxy from
6487 // reporting a `non-configurable` property as missing, which would let a frozen object
6488 // be rewritten by standing in front of it.
6489
6490 /// The target and handler of `object`, or `None` when it is not a proxy.
6491 ///
6492 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6493 /// one has to fail: the slots the traps would have been read from are gone.
6494 pub(crate) fn proxy_parts(
6495 &mut self,
6496 object: &Gc<JsObject>,
6497 ) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6498 let Some(state) = object.proxy_state() else {
6499 return Ok(None);
6500 };
6501 let state = state.borrow();
6502 match (&state.target, &state.handler) {
6503 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
6504 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
6505 }
6506 }
6507
6508 /// Call `handler[name]`, or answer `None` when the trap is absent.
6509 ///
6510 /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
6511 /// and only a value that is neither is `IsCallable`-checked and refused. Treating
6512 /// `null` as "present but not callable" made every `{ get: null }` proxy throw
6513 /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
6514 /// one per trap plus the `target-is-proxy` variants.
6515 ///
6516 /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
6517 /// this cannot simply be "any non-callable means no trap".
6518 fn proxy_trap(
6519 &mut self,
6520 handler: &Value,
6521 name: &str,
6522 args: Vec<Value>,
6523 ) -> JsResult<Option<Value>> {
6524 let Value::Object(table) = handler else {
6525 return Err(self.type_error("proxy handler is not an object"));
6526 };
6527 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
6528 match trap {
6529 Value::Undefined | Value::Null => Ok(None),
6530 Value::Object(function) if function.is_callable() => {
6531 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
6532 Ok(Some(answer))
6533 }
6534 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
6535 }
6536 }
6537
6538 /// Whether the target's own property `key` is one it refuses to lose.
6539 ///
6540 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
6541 /// its value behind the target's back.
6542 ///
6543 /// A **method**, not a free function, because §10.5.1's invariants say
6544 /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
6545 /// property table directly finds nothing (a proxy's table is empty by design), so every
6546 /// invariant check silently passed for a proxy target. That is what
6547 /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
6548 /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
6549 /// where an array's elements and its `length` — both fixed, both outside the table —
6550 /// are covered.
6551 fn fixed_property(
6552 &mut self,
6553 target: &Gc<JsObject>,
6554 key: &PropertyKey,
6555 ) -> JsResult<Option<Property>> {
6556 Ok(self
6557 .object_get_own_property(target, key)?
6558 .filter(|property| !property.configurable))
6559 }
6560
6561 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
6562 fn proxy_get(
6563 &mut self,
6564 object: &Gc<JsObject>,
6565 receiver: &Value,
6566 key: &PropertyKey,
6567 ) -> JsResult<Option<Value>> {
6568 let Some((target, handler)) = self.proxy_parts(object)? else {
6569 return Ok(None);
6570 };
6571 let key_value = self.key_value(key);
6572 let Some(result) = self.proxy_trap(
6573 &handler,
6574 "get",
6575 vec![Value::Object(target.clone()), key_value, receiver.clone()],
6576 )?
6577 else {
6578 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
6579 // inherited getter still sees the proxy.
6580 return Ok(Some(
6581 self.get_property_key_for(&target, Some(receiver), key)?
6582 .unwrap_or(Value::Undefined),
6583 ));
6584 };
6585 if let Some(fixed) = self.fixed_property(&target, key)? {
6586 if fixed.is_accessor() {
6587 // A fixed accessor with no getter must read as `undefined`.
6588 let has_getter = fixed
6589 .getter
6590 .as_ref()
6591 .is_some_and(|getter| !matches!(getter, Value::Undefined));
6592 if !has_getter && !matches!(result, Value::Undefined) {
6593 return Err(self.type_error(format!(
6594 "proxy 'get' must report undefined for the non-configurable property '{key}'"
6595 )));
6596 }
6597 } else if !fixed.writable {
6598 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6599 if !fixed_value.same_value(&result) {
6600 return Err(self.type_error(format!(
6601 "proxy 'get' disagrees with the non-configurable property '{key}'"
6602 )));
6603 }
6604 }
6605 }
6606 Ok(Some(result))
6607 }
6608
6609 /// `[[Set]]` on a proxy.
6610 ///
6611 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
6612 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
6613 /// read-only store has.
6614 fn proxy_set(
6615 &mut self,
6616 object: &Gc<JsObject>,
6617 key: &PropertyKey,
6618 value: Value,
6619 receiver: &Value,
6620 ) -> JsResult<Option<bool>> {
6621 let Some((target, handler)) = self.proxy_parts(object)? else {
6622 return Ok(None);
6623 };
6624 let key_value = self.key_value(key);
6625 let Some(result) = self.proxy_trap(
6626 &handler,
6627 "set",
6628 vec![
6629 Value::Object(target.clone()),
6630 key_value,
6631 value.clone(),
6632 receiver.clone(),
6633 ],
6634 )?
6635 else {
6636 // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
6637 // given — not the target. `OrdinarySet` step 3 is
6638 // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
6639 // object whose prototype is a typed array has to reach the proxy's own
6640 // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
6641 // calls and expects exactly one. Storing on the target instead put the value
6642 // in the target and never consulted the trap.
6643 let accepted = self.ordinary_set_with_receiver(
6644 &target,
6645 receiver,
6646 key,
6647 value,
6648 DeleteFailure::Ignore,
6649 )?;
6650 return Ok(Some(accepted));
6651 };
6652 if !result.to_boolean() {
6653 return Ok(Some(false));
6654 }
6655 if let Some(fixed) = self.fixed_property(&target, key)? {
6656 if fixed.is_accessor() {
6657 let has_setter = fixed
6658 .setter
6659 .as_ref()
6660 .is_some_and(|setter| !matches!(setter, Value::Undefined));
6661 if !has_setter {
6662 return Err(self.type_error(format!(
6663 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
6664 )));
6665 }
6666 } else if !fixed.writable {
6667 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6668 if !fixed_value.same_value(&value) {
6669 return Err(self.type_error(format!(
6670 "proxy 'set' changed the non-configurable property '{key}'"
6671 )));
6672 }
6673 }
6674 }
6675 // A new property cannot appear on a target that refuses new properties.
6676 if self.object_get_own_property(&target, key)?.is_none()
6677 && !self.object_is_extensible(&target)?
6678 {
6679 return Err(self.type_error(format!(
6680 "proxy 'set' added '{key}' to a non-extensible target"
6681 )));
6682 }
6683 Ok(Some(true))
6684 }
6685
6686 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
6687 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6688 let Some((target, handler)) = self.proxy_parts(object)? else {
6689 return Ok(None);
6690 };
6691 let key_value = self.key_value(key);
6692 let Some(result) = self.proxy_trap(
6693 &handler,
6694 "has",
6695 vec![Value::Object(target.clone()), key_value],
6696 )?
6697 else {
6698 return Ok(Some(self.has_own_or_inherited(&target, key)?));
6699 };
6700 if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
6701 return Err(self.type_error(format!(
6702 "proxy 'has' denied the non-configurable property '{key}'"
6703 )));
6704 }
6705 // A non-extensible target cannot grow, so every own property it *has* is fixed.
6706 if !result.to_boolean()
6707 && !self.object_is_extensible(&target)?
6708 && self.object_get_own_property(&target, key)?.is_some()
6709 {
6710 return Err(self.type_error(format!(
6711 "proxy 'has' denied the own property '{key}' of a non-extensible target"
6712 )));
6713 }
6714 Ok(Some(result.to_boolean()))
6715 }
6716
6717 /// `[[Delete]]` on a proxy.
6718 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6719 let Some((target, handler)) = self.proxy_parts(object)? else {
6720 return Ok(None);
6721 };
6722 let key_value = self.key_value(key);
6723 let Some(result) = self.proxy_trap(
6724 &handler,
6725 "deleteProperty",
6726 vec![Value::Object(target.clone()), key_value],
6727 )?
6728 else {
6729 return Ok(Some(self.delete_property_key(&target, key)?));
6730 };
6731 if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
6732 return Err(self.type_error(format!(
6733 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
6734 )));
6735 }
6736 if result.to_boolean()
6737 && !self.object_is_extensible(&target)?
6738 && self.object_get_own_property(&target, key)?.is_some()
6739 {
6740 return Err(self.type_error(format!(
6741 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
6742 )));
6743 }
6744 Ok(Some(result.to_boolean()))
6745 }
6746
6747 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
6748 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
6749 let Some((target, handler)) = self.proxy_parts(object)? else {
6750 return Ok(None);
6751 };
6752 let Some(result) =
6753 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
6754 else {
6755 // No trap: the target's own keys, already in the order an object reports.
6756 return Ok(Some(self.object_own_property_keys(&target)?));
6757 };
6758 // `CreateListFromArrayLike` with the string-or-symbol restriction.
6759 let list = self.list_from_array_like(&result, true)?;
6760 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
6761 for value in list {
6762 let key = self.propkey(&value)?;
6763 if keys.contains(&key) {
6764 return Err(self.type_error(format!(
6765 "proxy 'ownKeys' returned the duplicate key '{key}'"
6766 )));
6767 }
6768 keys.push(key);
6769 }
6770 // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
6771 // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
6772 // table is empty, which made every check below vacuous.
6773 let target_keys = self.object_own_property_keys(&target)?;
6774 let extensible = self.object_is_extensible(&target)?;
6775 for key in &target_keys {
6776 if keys.contains(key) {
6777 continue;
6778 }
6779 if self.fixed_property(&target, key)?.is_some() {
6780 return Err(self.type_error(format!(
6781 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
6782 )));
6783 }
6784 if !extensible {
6785 return Err(self.type_error(format!(
6786 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
6787 )));
6788 }
6789 }
6790 if !extensible {
6791 // §10.5.11 step 12: the lists must match one for one, in any order.
6792 if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
6793 {
6794 return Err(
6795 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
6796 );
6797 }
6798 }
6799 Ok(Some(keys))
6800 }
6801
6802 /// `[[GetOwnProperty]]` on a proxy.
6803 fn proxy_get_own_property(
6804 &mut self,
6805 object: &Gc<JsObject>,
6806 key: &PropertyKey,
6807 ) -> JsResult<Option<Option<Property>>> {
6808 let Some((target, handler)) = self.proxy_parts(object)? else {
6809 return Ok(None);
6810 };
6811 let key_value = self.key_value(key);
6812 let Some(result) = self.proxy_trap(
6813 &handler,
6814 "getOwnPropertyDescriptor",
6815 vec![Value::Object(target.clone()), key_value],
6816 )?
6817 else {
6818 // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
6819 // property table. Two things ride on that choice: a target that is itself a
6820 // proxy has to re-dispatch (its own table is empty, so reading it reported
6821 // `undefined` for every key, `Object.keys` then dropped them all), and an array's
6822 // indices and `length` live outside the table and need the ordinary synthesis.
6823 // `object_get_own_property` does both.
6824 return Ok(Some(self.object_get_own_property(&target, key)?));
6825 };
6826 // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
6827 // `ToPropertyDescriptor` runs, because that operation would box the primitive
6828 // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
6829 // empty descriptor instead of refusing.
6830 if !matches!(result, Value::Undefined | Value::Object(_)) {
6831 return Err(self.type_error(
6832 "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
6833 ));
6834 }
6835 let target_desc = self.object_get_own_property(&target, key)?;
6836 let extensible = self.object_is_extensible(&target)?;
6837 let Some(descriptor) = (match result {
6838 Value::Undefined => None,
6839 _ => Some(self.property_from_descriptor(&result)?),
6840 }) else {
6841 // Steps 12.a–12.d: reporting absent is allowed only when the target's own
6842 // descriptor is configurable *and* the target can still grow back.
6843 if let Some(target_desc) = &target_desc {
6844 if !target_desc.configurable {
6845 return Err(self.type_error(format!(
6846 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
6847 )));
6848 }
6849 if !extensible {
6850 return Err(self.type_error(format!(
6851 "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
6852 )));
6853 }
6854 }
6855 return Ok(Some(None));
6856 };
6857 // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
6858 // which is a stronger requirement than "the target is not contradicting it" — the
6859 // four branches below are each one test262 case.
6860 if !descriptor.configurable {
6861 let Some(target_desc) = &target_desc else {
6862 return Err(self.type_error(format!(
6863 "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
6864 )));
6865 };
6866 if target_desc.configurable {
6867 return Err(self.type_error(format!(
6868 "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
6869 )));
6870 }
6871 let target_is_data = !target_desc.is_accessor();
6872 let result_is_data = !descriptor.is_accessor();
6873 if result_is_data && !target_is_data {
6874 return Err(self.type_error(format!(
6875 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6876 )));
6877 }
6878 if target_is_data && !target_desc.writable {
6879 if !result_is_data {
6880 return Err(self.type_error(format!(
6881 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6882 )));
6883 }
6884 if descriptor.writable {
6885 return Err(self.type_error(format!(
6886 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
6887 )));
6888 }
6889 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
6890 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
6891 if !fixed_value.same_value(&reported) {
6892 return Err(self.type_error(format!(
6893 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
6894 )));
6895 }
6896 }
6897 // Step 16.d: a reported *read-only* data property needs a real read-only data
6898 // property behind it. Missing this let a trap bolt a frozen property onto a
6899 // writable target intent (`resultdesc-is-not-configurable-not-writable-
6900 // targetdesc-is-writable`).
6901 if result_is_data && !descriptor.writable {
6902 if !target_is_data {
6903 return Err(self.type_error(format!(
6904 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6905 )));
6906 }
6907 if target_desc.writable {
6908 return Err(self.type_error(format!(
6909 "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
6910 )));
6911 }
6912 }
6913 if descriptor.is_accessor() {
6914 // Step 16.e: a getter the target does not have may not be invented, and
6915 // vice versa.
6916 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
6917 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
6918 (Some(a), Some(b)) => a.same_value(b),
6919 _ => false,
6920 };
6921 if !same(&target_desc.getter, &descriptor.getter)
6922 || !same(&target_desc.setter, &descriptor.setter)
6923 {
6924 return Err(self.type_error(format!(
6925 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
6926 )));
6927 }
6928 }
6929 }
6930 // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
6931 // where the target's own is locked. Without it a handler could advertise
6932 // `{value: 1, configurable: true}` for a non-configurable property, and a caller
6933 // that believed it would try to redefine something it cannot.
6934 if descriptor.configurable
6935 && let Some(target_desc) = &target_desc
6936 && !target_desc.configurable
6937 {
6938 return Err(self.type_error(format!(
6939 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
6940 )));
6941 }
6942 // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
6943 // through the trap either, however well-formed the descriptor is. This is the
6944 // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
6945 // the frozen target does not own.
6946 if !extensible {
6947 let Some(target_desc) = &target_desc else {
6948 return Err(self.type_error(format!(
6949 "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
6950 )));
6951 };
6952 if target_desc.is_accessor() == descriptor.is_accessor() {
6953 let target_is_data = !target_desc.is_accessor();
6954 let result_is_data = !descriptor.is_accessor();
6955 if target_is_data && !target_desc.writable && descriptor.writable {
6956 return Err(self.type_error(format!(
6957 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
6958 )));
6959 }
6960 if !result_is_data && !target_is_data {
6961 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
6962 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
6963 (Some(a), Some(b)) => a.same_value(b),
6964 _ => false,
6965 };
6966 if !same(&target_desc.getter, &descriptor.getter)
6967 || !same(&target_desc.setter, &descriptor.setter)
6968 {
6969 return Err(self.type_error(format!(
6970 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
6971 )));
6972 }
6973 }
6974 }
6975 }
6976 Ok(Some(Some(descriptor)))
6977 }
6978
6979 /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
6980 ///
6981 /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
6982 /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
6983 /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
6984 /// for a data property. `Property` cannot express "this field is absent", so the whole
6985 /// property path is skipped and the descriptor is assembled here field by field.
6986 ///
6987 /// `current` is the property the trap reported, used only to tell a data property from
6988 /// an accessor.
6989 pub fn proxy_seal_property(
6990 &mut self,
6991 object: &Gc<JsObject>,
6992 key: &PropertyKey,
6993 frozen: bool,
6994 current: &Property,
6995 ) -> JsResult<bool> {
6996 let Some((_target, handler)) = self.proxy_parts(object)? else {
6997 return Err(self.type_error("not a proxy"));
6998 };
6999 let descriptor = self.new_object(None);
7000 descriptor.define_data("configurable", Value::Bool(false));
7001 if frozen && !current.is_accessor() {
7002 descriptor.define_data("writable", Value::Bool(false));
7003 }
7004 let key_value = self.key_value(key);
7005 let target = object
7006 .proxy_state()
7007 .and_then(|state| state.borrow().target.clone());
7008 let Some(target) = target else {
7009 return Err(self.type_error("cannot use a proxy that has been revoked"));
7010 };
7011 let Some(result) = self.proxy_trap(
7012 &handler,
7013 "defineProperty",
7014 vec![Value::Object(target), key_value, Value::Object(descriptor)],
7015 )?
7016 else {
7017 // No trap means the definition belongs to the target; `false` is its answer.
7018 return Ok(false);
7019 };
7020 Ok(result.to_boolean())
7021 }
7022
7023 /// `[[DefineOwnProperty]]` on a proxy.
7024 fn proxy_define_property(
7025 &mut self,
7026 object: &Gc<JsObject>,
7027 key: &PropertyKey,
7028 property: Property,
7029 ) -> JsResult<Option<bool>> {
7030 let Some((target, handler)) = self.proxy_parts(object)? else {
7031 return Ok(None);
7032 };
7033 let key_value = self.key_value(key);
7034 let descriptor = self.descriptor_from_property(&property);
7035 let Some(result) = self.proxy_trap(
7036 &handler,
7037 "defineProperty",
7038 vec![Value::Object(target.clone()), key_value, descriptor],
7039 )?
7040 else {
7041 // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7042 // going" answer and `object_define_own_property` turns it into exactly that
7043 // forwarding — see the note there. (Reading it as "not a proxy" would define
7044 // the property on the proxy object itself, whose table is empty and which no
7045 // read ever consults.)
7046 return Ok(None);
7047 };
7048 if !result.to_boolean() {
7049 return Ok(Some(false));
7050 }
7051 // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7052 // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7053 // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7054 // and treating them alike made four cases pass a descriptor the target contradicts.
7055 let target_desc = self.object_get_own_property(&target, key)?;
7056 let extensible = self.object_is_extensible(&target)?;
7057 let named = property
7058 .descriptor_fields
7059 .unwrap_or(crate::object::DescriptorFields {
7060 value: false,
7061 writable: false,
7062 enumerable: false,
7063 configurable: false,
7064 get: false,
7065 set: false,
7066 });
7067 if named.configurable && !property.configurable {
7068 let Some(target_desc) = &target_desc else {
7069 return Err(self.type_error(format!(
7070 "proxy 'defineProperty' invented the non-configurable '{key}'"
7071 )));
7072 };
7073 if target_desc.configurable {
7074 return Err(self.type_error(format!(
7075 "proxy 'defineProperty' made '{key}' non-configurable"
7076 )));
7077 }
7078 }
7079 // Step 11's other half: reporting that a property was made *configurable* needs a
7080 // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7081 // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7082 // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7083 // target`).
7084 if named.configurable
7085 && property.configurable
7086 && let Some(target_desc) = &target_desc
7087 && !target_desc.configurable
7088 {
7089 return Err(
7090 self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7091 );
7092 }
7093 // Step 12: a property cannot be reported *made writable* when the target's copy is
7094 // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7095 // the trap is allowed to claim a definition it did not perform, as long as the
7096 // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7097 // legal, and refusing it broke the commonest way to seed a proxy).
7098 if named.writable
7099 && property.writable
7100 && let Some(target_desc) = &target_desc
7101 && !target_desc.writable
7102 {
7103 return Err(self.type_error(format!(
7104 "proxy 'defineProperty' made the read-only '{key}' writable"
7105 )));
7106 }
7107 // Step 13: making a property read-only needs an existing read-only property.
7108 if named.writable
7109 && !property.writable
7110 && let Some(target_desc) = &target_desc
7111 && !target_desc.is_accessor()
7112 && target_desc.writable
7113 {
7114 return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7115 }
7116 // Step 14: a non-writable, non-configurable property's value is fixed.
7117 if named.value
7118 && let Some(target_desc) = &target_desc
7119 && !target_desc.is_accessor()
7120 && !target_desc.writable
7121 && !target_desc.configurable
7122 {
7123 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7124 let reported = property.value.clone().unwrap_or(Value::Undefined);
7125 if !fixed_value.same_value(&reported) {
7126 return Err(self.type_error(format!(
7127 "proxy 'defineProperty' changed the value of '{key}'"
7128 )));
7129 }
7130 }
7131 // Step 15: a non-extensible target cannot grow.
7132 if target_desc.is_none() && !extensible {
7133 return Err(self.type_error(format!(
7134 "proxy 'defineProperty' added '{key}' to a non-extensible target"
7135 )));
7136 }
7137 Ok(Some(true))
7138 }
7139
7140 /// `[[GetPrototypeOf]]` on a proxy.
7141 fn proxy_get_prototype_of(
7142 &mut self,
7143 object: &Gc<JsObject>,
7144 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7145 let Some((target, handler)) = self.proxy_parts(object)? else {
7146 return Ok(None);
7147 };
7148 let Some(result) = self.proxy_trap(
7149 &handler,
7150 "getPrototypeOf",
7151 vec![Value::Object(target.clone())],
7152 )?
7153 else {
7154 // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7155 // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7156 // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7157 // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7158 // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7159 return Ok(Some(self.object_prototype_of(&target)?));
7160 };
7161 let proto = match &result {
7162 Value::Null => None,
7163 Value::Object(proto) => Some(proto.clone()),
7164 _ => {
7165 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7166 }
7167 };
7168 if !self.object_is_extensible(&target)? {
7169 let actual = self.object_prototype_of(&target)?;
7170 if !same_proto(proto.as_ref(), actual.as_ref()) {
7171 return Err(self.type_error(
7172 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7173 ));
7174 }
7175 }
7176 Ok(Some(proto))
7177 }
7178
7179 /// `[[SetPrototypeOf]]` on a proxy.
7180 fn proxy_set_prototype_of(
7181 &mut self,
7182 object: &Gc<JsObject>,
7183 proto: Option<Gc<JsObject>>,
7184 ) -> JsResult<Option<bool>> {
7185 let Some((target, handler)) = self.proxy_parts(object)? else {
7186 return Ok(None);
7187 };
7188 let proto_value = match &proto {
7189 Some(proto) => Value::Object(proto.clone()),
7190 None => Value::Null,
7191 };
7192 let Some(result) = self.proxy_trap(
7193 &handler,
7194 "setPrototypeOf",
7195 vec![Value::Object(target.clone()), proto_value],
7196 )?
7197 else {
7198 // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7199 // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7200 // its stored prototype overwritten behind its back.
7201 return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7202 };
7203 if result.to_boolean()
7204 && !self.object_is_extensible(&target)?
7205 && !same_proto(
7206 Some(&proto).and_then(|p| p.clone()).as_ref(),
7207 self.object_prototype_of(&target)?.as_ref(),
7208 )
7209 {
7210 return Err(self.type_error(
7211 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7212 ));
7213 }
7214 Ok(Some(result.to_boolean()))
7215 }
7216
7217 /// `[[IsExtensible]]` on a proxy.
7218 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7219 let Some((target, handler)) = self.proxy_parts(object)? else {
7220 return Ok(None);
7221 };
7222 let Some(result) = self.proxy_trap(
7223 &handler,
7224 "isExtensible",
7225 vec![Value::Object(target.clone())],
7226 )?
7227 else {
7228 return Ok(Some(self.object_is_extensible(&target)?));
7229 };
7230 // The answer is not the proxy's to invent: it must agree with the target, or a
7231 // script could learn `false` while the target keeps accepting new properties.
7232 if result.to_boolean() != self.object_is_extensible(&target)? {
7233 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7234 }
7235 Ok(Some(result.to_boolean()))
7236 }
7237
7238 /// `[[PreventExtensions]]` on a proxy.
7239 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7240 let Some((target, handler)) = self.proxy_parts(object)? else {
7241 return Ok(None);
7242 };
7243 let Some(result) = self.proxy_trap(
7244 &handler,
7245 "preventExtensions",
7246 vec![Value::Object(target.clone())],
7247 )?
7248 else {
7249 // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7250 // its answer can be `false`.
7251 return Ok(Some(self.object_prevent_extensions(&target)?));
7252 };
7253 if result.to_boolean() && self.object_is_extensible(&target)? {
7254 return Err(self.type_error(
7255 "proxy 'preventExtensions' reported success but the target is still extensible",
7256 ));
7257 }
7258 Ok(Some(result.to_boolean()))
7259 }
7260
7261 /// `[[Call]]` on a proxy, through the `apply` trap.
7262 fn proxy_apply(
7263 &mut self,
7264 object: &Gc<JsObject>,
7265 this: Value,
7266 args: Vec<Value>,
7267 ) -> JsResult<Option<Value>> {
7268 let Some((target, handler)) = self.proxy_parts(object)? else {
7269 return Ok(None);
7270 };
7271 // The trap gets the arguments as one array, which is the shape the spec passes
7272 // and the shape `apply` traps are written against (`args[0]` is the first one).
7273 let arguments = self.new_array(args.clone());
7274 let this_for_trap = this.clone();
7275 let Some(result) = self.proxy_trap(
7276 &handler,
7277 "apply",
7278 vec![
7279 Value::Object(target.clone()),
7280 this_for_trap,
7281 Value::Object(arguments),
7282 ],
7283 )?
7284 else {
7285 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7286 };
7287 Ok(Some(result))
7288 }
7289
7290 /// `[[Construct]]` on a proxy, through the `construct` trap.
7291 fn proxy_construct(
7292 &mut self,
7293 object: &Gc<JsObject>,
7294 args: Vec<Value>,
7295 new_target: &Value,
7296 ) -> JsResult<Option<Value>> {
7297 let Some((target, handler)) = self.proxy_parts(object)? else {
7298 return Ok(None);
7299 };
7300 if !target.is_callable() {
7301 return Err(self.type_error("proxy target is not a constructor"));
7302 }
7303 let arguments = self.new_array(args.clone());
7304 let Some(result) = self.proxy_trap(
7305 &handler,
7306 "construct",
7307 vec![
7308 Value::Object(target.clone()),
7309 Value::Object(arguments),
7310 new_target.clone(),
7311 ],
7312 )?
7313 else {
7314 return Ok(Some(self.construct(
7315 Value::Object(target),
7316 new_target.clone(),
7317 args,
7318 )?));
7319 };
7320 if !matches!(result, Value::Object(_)) {
7321 return Err(self.type_error("proxy 'construct' must return an object"));
7322 }
7323 Ok(Some(result))
7324 }
7325
7326 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7327 pub(crate) fn has_own_or_inherited(
7328 &mut self,
7329 object: &Gc<JsObject>,
7330 key: &PropertyKey,
7331 ) -> JsResult<bool> {
7332 // The object itself first: it may be a proxy, and then the answer is its trap's.
7333 if let Some(answer) = self.proxy_has(object, key)? {
7334 return Ok(answer);
7335 }
7336 // An integer-indexed exotic object answers a canonical numeric index from
7337 // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7338 // prototype chain. That is observable twice: a view the buffer has been resized
7339 // away from has no indices, so `2 in view` is `false` even when
7340 // `Object.getPrototypeOf(view)[2]` exists (what
7341 // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7342 // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7343 // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7344 // goes through here, which is why the same rule is repeated in `has_property_key`
7345 // rather than living only there.
7346 if object.typed_array_parts().is_some()
7347 && let Some(numeric) = canonical_numeric_index(key)
7348 {
7349 return Ok(typed_array_index_is_valid(object, numeric));
7350 }
7351 // A host class answers `in` for its own keys, which may live nowhere in a property
7352 // table — `"x" in point` is true because the class says so, not because a property
7353 // exists.
7354 if let Some(exotic) = object.exotic()
7355 && let Some(answer) = exotic.has_property(self, object, key)?
7356 {
7357 return Ok(answer);
7358 }
7359 // `has_own` rather than `own_property_key`: an array's elements and its derived
7360 // `length` are invisible to the property table, and `Array.prototype` is an array.
7361 // A host class's `get_own_property` counts too, because the reference's
7362 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7363 // lives — a class with only `get_own_property` answers `in` through it.
7364 if self.exotic_has_own(object, key)? {
7365 return Ok(true);
7366 }
7367 // A hole is *not* the end of the search: the chain may still have the key, which
7368 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7369 for ancestor in object.chain() {
7370 // A proxy further up the chain answers for itself.
7371 if let Some(answer) = self.proxy_has(&ancestor, key)? {
7372 return Ok(answer);
7373 }
7374 // Same for a host class: a prototype may be one, and `in` reaches it.
7375 if let Some(exotic) = ancestor.exotic()
7376 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7377 {
7378 return Ok(answer);
7379 }
7380 if self.exotic_has_own(&ancestor, key)? {
7381 return Ok(true);
7382 }
7383 }
7384 Ok(false)
7385 }
7386
7387 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7388 /// trap included.
7389 ///
7390 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7391 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7392 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7393 if let Some(exotic) = object.exotic()
7394 && let Some(answer) = exotic.get_own_property(self, object, key)?
7395 {
7396 return Ok(answer.is_some());
7397 }
7398 Ok(has_own(object, key))
7399 }
7400
7401 /// `CreateListFromArrayLike`, optionally restricted to property keys.
7402 ///
7403 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7404 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7405 /// `TypeError` instead of a property named `"1.5"`.
7406 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7407 let object = self.object_from(value)?;
7408 let length = self
7409 .get_property(&object, "length")?
7410 .map(|value| value.to_number())
7411 .unwrap_or(0.0);
7412 if !length.is_finite() || length < 0.0 {
7413 return Err(self.type_error("invalid array-like length"));
7414 }
7415 let length = length as usize;
7416 let mut items = Vec::with_capacity(length.min(1024));
7417 for index in 0..length {
7418 let item = self
7419 .get_property(&object, &index.to_string())?
7420 .unwrap_or(Value::Undefined);
7421 if keys_only && matches!(&item, Value::Symbol(_)) {
7422 items.push(item);
7423 continue;
7424 }
7425 if keys_only && !matches!(&item, Value::String(_)) {
7426 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7427 }
7428 items.push(item);
7429 }
7430 Ok(items)
7431 }
7432
7433 /// A `Property` from the descriptor object a trap returned.
7434 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7435 let object = self.object_from(value)?;
7436 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7437 interp.get_property(&object, name)
7438 };
7439 let getter = field(self, "get")?;
7440 let setter = field(self, "set")?;
7441 let accessor = getter.is_some() || setter.is_some();
7442 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7443 Ok(interp
7444 .get_property(&object, name)?
7445 .is_some_and(|value| value.to_boolean()))
7446 };
7447 let enumerable = boolean(self, "enumerable")?;
7448 let configurable = boolean(self, "configurable")?;
7449 if accessor {
7450 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7451 return Err(
7452 self.type_error("a descriptor cannot be both a data property and an accessor")
7453 );
7454 }
7455 Ok(Property {
7456 getter: getter.or(Some(Value::Undefined)),
7457 setter: setter.or(Some(Value::Undefined)),
7458 enumerable,
7459 configurable,
7460 writable: false,
7461 value: None,
7462 descriptor_fields: None,
7463 })
7464 } else {
7465 Ok(Property {
7466 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7467 writable: boolean(self, "writable")?,
7468 enumerable,
7469 configurable,
7470 getter: None,
7471 setter: None,
7472 descriptor_fields: None,
7473 })
7474 }
7475 }
7476
7477 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7478 fn descriptor_from_property(&mut self, property: &Property) -> Value {
7479 let object = self.new_object(None);
7480 // A partial descriptor names only some fields, and the trap must see exactly those:
7481 // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7482 // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7483 // case, where every field is present.
7484 let fields = property.descriptor_fields;
7485 let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7486 fields.is_none_or(|fields| field(&fields))
7487 };
7488 if property.is_accessor() {
7489 let getter = property.getter.clone().unwrap_or(Value::Undefined);
7490 let setter = property.setter.clone().unwrap_or(Value::Undefined);
7491 object.define_data("get", getter);
7492 object.define_data("set", setter);
7493 } else {
7494 if names(|fields| fields.value) {
7495 let value = property.value.clone().unwrap_or(Value::Undefined);
7496 object.define_data("value", value);
7497 }
7498 if names(|fields| fields.writable) {
7499 object.define_data("writable", Value::Bool(property.writable));
7500 }
7501 }
7502 if names(|fields| fields.enumerable) {
7503 object.define_data("enumerable", Value::Bool(property.enumerable));
7504 }
7505 if names(|fields| fields.configurable) {
7506 object.define_data("configurable", Value::Bool(property.configurable));
7507 }
7508 Value::Object(object)
7509 }
7510
7511 // -- calling ------------------------------------------------------------
7512
7513 /// Call `callee` with `this` and `args`.
7514 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
7515 let Value::Object(function) = &callee else {
7516 // `typeof x === "function"` is not enough to make `x()` legal: only a
7517 // callable object is. `null` and `undefined` need no special wording
7518 // here — their `ToString` already reads the way the reference's does.
7519 let what = format!("{} is not a function", callee.to_js_string());
7520 return Err(Signal::Throw(self.make_error("TypeError", &what)));
7521 };
7522 // A proxy of a function is called through its `apply` trap. It has no
7523 // `ObjectKind::Function` of its own, so this has to come before the dispatch
7524 // below, and a proxy of a non-function has nothing to forward to.
7525 if function.proxy_state().is_some() {
7526 return match self.proxy_apply(function, this, args)? {
7527 Some(result) => Ok(result),
7528 None => Err(Signal::Throw(
7529 self.make_error("TypeError", "proxy target is not callable"),
7530 )),
7531 };
7532 }
7533 let callable = function.with(|data| match &data.kind {
7534 ObjectKind::Function(callable) => match callable {
7535 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
7536 // The `Rc` is cloned out so the borrow of this object's data is released
7537 // before the closure runs: the closure may touch the same object.
7538 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
7539 Callable::Bound {
7540 target,
7541 this,
7542 args: leading,
7543 } => Some(NativeCall::Bound {
7544 target: target.clone(),
7545 this: this.clone(),
7546 leading: leading.clone(),
7547 }),
7548 Callable::Bytecode { code, env } => {
7549 Some(NativeCall::Bytecode(code.clone(), env.clone()))
7550 }
7551 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
7552 Callable::PromiseResolve(promise) => {
7553 Some(NativeCall::PromiseResolve(promise.clone()))
7554 }
7555 Callable::PromiseReject(promise) => {
7556 Some(NativeCall::PromiseReject(promise.clone()))
7557 }
7558 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
7559 state: state.clone(),
7560 }),
7561 Callable::ThenShim {
7562 handler,
7563 resolve,
7564 reject,
7565 fulfilled,
7566 } => Some(NativeCall::ThenShim {
7567 handler: handler.clone(),
7568 resolve: resolve.clone(),
7569 reject: reject.clone(),
7570 fulfilled: *fulfilled,
7571 }),
7572 Callable::AwaitResume {
7573 coroutine,
7574 promise,
7575 kind,
7576 } => Some(NativeCall::AwaitResume {
7577 coroutine: coroutine.clone(),
7578 promise: promise.clone(),
7579 kind: *kind,
7580 }),
7581 Callable::CombinatorSettle {
7582 state,
7583 index,
7584 fulfilled,
7585 } => Some(NativeCall::CombinatorSettle {
7586 state: state.clone(),
7587 index: *index,
7588 fulfilled: *fulfilled,
7589 }),
7590 Callable::FinallyShim {
7591 callback,
7592 fulfilled,
7593 constructor,
7594 } => Some(NativeCall::FinallyShim {
7595 callback: callback.clone(),
7596 fulfilled: *fulfilled,
7597 constructor: constructor.clone(),
7598 }),
7599 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
7600 Callable::CompletedReturn {
7601 generator,
7602 promise,
7603 rejected,
7604 } => Some(NativeCall::CompletedReturn {
7605 generator: generator.clone(),
7606 promise: promise.clone(),
7607 rejected: *rejected,
7608 }),
7609 Callable::YieldResult {
7610 generator,
7611 promise,
7612 done,
7613 } => Some(NativeCall::YieldResult {
7614 generator: generator.clone(),
7615 promise: promise.clone(),
7616 done: *done,
7617 }),
7618 Callable::DisposeStep {
7619 remaining,
7620 promise,
7621 error,
7622 rejected,
7623 } => Some(NativeCall::DisposeStep {
7624 remaining: remaining.clone(),
7625 promise: promise.clone(),
7626 error: error.clone(),
7627 rejected: *rejected,
7628 }),
7629 Callable::GeneratorResume {
7630 generator,
7631 promise,
7632 kind,
7633 } => Some(NativeCall::GeneratorResume {
7634 generator: generator.clone(),
7635 promise: promise.clone(),
7636 kind: *kind,
7637 }),
7638 Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
7639 Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
7640 Callable::SettlePromise {
7641 promise,
7642 value,
7643 rejected,
7644 } => Some(NativeCall::SettlePromise {
7645 promise: promise.clone(),
7646 value: value.clone(),
7647 rejected: *rejected,
7648 }),
7649 },
7650 _ => None,
7651 });
7652 match callable {
7653 Some(NativeCall::Host(func)) => {
7654 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
7655 // function by name rather than stopping at the caller.
7656 let frame_less = function
7657 .own_property("_frame_less")
7658 .and_then(|property| property.value)
7659 .is_some_and(|value| value.to_boolean());
7660 let outer = if frame_less {
7661 None
7662 } else {
7663 self.native_frames
7664 .push((function.clone(), self.frames.len()));
7665 Some(self.current_native.replace(function.clone()))
7666 };
7667 // Same frame bookkeeping as a `Native`, plus `new.target`: a host
7668 // constructor reads it through `current_new_target` because it is handed
7669 // `undefined` for `this`. Taking the parked value here is what stops a
7670 // *plain* call made from inside a constructor body from seeing the
7671 // enclosing `new.target`.
7672 let parked = self.pending_new_target.take();
7673 let result = {
7674 let outer_new_target = std::mem::replace(
7675 &mut self.active_new_target,
7676 parked.unwrap_or(Value::Undefined),
7677 );
7678 let result = {
7679 let mut body = func.borrow_mut();
7680 body(self, this, &args)
7681 };
7682 self.active_new_target = outer_new_target;
7683 result
7684 };
7685 if !frame_less {
7686 self.native_frames.pop();
7687 self.current_native = outer.flatten();
7688 }
7689 result
7690 }
7691 Some(NativeCall::Native(func)) => {
7692 // A function marked `_frame_less` is one the reference implements
7693 // without a call frame — `eval` is the only one so far.
7694 let frame_less = function
7695 .own_property("_frame_less")
7696 .and_then(|property| property.value)
7697 .is_some_and(|value| value.to_boolean());
7698 let outer = if frame_less {
7699 None
7700 } else {
7701 self.native_frames
7702 .push((function.clone(), self.frames.len()));
7703 Some(self.current_native.replace(function.clone()))
7704 };
7705 let parked = self.pending_new_target.take();
7706 let outer_new_target = std::mem::replace(
7707 &mut self.active_new_target,
7708 parked.unwrap_or(Value::Undefined),
7709 );
7710 let result = func(self, this, &args);
7711 self.active_new_target = outer_new_target;
7712 if !frame_less {
7713 self.native_frames.pop();
7714 self.current_native = outer.flatten();
7715 }
7716 result
7717 }
7718 Some(NativeCall::Revoker(slots)) => {
7719 // Idempotent: revoking twice answers `undefined` again rather than
7720 // complaining, which is what the spec says and what a `finally` block
7721 // relies on.
7722 let mut state = slots.borrow_mut();
7723 state.target = None;
7724 state.handler = None;
7725 Ok(Value::Undefined)
7726 }
7727 Some(NativeCall::PromiseResolve(promise)) => {
7728 // One-shot: a second call is silently ignored, which
7729 // `fulfill_promise`/`reject_promise` enforce by refusing to settle twice.
7730 let value = args.first().cloned().unwrap_or(Value::Undefined);
7731 // §27.2.1.3.2 steps 7–8: a self-resolution is **rejected, not thrown** —
7732 // the resolve function performs `RejectPromise` and returns `undefined`.
7733 // (`ResolvePromise` itself throws as well, so the engine's own callers see
7734 // it; only this wrapper swallows it.)
7735 let _ = self.resolve_promise_with(&promise, value);
7736 Ok(Value::Undefined)
7737 }
7738 Some(NativeCall::PromiseReject(promise)) => {
7739 let reason = args.first().cloned().unwrap_or(Value::Undefined);
7740 self.reject_promise(&promise, reason);
7741 Ok(Value::Undefined)
7742 }
7743 Some(NativeCall::ThenShim {
7744 handler,
7745 resolve,
7746 reject,
7747 fulfilled,
7748 }) => {
7749 // `PerformPromiseThen` with a capability: run the handler, then settle
7750 // through the capability's own pair. A throw from the handler is the
7751 // rejection, and a throw from the capability's `resolve` is not caught —
7752 // exactly the spec's `?`.
7753 let value = args.first().cloned().unwrap_or(Value::Undefined);
7754 match handler {
7755 Some(handler) => {
7756 match self.call_value(handler, Value::Undefined, vec![value]) {
7757 Ok(result) => {
7758 self.call_value(resolve, Value::Undefined, vec![result])?;
7759 }
7760 Err(Signal::Throw(reason)) => {
7761 self.call_value(reject, Value::Undefined, vec![reason])?;
7762 }
7763 Err(signal) => return Err(signal),
7764 }
7765 }
7766 None => {
7767 let handler = if fulfilled { resolve } else { reject };
7768 self.call_value(handler, Value::Undefined, vec![value])?;
7769 }
7770 }
7771 Ok(Value::Undefined)
7772 }
7773 Some(NativeCall::CapabilityExecutor { state }) => {
7774 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
7775 // slot holds a value yet. The test is on the *values*, not on a call count —
7776 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
7777 // called-twice`'s first case does exactly that), while a second call after a
7778 // real pair is the `TypeError`.
7779 let defined = |name: &str| {
7780 state
7781 .own_property(name)
7782 .and_then(|property| property.value)
7783 .is_some_and(|value| !matches!(value, Value::Undefined))
7784 };
7785 if defined("resolve") || defined("reject") {
7786 return Err(self.type_error("promise capability executor called twice"));
7787 }
7788 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
7789 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
7790 state.define_data("resolve", resolve);
7791 state.define_data("reject", reject);
7792 Ok(Value::Undefined)
7793 }
7794 Some(NativeCall::CombinatorSettle {
7795 state,
7796 index,
7797 fulfilled,
7798 }) => {
7799 let value = args.first().cloned().unwrap_or(Value::Undefined);
7800 self.settle_combinator(&state, index, fulfilled, value)?;
7801 Ok(Value::Undefined)
7802 }
7803 Some(NativeCall::AwaitResume {
7804 coroutine,
7805 promise,
7806 kind,
7807 }) => {
7808 // Resume *inline*, in the reaction that delivered the value. Deferring it
7809 // by another job inserts a tick between every `await` and its
7810 // continuation, which reorders `await` against unrelated `then` chains —
7811 // `f().then(g)` then runs before `f`'s own next statement.
7812 self.drive_async(
7813 &coroutine,
7814 &promise,
7815 kind,
7816 args.first().cloned().unwrap_or(Value::Undefined),
7817 )
7818 .map(|()| Value::Undefined)
7819 }
7820 Some(NativeCall::ReturnValue(value)) => Ok(value),
7821 Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
7822 Some(NativeCall::FinallyShim {
7823 callback,
7824 fulfilled,
7825 constructor,
7826 }) => {
7827 // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
7828 // own value is discarded; what the caller sees is the *original* outcome,
7829 // delayed until `PromiseResolve(C, result)` has settled.
7830 //
7831 // Two details are observable and both have a test:
7832 //
7833 // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
7834 // `PerformPromiseThen`. A callback that returns a thenable with its own
7835 // `then` must have that `then` called
7836 // (`resolved-observable-then-calls` counts it);
7837 // * only the **fulfil** handler is supplied. A returned promise that
7838 // *rejects* rejects the whole `finally`, rather than having its failure
7839 // swallowed and the original value passed through.
7840 let original = args.first().cloned().unwrap_or(Value::Undefined);
7841 let result = match &callback {
7842 Some(callback) => {
7843 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
7844 }
7845 None => Value::Undefined,
7846 };
7847 // `PromiseResolve(C, result)`: a `result` that is already a promise of this
7848 // constructor is reused rather than rewrapped, which is what keeps
7849 // `mp1.finally(() => mp2)` from gaining a layer.
7850 let resolved = self.promise_resolve_for(&constructor, result)?;
7851 let thunk = if fulfilled {
7852 Callable::ReturnValue(original)
7853 } else {
7854 Callable::ThrowValue(original)
7855 };
7856 // `length: 0` and `name: ""`, and **not** a constructor — the three things
7857 // `resolved-observable-then-calls-argument` reads off the thunk while it has
7858 // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
7859 // function with no `length` at all.
7860 let thunk = self.builtin_function("", 0, thunk);
7861 let then = self.read_field(&resolved, "then")?;
7862 if !matches!(&then, Value::Object(object) if object.is_callable()) {
7863 return Err(self.type_error("then is not a function"));
7864 }
7865 self.call_value(then, resolved, vec![Value::Object(thunk)])
7866 }
7867 Some(NativeCall::DisposeStep {
7868 remaining,
7869 promise,
7870 error,
7871 rejected,
7872 }) => {
7873 let error = if rejected {
7874 let reason = args.first().cloned().unwrap_or(Value::Undefined);
7875 self.merge_dispose_error(reason, error)
7876 } else {
7877 error
7878 };
7879 self.dispose_step(&remaining, &promise, error)?;
7880 Ok(Value::Undefined)
7881 }
7882 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
7883 Some(NativeCall::CompletedReturn {
7884 generator,
7885 promise,
7886 rejected,
7887 }) => {
7888 let value = args.first().cloned().unwrap_or(Value::Undefined);
7889 let outcome = if rejected {
7890 AsyncOutcome::Error(value)
7891 } else {
7892 AsyncOutcome::Value(self.iterator_result(value, true)?)
7893 };
7894 self.settle_async_request(&generator, &promise, outcome)?;
7895 Ok(Value::Undefined)
7896 }
7897 Some(NativeCall::YieldResult {
7898 generator,
7899 promise,
7900 done,
7901 }) => {
7902 let value = args.first().cloned().unwrap_or(Value::Undefined);
7903 let result = self.iterator_result(value, done)?;
7904 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
7905 Ok(Value::Undefined)
7906 }
7907 Some(NativeCall::GeneratorResume {
7908 generator,
7909 promise,
7910 kind,
7911 }) => {
7912 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
7913 // tick and reorders the generator against other chains.
7914 self.step_async_generator(
7915 &generator,
7916 &promise,
7917 kind,
7918 args.first().cloned().unwrap_or(Value::Undefined),
7919 )
7920 .map(|()| Value::Undefined)
7921 }
7922 Some(NativeCall::SettlePromise {
7923 promise,
7924 value,
7925 rejected,
7926 }) => {
7927 if rejected {
7928 self.reject_promise(&promise, value);
7929 } else {
7930 self.fulfill_promise(&promise, value);
7931 }
7932 Ok(Value::Undefined)
7933 }
7934 Some(NativeCall::Bound {
7935 target,
7936 this: bound_this,
7937 leading,
7938 }) => {
7939 let mut all = leading;
7940 all.extend(args);
7941 self.call_value(target, bound_this, all)
7942 }
7943 Some(NativeCall::Bytecode(code, env)) => {
7944 if code.code.kind.is_generator() {
7945 return self.new_generator(callee, this, args);
7946 }
7947 if code.code.kind.is_async() {
7948 // Same coroutine machinery as a generator; the difference is only in
7949 // what the completion does — see `new_async_function`.
7950 return self.new_async_function(callee, this, args);
7951 }
7952 self.execute(code, env, this, args, callee)
7953 }
7954 None => Err(Signal::Throw(
7955 self.make_error("TypeError", "not a function"),
7956 )),
7957 }
7958 }
7959
7960 /// Give a freshly built function its own `prototype` object.
7961 ///
7962 /// Every function that can be used with `new` carries one, and its
7963 /// `constructor` points back at the function — a reference cycle, which is
7964 /// exactly what the collector's cycle pass exists to reclaim.
7965 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
7966 self.install_function_prototype_with(function, None);
7967 }
7968
7969 /// [`Interp::install_function_prototype`] with an explicit parent for the new
7970 /// `prototype` object.
7971 ///
7972 /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
7973 /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
7974 /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
7975 /// `None` means `%Object.prototype%`.
7976 fn install_function_prototype_with(
7977 &mut self,
7978 function: &Gc<JsObject>,
7979 parent: Option<Gc<JsObject>>,
7980 ) {
7981 let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
7982 let prototype = self.new_object(Some(parent));
7983 let constructor = Value::Object(function.clone());
7984 prototype.define(
7985 "constructor",
7986 Property::with_attributes(constructor, true, false),
7987 );
7988 let value = Value::Object(prototype);
7989 function.define("prototype", Property::prototype_of(value, true));
7990 }
7991
7992 /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
7993 /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
7994 /// [`Interp::install_function_prototype`] — **no `constructor` property**.
7995 ///
7996 /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
7997 /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
7998 /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
7999 /// is `[]` there.
8000 fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
8001 let prototype = self.new_object(Some(parent));
8002 let value = Value::Object(prototype);
8003 function.define("prototype", Property::prototype_of(value, true));
8004 }
8005
8006 /// The `[[Prototype]]` a newly created generator object gets:
8007 /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
8008 ///
8009 /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
8010 /// function's `prototype` is writable, so a script can replace it with anything, and
8011 /// only an *object* is consulted.
8012 fn generator_instance_proto(
8013 &mut self,
8014 function: &Gc<JsObject>,
8015 default: Gc<JsObject>,
8016 ) -> JsResult<Gc<JsObject>> {
8017 match self.get_property(function, "prototype")? {
8018 Some(Value::Object(prototype)) => Ok(prototype),
8019 _ => Ok(default),
8020 }
8021 }
8022
8023 /// A getter or setter that reads or writes the reference cell behind a mapped
8024 /// `arguments` index.
8025 ///
8026 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
8027 /// count — which is what the collector treats as "a reference from outside the
8028 /// heap". The closure therefore keeps the cell alive for exactly as long as the
8029 /// accessor is reachable, which is the same lifetime the arguments object has.
8030 ///
8031 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8032 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8033 /// parameter value and the arguments object reaches the closure, never the other
8034 /// way round. Nothing the collector has to see is hidden.
8035 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8036 let name = if is_setter { "set" } else { "get" };
8037 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8038 if is_setter {
8039 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8040 Ok(Value::Undefined)
8041 } else {
8042 Ok(cell.get())
8043 }
8044 };
8045 self.new_host_function(name, 1, Box::new(func))
8046 }
8047
8048 /// The object `special_object` builds.
8049 ///
8050 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8051 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8052 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8053 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8054 /// write through `arguments` does not reach the parameter.
8055 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8056 match magic {
8057 0 | 1 => {
8058 let args = self.frame().passed().to_vec();
8059 let proto = self.realm.object_proto.clone();
8060 let object = self.new_object(Some(proto));
8061 // The marker `Object.prototype.toString` needs: an arguments object is an
8062 // ordinary object apart from reporting `[object Arguments]`, and that has
8063 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8064 // show up ahead of them in a key listing anyway — it is non-enumerable.
8065 self.internal_set(&object, "_class", self.string("Arguments"));
8066 // `length` is writable and configurable but neither enumerable nor a
8067 // plain data property: `Object.keys(arguments)` lists the indices only,
8068 // which is how `{...arguments}` copies them without the length.
8069 object.define(
8070 "length",
8071 Property::with_attributes(Value::Int(args.len() as i32), true, false),
8072 );
8073 // `magic == 1` is sloppy mode, where each index is *mapped* to the
8074 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8075 // change `a`, and assigning `a` has to change `arguments[0]`.
8076 //
8077 // The shared storage is the parameter's reference cell. The compiler
8078 // gives every parameter of such a function one (see
8079 // `provide_body_arguments`), and the cell outlives the frame, so this
8080 // keeps working after the arguments object escapes.
8081 //
8082 // The index becomes an accessor rather than a data property. A mapped
8083 // index reports as a plain writable/enumerable data property through
8084 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8085 // the getter/setter pair is only the plumbing underneath.
8086 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8087 let frame = self.frame();
8088 frame
8089 .code
8090 .arg_cell
8091 .iter()
8092 .map(|cell| {
8093 (*cell >= 0)
8094 .then(|| frame.cells.get(*cell as usize).cloned())
8095 .flatten()
8096 })
8097 .collect()
8098 } else {
8099 Vec::new()
8100 };
8101 // Tell the object which indices are mapped, so
8102 // `Object.getOwnPropertyDescriptor` can report them as the data
8103 // properties the spec describes instead of the accessors that
8104 // implement the aliasing.
8105 if magic == 1 {
8106 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8107 for cell in &mapped_cells {
8108 table.push(cell.clone());
8109 }
8110 object.set_mapped_arguments(table);
8111 }
8112 for (index, value) in args.into_iter().enumerate() {
8113 match mapped_cells.get(index).cloned().flatten() {
8114 Some(cell) => {
8115 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8116 let setter = self.new_mapped_arguments_accessor(cell, true);
8117 object.define(
8118 &index.to_string(),
8119 Property::accessor_with(
8120 Some(Value::Object(getter)),
8121 Some(Value::Object(setter)),
8122 true,
8123 ),
8124 );
8125 }
8126 None => object.define_data(&index.to_string(), value),
8127 }
8128 }
8129 // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8130 // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8131 // non-enumerable and non-configurable. It is not a nicety — it is the only
8132 // documented way to reach `%ThrowTypeError%`:
8133 //
8134 // Object.getOwnPropertyDescriptor(function(){"use strict";
8135 // return arguments;}(), "callee").get
8136 //
8137 // and the whole `ThrowTypeError/` directory is written against that
8138 // expression. Without it 13 cases failed with `cannot read property 'get'
8139 // of undefined`, which reads like a test harness bug rather than a missing
8140 // accessor.
8141 //
8142 // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8143 // writable data property holding the function being called, and
8144 // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8145 // `hasOwnProperty("callee")` hold there.
8146 if magic == 1 {
8147 let callee = self.frame().callee.clone();
8148 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8149 object.define("callee", Property::with_attributes(callee, true, false));
8150 } else if let Some(thrower) = self.realm.throw_type_error.clone()
8151 && object.own_property("callee").is_none()
8152 {
8153 object.define(
8154 "callee",
8155 Property {
8156 getter: Some(Value::Object(thrower.clone())),
8157 setter: Some(Value::Object(thrower)),
8158 enumerable: false,
8159 configurable: false,
8160 ..Property::default()
8161 },
8162 );
8163 }
8164 // An arguments object is iterable: `[...arguments]` and
8165 // `for (const a of arguments)` both work, through the *array* iterator
8166 // because the object is array-like. Without this the whole spread form
8167 // reported "not iterable".
8168 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8169 let values = self
8170 .realm
8171 .array_proto
8172 .own_property("values")
8173 .and_then(|property| property.value);
8174 if let Some(values) = values {
8175 object.define_key(
8176 &iterator_key,
8177 Property::with_attributes(values, true, false),
8178 );
8179 }
8180 Ok(Value::Object(object))
8181 }
8182 // `this.active_func`: the constructor `super()` resolves against.
8183 //
8184 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8185 // own, so it inherits this from the function it was written in along with `this`
8186 // — and that is a lexical relationship, not a stack one: an arrow that escaped
8187 // the constructor and is called back later (`iter.return = () => super()`) has
8188 // the constructor nowhere on the stack. The compiler therefore reads it out of
8189 // a closure variable of the enclosing function, exactly as the reference does
8190 // with its `this_active_func` local.
8191 2 => Ok(self
8192 .current_callee()
8193 .map_or(Value::Undefined, Value::Object)),
8194 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8195 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8196 // its own either, so the lookup walks out to the nearest non-arrow frame for
8197 // the same reason as `this.active_func` above — without that, `super()` inside
8198 // an arrow passed `undefined` as the new target and the parent constructor was
8199 // then rejected for being invoked without `new`.
8200 3 => Ok(self
8201 .eval_new_target
8202 .clone()
8203 .unwrap_or_else(|| self.frame().new_target.clone())),
8204 // `[[HomeObject]]` of the function being run: what `super` is relative to.
8205 // An arrow has none of its own, so the lookup walks out to the enclosing
8206 // method — which is why `super` works inside an arrow inside a method.
8207 4 => Ok(self
8208 .frames
8209 .iter()
8210 .rev()
8211 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8212 .map_or(Value::Undefined, Value::Object)),
8213 // `import.meta`: the innermost module body's meta object. Outside a module
8214 // the compiler never emits this, so an empty fallback is unreachable rather
8215 // than permissive.
8216 6 => {
8217 let name = self.module_stack.last().cloned();
8218 let meta = name
8219 .and_then(|name| self.modules.get(&name).cloned())
8220 .and_then(|module| module.with(|r| r.import_meta.clone()));
8221 Ok(meta.map_or(Value::Undefined, Value::Object))
8222 }
8223 other => Err(Signal::Throw(self.make_error(
8224 "InternalError",
8225 &format!("special_object {other} is not implemented yet"),
8226 ))),
8227 }
8228 }
8229
8230 /// `[[HomeObject]]` of the innermost function that has one, if any.
8231 ///
8232 /// An arrow has none, so the search walks out to the enclosing method — the same
8233 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8234 /// inside a method.
8235 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8236 self.frames
8237 .iter()
8238 .rev()
8239 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8240 }
8241
8242 /// The dispose method a `using` declaration should snapshot, or an error.
8243 ///
8244 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8245 /// is what makes a resource that only knows the synchronous protocol usable in both
8246 /// forms.
8247 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8248 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8249 if value.is_nullish() {
8250 return Ok(Value::Undefined);
8251 }
8252 let Some(object) = value.as_object() else {
8253 return Err(self.type_error("not an object"));
8254 };
8255 let mut method = if await_form {
8256 let found = self.get_property_key(
8257 object,
8258 &self.realm.well_known_key(WellKnown::AsyncDisposable),
8259 )?;
8260 match found {
8261 Some(found) if !found.is_nullish() => Some(found),
8262 _ => self
8263 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8264 }
8265 } else {
8266 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8267 };
8268 let Some(found) = method.take() else {
8269 return Err(self.type_error("value is not disposable"));
8270 };
8271 if found.is_nullish() {
8272 return Err(self.type_error("value is not disposable"));
8273 }
8274 let callable = found.as_object().is_some_and(|object| object.is_callable());
8275 if !callable {
8276 return Err(self.type_error("dispose method is not a function"));
8277 }
8278 Ok(found)
8279 }
8280
8281 /// Call one resource's disposer, folding a failure into `error_state`.
8282 ///
8283 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8284 /// because a captured `using` binding lives in its reference cell and the local slot is
8285 /// stale — a closure over the resource is legal and must not change what is disposed.
8286 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8287 let value = self.get_loc(slot);
8288 let method = self.get_loc(slot + 1);
8289 // A resource that was never initialised — its declaration threw — or that is
8290 // `null`/`undefined` has nothing to dispose.
8291 if value.is_nullish() || matches!(value, Value::Uninitialized) {
8292 return Ok(error_state);
8293 }
8294 if matches!(method, Value::Undefined | Value::Uninitialized) {
8295 return Ok(error_state);
8296 }
8297 match self.call_value(method, value, Vec::new()) {
8298 Ok(_) => Ok(error_state),
8299 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8300 Err(other) => Err(other),
8301 }
8302 }
8303
8304 /// Combine a disposal failure with whatever was already going wrong.
8305 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8306 if matches!(error_state, Value::Uninitialized) {
8307 return new_error;
8308 }
8309 self.new_suppressed_error(new_error, error_state)
8310 }
8311
8312 /// A `SuppressedError` instance built straight from its prototype.
8313 ///
8314 /// Not through the constructor: a script that rewrites
8315 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8316 /// error wrapping.
8317 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8318 let proto = self
8319 .realm
8320 .suppressed_error_proto
8321 .clone()
8322 .unwrap_or_else(|| self.realm.error_proto.clone());
8323 let object = self.new_object(Some(proto));
8324 object.define("error", Property::with_attributes(error, true, true));
8325 object.define(
8326 "suppressed",
8327 Property::with_attributes(suppressed, true, true),
8328 );
8329 object.define(
8330 "message",
8331 Property::with_attributes(self.string("SuppressedError"), true, true),
8332 );
8333 self.internal_set(&object, "_class", self.string("Error"));
8334 self.add_stack(&object);
8335 Value::Object(object)
8336 }
8337
8338 /// Call `callee`, or push its frame and let the main loop run it.
8339 ///
8340 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8341 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8342 /// continues, so `function f(){ return f() }` costs heap and stops at
8343 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8344 /// is entered directly, and natives do not re-enter JavaScript in this
8345 /// milestone.
8346 ///
8347 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8348 /// because the returning frame will.
8349 /// The elements of an array-like value, as a call argument list.
8350 ///
8351 /// `apply` accepts any array-like, not only a real array: the reference reads
8352 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8353 /// `ToIndex(value)`: `ToIntegerOrInfinity` and then the `2^53 - 1` bound.
8354 ///
8355 /// Used by the paths that take a *length* from script data — the typed-array
8356 /// constructor's array-like argument, `Array.from`. `ToIntegerOrInfinity` runs
8357 /// `ToNumber`, so a Symbol is a `TypeError`; a value past `2^53 - 1` is a
8358 /// `RangeError` rather than a silently clamped count.
8359 pub fn to_index(&mut self, value: &Value) -> JsResult<usize> {
8360 let number = self.to_js_number(value)?;
8361 if number.is_nan() {
8362 return Ok(0);
8363 }
8364 let number = number.trunc();
8365 if number < 0.0 || number > 9_007_199_254_740_991.0 {
8366 return Err(self.range_error("invalid length"));
8367 }
8368 Ok(number as usize)
8369 }
8370
8371 /// `CreateListFromArrayLike(value)`: the elements of an array-like, for `apply` and the
8372 /// other callers that take an argument list from script data.
8373 ///
8374 /// The length is `ToLength`, which *clamps* rather than refusing — the typed-array
8375 /// constructor and `Array.from` need `ToIndex` instead (see
8376 /// [`Interp::to_index`]), which is why they do not go through here.
8377 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8378 let Some(object) = value.as_object().cloned() else {
8379 if value.is_nullish() {
8380 // `f.apply(this, null)` passes no arguments at all.
8381 return Ok(Vec::new());
8382 }
8383 return Err(self.type_error("createListFromArrayLike called on non-object"));
8384 };
8385 let length = match self.get_property(&object, "length")? {
8386 Some(length) => length.to_number(),
8387 None => 0.0,
8388 };
8389 if !length.is_finite() || length <= 0.0 {
8390 return Ok(Vec::new());
8391 }
8392 let length = (length as usize).min(1_000_000);
8393 let mut args = Vec::with_capacity(length);
8394 for index in 0..length {
8395 let element = self.get_property(&object, &index.to_string())?;
8396 args.push(element.unwrap_or(Value::Undefined));
8397 }
8398 Ok(args)
8399 }
8400
8401 /// Turn a call to a generator function into a generator object.
8402 ///
8403 /// The frame is built exactly as an ordinary call would build it, then detached and
8404 /// stored in the generator before any body instruction runs — which is what makes
8405 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8406 /// is `initial_yield`, the first instruction of every suspending body.
8407 pub fn new_generator(
8408 &mut self,
8409 function: Value,
8410 this: Value,
8411 args: Vec<Value>,
8412 ) -> JsResult<Value> {
8413 let Some(object) = function.as_object().cloned() else {
8414 return Err(self.type_error("not a generator function"));
8415 };
8416 let Some((code, env)) = bytecode_of(&object) else {
8417 return Err(self.type_error("not a generator function"));
8418 };
8419 let is_async = code.code.kind.is_async();
8420 self.push_frame(code, env, this, args, function)?;
8421 let frame = self.frames.pop().expect("push_frame just pushed it");
8422 // A fresh generator is *suspended at start*: the body has not run, so a
8423 // `return`/`throw` on it finishes without executing anything.
8424 let mut state = GeneratorState {
8425 frame: Some(frame),
8426 phase: GeneratorPhase::SuspendedStart,
8427 parked_on_await: false,
8428 parked_on_yield_star: false,
8429 requests: std::collections::VecDeque::new(),
8430 async_busy: false,
8431 is_async,
8432 };
8433 // Run to the first suspension. For a generator that is `initial_yield`, so no
8434 // body code runs; for a malformed body it would be the first `yield`.
8435 // An `async function*` answers an async generator: same coroutine, but its
8436 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8437 let default_proto = if is_async {
8438 self.realm
8439 .async_generator_proto
8440 .clone()
8441 .unwrap_or_else(|| self.realm.generator_proto.clone())
8442 } else {
8443 self.realm.generator_proto.clone()
8444 };
8445 // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
8446 // `prototype` object when it is one, the intrinsic otherwise. Every generator having
8447 // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
8448 // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
8449 let proto = self.generator_instance_proto(&object, default_proto)?;
8450 let generator = self.new_object(Some(proto));
8451 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8452 Ok(_) => {}
8453 Err(error) => return Err(error),
8454 }
8455 generator.with_mut(|data| {
8456 data.kind = ObjectKind::Generator(Box::new(state));
8457 });
8458 Ok(Value::Object(generator))
8459 }
8460
8461 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8462 ///
8463 /// Returns the `{value, done}` object itself rather than the pair, because a
8464 /// `yield*` suspension already has one — the inner iterator's own result — and the
8465 /// protocol says to hand that straight through rather than nest it.
8466 /// Advance a generator and report *why* it parked.
8467 ///
8468 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
8469 /// "hand this value to the caller" — but an async generator does: an `await` has to
8470 /// settle before it can answer, while a `yield` is the answer.
8471 fn resume_generator_detailed(
8472 &mut self,
8473 generator: &Gc<JsObject>,
8474 kind: ResumeKind,
8475 value: Value,
8476 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8477 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
8478 ObjectKind::Generator(state) => {
8479 let is_async = state.is_async;
8480 Some(std::mem::replace(
8481 state.as_mut(),
8482 GeneratorState {
8483 frame: None,
8484 phase: GeneratorPhase::Executing,
8485 parked_on_await: false,
8486 parked_on_yield_star: false,
8487 requests: std::collections::VecDeque::new(),
8488 // **Busy while the body runs**, so a `next()` called *from inside*
8489 // the body queues instead of being served. §27.6.3.7
8490 // `AsyncGeneratorResumeNext` returns immediately for the state
8491 // "executing", and the request is served once the body suspends;
8492 // with `false` here the re-entrant call found an empty frame and
8493 // rejected (`request-queue-order-state-executing`).
8494 async_busy: is_async,
8495 is_async,
8496 },
8497 ))
8498 }
8499 _ => None,
8500 }) else {
8501 return Err(self.type_error("not a generator"));
8502 };
8503 let result = self.step_generator(&mut state, kind, value);
8504 // Requests queued *while* the body ran live on the placeholder, because the real
8505 // state is out of the object for the duration. They have to be folded back in
8506 // before the placeholder is overwritten, or the promise they carry never settles.
8507 let queued = generator.with_mut(|data| match &mut data.kind {
8508 ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
8509 _ => std::collections::VecDeque::new(),
8510 });
8511 state.requests.extend(queued);
8512 generator.with_mut(|data| {
8513 data.kind = ObjectKind::Generator(Box::new(state));
8514 });
8515 result
8516 }
8517
8518 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8519 ///
8520 /// Returns the `{value, done}` object itself rather than the pair, because a
8521 /// `yield*` suspension already has one — the inner iterator's own result — and the
8522 /// protocol says to hand that straight through rather than nest it.
8523 pub fn resume_generator(
8524 &mut self,
8525 generator: &Gc<JsObject>,
8526 kind: ResumeKind,
8527 value: Value,
8528 ) -> JsResult<Value> {
8529 let (value, done, ready, _reason) =
8530 self.resume_generator_detailed(generator, kind, value)?;
8531 if ready {
8532 return Ok(value);
8533 }
8534 self.iterator_result(value, done)
8535 }
8536
8537 /// `next`/`return`/`throw` on an async generator, which answer a promise.
8538 ///
8539 /// The body is the same coroutine a sync generator runs; what changes is that an
8540 /// `await` inside it has to settle before the method can answer, so the step is
8541 /// driven off the job queue rather than returning inline.
8542 pub fn resume_async_generator(
8543 &mut self,
8544 generator: &Gc<JsObject>,
8545 kind: ResumeKind,
8546 value: Value,
8547 ) -> JsResult<Value> {
8548 let promise = self.new_promise();
8549 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
8550 // that order, and the second value must reach the *second* `yield`.
8551 let idle = generator.with_mut(|data| match &mut data.kind {
8552 ObjectKind::Generator(state) => {
8553 state.requests.push_back(AsyncRequest {
8554 kind,
8555 value,
8556 promise: promise.clone(),
8557 });
8558 !state.async_busy
8559 }
8560 _ => false,
8561 });
8562 if idle {
8563 self.next_async_request(generator)?;
8564 }
8565 Ok(Value::Object(promise))
8566 }
8567
8568 /// Serve the front queued request, if the generator is free to run one.
8569 ///
8570 /// A finished generator answers from the queue without running anything:
8571 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
8572 /// first, and `throw(e)` rejects.
8573 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
8574 enum Front {
8575 Idle,
8576 Run(ResumeKind, Value, Gc<JsObject>),
8577 Finished(ResumeKind, Value, Gc<JsObject>),
8578 }
8579 let front = generator.with_mut(|data| match &mut data.kind {
8580 ObjectKind::Generator(state) => {
8581 let Some(request) = state.requests.front() else {
8582 return Front::Idle;
8583 };
8584 // Busy means a request is still in flight — awaiting inside the body, not
8585 // finished. Serving another now would interleave two requests.
8586 if state.async_busy && state.phase != GeneratorPhase::Completed {
8587 return Front::Idle;
8588 }
8589 let kind = request.kind;
8590 let value = request.value.clone();
8591 let promise = request.promise.clone();
8592 state.async_busy = true;
8593 if state.phase == GeneratorPhase::Completed {
8594 Front::Finished(kind, value, promise)
8595 } else {
8596 Front::Run(kind, value, promise)
8597 }
8598 }
8599 _ => Front::Idle,
8600 });
8601 match front {
8602 Front::Idle => Ok(()),
8603 Front::Run(kind, value, promise) => {
8604 self.step_async_generator(generator, &promise, kind, value)
8605 }
8606 Front::Finished(kind, value, promise) => match kind {
8607 ResumeKind::Throw => {
8608 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
8609 }
8610 ResumeKind::Next | ResumeKind::Start => {
8611 let result = self.iterator_result(Value::Undefined, true)?;
8612 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
8613 }
8614 ResumeKind::Return => {
8615 // `js_async_generator_completed_return`: the value is awaited before it
8616 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
8617 // finished generator answers `1`, not a promise.
8618 let resolved = match self.promise_resolve_intrinsic(value) {
8619 Ok(resolved) => resolved,
8620 Err(Signal::Throw(reason)) => {
8621 return self.settle_async_request(
8622 generator,
8623 &promise,
8624 AsyncOutcome::Error(reason),
8625 );
8626 }
8627 Err(other) => return Err(other),
8628 };
8629 let done = JsObject::function(
8630 self.heap,
8631 Some(self.realm.function_proto.clone()),
8632 Callable::CompletedReturn {
8633 generator: generator.clone(),
8634 promise: promise.clone(),
8635 rejected: false,
8636 },
8637 );
8638 let failed = JsObject::function(
8639 self.heap,
8640 Some(self.realm.function_proto.clone()),
8641 Callable::CompletedReturn {
8642 generator: generator.clone(),
8643 promise: promise.clone(),
8644 rejected: true,
8645 },
8646 );
8647 let Value::Object(resolved) = resolved else {
8648 return self.settle_async_request(
8649 generator,
8650 &promise,
8651 AsyncOutcome::Error(Value::Undefined),
8652 );
8653 };
8654 self.perform_then(
8655 &resolved,
8656 Some(Value::Object(done)),
8657 Some(Value::Object(failed)),
8658 )?;
8659 Ok(())
8660 }
8661 },
8662 }
8663 }
8664
8665 /// Settle the front request and start the next one.
8666 ///
8667 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
8668 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
8669 /// generator would strand every later request.
8670 fn settle_async_request(
8671 &mut self,
8672 generator: &Gc<JsObject>,
8673 promise: &Gc<JsObject>,
8674 outcome: AsyncOutcome,
8675 ) -> JsResult<()> {
8676 let settled = generator.with_mut(|data| match &mut data.kind {
8677 ObjectKind::Generator(state) => {
8678 let front = state.requests.front();
8679 debug_assert!(
8680 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
8681 "a request settled outside its turn"
8682 );
8683 state.requests.pop_front();
8684 state.async_busy = false;
8685 true
8686 }
8687 _ => false,
8688 });
8689 if settled {
8690 match outcome {
8691 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
8692 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
8693 }
8694 }
8695 self.next_async_request(generator)
8696 }
8697
8698 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
8699 ///
8700 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
8701 /// disposer runs **synchronously** — the reference starts it before returning, which
8702 /// a test can observe by logging after the call — and the rest follow once their
8703 /// predecessor settles.
8704 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
8705 let promise = self.new_promise();
8706 let mut pairs = Vec::with_capacity(resources.len());
8707 for (value, method) in resources {
8708 let pair = self.new_array(vec![value, method]);
8709 pairs.push(Value::Object(pair));
8710 }
8711 let remaining = self.new_array(pairs);
8712 self.dispose_step(&remaining, &promise, Value::Uninitialized)?;
8713 Ok(Value::Object(promise))
8714 }
8715
8716 /// One link of the `disposeAsync` chain.
8717 ///
8718 /// Loops while the disposers finish synchronously, and parks on the first thenable it
8719 /// meets — pushing itself back in as the continuation, with the accumulated error
8720 /// carried along so a later failure can still be folded into the `SuppressedError`.
8721 fn dispose_step(
8722 &mut self,
8723 remaining: &Gc<JsObject>,
8724 promise: &Gc<JsObject>,
8725 mut error: Value,
8726 ) -> JsResult<()> {
8727 loop {
8728 let length = remaining.array_length().unwrap_or(0);
8729 if length == 0 {
8730 if matches!(error, Value::Uninitialized) {
8731 self.fulfill_promise(promise, Value::Undefined);
8732 } else {
8733 self.reject_promise(promise, error);
8734 }
8735 return Ok(());
8736 }
8737 let Some(Value::Object(pair)) = remaining
8738 .array_get(length - 1)
8739 .filter(|v| !matches!(v, Value::Hole))
8740 else {
8741 remaining.array_truncate(self.heap, length - 1);
8742 continue;
8743 };
8744 remaining.array_truncate(self.heap, length - 1);
8745 let value = pair.array_get(0).unwrap_or(Value::Undefined);
8746 let Some(Value::Object(method)) = pair.array_get(1) else {
8747 continue;
8748 };
8749 if !method.is_callable() {
8750 continue;
8751 }
8752 match self.call_value(Value::Object(method), value, Vec::new()) {
8753 Ok(result) => {
8754 if !self.is_thenable(&result)? {
8755 // Finished synchronously; the next disposer is the next iteration.
8756 continue;
8757 }
8758 let awaited = match self.promise_resolve_value(result) {
8759 Ok(awaited) => awaited,
8760 Err(Signal::Throw(reason)) => {
8761 self.reject_promise(promise, reason);
8762 return Ok(());
8763 }
8764 Err(other) => return Err(other),
8765 };
8766 let Value::Object(awaited) = awaited else {
8767 continue;
8768 };
8769 let ok = JsObject::function(
8770 self.heap,
8771 Some(self.realm.function_proto.clone()),
8772 Callable::DisposeStep {
8773 remaining: remaining.clone(),
8774 promise: promise.clone(),
8775 error: error.clone(),
8776 rejected: false,
8777 },
8778 );
8779 let failed = JsObject::function(
8780 self.heap,
8781 Some(self.realm.function_proto.clone()),
8782 Callable::DisposeStep {
8783 remaining: remaining.clone(),
8784 promise: promise.clone(),
8785 error,
8786 rejected: true,
8787 },
8788 );
8789 self.perform_then(
8790 &awaited,
8791 Some(Value::Object(ok)),
8792 Some(Value::Object(failed)),
8793 )?;
8794 return Ok(());
8795 }
8796 Err(Signal::Throw(thrown)) => {
8797 error = self.merge_dispose_error(thrown, error);
8798 }
8799 Err(other) => return Err(other),
8800 }
8801 }
8802 }
8803
8804 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
8805 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
8806 let Value::Object(object) = value else {
8807 return Ok(false);
8808 };
8809 Ok(matches!(
8810 self.get_property(object, "then")?,
8811 Some(Value::Object(then)) if then.is_callable()
8812 ))
8813 }
8814
8815 /// One step of an async generator, settling `promise` with an `{value, done}` result.
8816 fn step_async_generator(
8817 &mut self,
8818 generator: &Gc<JsObject>,
8819 promise: &Gc<JsObject>,
8820 kind: ResumeKind,
8821 value: Value,
8822 ) -> JsResult<()> {
8823 // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
8824 // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
8825 // is abrupt — a `constructor` getter that throws — the generator is resumed with a
8826 // *throw* completion instead, so the body's own `try { yield } catch` sees it:
8827 // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
8828 // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
8829 // out of the same read, one as a rejection and one as a rethrow.
8830 //
8831 // Narrow on purpose: only a value that is *already a promise* is inspected, so
8832 // nothing changes for `return 1` and the extra read is a plain data-property
8833 // lookup on the intrinsic case.
8834 if kind == ResumeKind::Return
8835 && let Value::Object(object) = &value
8836 && self.promise_state(object).is_some()
8837 && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
8838 {
8839 return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
8840 }
8841 let stepped = self.resume_generator_detailed(generator, kind, value);
8842 let (value, done, ready, reason) = match stepped {
8843 Ok(stepped) => stepped,
8844 Err(Signal::Throw(reason)) => {
8845 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
8846 }
8847 Err(other) => return Err(other),
8848 };
8849 // Only an `await` has to wait before the method can answer.
8850 if !done && reason == Some(SuspendKind::Await) {
8851 let awaited = match self.promise_resolve_value(value) {
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 let resumed = JsObject::function(
8866 self.heap,
8867 Some(self.realm.function_proto.clone()),
8868 Callable::GeneratorResume {
8869 generator: generator.clone(),
8870 promise: promise.clone(),
8871 kind: ResumeKind::Next,
8872 },
8873 );
8874 let raised = JsObject::function(
8875 self.heap,
8876 Some(self.realm.function_proto.clone()),
8877 Callable::GeneratorResume {
8878 generator: generator.clone(),
8879 promise: promise.clone(),
8880 kind: ResumeKind::Throw,
8881 },
8882 );
8883 self.perform_then(
8884 &awaited,
8885 Some(Value::Object(resumed)),
8886 Some(Value::Object(raised)),
8887 )?;
8888 return Ok(());
8889 }
8890 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
8891 // completes it — both arrive as the settled value rather than as the promise
8892 // object. A plain value skips the round trip, which is also what keeps `yield 1`
8893 // from costing an extra tick.
8894 let awaits_value = self.is_thenable(&value)?;
8895 if awaits_value {
8896 // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
8897 // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
8898 // value that merely gets `yield`ed is awaited by the body's own `Await`, where
8899 // no `PromiseResolve` appears, so that path keeps the shortcut.
8900 let awaited = match if done {
8901 self.promise_resolve_intrinsic(value)
8902 } else {
8903 self.promise_resolve_value(value)
8904 } {
8905 Ok(awaited) => awaited,
8906 Err(Signal::Throw(reason)) => {
8907 return self.settle_async_request(
8908 generator,
8909 promise,
8910 AsyncOutcome::Error(reason),
8911 );
8912 }
8913 Err(other) => return Err(other),
8914 };
8915 let Value::Object(awaited) = awaited else {
8916 return Ok(());
8917 };
8918 // A rejected yield throws *at the yield* inside the body, so the rejection
8919 // resumes the generator rather than the method's promise.
8920 let answer = JsObject::function(
8921 self.heap,
8922 Some(self.realm.function_proto.clone()),
8923 Callable::YieldResult {
8924 generator: generator.clone(),
8925 promise: promise.clone(),
8926 done,
8927 },
8928 );
8929 let raise = JsObject::function(
8930 self.heap,
8931 Some(self.realm.function_proto.clone()),
8932 Callable::GeneratorResume {
8933 generator: generator.clone(),
8934 promise: promise.clone(),
8935 kind: ResumeKind::Throw,
8936 },
8937 );
8938 self.perform_then(
8939 &awaited,
8940 Some(Value::Object(answer)),
8941 Some(Value::Object(raise)),
8942 )?;
8943 return Ok(());
8944 }
8945 let result = if ready {
8946 // `yield*` handed back the inner iterator's own result object.
8947 value
8948 } else {
8949 self.iterator_result(value, done)?
8950 };
8951 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
8952 }
8953
8954 /// The `{value, done}` object an iterator method answers with.
8955 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
8956 let result = self.new_object(Some(self.realm.object_proto.clone()));
8957 result.define_data("value", value);
8958 result.define_data("done", Value::Bool(done));
8959 Ok(Value::Object(result))
8960 }
8961
8962 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
8963 fn step_generator(
8964 &mut self,
8965 state: &mut GeneratorState,
8966 kind: ResumeKind,
8967 value: Value,
8968 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8969 match state.phase {
8970 GeneratorPhase::Executing => {
8971 return Err(self.type_error("cannot invoke a running generator"));
8972 }
8973 GeneratorPhase::Completed => {
8974 // A finished generator answers every resumption without running.
8975 return Ok(match kind {
8976 ResumeKind::Throw => return Err(Signal::Throw(value)),
8977 ResumeKind::Return => (value, true, false, None),
8978 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
8979 });
8980 }
8981 GeneratorPhase::SuspendedStart => {
8982 if kind != ResumeKind::Next && kind != ResumeKind::Start {
8983 // The body never started, so there is nothing to unwind or return
8984 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
8985 state.frame = None;
8986 state.phase = GeneratorPhase::Completed;
8987 return Ok(match kind {
8988 ResumeKind::Throw => return Err(Signal::Throw(value)),
8989 _ => (value, true, false, None),
8990 });
8991 }
8992 }
8993 GeneratorPhase::SuspendedYield => {}
8994 }
8995
8996 let Some(mut frame) = state.frame.take() else {
8997 return Ok((Value::Undefined, true, false, None));
8998 };
8999 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
9000 // number that says which method resumed it; the emitted `if_false` branches on
9001 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
9002 let mut raised = None;
9003 match kind {
9004 ResumeKind::Next | ResumeKind::Start => {
9005 if state.phase == GeneratorPhase::SuspendedYield {
9006 frame.stack.push(value);
9007 // An `await` resumes with its value alone; only a `yield` gets the
9008 // magic number that says which of `next`/`return` resumed it.
9009 if !state.parked_on_await {
9010 frame.stack.push(Value::Int(RESUME_NEXT));
9011 }
9012 }
9013 }
9014 ResumeKind::Return => {
9015 // A `return` on a not-yet-started generator is handled above, so this is
9016 // always a real resumption.
9017 frame.stack.push(value);
9018 frame.stack.push(Value::Int(RESUME_RETURN));
9019 }
9020 ResumeKind::Throw => {
9021 // At a `yield*` the exception is *data* for the delegation: the compiled
9022 // code resumes with the value and magic `2` and calls the inner iterator's
9023 // `throw`. Everywhere else it is raised at the suspension point, so the
9024 // body's own handler sees it.
9025 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
9026 frame.stack.push(value);
9027 frame.stack.push(Value::Int(RESUME_THROW));
9028 } else {
9029 raised = Some(value);
9030 }
9031 }
9032 }
9033 state.phase = GeneratorPhase::Executing;
9034
9035 let depth = self.frames.len();
9036 self.frames.push(frame);
9037 // A `throw` unwinds from where the frame parked, exactly as if the exception had
9038 // happened at the `yield`.
9039 if let Some(exception) = raised {
9040 if self.catch_here(exception.clone()).is_none() {
9041 self.pop_frame();
9042 state.phase = GeneratorPhase::Completed;
9043 return Err(Signal::Throw(exception));
9044 }
9045 }
9046
9047 // Only the generator's *own* frame ends the generator. The body may call ordinary
9048 // functions, and those push frames of their own: a `Step::Return` from one of them
9049 // is a nested call finishing, not the generator completing. Miscounting that is
9050 // silent — the generator reports the callee's value as its own result and marks
9051 // itself done — so the depth comparison is load-bearing, not defensive.
9052 let own_frame = depth + 1;
9053 loop {
9054 match self.step() {
9055 Ok(Step::Continue) => {}
9056 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9057 let mut frame = self.frames.pop().expect("a frame is live");
9058 // `yield` left the value on the stack; `initial_yield` left nothing.
9059 let yielded = if reason == SuspendKind::Initial {
9060 Value::Undefined
9061 } else {
9062 frame.stack.pop().unwrap_or(Value::Undefined)
9063 };
9064 state.frame = Some(frame);
9065 state.parked_on_await = reason == SuspendKind::Await;
9066 state.parked_on_yield_star =
9067 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9068 state.phase = if reason == SuspendKind::Initial {
9069 GeneratorPhase::SuspendedStart
9070 } else {
9071 GeneratorPhase::SuspendedYield
9072 };
9073 // `yield*` hands the inner iterator's own result object straight
9074 // back, so the caller sees one `{value, done}` rather than a nested
9075 // one — which is why the third field says "already a result".
9076 return Ok((
9077 yielded,
9078 false,
9079 reason == SuspendKind::YieldStar,
9080 Some(reason),
9081 ));
9082 }
9083 Ok(Step::Suspend(_)) => {
9084 // A `yield` in a frame other than the generator's would mean a
9085 // generator body entered as an ordinary call, which
9086 // `call_or_push` prevents.
9087 self.unwind_to(depth);
9088 state.phase = GeneratorPhase::Completed;
9089 return Err(Signal::Throw(self.make_error(
9090 "InternalError",
9091 "a generator body ran as an ordinary call",
9092 )));
9093 }
9094 Ok(Step::Return(value)) => {
9095 self.pop_frame();
9096 if self.frames.len() > depth {
9097 // A nested call finished: hand the value back to its caller and
9098 // keep running the generator body.
9099 self.frames
9100 .last_mut()
9101 .expect("a caller is live")
9102 .stack
9103 .push(value);
9104 continue;
9105 }
9106 state.phase = GeneratorPhase::Completed;
9107 // The reference closes the generator's closure variables here; ours
9108 // live in cells the frame owned, which the drop below releases.
9109 return Ok((value, true, false, None));
9110 }
9111 Err(Signal::Throw(exception)) => {
9112 // The frame that threw gets the first chance to catch, exactly as in
9113 // the ordinary call loop; a frame above the generator's is popped and
9114 // the exception carries on down.
9115 let exception = exception;
9116 loop {
9117 if self.frames.len() <= depth {
9118 // The generator's own frame is gone, so nothing here caught it.
9119 state.phase = GeneratorPhase::Completed;
9120 return Err(Signal::Throw(exception));
9121 }
9122 if self.catch_here(exception.clone()).is_some() {
9123 break;
9124 }
9125 self.pop_frame();
9126 }
9127 }
9128 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9129 }
9130 }
9131 }
9132
9133 /// Pop frames until `depth` are left, keeping their buffers.
9134 fn unwind_to(&mut self, depth: usize) {
9135 while self.frames.len() > depth {
9136 self.pop_frame();
9137 }
9138 }
9139 fn call_or_push(
9140 &mut self,
9141 callee: Value,
9142 this: Value,
9143 args: Vec<Value>,
9144 ) -> JsResult<Option<Value>> {
9145 if let Value::Object(function) = &callee
9146 && let Some((code, env)) = bytecode_of(function)
9147 {
9148 // Calling a generator function does not run anything: it captures the
9149 // arguments in a frame and hands back the generator object.
9150 if code.code.kind.is_generator() {
9151 return self.new_generator(callee, this, args).map(Some);
9152 }
9153 // An async function answers a promise and runs its body as a coroutine, so it
9154 // takes the same path as a plain call into it.
9155 if code.code.kind.is_async() {
9156 return self.new_async_function(callee, this, args).map(Some);
9157 }
9158 self.push_frame(code, env, this, args, callee)?;
9159 return Ok(None);
9160 }
9161 self.call_value(callee, this, args).map(Some)
9162 }
9163
9164 /// `new callee(args)`.
9165 ///
9166 /// A constructor differs from a plain call in three ways: it gets a fresh object
9167 /// as `this` whose prototype is the constructor's `prototype` property, its
9168 /// return value is *replaced* by that object unless it returns an object itself,
9169 /// and a native constructor is expected to initialise the object it is given
9170 /// rather than build one.
9171 pub fn construct(
9172 &mut self,
9173 callee: Value,
9174 new_target: Value,
9175 args: Vec<Value>,
9176 ) -> JsResult<Value> {
9177 // `new` on a bound function constructs its *target*, prepending the arguments
9178 // the bind fixed and ignoring the bound `this` — a bound function is a
9179 // constructor only when its target is one, and `new` always makes a fresh
9180 // object of the target's prototype rather than reusing the bound receiver.
9181 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9182 // ran the body with `this === null` and threw on `this.x = a`.
9183 let mut callee = callee;
9184 let mut new_target = new_target;
9185 let mut args = args;
9186 loop {
9187 let Some(object) = callee.as_object().cloned() else {
9188 return Err(Signal::Throw(
9189 self.make_error("TypeError", "not a constructor"),
9190 ));
9191 };
9192 // A proxy of a function constructs through its `construct` trap, and the
9193 // trap's answer is the result directly — no fresh object is made here.
9194 if object.proxy_state().is_some() {
9195 return match self.proxy_construct(&object, args, &new_target)? {
9196 Some(result) => Ok(result),
9197 None => Err(Signal::Throw(
9198 self.make_error("TypeError", "proxy target is not a constructor"),
9199 )),
9200 };
9201 }
9202 // A generator function has no `[[Construct]]`, and the reference names it in
9203 // the message: `new (function* G(){})()` reports "G is not a constructor".
9204 if object.with(|data| match &data.kind {
9205 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9206 code.code.kind.is_generator()
9207 }
9208 _ => false,
9209 }) {
9210 let name = object
9211 .own_property("name")
9212 .and_then(|property| property.value)
9213 .map(|value| value.to_js_string())
9214 .unwrap_or_default();
9215 return Err(Signal::Throw(
9216 self.make_error("TypeError", &format!("{name} is not a constructor")),
9217 ));
9218 }
9219 let bound = object.with(|data| match &data.kind {
9220 ObjectKind::Function(Callable::Bound {
9221 target,
9222 args: leading,
9223 ..
9224 }) => Some((target.clone(), leading.clone())),
9225 _ => None,
9226 });
9227 let Some((target, leading)) = bound else {
9228 // Not a bound function, so this object is the callee. §7.2.4
9229 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9230 // refusals above cover only the built-ins the reference also refuses by
9231 // name. Everything else — a method, an arrow, an async function — has no
9232 // `[[Construct]]` either, and answering "yes" here made
9233 // `new (Array.prototype.map)` build an object instead of throwing.
9234 if !object.is_constructor() {
9235 let name = object
9236 .own_property("name")
9237 .and_then(|property| property.value)
9238 .map(|value| value.to_js_string())
9239 .unwrap_or_default();
9240 return Err(Signal::Throw(
9241 self.make_error("TypeError", &format!("{name} is not a constructor")),
9242 ));
9243 }
9244 break;
9245 };
9246 let mut all = leading;
9247 all.extend(args);
9248 args = all;
9249 // A bound function that is its own `new.target` stands in for its target:
9250 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9251 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9252 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9253 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9254 _ => false,
9255 };
9256 if same_wrapper {
9257 new_target = target.clone();
9258 }
9259 callee = target;
9260 }
9261 let Value::Object(function) = &callee else {
9262 unreachable!("the loop above only breaks on an object");
9263 };
9264 // The fresh object's prototype comes from `new.target`, not from the callee: a
9265 // derived constructor reaches here through `super()`, and the instance must be a
9266 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9267 // an object inheriting `D.prototype` rather than `C.prototype`.
9268 let prototype_source = match new_target.as_object() {
9269 Some(target) => target.clone(),
9270 None => function.clone(),
9271 };
9272 // A native constructor builds its own instance, through `new_ctor_instance`, once it
9273 // has validated its arguments. Pre-building one here would read
9274 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9275 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9276 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9277 let is_native = function.native_creates_own_instance();
9278 let this = if is_native {
9279 Value::Undefined
9280 } else {
9281 let prototype = self.get_property(&prototype_source, "prototype")?;
9282 let prototype = match prototype {
9283 Some(Value::Object(proto)) => Some(proto),
9284 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
9285 // object, the answer is the realm's *intrinsic* prototype for this
9286 // constructor, not `%Object.prototype%`.
9287 _ => {
9288 let fallback = self.get_property(function, "prototype")?;
9289 match fallback {
9290 Some(Value::Object(proto)) => Some(proto),
9291 _ => Some(self.realm.object_proto.clone()),
9292 }
9293 }
9294 };
9295 Value::Object(self.new_object(prototype))
9296 };
9297 // `new.target` inside the body is the constructor that was written, so a bound
9298 // function's target sees itself rather than the bound wrapper.
9299 //
9300 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
9301 // `?`, so assigning `None` after the call would be skipped and the failed
9302 // `new.target` would stay visible to every later native call. The symptom was a
9303 // native constructor refusing a plain call — `var s = Symbol(); new
9304 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
9305 // "FinalizationRegistry is not a constructor".
9306 let outer_new_target = self.pending_new_target.replace(new_target);
9307 let callee = callee.clone();
9308 let result = self.call_value(callee, this.clone(), args);
9309 self.pending_new_target = outer_new_target;
9310 let result = result?;
9311 // A constructor that returns an object overrides `this`; any other return value
9312 // (including `undefined`) is ignored — **except** in a derived constructor, where
9313 // §15.7.1 step 12 makes a non-object return a `TypeError`
9314 // (`Function/internals/Construct/derived-return-val`).
9315 let derived = function.with(|data| match &data.kind {
9316 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9317 code.code.is_derived_constructor
9318 }
9319 _ => false,
9320 });
9321 Ok(match result {
9322 Value::Object(_) => result,
9323 // A bare `return;` answers `undefined`, which is **legal** even in a derived
9324 // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
9325 Value::Undefined => this,
9326 _ if derived => {
9327 return Err(Signal::Throw(self.make_error(
9328 "TypeError",
9329 "derived constructor may only return an object or undefined",
9330 )));
9331 }
9332 _ => this,
9333 })
9334 }
9335
9336 /// `new.target` for the call currently being made.
9337 ///
9338 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9339 /// it as `this`), but a *host* constructor that builds its own instance is handed
9340 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9341 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9342 /// it here.
9343 ///
9344 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9345 /// receives for a plain call.
9346 pub fn current_new_target(&self) -> Value {
9347 self.active_new_target.clone()
9348 }
9349
9350 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9351 ///
9352 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9353 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9354 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9355 let constructor = self.realm.errors.get("AggregateError").cloned();
9356 let Some(constructor) = constructor else {
9357 return self.make_error("AggregateError", message);
9358 };
9359 let list = self.new_array(errors);
9360 match self.construct(
9361 Value::Object(constructor.clone()),
9362 Value::Object(constructor),
9363 vec![Value::Object(list), self.string(message)],
9364 ) {
9365 Ok(value) => value,
9366 // A user could have replaced `AggregateError` with something that throws; the
9367 // engine still owes the caller a rejection, so it falls back rather than
9368 // turning `Promise.any`'s rejection into a throw.
9369 Err(_) => self.make_error("AggregateError", message),
9370 }
9371 }
9372
9373 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9374 ///
9375 /// The error classes themselves arrive with the builtins milestone; what
9376 /// matters here is that the thrown value stringifies the way a script printing
9377 /// the caught value expects.
9378 ///
9379 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9380 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9381 /// rely on when they print a caught value.
9382 pub fn make_error(&self, name: &str, message: &str) -> Value {
9383 let proto = self
9384 .realm
9385 .errors
9386 .get(name)
9387 .map(|constructor| self.prototype_of(constructor))
9388 .unwrap_or_else(|| self.realm.error_proto.clone());
9389 let error = self.new_object(Some(proto));
9390 // `name` and `message` are own properties of the instance, which is what
9391 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9392 // `Error`.
9393 error.define(
9394 "name",
9395 Property::with_attributes(self.string(name), true, false),
9396 );
9397 error.define(
9398 "message",
9399 Property::with_attributes(self.string(message), true, false),
9400 );
9401 // The internal class, which is what tells a printer this is an error rather than a
9402 // plain object with `name` and `message` properties. The constructor path sets it
9403 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9404 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
9405 // literally `"Error"` in both places — the *name* is read from `name`, which is why
9406 // a `RangeError` still prints as `RangeError`.
9407 self.internal_set(&error, "_class", self.string("Error"));
9408 // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
9409 // answered `false` from `Error.isError` while a constructed one answered `true`,
9410 // because only the constructor set the slot. The reference answers `true` for both
9411 // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
9412 // accessor gated on this slot the omission stopped being cosmetic: `print_error`
9413 // tests `typeof stack === "string"` to decide on a trailing newline, so every
9414 // engine-thrown error lost its blank line.
9415 self.internal_set(&error, "_error_data", Value::Bool(true));
9416 // The trace is captured where the error is *made*, which is where the reference
9417 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
9418 // way out, so a caught engine error already has its stack even if the handler
9419 // never rethrows it.
9420 self.add_stack(&error);
9421 Value::Object(error)
9422 }
9423
9424 /// Give an error object its `stack` property, from the current frame stack.
9425 ///
9426 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
9427 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
9428 /// `stack` a script set, is not rewritten.
9429 pub fn add_stack(&self, object: &Gc<JsObject>) {
9430 self.add_stack_skipping(object, 0);
9431 }
9432
9433 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
9434 ///
9435 /// An `Error` constructor passes 1: the reference builds those traces with
9436 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
9437 /// constructor itself, while a `RangeError` raised inside `toISOString` does
9438 /// report `at toISOString (native)`.
9439 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
9440 if object.has_own("stack") {
9441 return;
9442 }
9443 // The trace is *captured* here but not installed as a property: `stack` is an
9444 // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
9445 // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
9446 // is kept in a hidden slot and the getter materialises it on first read.
9447 //
9448 // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
9449 // shows it — this is the same discipline `_error_data` and `_class` follow.
9450 let trace = self.stack_trace_skipping(skip);
9451 let text = self.string(trace);
9452 self.internal_set(object, "_stack_trace", text);
9453 }
9454
9455 /// The function object currently being called, if any.
9456 ///
9457 /// A native function is a bare `fn` pointer, so it cannot capture which class
9458 /// it belongs to; it reads that from the callee instead. This is also what a
9459 /// stack trace would use.
9460 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
9461 match &self.frames.last()?.callee {
9462 Value::Object(object) => Some(object.clone()),
9463 _ => None,
9464 }
9465 }
9466
9467 /// The `prototype` property of a constructor, falling back to
9468 /// `Object.prototype` for anything that is not shaped like one.
9469 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
9470 constructor
9471 .own_property("prototype")
9472 .and_then(|property| property.value)
9473 .and_then(|value| value.as_object().cloned())
9474 .unwrap_or_else(|| self.realm.object_proto.clone())
9475 }
9476
9477 /// Throw a `TypeError` carrying `message`.
9478 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
9479 Signal::Throw(self.make_error("TypeError", message.as_ref()))
9480 }
9481
9482 /// Throw a `RangeError` carrying `message`.
9483 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
9484 Signal::Throw(self.make_error("RangeError", message.as_ref()))
9485 }
9486
9487 /// The `ReferenceError` a read of an uninitialised binding raises.
9488 /// The name of the binding `slot` refers to, for an error message.
9489 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
9490 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 }
9508
9509 /// Whether `slot` names a `const` binding, which rejects every store after its
9510 /// initialiser.
9511 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
9512 match kind {
9513 VarSlot::Loc => self
9514 .frame()
9515 .code
9516 .code
9517 .vars
9518 .get(slot)
9519 .is_some_and(|v| v.is_const),
9520 VarSlot::Closure => self
9521 .frame()
9522 .code
9523 .code
9524 .closure_vars
9525 .get(slot)
9526 .is_some_and(|c| c.is_const),
9527 }
9528 }
9529
9530 /// The `TypeError` a store to a `const` binding raises.
9531 ///
9532 /// `const` is enforced here rather than at compile time because the binding can be
9533 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
9534 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
9535 /// both halves of what "checked store" means: the dead zone is over, and the
9536 /// binding is writable.
9537 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
9538 let name = self.binding_name(slot, kind);
9539 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
9540 }
9541
9542 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
9543 let name = match kind {
9544 VarSlot::Loc => self
9545 .frame()
9546 .code
9547 .code
9548 .vars
9549 .get(slot)
9550 .map(|v| v.name.clone()),
9551 VarSlot::Closure => self
9552 .frame()
9553 .code
9554 .code
9555 .closure_vars
9556 .get(slot)
9557 .map(|c| c.name.clone()),
9558 }
9559 .unwrap_or_default();
9560 Signal::Throw(self.make_error(
9561 "ReferenceError",
9562 &format!("cannot access '{name}' before initialization"),
9563 ))
9564 }
9565
9566 fn throw_reference(&self, name: &str) -> Signal {
9567 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
9568 }
9569
9570 // -- the instruction loop -----------------------------------------------
9571
9572 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
9573 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
9574 // measured at 16% of a tight arithmetic loop's total time.
9575 #[inline(always)]
9576 fn step(&mut self) -> JsResult<Step> {
9577 // The instruction is already decoded (see [`crate::insn`]), so this is an index
9578 // and a `Copy` read rather than a table lookup plus a width switch. Only the
9579 // borrow lives across the boundary; nothing is cloned.
9580 // **One** borrow of the frame: fetch the record, then advance in the same scope.
9581 // The obvious version borrowed it three times (`last` to read, `last_mut` to
9582 // write, and once more inside the handler), and each is a bounds check plus an
9583 // `Option` unwrap — on the one path every instruction takes.
9584 let Some((insn, next)) = ({
9585 let frame = self
9586 .frames
9587 .last_mut()
9588 .expect("step() is only called with a live frame");
9589 // Past the last instruction is a normal return: the compiler ends a function
9590 // with `return`, and a jump to the end of a block lands here.
9591 let insn = frame.insns().get(frame.pc).copied();
9592 match insn {
9593 None => None,
9594 Some(insn) => {
9595 // A fused record stands for the next few instructions, so the next
9596 // `pc` is its width ahead — the instructions it replaces are never
9597 // dispatched. `at` is the byte offset a stack trace reports; it stays
9598 // an offset because the line table is keyed by bytes.
9599 frame.at = insn.offset as usize;
9600 frame.pc += insn.width();
9601 Some((insn, frame.pc))
9602 }
9603 }
9604 }) else {
9605 return Ok(Step::Return(Value::Undefined));
9606 };
9607 self.check_memory()?;
9608 self.check_interrupt()?;
9609 if insn.fused == crate::insn::Fused::None {
9610 self.execute_instruction(insn.op, insn.a, insn.b, next)
9611 } else {
9612 self.execute_fused(insn)
9613 }
9614 }
9615
9616 /// Run a fused instruction: several bytecode instructions in one dispatch.
9617 ///
9618 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
9619 /// it cannot throw and cannot allocate — and anything else falls back to the real
9620 /// instructions, in their real order, so an exception leaves the operand stack
9621 /// exactly as it would have been.
9622 #[inline]
9623 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
9624 use crate::insn::Fused;
9625 let slot = insn.a as usize;
9626 match insn.fused {
9627 // `x = k`: `push k; put_loc x`.
9628 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
9629 // `x += k`: `get_loc x; push k; add; put_loc x`.
9630 Fused::AddImmLoc => {
9631 let delta = insn.b as i32;
9632 match self.get_loc(slot) {
9633 Value::Int(left) => {
9634 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
9635 // that built two `Value`s, called a function, and matched on them
9636 // again to reach this same `checked_add`. It is the innermost
9637 // operation of every accumulator in every program.
9638 let answer = match left.checked_add(delta) {
9639 Some(sum) => Value::Int(sum),
9640 None => Value::Float(left as f64 + delta as f64),
9641 };
9642 self.put_loc(slot, answer);
9643 }
9644 other => {
9645 self.push(other);
9646 self.push(Value::Int(delta));
9647 self.binary_add()?;
9648 let value = self.pop();
9649 self.put_loc(slot, value);
9650 }
9651 }
9652 }
9653 // `x += "literal"` and `x += y`: the two shapes that can append in place.
9654 Fused::AddAtomLoc => {
9655 let text = self.atom_wtf8(insn.b as usize);
9656 let right = self.string_wtf8(text);
9657 self.add_into_loc(slot, right)?;
9658 }
9659 Fused::AddLocLoc => {
9660 let source = (insn.a & 0xFFFF) as usize;
9661 let target = (insn.a >> 16) as usize;
9662 let right = self.get_loc(source);
9663 self.add_into_loc(target, right)?;
9664 }
9665 Fused::AddArgLoc => {
9666 let source = (insn.a & 0xFFFF) as usize;
9667 let target = (insn.a >> 16) as usize;
9668 let right = self.get_arg(source);
9669 self.add_into_loc(target, right)?;
9670 }
9671 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
9672 Fused::PostIncLoc => match self.get_loc(slot) {
9673 Value::Int(left) => {
9674 let answer = match left.checked_add(1) {
9675 Some(sum) => Value::Int(sum),
9676 None => Value::Float(left as f64 + 1.0),
9677 };
9678 self.put_loc(slot, answer);
9679 }
9680 other => {
9681 self.push(other);
9682 let raw = self.pop();
9683 let (old, updated) = self.advance_numeric(raw, true)?;
9684 self.push(old);
9685 self.push(updated);
9686 let value = self.pop();
9687 self.put_loc(slot, value);
9688 self.pop();
9689 }
9690 },
9691 // `if (!(x < arg)) goto target`: a loop header.
9692 //
9693 // The comparison is computed rather than replayed on the operand stack. That
9694 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
9695 // that throws: the effects happen in the same order, and a handler truncates
9696 // the stack down to its marker, so the intermediate values are unobservable.
9697 Fused::LtLocArgJump => {
9698 let loc = (insn.a >> 16) as usize;
9699 let arg = (insn.a & 0xFFFF) as usize;
9700 let left = self.get_loc(loc);
9701 let right = self.get_arg(arg);
9702 let taken = match (&left, &right) {
9703 (Value::Int(left), Value::Int(right)) => !(left < right),
9704 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9705 };
9706 if taken {
9707 self.frame_mut().pc = insn.b as usize;
9708 }
9709 }
9710 // `i < k` in a loop header, where `k` is an integer literal.
9711 Fused::LtLocImmJump => {
9712 let left = self.get_loc(insn.a as usize);
9713 let right = Value::Int(insn.imm as i32);
9714 let taken = match &left {
9715 Value::Int(left) => !(*left < insn.imm as i32),
9716 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9717 };
9718 if taken {
9719 self.frame_mut().pc = insn.b as usize;
9720 }
9721 }
9722 Fused::None => unreachable!("only called for a fused record"),
9723 }
9724 Ok(Step::Continue)
9725 }
9726
9727 /// Run records that cannot call script, cannot throw and cannot change frames.
9728 ///
9729 /// Returns `Some(value)` when the function ran off the end of its instructions (a
9730 /// normal return), and `None` when it stopped in front of an instruction the slow path
9731 /// has to handle — `pc` is written back either way, so `step` resumes at the right
9732 /// place.
9733 ///
9734 /// **The invariant is the whole point.** Every arm here is restricted to work that
9735 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
9736 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
9737 /// that the memory limit has to see. An opcode whose operands turn out to need any of
9738 /// that **stops the loop** instead of trying, so the slow path gets the instruction
9739 /// untouched and with its operands still on the stack. That is why the fallback is a
9740 /// `break` and not a duplicated slow arm: a second implementation of the same
9741 /// semantics is how a wrong answer gets in with no test noticing.
9742 ///
9743 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
9744 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
9745 fn run_fast(&mut self) -> JsResult<Option<Value>> {
9746 use crate::insn::Fused;
9747 // The outer loop exists only so a `Call` can come back through here: once a
9748 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
9749 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
9750 // frame. Re-entering re-reads both from whichever frame is now on top. Every
9751 // other exit from the inner loop returns, so this costs one loop per call.
9752 'outer: loop {
9753 // One reference-count bump per *slow* instruction (a call, an allocation, a
9754 // property access), never one per instruction — that distinction is worth
9755 // two orders of magnitude and was measured as such.
9756 let (code, mut pc) = {
9757 let frame = self.frame();
9758 (frame.code.clone(), frame.pc)
9759 };
9760 let insns = &code.insns;
9761 loop {
9762 let Some(insn) = insns.get(pc).copied() else {
9763 self.frame_mut().pc = pc;
9764 return Ok(Some(Value::Undefined));
9765 };
9766 match insn.fused {
9767 // `x = k`
9768 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
9769 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
9770 // object — stops the loop so `binary_add` can decide.
9771 Fused::AddImmLoc => {
9772 let slot = insn.a as usize;
9773 let delta = insn.b as i32;
9774 let Value::Int(left) = self.get_loc(slot) else {
9775 return Ok(self.stop(pc));
9776 };
9777 let sum = match left.checked_add(delta) {
9778 Some(sum) => Value::Int(sum),
9779 None => Value::Float(left as f64 + delta as f64),
9780 };
9781 self.put_loc(slot, sum);
9782 }
9783 // `x += "literal"` / `x += y`: the operand is a string, so the append
9784 // either allocates one or grows one. Both are the slow path's business;
9785 // the fusion's job is only to make the *slot* the sole owner, which is what
9786 // `execute_fused` needs and what `get_loc` alone destroys.
9787 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
9788 return Ok(self.stop(pc));
9789 }
9790 // `x++` on an integer, old value dropped.
9791 Fused::PostIncLoc => {
9792 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
9793 // value is read in place and overwritten in place, so the reference
9794 // count it held is released by the same assignment that stores the
9795 // new one. `get_loc` plus `put_loc` did two borrows, two table
9796 // lookups and a clone, and this arm is the whole body of a counting
9797 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
9798 let slot = insn.a as usize;
9799 let frame = self.frames.last_mut().expect("a frame is live");
9800 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
9801 let target = if cell < 0 {
9802 frame.locals.get_mut(slot)
9803 } else {
9804 None
9805 };
9806 let Some(target) = target else {
9807 return Ok(self.stop(pc));
9808 };
9809 let Value::Int(left) = *target else {
9810 return Ok(self.stop(pc));
9811 };
9812 *target = match left.checked_add(1) {
9813 Some(sum) => Value::Int(sum),
9814 None => Value::Float(left as f64 + 1.0),
9815 };
9816 }
9817 // A loop header, `if (!(x < arg)) goto target`, with both sides already
9818 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
9819 // bound stayed small integers.
9820 Fused::LtLocArgJump => {
9821 let loc = (insn.a >> 16) as usize;
9822 let arg = (insn.a & 0xFFFF) as usize;
9823 // One borrow for both slots: this arm *is* the whole loop of a
9824 // `for (i = 0; i < n; i++)` with an argument bound, so a second
9825 // `frames.last()` here is paid on every iteration. Measured 7.5% on
9826 // `dispatch:empty-loop`.
9827 let (left, right) = {
9828 let frame = self.frame();
9829 (frame.read_loc(loc), frame.read_arg(arg))
9830 };
9831 // Heavily measured: the bound is very often a `Float` even when the
9832 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
9833 // `JSON.parse` or a division is one — so requiring both sides to be
9834 // `Int` sent every iteration of those loops down the slow path. The
9835 // comparison below is the same one `relational` makes for two numbers.
9836 if !is_number(&left) || !is_number(&right) {
9837 return Ok(self.stop(pc));
9838 }
9839 // `if_false` branches on the comparison being false, which is **not**
9840 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
9841 // `>=` is also false and would keep it running forever. Clippy wants the
9842 // negation folded; that would be a wrong answer.
9843 let ordered = left.to_number() < right.to_number();
9844 let take_branch = !ordered;
9845 if take_branch {
9846 pc = insn.b as usize;
9847 continue;
9848 }
9849 }
9850 // The same header with a literal bound: `if (!(x < k)) goto target`.
9851 // The bound is an immediate, so only the counter needs a type test.
9852 #[allow(clippy::neg_cmp_op_on_partial_ord)]
9853 Fused::LtLocImmJump => {
9854 let left = self.get_loc(insn.a as usize);
9855 if !is_number(&left) {
9856 return Ok(self.stop(pc));
9857 }
9858 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
9859 if take_branch {
9860 pc = insn.b as usize;
9861 continue;
9862 }
9863 }
9864 Fused::None => match insn.op {
9865 // -- branches ---------------------------------------------------
9866 // A jump is an assignment now, because the target is an instruction
9867 // index. No arithmetic, no resolution table.
9868 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9869 let target = insn.a as usize;
9870 // A **back-edge** is a loop, and it is the only place an
9871 // instruction-level checkpoint can stop one: `for(;;){}` compiles
9872 // to a jump to itself and never leaves this loop, so the
9873 // per-instruction checks in `step` never run. That is exactly the
9874 // hole this arm closes — a host's `JS_SetInterruptHandler` did
9875 // nothing to a `for(;;){}` until it did, which is what
9876 // `tests/c/embed.c` is for.
9877 //
9878 // Polling here rather than on every instruction in this loop is
9879 // also the reference's choice (`OP_goto` calls
9880 // `js_poll_interrupts`), and it costs one compare per branch
9881 // instead of one decrement per instruction.
9882 if target <= pc {
9883 self.frame_mut().pc = target;
9884 self.check_memory()?;
9885 self.check_interrupt()?;
9886 }
9887 pc = target;
9888 continue;
9889 }
9890 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
9891 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
9892 let taken = self.pop().to_boolean();
9893 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
9894 if taken == want {
9895 pc = insn.a as usize;
9896 continue;
9897 }
9898 }
9899 // -- slot access -------------------------------------------------
9900 // A load's slot is already an operand (see `insn::implicit_operand`);
9901 // a captured one goes through its cell, which runs no script.
9902 Opcode::GetLoc
9903 | Opcode::GetLoc8
9904 | Opcode::GetLoc0
9905 | Opcode::GetLoc1
9906 | Opcode::GetLoc2
9907 | Opcode::GetLoc3 => {
9908 let value = self.get_loc(insn.a as usize);
9909 self.push(value);
9910 }
9911 Opcode::PutLoc
9912 | Opcode::PutLoc8
9913 | Opcode::PutLoc0
9914 | Opcode::PutLoc1
9915 | Opcode::PutLoc2
9916 | Opcode::PutLoc3 => {
9917 let value = self.pop();
9918 self.put_loc(insn.a as usize, value);
9919 }
9920 Opcode::GetArg
9921 | Opcode::GetArg0
9922 | Opcode::GetArg1
9923 | Opcode::GetArg2
9924 | Opcode::GetArg3 => {
9925 let value = self.get_arg(insn.a as usize);
9926 self.push(value);
9927 }
9928 Opcode::PutArg
9929 | Opcode::PutArg0
9930 | Opcode::PutArg1
9931 | Opcode::PutArg2
9932 | Opcode::PutArg3 => {
9933 let value = self.pop();
9934 self.put_arg(insn.a as usize, value);
9935 }
9936 // `a[i]` with an integer index on a dense array: see `fast_array_get`
9937 // for why a non-hole own element is exactly the slow path's answer.
9938 // The two operands are *peeked*, so a miss leaves the stack as the
9939 // slow path expects to find it.
9940 Opcode::GetArrayEl => {
9941 // One lookup, not two. The guard used `if …is_some()` and the arm
9942 // then called it again to get the value — two `peek`s, two
9943 // `array_get`s and two `Value` clones for one element.
9944 // `fast_array_get` was 13.1% of `array:indexed`, and the same
9945 // double call was the first version of the `get_field` fast path.
9946 let Some(value) = self.fast_array_get() else {
9947 return Ok(self.stop(pc));
9948 };
9949 // `a[i]` consumes both operands and leaves the element in their
9950 // place: one `truncate` and one write, no `pop`/`push` pair.
9951 let frame = self.frame_mut();
9952 frame.stack.truncate(frame.stack.len() - 2);
9953 frame.stack.push(value);
9954 }
9955 // `a[i] = v` on a dense array with an integer index: see
9956 // `fast_array_set` for why the whole store is one step.
9957 Opcode::PutArrayEl if self.fast_array_set() => {}
9958 // `o.x` resolved from the inline cache without leaving the loop.
9959 //
9960 // The cache is keyed by `(receiver identity, atom, site)` and a
9961 // monomorphic read re-validates the same chain every iteration, so
9962 // each one used to cost a `stop(pc)` — a write of `pc` into the
9963 // frame, a return out of this loop, a re-dispatch through `step` and
9964 // a re-entry. `property:monomorphic` spent 18% in
9965 // `read_field_cached` and 21% in `push`, both across that boundary.
9966 //
9967 // The site is `pc + width`, which is exactly the `next` the slow arm
9968 // passes — the two must agree or every fast lookup misses and
9969 // re-records the same entry forever.
9970 //
9971 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
9972 // slow arm finds the receiver where it expects it.
9973 // `name` resolved from the global-variable cache inside the loop.
9974 //
9975 // Same shape as `get_field` above and for the same reason: `get_var`
9976 // was not in the fast loop, so reading a global — which `fib` does
9977 // once per recursive call, for its own name — cost a `stop(pc)`, a
9978 // return out of the loop, a `step` re-dispatch and a re-entry, before
9979 // `get_global` even started its `scopes_are_plain` checks.
9980 //
9981 // Everything here is exactly `get_global`'s first branch: not lexical,
9982 // no `eval` scope, cache hit. Anything else leaves the stack untouched
9983 // and lets the slow arm decide.
9984 Opcode::GetVar => {
9985 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
9986 return Ok(self.stop(pc));
9987 };
9988 self.push(value);
9989 }
9990 Opcode::GetField | Opcode::GetField2 => {
9991 let Some(value) =
9992 self.fast_field_get(insn.a as usize, pc + insn.width())
9993 else {
9994 return Ok(self.stop(pc));
9995 };
9996 if insn.op == Opcode::GetField2 {
9997 // `get_field2` keeps the receiver for the `call_method` that
9998 // follows.
9999 self.push(value);
10000 } else {
10001 // `get_field` replaces the receiver, so this is one store over
10002 // the top slot rather than a `pop` and a `push`: the length
10003 // never changes, so neither `Vec` arm has a capacity check or a
10004 // drop to run beyond the one the overwrite itself does.
10005 let frame = self.frame_mut();
10006 match frame.stack.last_mut() {
10007 Some(slot) => *slot = value,
10008 None => return Ok(self.stop(pc)),
10009 }
10010 }
10011 }
10012 // -- constants ---------------------------------------------------
10013 Opcode::PushMinus1
10014 | Opcode::Push0
10015 | Opcode::Push1
10016 | Opcode::Push2
10017 | Opcode::Push3
10018 | Opcode::Push4
10019 | Opcode::Push5
10020 | Opcode::Push6
10021 | Opcode::Push7
10022 | Opcode::PushI8
10023 | Opcode::PushI16
10024 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
10025 // -- stack shuffling ---------------------------------------------
10026 Opcode::Drop => {
10027 self.pop();
10028 }
10029 // -- arithmetic on two integers ----------------------------------
10030 //
10031 // The operands are *looked at* before they are popped, so a non-integer
10032 // pair leaves the stack exactly as the slow path expects to find it.
10033 Opcode::Add if self.numeric_pair() => {
10034 let right = self.pop();
10035 let left = self.pop();
10036 // Exactly [`add_numbers`], which is what the slow arm reaches.
10037 let answer = match (&left, &right) {
10038 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10039 Some(sum) => Value::Int(sum),
10040 None => Value::Float(*a as f64 + *b as f64),
10041 },
10042 _ => Value::Float(left.to_number() + right.to_number()),
10043 };
10044 self.push(answer);
10045 }
10046 Opcode::Sub
10047 | Opcode::And
10048 | Opcode::Or
10049 | Opcode::Xor
10050 | Opcode::Shl
10051 | Opcode::Sar
10052 | Opcode::Shr
10053 if self.numeric_pair() =>
10054 {
10055 let right = self.pop();
10056 let left = self.pop();
10057 let answer =
10058 arithmetic(insn.op, left, right).expect("numbers cannot throw");
10059 self.push(answer);
10060 }
10061 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10062 if self.numeric_pair() =>
10063 {
10064 let right = self.pop();
10065 let left = self.pop();
10066 let answer = self
10067 .relational(insn.op, left, right)
10068 .expect("numbers cannot throw");
10069 self.push(answer);
10070 }
10071 // -- calls -------------------------------------------------------
10072 //
10073 // A plain call: `callee(arg0, …, argN) -> result`.
10074 //
10075 // This arm exists because of one measurement. `call:recursion` had
10076 // **20.4% of its profile in `execute_instruction`** — the *slow*
10077 // executor — and `fib`'s recursive call is the only thing in that
10078 // function which is not a fast arm. Every call therefore left this
10079 // loop via `stop()`, went through `step()`'s dispatch and
10080 // `execute_instruction`'s match over every opcode, and came back here
10081 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
10082 //
10083 // Two things make it safe to do here rather than only in the slow path:
10084 //
10085 // * the caller's `pc` is stored *before* the call, which is what
10086 // `step` does too — so when the callee returns, the caller resumes
10087 // after the call and not at it;
10088 // * `check_memory` runs, because `step` calls it once per instruction
10089 // and a call allocates a frame, its locals and its cells. Skipping
10090 // the checkpoint here would let a `--memory-limit` script overshoot
10091 // by one call per instruction.
10092 Opcode::Call
10093 | Opcode::Call0
10094 | Opcode::Call1
10095 | Opcode::Call2
10096 | Opcode::Call3 => {
10097 let argc = self.argc_operand(insn.op, insn.a);
10098 let next = pc + insn.width();
10099 {
10100 let frame = self
10101 .frames
10102 .last_mut()
10103 .expect("run_fast() is only called with a live frame");
10104 // `at` is what a stack trace reports for this frame, so a throw
10105 // inside the callee has to see the call site and not whatever
10106 // the last `stop()` left there.
10107 frame.at = insn.offset as usize;
10108 frame.pc = next;
10109 }
10110 self.check_memory()?;
10111 self.check_interrupt()?;
10112 let args = self.pop_n(argc);
10113 let callee = self.pop();
10114 // A plain call has no receiver; the callee decides what to do with
10115 // `undefined` (a sloppy function substitutes the global object).
10116 if let Some(result) =
10117 self.call_or_push(callee, Value::Undefined, args)?
10118 {
10119 // Native, host, generator, async, bound — no frame was pushed,
10120 // so this loop is still describing the right function. `pc`
10121 // is advanced by the loop tail like every other arm; only the
10122 // frame's copy had to be written here, and it already was.
10123 self.push(result);
10124 } else {
10125 // A bytecode callee: its frame is on top now, and `insns` and
10126 // `pc` both belong to the caller. Start over on the new frame.
10127 continue 'outer;
10128 }
10129 }
10130 // -- return ------------------------------------------------------
10131 Opcode::Return => {
10132 let value = self.pop();
10133 self.frame_mut().pc = pc + insn.width();
10134 return Ok(Some(value));
10135 }
10136 Opcode::ReturnUndef => {
10137 self.frame_mut().pc = pc + insn.width();
10138 return Ok(Some(Value::Undefined));
10139 }
10140 // Everything else needs the slow path.
10141 _ => return Ok(self.stop(pc)),
10142 },
10143 }
10144 pc += insn.width();
10145 }
10146 }
10147 }
10148
10149 /// Whether the top two operand-stack values are both numbers.
10150 ///
10151 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
10152 /// cannot run script, so the arm may not throw and may not change frames.
10153 fn numeric_pair(&self) -> bool {
10154 is_number(&self.peek(0)) && is_number(&self.peek(1))
10155 }
10156
10157 /// `a[i]` for a dense array and an integer index, without the string round trip.
10158 ///
10159 /// The slow path answers this by turning `i` into a string (`propkey` →
10160 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
10161 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
10162 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
10163 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
10164 /// without even the cheap `Int` formatting.
10165 ///
10166 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
10167 /// unambiguously the one the slow path would give:
10168 ///
10169 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
10170 /// `2^32-1` is the length, not an index),
10171 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
10172 /// typed array or an ordinary object, all of which have their own rules),
10173 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
10174 /// starts walking the prototype chain, and `a[i]` on a hole must find
10175 /// `Array.prototype[i]` if it exists rather than `undefined`.
10176 ///
10177 /// The last condition is the one that makes this safe rather than merely fast: an own
10178 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
10179 /// `get_var` answered from the global-variable cache, or `None`.
10180 ///
10181 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10182 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10183 /// records nothing — the slow arm is about to walk the chain and record it.
10184 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10185 let frame = self.frame();
10186 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10187 // "Lexical" is presence in the realm's table, not the closure var's flag: a
10188 // `GlobalRef` forwarded through a nested function has its flags cleared.
10189 if self.realm.globals.contains_key(name) {
10190 return None;
10191 }
10192 if !self.scopes_are_plain() {
10193 return None;
10194 }
10195 let object = &self.realm.global;
10196 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10197 let cached = self.global_cache[site].as_ref()?;
10198 if !object.upgrades_to(&cached.object) {
10199 return None;
10200 }
10201 object.data_property_at(cached.index, name)
10202 }
10203
10204 /// `o.x` answered entirely from the inline cache, or `None`.
10205 ///
10206 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
10207 /// about to do exactly that and recording it twice would rebuild the chain for every
10208 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
10209 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
10210 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
10211 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
10212 // an object receiver is a reference-count bump that the answer never needs.
10213 let frame = self.frame();
10214 let object = frame.stack.last()?;
10215 let Value::Object(target) = object else {
10216 return None;
10217 };
10218 // A proxy traps the lookup, so no cache entry ever describes it.
10219 if target.proxy_state().is_some() {
10220 return None;
10221 }
10222 let key = frame.code.atom_keys.get(atom)?;
10223 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
10224 if cached.key != *key {
10225 return None;
10226 }
10227 Self::cached_hit(target, cached)
10228 }
10229
10230 fn fast_array_get(&self) -> Option<Value> {
10231 let Value::Int(index) = self.peek(0) else {
10232 return None;
10233 };
10234 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
10235 // set for an `i32`.
10236 if index < 0 {
10237 return None;
10238 }
10239 let Value::Object(object) = self.peek(1) else {
10240 return None;
10241 };
10242 match object.array_get(index as usize) {
10243 Some(value) if !matches!(value, Value::Hole) => Some(value),
10244 _ => None,
10245 }
10246 }
10247
10248 /// `a[i] = v` on a dense array with an integer index, as one store.
10249 ///
10250 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
10251 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
10252 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
10253 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
10254 /// reference at the time it was measured (14.7x).
10255 ///
10256 /// Every condition here is one the slow path would also have to satisfy before
10257 /// storing into the element vector:
10258 ///
10259 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
10260 /// accepts as an index;
10261 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
10262 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
10263 /// one inside a recorded descriptor, reports `false` and the caller stops.
10264 ///
10265 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
10266 /// writes the own element too once `array_set` says it did.
10267 fn fast_array_set(&mut self) -> bool {
10268 // Every test runs *before* anything is popped: a refusal has to leave the stack
10269 // exactly as the slow path expects to find it. Popping first and reporting the
10270 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
10271 // then ran the slow path with nothing to write.
10272 let Value::Int(index) = self.peek(1) else {
10273 return false;
10274 };
10275 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
10276 if index < 0 {
10277 return false;
10278 }
10279 // Only a real array: a typed array's elements live in its buffer, a string-like
10280 // object has no element vector, and `array_set` on either does nothing.
10281 let Value::Object(object) = self.peek(2) else {
10282 return false;
10283 };
10284 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
10285 return false;
10286 }
10287 // A non-extensible array reports `false` here, but the *slow* path has to decide
10288 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
10289 // that with the key and the stack still intact.
10290 if !object.is_extensible() {
10291 return false;
10292 }
10293 // Inside the logical length, so the store cannot change `length`. Combined with
10294 // extensibility above, the only growth left for `array_set` is filling a hole in
10295 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
10296 // shape this fast path exists for. A store past the length would grow the array,
10297 // and whether that is allowed is the slow path's question.
10298 if index as usize >= object.array_length().unwrap_or(0) {
10299 return false;
10300 }
10301 // Only an *own element* can take the inline store. A hole is not an own property,
10302 // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
10303 // trap or a setter decides, and where `new Array(1)` with a proxy above it must
10304 // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
10305 // the one case this path used to swallow.
10306 //
10307 // The cost is small: `array:indexed` only reads after a 64-element fill, and
10308 // `array:push` appends past the length, which this path already refused.
10309 if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
10310 {
10311 return false;
10312 }
10313 // The bound `array_set` refuses past. Checking it here keeps that arm from having
10314 // to report a failure after the operands are gone.
10315 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
10316 return false;
10317 }
10318 let value = self.pop();
10319 self.pop();
10320 self.pop();
10321 object.array_store(self.heap, index as usize, value)
10322 }
10323
10324 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
10325 fn stop(&mut self, pc: usize) -> Option<Value> {
10326 self.frame_mut().pc = pc;
10327 None
10328 }
10329
10330 fn push(&mut self, value: Value) {
10331 self.frame_mut().stack.push(value);
10332 }
10333
10334 fn pop(&mut self) -> Value {
10335 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10336 }
10337
10338 fn pop_n(&mut self, count: usize) -> Vec<Value> {
10339 let frame = self.frame_mut();
10340 let start = frame.stack.len().saturating_sub(count);
10341 frame.stack.split_off(start)
10342 }
10343
10344 fn peek(&self, back: usize) -> Value {
10345 let frame = self.frame();
10346 frame
10347 .stack
10348 .get(frame.stack.len().wrapping_sub(1 + back))
10349 .cloned()
10350 .unwrap_or(Value::Undefined)
10351 }
10352
10353 #[allow(clippy::too_many_lines)]
10354 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10355 use Opcode::*;
10356 match op {
10357 // -- constants and stack shuffling -----------------------------
10358 Nop => {}
10359 PushMinus1 => self.push(Value::Int(-1)),
10360 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10361 let value = match op {
10362 Push0 => 0,
10363 Push1 => 1,
10364 Push2 => 2,
10365 Push3 => 3,
10366 Push4 => 4,
10367 Push5 => 5,
10368 Push6 => 6,
10369 _ => 7,
10370 };
10371 self.push(Value::Int(value));
10372 }
10373 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
10374 PushBigintI32 => {
10375 // The immediate form of a `BigInt` literal; the reference has the same
10376 // split between this and a constant-pool entry.
10377 let value = crate::bigint::BigInt::from_i64(a as i64);
10378 self.push(self.bigint(value));
10379 }
10380 PushTrue => self.push(Value::Bool(true)),
10381 PushFalse => self.push(Value::Bool(false)),
10382 PushEmptyString => self.push(self.string("")),
10383 Undefined => self.push(Value::Undefined),
10384 Null => self.push(Value::Null),
10385 Object => {
10386 let proto = self.realm.object_proto.clone();
10387 self.push(Value::Object(self.new_object(Some(proto))));
10388 }
10389 PushThis => {
10390 let this = self.frame().this.clone();
10391 self.push(this);
10392 }
10393 PushConst | PushConst8 => {
10394 let value = self.constant(a as usize)?;
10395 self.push(value);
10396 }
10397 PushAtomValue => {
10398 let text = self.atom_wtf8(a as usize);
10399 self.push(self.string_wtf8(text));
10400 }
10401 Dup => {
10402 let value = self.peek(0);
10403 self.push(value);
10404 }
10405 Dup2 => {
10406 // `a b -> a b a b`
10407 let b = self.peek(0);
10408 let a = self.peek(1);
10409 self.push(a);
10410 self.push(b);
10411 }
10412 Dup3 => {
10413 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
10414 // prototype and key while reading the current value through them.
10415 let c = self.peek(0);
10416 let b = self.peek(1);
10417 let a = self.peek(2);
10418 self.push(a);
10419 self.push(b);
10420 self.push(c);
10421 }
10422 Swap => {
10423 // `a b -> b a`
10424 let bottom = self.pop();
10425 let top = self.pop();
10426 self.push(bottom);
10427 self.push(top);
10428 }
10429 Perm3 => {
10430 // `a b c -> b a c`, the reference's reordering for a spread method
10431 // call: `obj func array` becomes the `func this array` that `apply`
10432 // takes.
10433 let c = self.pop();
10434 let b = self.pop();
10435 let a = self.pop();
10436 self.push(b);
10437 self.push(a);
10438 self.push(c);
10439 }
10440 Dup1 => {
10441 let value = self.peek(1);
10442 self.push(value);
10443 }
10444 Drop => {
10445 self.pop();
10446 }
10447 Nip => {
10448 // `a b -> b`
10449 let top = self.pop();
10450 self.pop();
10451 self.push(top);
10452 }
10453 Perm4 => {
10454 // `obj prop a b -> a obj prop b`, the reference's reordering for a
10455 // postfix update of a computed element: it puts the *old* value
10456 // underneath the receiver and key so `put_array_el` can consume them
10457 // and leave the old value as the expression's result.
10458 let d = self.pop();
10459 let c = self.pop();
10460 let b = self.pop();
10461 let a = self.pop();
10462 self.push(c);
10463 self.push(a);
10464 self.push(b);
10465 self.push(d);
10466 }
10467 Insert2 => {
10468 // `obj a -> a obj a`
10469 let value = self.pop();
10470 let object = self.pop();
10471 self.push(value.clone());
10472 self.push(object);
10473 self.push(value);
10474 }
10475 Insert3 => {
10476 // `obj prop a -> a obj prop a`
10477 let value = self.pop();
10478 let key = self.pop();
10479 let object = self.pop();
10480 self.push(value.clone());
10481 self.push(object);
10482 self.push(key);
10483 self.push(value);
10484 }
10485 Insert4 => {
10486 // `this obj prop a -> a this obj prop a`
10487 //
10488 // `put_super_value` consumes all four and yields nothing, so the copy
10489 // underneath is what leaves the assignment an expression value.
10490 let value = self.pop();
10491 let key = self.pop();
10492 let object = self.pop();
10493 let receiver = self.pop();
10494 self.push(value.clone());
10495 self.push(receiver);
10496 self.push(object);
10497 self.push(key);
10498 self.push(value);
10499 }
10500 Swap2 => {
10501 // `a b c d -> c d a b`
10502 let d = self.pop();
10503 let c = self.pop();
10504 let b = self.pop();
10505 let a = self.pop();
10506 self.push(c);
10507 self.push(d);
10508 self.push(a);
10509 self.push(b);
10510 }
10511 Rot3l => {
10512 // `x a b -> a b x`
10513 let b = self.pop();
10514 let a = self.pop();
10515 let x = self.pop();
10516 self.push(a);
10517 self.push(b);
10518 self.push(x);
10519 }
10520 Rot3r => {
10521 // `a b c -> c a b`
10522 let c = self.pop();
10523 let b = self.pop();
10524 let a_value = self.pop();
10525 self.push(c);
10526 self.push(a_value);
10527 self.push(b);
10528 }
10529
10530 Rest => {
10531 // `...rest` in a parameter list: the arguments from index `a` on, as a
10532 // real array. It takes nothing off the stack — the arguments are in the
10533 // frame, not on it.
10534 let frame = self.frame();
10535 let from = a as usize;
10536 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
10537 let array = self.new_array(collected);
10538 self.push(Value::Object(array));
10539 }
10540
10541 // -- slots ------------------------------------------------------
10542 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
10543 let slot = self.slot_operand(op, a);
10544 let value = self.get_loc(slot);
10545 self.push(value);
10546 }
10547 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
10548 let slot = self.slot_operand(op, a);
10549 let value = self.pop();
10550 self.put_loc(slot, value);
10551 }
10552 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
10553 let slot = self.slot_operand(op, a);
10554 let value = self.pop();
10555 self.put_loc(slot, value.clone());
10556 self.push(value);
10557 }
10558 // The `_check` forms are the temporal dead zone: they throw when the
10559 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
10560 // *reads*, so only the two writes may pop — mishandling that quietly
10561 // consumes the value the caller pushed just before.
10562 GetLocCheck => {
10563 let slot = self.slot_operand(op, a);
10564 let value = self.get_loc(slot);
10565 if matches!(value, Value::Uninitialized) {
10566 return Err(self.dead_zone(slot, VarSlot::Loc));
10567 }
10568 self.push(value);
10569 }
10570 PutLocCheck | SetLocCheck => {
10571 let slot = self.slot_operand(op, a);
10572 let value = self.pop();
10573 if matches!(value, Value::Uninitialized) {
10574 return Err(self.dead_zone(slot, VarSlot::Loc));
10575 }
10576 // The initialiser goes through `put_loc`, not this, so any store that
10577 // reaches here is a later assignment — which a `const` refuses.
10578 if self.is_read_only(slot, VarSlot::Loc) {
10579 return Err(self.read_only(slot, VarSlot::Loc));
10580 }
10581 if op == SetLocCheck {
10582 self.put_loc(slot, value.clone());
10583 self.push(value);
10584 } else {
10585 self.put_loc(slot, value);
10586 }
10587 }
10588 PutLocCheckInit => {
10589 // The one store that *initialises* a lexical slot: `this` in a derived
10590 // constructor, which only exists after `super()` has run. A second
10591 // initialisation is the error the reference reports as
10592 // "'this' can be initialized only once".
10593 let slot = self.slot_operand(op, a);
10594 let value = self.pop();
10595 if !matches!(self.get_loc(slot), Value::Uninitialized) {
10596 return Err(Signal::Throw(self.make_error(
10597 "ReferenceError",
10598 "'this' can be initialized only once",
10599 )));
10600 }
10601 self.put_loc(slot, value);
10602 }
10603 CheckCtor => {
10604 // A class constructor may only run under `new`, which is what makes
10605 // `class A {}; A()` a TypeError.
10606 if matches!(self.frame().new_target, Value::Undefined) {
10607 return Err(Signal::Throw(self.make_error(
10608 "TypeError",
10609 "class constructors must be invoked with 'new'",
10610 )));
10611 }
10612 }
10613 InitCtor => {
10614 // The body a derived class gets when it declares no constructor:
10615 // forward every argument to the parent constructor, keeping `new.target`.
10616 if matches!(self.frame().new_target, Value::Undefined) {
10617 return Err(Signal::Throw(self.make_error(
10618 "TypeError",
10619 "class constructors must be invoked with 'new'",
10620 )));
10621 }
10622 let Some(callee) = self.current_callee() else {
10623 return Err(Signal::Throw(
10624 self.make_error("TypeError", "no constructor to inherit from"),
10625 ));
10626 };
10627 let parent = callee.proto().map_or(Value::Null, Value::Object);
10628 let new_target = self.frame().new_target.clone();
10629 let args = self.frame().passed().to_vec();
10630 let result = self.construct(parent, new_target, args)?;
10631 self.push(result);
10632 }
10633 SetLocUninitialized => {
10634 let slot = self.slot_operand(op, a);
10635 self.put_loc(slot, Value::Uninitialized);
10636 }
10637 CloseLoc => {
10638 // "Close" a binding: give it a *fresh* cell holding the current
10639 // value. Closures created before this point keep the old cell and the
10640 // ones created after see the new one, which is what makes every
10641 // iteration of `for (let i ...)` capture its own `i`, and what freezes
10642 // a block-scoped binding when the block ends.
10643 //
10644 // Clearing the slot instead (which this used to do) broke both: a
10645 // closure over a captured block variable read `undefined`, and a loop
10646 // terminated after one iteration.
10647 let slot = self.slot_operand(op, a);
10648 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
10649 if index >= 0 {
10650 let current = self.frame().cells[index as usize].get();
10651 let fresh = self.new_cell(current);
10652 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
10653 *cell = fresh;
10654 }
10655 }
10656 }
10657 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
10658 let slot = self.slot_operand(op, a);
10659 let value = self.get_arg(slot);
10660 self.push(value);
10661 }
10662 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
10663 let slot = self.slot_operand(op, a);
10664 let value = self.pop();
10665 self.put_arg(slot, value);
10666 }
10667 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
10668 let slot = self.slot_operand(op, a);
10669 let value = self.pop();
10670 self.put_arg(slot, value.clone());
10671 self.push(value);
10672 }
10673
10674 // -- closure variables ------------------------------------------
10675 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
10676 let slot = self.slot_operand(op, a);
10677 // A name a direct `eval` created shadows the binding the compiler chose.
10678 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
10679 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
10680 // and only a runtime lookup can know that.
10681 if let Some(cell) = self.eval_created_local(slot) {
10682 self.push(cell.get());
10683 return self.step();
10684 }
10685 let value = self.cell_value(slot)?;
10686 self.push(value);
10687 }
10688 GetVarRefCheck => {
10689 let slot = self.slot_operand(op, a);
10690 let value = self.cell_value(slot)?;
10691 if matches!(value, Value::Uninitialized) {
10692 return Err(self.dead_zone(slot, VarSlot::Closure));
10693 }
10694 self.push(value);
10695 }
10696 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
10697 let slot = self.slot_operand(op, a);
10698 let value = self.pop();
10699 if let Some(cell) = self.eval_created_local(slot) {
10700 cell.set(value);
10701 return self.step();
10702 }
10703 // Same rule as `PutLocCheck`: a checked store to a captured binding
10704 // refuses a `const` once its initialiser has run.
10705 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
10706 return Err(self.read_only(slot, VarSlot::Closure));
10707 }
10708 self.set_cell(slot, value)?;
10709 }
10710 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
10711 let slot = self.slot_operand(op, a);
10712 let value = self.pop();
10713 if let Some(cell) = self.eval_created_local(slot) {
10714 cell.set(value.clone());
10715 self.push(value);
10716 return self.step();
10717 }
10718 self.set_cell(slot, value.clone())?;
10719 self.push(value);
10720 }
10721
10722 // -- globals ----------------------------------------------------
10723 GetVar => {
10724 let value = self.get_global(a as usize)?;
10725 self.push(value);
10726 }
10727 GetVarUndef => {
10728 let value = self
10729 .get_global(a as usize)
10730 .or_else(|_| Ok(Value::Undefined))?;
10731 self.push(value);
10732 }
10733 DeleteVar => {
10734 // `delete name` for a name that is not a declared binding. A lexical
10735 // global lives in the reference table and cannot be deleted; anything
10736 // reachable only as a property of the global object is *implicit* —
10737 // `x = 1` with no declaration — and goes away if it is configurable,
10738 // which is what `delete` on an implicit global answers.
10739 let name = self.atom_text(a as usize);
10740 let global = self.realm.global.clone();
10741 let deleted = if self.realm.globals.contains_key(&name) {
10742 false
10743 } else if global.own_property(&name).is_some() {
10744 self.delete_property(&global, &name)?
10745 } else {
10746 true
10747 };
10748 self.push(Value::Bool(deleted));
10749 }
10750 PutVar => {
10751 let value = self.pop();
10752 self.put_global(a as usize, value)?;
10753 }
10754 PutVarInit => {
10755 let slot = a as usize;
10756 let value = self.pop();
10757 self.init_global(slot, value)?;
10758 }
10759
10760 // -- arithmetic -------------------------------------------------
10761 Add => self.binary_add()?,
10762 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
10763 let raw_right = self.pop();
10764 let raw_left = self.pop();
10765 // BigInt arithmetic is a separate path, and not only for the type of the
10766 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
10767 // rather than a silent conversion.
10768 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
10769 let left = self.primitive_of(raw_left)?;
10770 let right = self.primitive_of(raw_right)?;
10771 let value = self.bigint_arithmetic(op, left, right)?;
10772 self.push(value);
10773 } else {
10774 let right = self.numeric(raw_right)?;
10775 let left = self.numeric(raw_left)?;
10776 self.push(arithmetic(op, left, right)?);
10777 }
10778 }
10779 Neg => {
10780 let raw = self.pop();
10781 match raw {
10782 // A bigint negates exactly, however wide it is.
10783 Value::BigInt(big) => {
10784 let negated = big.negate();
10785 self.push(self.bigint(negated));
10786 }
10787 other => {
10788 let value = self.numeric(other)?;
10789 self.push(negate(value));
10790 }
10791 }
10792 }
10793 Plus => {
10794 let value = self.pop();
10795 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
10796 // unary plus is defined to produce a *number*, which a bigint cannot
10797 // become without loss. It used to fall through to `NaN`.
10798 if matches!(value, Value::BigInt(_)) {
10799 return Err(self.type_error("cannot convert bigint to number"));
10800 }
10801 let numeric = self.numeric_of(value)?;
10802 self.push(numeric);
10803 }
10804 Inc => {
10805 let raw = self.pop();
10806 let (_, updated) = self.advance_numeric(raw, true)?;
10807 self.push(updated);
10808 }
10809 Dec => {
10810 let raw = self.pop();
10811 let (_, updated) = self.advance_numeric(raw, false)?;
10812 self.push(updated);
10813 }
10814 PostInc | PostDec => {
10815 // `x -> x x+1`: the *new* value ends up on top, so the store the
10816 // compiler emits right after (`put_var`) writes the incremented
10817 // one, while the old value stays underneath for the expression's
10818 // own result. Getting this backwards makes `i++` a no-op, which
10819 // turns `while (i < 3)` into an infinite loop.
10820 let raw = self.pop();
10821 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
10822 self.push(old);
10823 self.push(updated);
10824 }
10825 Not => {
10826 let raw = self.pop();
10827 match raw {
10828 // `~x` on a bigint is `-x - 1`, exact at any width.
10829 Value::BigInt(big) => {
10830 let inverted = big.bitnot();
10831 self.push(self.bigint(inverted));
10832 }
10833 other => {
10834 let value = self.numeric(other)?;
10835 self.push(Value::Int(!value.to_int32()));
10836 }
10837 }
10838 }
10839 Lnot => {
10840 let value = self.pop();
10841 self.push(Value::Bool(!value.to_boolean()));
10842 }
10843
10844 // -- comparison -------------------------------------------------
10845 Lt | Lte | Gt | Gte => {
10846 let right = self.pop();
10847 let left = self.pop();
10848 let answer = self.relational(op, left, right)?;
10849 self.push(answer);
10850 }
10851 Eq | Neq => {
10852 let right = self.pop();
10853 let left = self.pop();
10854 let equal = self.abstract_equals(left, right)?;
10855 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
10856 }
10857 StrictEq => {
10858 let right = self.pop();
10859 let left = self.pop();
10860 self.push(Value::Bool(left.strict_equals(&right)));
10861 }
10862 StrictNeq => {
10863 let right = self.pop();
10864 let left = self.pop();
10865 self.push(Value::Bool(!left.strict_equals(&right)));
10866 }
10867 IsUndefined => {
10868 // `=== undefined`, which is what a destructuring default tests. It is
10869 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
10870 let value = self.pop();
10871 self.push(Value::Bool(matches!(value, Value::Undefined)));
10872 }
10873 IsUndefinedOrNull => {
10874 let value = self.pop();
10875 self.push(Value::Bool(value.is_nullish()));
10876 }
10877 Typeof => {
10878 let value = self.pop();
10879 self.push(self.string(value.type_of()));
10880 }
10881 ToObject => {
10882 // A destructuring *object* pattern starts here, which is why
10883 // `var {} = null` throws. Only `undefined` and `null` are refused; a
10884 // primitive is boxed.
10885 let value = self.pop();
10886 let object = self.object_from(&value)?;
10887 self.push(Value::Object(object));
10888 }
10889 Instanceof => {
10890 let constructor = self.pop();
10891 let object = self.pop();
10892 let answer = self.instance_of(&object, &constructor)?;
10893 self.push(Value::Bool(answer));
10894 }
10895 In => {
10896 let object = self.pop();
10897 let key = self.pop();
10898 let answer = self.has_property(&key, &object)?;
10899 self.push(Value::Bool(answer));
10900 }
10901
10902 // -- control flow -----------------------------------------------
10903 Goto | Goto8 | Goto16 => {
10904 self.frame_mut().pc = a as usize;
10905 }
10906 IfTrue | IfTrue8 => {
10907 let value = self.pop();
10908 if value.to_boolean() {
10909 self.frame_mut().pc = a as usize;
10910 }
10911 }
10912 IfFalse | IfFalse8 => {
10913 let value = self.pop();
10914 if !value.to_boolean() {
10915 self.frame_mut().pc = a as usize;
10916 }
10917 }
10918 Catch => {
10919 // Pushes the handler target onto the value stack; `unwind` finds it.
10920 self.push(Value::CatchOffset(a));
10921 }
10922 Gosub => {
10923 self.push(Value::ReturnAddress(next as u32));
10924 self.frame_mut().pc = a as usize;
10925 }
10926 Ret => {
10927 let value = self.pop();
10928 match value {
10929 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
10930 _ => {
10931 return Err(Signal::Throw(
10932 self.make_error("InternalError", "invalid return address"),
10933 ));
10934 }
10935 }
10936 }
10937 NipCatch => {
10938 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
10939 // including the marker, keeping the top value.
10940 let top = self.pop();
10941 loop {
10942 match self.pop() {
10943 Value::CatchOffset(_) | Value::Undefined => break,
10944 _ => {}
10945 }
10946 if self.frame().stack.is_empty() {
10947 break;
10948 }
10949 }
10950 self.push(top);
10951 }
10952 Throw => {
10953 let value = self.pop();
10954 return Err(Signal::Throw(value));
10955 }
10956 ThrowError => {
10957 let name = self.atom_text(a as usize);
10958 let (class, message) = match b {
10959 0 => ("TypeError", format!("'{name}' is read-only")),
10960 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
10961 2 => ("ReferenceError", format!("'{name}' is not initialized")),
10962 // `delete super.x` is a syntax-level mistake the reference reports
10963 // with this wording, not a property-access failure.
10964 3 => (
10965 "ReferenceError",
10966 "unsupported reference to 'super'".to_string(),
10967 ),
10968 4 => (
10969 "TypeError",
10970 "iterator does not have a throw method".to_string(),
10971 ),
10972 5 => (
10973 "ReferenceError",
10974 "invalid assignment left-hand side".to_string(),
10975 ),
10976 _ => ("TypeError", format!("invalid operation on '{name}'")),
10977 };
10978 return Err(Signal::Throw(self.make_error(class, &message)));
10979 }
10980 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
10981 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
10982 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
10983 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
10984 Await => return Ok(Step::Suspend(SuspendKind::Await)),
10985 ReturnAsync => {
10986 // The reference's `return_async` returns `undefined` and lets the resume
10987 // machinery pick the real value off `sp[-1]`, which is how it tells a
10988 // completion from a suspension. Carrying the value explicitly says the
10989 // same thing without the implicit stack slot.
10990 let value = self.pop();
10991 return Ok(Step::Return(value));
10992 }
10993 Return => {
10994 let value = self.pop();
10995 return Ok(Step::Return(value));
10996 }
10997 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
10998
10999 // -- calls ------------------------------------------------------
11000 Call | Call0 | Call1 | Call2 | Call3 => {
11001 let argc = self.argc_operand(op, a);
11002 let args = self.pop_n(argc);
11003 let callee = self.pop();
11004 // A plain call has no receiver; the callee decides what to do with
11005 // `undefined` (a sloppy function substitutes the global object).
11006 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
11007 self.push(result);
11008 }
11009 }
11010 CallConstructor => {
11011 // `constructor this_obj args… -> object`. The duplicated
11012 // constructor is `new.target`; this milestone does not expose it,
11013 // so the extra copy is simply consumed here.
11014 let argc = a as usize;
11015 let args = self.pop_n(argc);
11016 let new_target = self.pop();
11017 let callee = self.pop();
11018 let result = self.construct(callee, new_target, args)?;
11019 self.push(result);
11020 }
11021 CallMethod => {
11022 let argc = a as usize;
11023 let args = self.pop_n(argc);
11024 let callee = self.pop();
11025 let this = self.pop();
11026 if let Some(result) = self.call_or_push(callee, this, args)? {
11027 self.push(result);
11028 }
11029 }
11030 Apply => {
11031 // `func this array -> result`, the spread-call form: the compiler
11032 // builds one array of arguments, and all that is left here is to
11033 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
11034 let array = self.pop();
11035 let this = self.pop();
11036 let callee = self.pop();
11037 let args = self.array_like_to_args(&array)?;
11038 if a & 1 != 0 {
11039 let result = self.construct(callee, this, args)?;
11040 self.push(result);
11041 } else if let Some(result) = self.call_or_push(callee, this, args)? {
11042 self.push(result);
11043 }
11044 }
11045 TailCall | TailCallMethod => {
11046 // `tail_call` is `call` whose result is returned immediately — the
11047 // reference jumps straight to `done` instead of storing the value and
11048 // running on. The callee still gets its own frame, so deep tail
11049 // recursion hits the stack limit exactly like plain recursion does;
11050 // marking this frame lets the return path unwind without needing
11051 // instructions after the call.
11052 let argc = if op == TailCallMethod {
11053 a as usize
11054 } else {
11055 self.argc_operand(op, a)
11056 };
11057 let args = self.pop_n(argc);
11058 let callee = self.pop();
11059 let this = if op == TailCallMethod {
11060 self.pop()
11061 } else {
11062 Value::Undefined
11063 };
11064 if let Value::Object(function) = &callee
11065 && let Some((code, env)) = bytecode_of(function)
11066 {
11067 // A generator or async body is not run here at all: calling it only
11068 // *creates* the generator/coroutine, so it must not inherit this
11069 // frame. Doing so made `function f(){ return g() }` push `g`'s body
11070 // onto `f`'s frame, and the first `yield`/`await` then reported
11071 // "a generator body ran as an ordinary call".
11072 if code.code.kind.is_generator() || code.code.kind.is_async() {
11073 let value = self.call_value(callee, this, args)?;
11074 return Ok(Step::Return(value));
11075 }
11076 self.frame_mut().tail = true;
11077 self.push_frame(code, env, this, args, callee)?;
11078 return Ok(Step::Continue);
11079 }
11080 // A native callee has no frame to reuse, so its value is simply
11081 // returned.
11082 let value = self.call_value(callee, this, args)?;
11083 return Ok(Step::Return(value));
11084 }
11085
11086 // -- objects ----------------------------------------------------
11087 SpecialObject => {
11088 let value = self.special_object(a)?;
11089 self.push(value);
11090 }
11091 PrivateSymbol => {
11092 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
11093 // symbol each time it is evaluated, which is why the compiler evaluates it
11094 // once (at class definition) and stores it in a class-scope binding.
11095 let name = self.atom_text(a as usize);
11096 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
11097 self.push(Value::Symbol(symbol));
11098 }
11099 GetPrivateField => {
11100 // `obj symbol -> value`. A missing private field is a TypeError, which is what
11101 // makes `#x` inaccessible on any object not built by this class.
11102 let symbol = self.pop();
11103 let object = self.pop();
11104 let value = self.read_private_field(&object, &symbol)?;
11105 self.push(value);
11106 }
11107 PutPrivateField => {
11108 // `obj value symbol ->`, and the store is a plain assignment to a property the
11109 // class already created, so there is no setter to consult.
11110 let symbol = self.pop();
11111 let value = self.pop();
11112 let object = self.pop();
11113 self.write_private_field(&object, &symbol, value)?;
11114 }
11115 DefinePrivateField => {
11116 // `obj symbol value -> obj`: a field initialiser creates the property, and
11117 // redefining one is a TypeError ("already exists").
11118 let value = self.pop();
11119 let symbol = self.pop();
11120 let object = self.pop();
11121 self.define_private_field(&object, &symbol, value)?;
11122 self.push(object);
11123 }
11124 PrivateIn => {
11125 // `obj key -> bool`: `#x in o`. The second operand decides which question is
11126 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
11127 // is a field, so this is an own-property test; a *function* is a method or
11128 // accessor, so this is a brand check.
11129 let key = self.pop();
11130 let object = self.pop();
11131 let Some(target) = object.as_object() else {
11132 return Err(Signal::Throw(
11133 self.make_error("TypeError", "invalid 'in' operand"),
11134 ));
11135 };
11136 let present = match &key {
11137 Value::Object(_) => self.check_brand(target, &key)?,
11138 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
11139 };
11140 self.push(Value::Bool(present));
11141 }
11142 AddBrand => {
11143 // `obj home ->`: create the class brand on `home` if it has none, then give
11144 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
11145 // class definition: only the prototype's copy of the symbol is wanted.
11146 let home = self.pop();
11147 let object = self.pop();
11148 self.add_brand(&object, &home)?;
11149 }
11150 CheckBrand => {
11151 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
11152 // Both stay, because the caller needs them — `nip` halves a read into its
11153 // value and `call_method` uses the pair as receiver and callee.
11154 let function = self.peek(0);
11155 let object = self.peek(1);
11156 let Some(target) = object.as_object() else {
11157 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11158 };
11159 if !self.check_brand(target, &function)? {
11160 return Err(Signal::Throw(
11161 self.make_error("TypeError", "invalid brand on object"),
11162 ));
11163 }
11164 }
11165 GetLength => {
11166 // `get_length` is the `.length` read; an array and a string answer
11167 // from their own length, anything else from the property.
11168 let target = self.pop();
11169 let value = match &target {
11170 Value::Object(object) => match object.array_length() {
11171 Some(length) => crate::object::length_value(length),
11172 None => self.read_field(&target, "length")?,
11173 },
11174 Value::String(text) => Value::Int(text.utf16_len() as i32),
11175 _ => self.read_field(&target, "length")?,
11176 };
11177 self.push(value);
11178 }
11179 GetField | GetField2 => {
11180 let object = self.pop();
11181 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
11182 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
11183 // just below is what lets the borrow outlive the `&mut self` the lookup
11184 // needs — one refcount bump instead of a key clone plus its drop, on the
11185 // hottest property path there is: every `o.x` and every `o.m()` receiver.
11186 let code = self.frame().code.clone();
11187 let key = &code.atom_keys[a as usize];
11188 let value = self.read_field_cached(&object, key, next)?;
11189 if op == GetField2 {
11190 self.push(object);
11191 }
11192 self.push(value);
11193 }
11194 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
11195 let key = self.pop();
11196 let object = self.pop();
11197 let key = self.propkey(&key)?;
11198 let value = self.read_field_key(&object, &key)?;
11199 if matches!(op, GetArrayEl2 | GetArrayEl3) {
11200 self.push(object);
11201 }
11202 if op == GetArrayEl3 {
11203 // The key goes back in its *value* form, which the compiler stores
11204 // into the target of a destructuring assignment.
11205 self.push(match &key {
11206 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11207 PropertyKey::String(text) => self.string_wtf8(text.clone()),
11208 });
11209 }
11210 self.push(value);
11211 }
11212 PutField => {
11213 let value = self.pop();
11214 let object = self.pop();
11215 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
11216 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
11217 // only reads. `this.value = …` is the write half of the hottest loop in
11218 // `property:method-call`, and `own_property_key` was 4.8% of the case.
11219 let code = self.frame().code.clone();
11220 let key = &code.atom_keys[a as usize];
11221 self.write_field_key(&object, key, value)?;
11222 }
11223 PutArrayEl => {
11224 let value = self.pop();
11225 let key = self.pop();
11226 let object = self.pop();
11227 let key = self.propkey(&key)?;
11228 self.write_field_key(&object, &key, value)?;
11229 }
11230 DefineField => {
11231 let value = self.pop();
11232 let object = self.pop();
11233 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
11234 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
11235 // three U+FFFD — a property under a different name from the one
11236 // `o["\uD800"]` reads.
11237 let code = self.frame().code.clone();
11238 let key = code.atom_keys[a as usize].clone();
11239 // No naming here. `{m: function(){}}` is named by the *compiler*, which
11240 // emits `set_name` — and only where `NamedEvaluation` applies, so
11241 // `{m: (0, function(){})}` stays anonymous. Naming every function that
11242 // reaches a property definition got that case wrong, and the compiler is
11243 // the only place that can tell the two apart.
11244 if let Some(target) = object.as_object() {
11245 // Only an *array* stores into the element vector. A numeric key
11246 // on an ordinary object is an ordinary property, which is what
11247 // makes `{1: 'a'}` iterate as a key rather than disappear.
11248 let stored = target.is_array()
11249 && key.as_str().and_then(array_index).is_some_and(|index| {
11250 target.array_set(self.heap, index as usize, value.clone())
11251 });
11252 if !stored {
11253 target.define_data_key(&key, value);
11254 }
11255 }
11256 self.push(object);
11257 }
11258 DefineArrayEl => {
11259 // `obj key value -> obj key`. The *value* form of the key is what goes
11260 // back on the stack — the compiler stores it into the pattern's binding —
11261 // so the symbol is not stringified on the way through.
11262 let value = self.pop();
11263 let key_value = self.pop();
11264 let object = self.peek(0);
11265 let key = self.propkey(&key_value)?;
11266 self.write_field_key(&object, &key, value)?;
11267 self.push(key_value);
11268 }
11269 SetHomeObject => {
11270 // `obj func -> obj func`: records the object a method was defined on so
11271 // `super` inside it resolves against that object's prototype.
11272 let function = self.peek(0);
11273 let home = self.peek(1);
11274 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
11275 function.set_home_object(Some(home.clone()));
11276 }
11277 }
11278 Regexp => {
11279 // `pattern flags -> regexp`. A literal compiles here rather than through the
11280 // constructor, which is both what the reference's dedicated opcode is for
11281 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
11282 let flags = self.pop();
11283 let pattern = self.pop();
11284 let pattern = self.to_js_string(&pattern)?;
11285 let flags = self.to_js_string(&flags)?;
11286 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
11287 self.push(Value::Object(object));
11288 }
11289 UsingDisposeInit => {
11290 // The error state a disposal accumulates into. Uninitialised means "no
11291 // failure yet"; anything else is the exception being propagated.
11292 self.push(Value::Uninitialized);
11293 }
11294 UsingCheck => {
11295 // `value -> value, method`: validate and snapshot the disposer now, so a
11296 // later change to `Symbol.dispose` cannot change what gets called, and so a
11297 // value that is not disposable fails before the body runs.
11298 let value = self.pop();
11299 let method = self.using_method_for(&value, a as u8 == 1)?;
11300 self.push(value);
11301 self.push(method);
11302 }
11303 UsingDispose => {
11304 // `error_state -> error_state'`: dispose the variable at `slot` — its value
11305 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
11306 // the pending error.
11307 let slot = self.slot_operand(op, a);
11308 let error_state = self.pop();
11309 let merged = self.using_dispose_once(slot, error_state)?;
11310 self.push(merged);
11311 }
11312 UsingDisposeMerge => {
11313 let new_error = self.pop();
11314 let error_state = self.pop();
11315 let merged = self.merge_dispose_error(new_error, error_state);
11316 self.push(merged);
11317 }
11318 UsingDisposeEnd => {
11319 // A disposal that failed replaces the block's normal completion, so the
11320 // error state becomes a real throw here rather than at the call site.
11321 let error_state = self.pop();
11322 if !matches!(error_state, Value::Uninitialized) {
11323 return Err(Signal::Throw(error_state));
11324 }
11325 }
11326 UsingDisposeAsync => {
11327 // `await using` needs a promise to await and this runtime has no
11328 // `Promise` builtin, so the disposer is called synchronously and its result
11329 // discarded. That is correct for a disposer that returns nothing and is
11330 // reported as a gap rather than silently skipped.
11331 let slot = self.slot_operand(op, a);
11332 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
11333 self.push(error_state);
11334 }
11335 GetSuper => {
11336 // `obj -> obj's prototype`: the starting point of a `super` lookup.
11337 let object = self.pop();
11338 let proto = match &object {
11339 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
11340 _ => Value::Null,
11341 };
11342 self.push(proto);
11343 }
11344 GetSuperValue => {
11345 // `receiver proto key -> value`, searching from `proto` but reporting to
11346 // `receiver`, which is what `super.g` must do for a getter to see `this`.
11347 //
11348 // Three values in, one out: the receiver is *consumed*, not left under the
11349 // result. Leaving it there was invisible for `super.x` in `return` or
11350 // statement position (the result is what gets popped) and corrupted the
11351 // frame everywhere else — `print(super.x)` left the class where the call
11352 // opcode looks for the receiver and called the class itself.
11353 let key = self.pop();
11354 let proto = self.pop();
11355 let receiver = self.pop();
11356 let value = self.super_read(&receiver, &proto, &key)?;
11357 self.push(value);
11358 }
11359 PutSuperValue => {
11360 // `receiver proto key value ->`: a store that starts at `proto` but
11361 // assigns to `receiver`.
11362 let value = self.pop();
11363 let key = self.pop();
11364 let proto = self.pop();
11365 let receiver = self.pop();
11366 self.super_write(&receiver, &proto, &key, value)?;
11367 }
11368 DefineClass => {
11369 // `parent ctor -> ctor proto`: the constructor becomes the class and a
11370 // fresh prototype object lands on top for the methods to go on.
11371 let name = self.atom_text(a as usize);
11372 let (ctor, proto) = self.define_class(&name, b)?;
11373 self.push(ctor);
11374 self.push(Value::Object(proto));
11375 }
11376 DefineClassComputed => {
11377 // `parent ctor key -> ctor proto key`: the computed name stays put so
11378 // `define_field`-style consumers can still read it.
11379 let key = self.pop();
11380 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11381 let (ctor, proto) = self.define_class(&name, b)?;
11382 self.push(ctor);
11383 self.push(Value::Object(proto));
11384 self.push(key);
11385 }
11386 DefineMethod => {
11387 let function = self.pop();
11388 let object = self.pop();
11389 // The exact key, like `define_field`: a quoted method key may hold an
11390 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
11391 // that `o["\uD800"]` finds.
11392 let code = self.frame().code.clone();
11393 let key = code.atom_keys[a as usize].clone();
11394 // A method's `[[HomeObject]]` is the object it was defined on, which is
11395 // what `super` inside it resolves against.
11396 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11397 function.set_home_object(Some(object.clone()));
11398 }
11399 if let Some(text) = key.as_wtf8() {
11400 self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
11401 } else {
11402 self.set_function_name(
11403 &function,
11404 &key_with_accessor_prefix(&key.to_string(), b),
11405 );
11406 }
11407 if let Some(array) = object.as_object() {
11408 define_function_property(array, &key, function, b);
11409 }
11410 self.push(object);
11411 }
11412 DefineMethodComputed => {
11413 let function = self.pop();
11414 let key = self.pop();
11415 let object = self.pop();
11416 let key = self.propkey(&key)?;
11417 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
11418 // the name: `super` inside a computed method resolves through it. Without
11419 // this, `class B extends A { [k]() { return super.m() } }` read the
11420 // home object as null and threw.
11421 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11422 function.set_home_object(Some(object.clone()));
11423 }
11424 match key.as_wtf8() {
11425 Some(text) => {
11426 let name = accessor_prefixed(text, a);
11427 self.set_function_name_wtf8(&function, &name);
11428 }
11429 None => self.set_function_name(
11430 &function,
11431 &key_with_accessor_prefix(&key.to_string(), a),
11432 ),
11433 }
11434 if let Some(array) = object.as_object() {
11435 define_function_property(array, &key, function, a);
11436 }
11437 self.push(object);
11438 }
11439 SetProto => {
11440 let proto = self.pop();
11441 let object = self.pop();
11442 if let Some(target) = object.as_object() {
11443 target.set_proto(proto.as_object().cloned());
11444 }
11445 self.push(object);
11446 }
11447 CopyDataProperties => {
11448 let exclusion = self.pop();
11449 let source = self.pop();
11450 let target = self.peek(0);
11451 self.copy_properties(&target, &source, &exclusion)?;
11452 self.push(source);
11453 self.push(exclusion);
11454 }
11455 ToPropkey => {
11456 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
11457 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
11458 // ordinary `"Symbol(b)"` property.
11459 let value = self.pop();
11460 let key = match self.propkey(&value)? {
11461 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
11462 PropertyKey::String(text) => self.string_wtf8(text),
11463 };
11464 self.push(key);
11465 }
11466 SetName => {
11467 let function = self.peek(0);
11468 let name = self.atom_wtf8(a as usize);
11469 self.set_function_name_wtf8(&function, &name);
11470 }
11471 SetNameComputed => {
11472 let key = self.peek(1);
11473 let function = self.peek(0);
11474 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11475 self.set_function_name(&function, &name);
11476 }
11477
11478 // -- arrays -----------------------------------------------------
11479 ArrayFrom => {
11480 let count = a as usize;
11481 let elements = self.pop_n(count);
11482 let array = self.new_array(elements);
11483 self.push(Value::Object(array));
11484 }
11485 Append => {
11486 // `array index iterable -> array new_index`
11487 let iterable = self.pop();
11488 self.pop();
11489 let array = self.peek(0);
11490 let added = self.append_enumerate(&array, &iterable)?;
11491 self.push(Value::Int(added));
11492 }
11493
11494 // -- iteration --------------------------------------------------
11495 ForInStart => {
11496 let value = self.pop();
11497 let record = self.for_in_record(&value)?;
11498 self.push(Value::Object(record));
11499 }
11500 ForInNext => {
11501 // `record -> record key done`. The flag is *done*, not "found":
11502 // the compiler tests it with `if_false` to jump back into the body,
11503 // so reporting `true` while keys remain would end the loop at once.
11504 let record = self.peek(0);
11505 match self.for_in_advance(&record)? {
11506 Some(key) => {
11507 let text = self.string(key);
11508 self.push(text);
11509 self.push(Value::Bool(false));
11510 }
11511 None => {
11512 self.push(Value::Undefined);
11513 self.push(Value::Bool(true));
11514 }
11515 }
11516 }
11517 ForOfStart => {
11518 let value = self.pop();
11519 let iterator = self.get_iterator(&value)?;
11520 self.push(iterator.object);
11521 self.push(iterator.next);
11522 self.push(Value::CatchOffset(0));
11523 }
11524 ForOfNext => {
11525 // `iter next catch_offset -> iter next catch_offset value done`.
11526 //
11527 // The operand is how many values sit *above* the iterator triple: a
11528 // destructuring rest element keeps its target array and running index
11529 // there while draining the iterator, so the triple is not at the top.
11530 let extra = a as usize;
11531 let iterator_slot = 2 + extra;
11532 // An exhausted iterator is replaced by `undefined` (see below), so a
11533 // second step must not call `next` again — `Array.from` and a
11534 // destructuring pattern both keep stepping past the end.
11535 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
11536 (Value::Undefined, true)
11537 } else {
11538 let iterator = Iterator {
11539 object: self.peek(iterator_slot),
11540 next: self.peek(1 + extra),
11541 };
11542 self.iterator_step(&iterator)?
11543 };
11544 if done {
11545 // The result's `value` is meaningless once the iterator is done:
11546 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
11547 // rather than binding the generator's return value.
11548 let top = self.frame().stack.len() - 1 - iterator_slot;
11549 self.frame_mut().stack[top] = Value::Undefined;
11550 self.push(Value::Undefined);
11551 self.push(Value::Bool(true));
11552 } else {
11553 self.push(value);
11554 self.push(Value::Bool(false));
11555 }
11556 }
11557 IteratorNext => {
11558 // `iter next catch val -> iter next catch val'`: replace the argument with
11559 // the result of `next(val)`. The triple below stays put, which is why the
11560 // three instructions of the `yield*` loop all address the stack the same way.
11561 let value = self.pop();
11562 let object = self.peek(2);
11563 let next = self.peek(1);
11564 let result = self.call_value(next, object, vec![value])?;
11565 self.push(result);
11566 }
11567 IteratorCall => {
11568 // `iter next catch val -> iter next catch val' flag`.
11569 //
11570 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
11571 // The flag is `true` when the method was missing, which is how the
11572 // caller learns that the inner iterator cannot take part in the
11573 // unwinding.
11574 let value = self.pop();
11575 let object = self.peek(2);
11576 let key = if a & 1 != 0 { "throw" } else { "return" };
11577 let method = self.read_field(&object, key)?;
11578 if matches!(method, Value::Undefined | Value::Null) {
11579 self.push(value);
11580 self.push(Value::Bool(true));
11581 } else {
11582 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
11583 let result = self.call_value(method, object, argument)?;
11584 self.push(result);
11585 self.push(Value::Bool(false));
11586 }
11587 }
11588 IteratorCheckObject => {
11589 if !matches!(self.peek(0), Value::Object(_)) {
11590 return Err(Signal::Throw(
11591 self.make_error("TypeError", "iterator must return an object"),
11592 ));
11593 }
11594 }
11595 IteratorClose => {
11596 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
11597 // calling the iterator's `return` so it can release whatever it holds.
11598 //
11599 // The catch offset goes first, so an exception from `return` is not caught
11600 // by the loop being abandoned. This used to pop the three operands and call
11601 // nothing at all, which made `break` out of a `for of` invisible to an
11602 // iterator with a `return` method.
11603 self.pop();
11604 self.pop();
11605 let iterator = self.pop();
11606 if !matches!(iterator, Value::Undefined) {
11607 let method = self.read_field(&iterator, "return")?;
11608 if !matches!(method, Value::Undefined | Value::Null) {
11609 let result = self.call_value(method, iterator.clone(), Vec::new())?;
11610 // §7.4.6: a `return` that answers a non-object is a TypeError.
11611 if !matches!(result, Value::Object(_)) {
11612 return Err(Signal::Throw(
11613 self.make_error("TypeError", "iterator must return an object"),
11614 ));
11615 }
11616 }
11617 }
11618 }
11619 Import => {
11620 // `import(specifier)`: the options slot is on top and is not read yet.
11621 let _options = self.pop();
11622 let specifier = self.pop();
11623 let promise = self.dynamic_import(specifier)?;
11624 self.push(promise);
11625 }
11626 ForAwaitOfStart => {
11627 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
11628 // `Symbol.iterator` fallback.
11629 let value = self.pop();
11630 let iterator = self.get_async_iterator(&value)?;
11631 self.push(iterator.object);
11632 self.push(iterator.next);
11633 self.push(Value::CatchOffset(0));
11634 }
11635 ForAwaitOfNext => {
11636 // `for await` steps the iterator and leaves the *result* wrapped in a
11637 // promise, so the `await` the compiler emits right after this can suspend
11638 // on it. Unwrapping happens in `iterator_get_value_done`.
11639 let extra = a as usize;
11640 let iterator_slot = 2 + extra;
11641 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
11642 Value::Undefined
11643 } else {
11644 let iterator = Iterator {
11645 object: self.peek(iterator_slot),
11646 next: self.peek(1 + extra),
11647 };
11648 let next = iterator.next.clone();
11649 self.call_value(next, iterator.object, Vec::new())?
11650 };
11651 let promise = self.promise_resolve_value(result)?;
11652 self.push(promise);
11653 }
11654 IteratorGetValueDone => {
11655 // `result -> value done`. A missing result object means the iterator was
11656 // already exhausted, which the loop treats as `done`.
11657 let result = self.pop();
11658 let done = match &result {
11659 Value::Object(object) => self
11660 .get_property(object, "done")?
11661 .is_some_and(|value| value.to_boolean()),
11662 _ => true,
11663 };
11664 if done {
11665 // Clear the iterator object so the `iterator_close` the loop emits on
11666 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
11667 // on normal completion, and this is where a normal completion is
11668 // recognised — the same trick `for_of_next` uses, which also replaces
11669 // the slot with `undefined`.
11670 //
11671 // The layout is fixed because only `for await` emits this opcode:
11672 // `iter next catch [result]`, so the iterator is three below the top.
11673 let depth = self.frame().stack.len();
11674 if depth >= 3 {
11675 self.frame_mut().stack[depth - 3] = Value::Undefined;
11676 }
11677 self.push(Value::Undefined);
11678 self.push(Value::Bool(true));
11679 } else {
11680 let Value::Object(object) = &result else {
11681 self.push(Value::Undefined);
11682 self.push(Value::Bool(true));
11683 return Ok(Step::Continue);
11684 };
11685 let value = self
11686 .get_property(object, "value")?
11687 .unwrap_or(Value::Undefined);
11688 self.push(value);
11689 self.push(Value::Bool(false));
11690 }
11691 }
11692
11693 Delete => {
11694 // `delete obj[key]`, where the key was just pushed. Deleting an array
11695 // index leaves a *hole* rather than closing the gap, and a
11696 // non-configurable property answers `false` and stays.
11697 let key = self.pop();
11698 let target = self.pop();
11699 let key = self.propkey(&key)?;
11700 let text_label = key.as_str().unwrap_or("").to_string();
11701 let deleted = match &target {
11702 Value::Object(object) => {
11703 let object = object.clone();
11704 self.delete_property_key(&object, &key)?
11705 }
11706 // A string's `length` and its index properties are
11707 // non-configurable, so deleting one answers `false`.
11708 Value::String(text) => {
11709 !(text_label == "length"
11710 || array_index(&text_label)
11711 .is_some_and(|index| (index as usize) < text.utf16_len()))
11712 }
11713 // "delete null.a" is a TypeError, not a no-op: the operator needs an
11714 // object to delete from, and only a *boxable* primitive has one.
11715 Value::Undefined | Value::Null => {
11716 return Err(Signal::Throw(
11717 self.make_error("TypeError", "cannot convert to object"),
11718 ));
11719 }
11720 // Any other primitive has no own properties; deleting nothing
11721 // succeeds.
11722 _ => true,
11723 };
11724 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
11725 // `TypeError` rather than a `false` result. Sloppy mode silently reports
11726 // the refusal, which is why the same statement throws here but not there.
11727 if !deleted && self.current_strict() {
11728 return Err(Signal::Throw(
11729 self.make_error("TypeError", "cannot delete property"),
11730 ));
11731 }
11732 self.push(Value::Bool(deleted));
11733 }
11734
11735 // -- exceptions and bookkeeping ---------------------------------
11736 Fclosure | Fclosure8 => {
11737 let value = self.closure(a as usize)?;
11738 self.push(value);
11739 }
11740
11741 other => {
11742 let name = other.info().name;
11743 return Err(Signal::Throw(self.make_error(
11744 "InternalError",
11745 &format!("{name} is not implemented yet"),
11746 )));
11747 }
11748 }
11749 Ok(Step::Continue)
11750 }
11751
11752 // -- operand helpers ----------------------------------------------------
11753
11754 /// The slot index an operand names, taking short forms into account.
11755 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
11756 use Opcode::*;
11757 match op {
11758 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
11759 | SetVarRef0 => 0,
11760 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
11761 | SetVarRef1 => 1,
11762 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
11763 | SetVarRef2 => 2,
11764 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
11765 | SetVarRef3 => 3,
11766 _ => a as usize,
11767 }
11768 }
11769
11770 /// The argument count of a call, taking `call0`…`call3` into account.
11771 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
11772 use Opcode::*;
11773 match op {
11774 Call0 => 0,
11775 Call1 => 1,
11776 Call2 => 2,
11777 Call3 => 3,
11778 _ => a as usize,
11779 }
11780 }
11781
11782 /// The atom's name as a property key.
11783 ///
11784 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
11785 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
11786 /// `String::clone` was a heap allocation and a copy — per property access.
11787 /// The atom at `index`, as a property key.
11788 ///
11789 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
11790 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
11791 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
11792 /// 5.3% of `property:monomorphic`.
11793 /// The atom's text, exactly — including an unpaired surrogate.
11794 ///
11795 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
11796 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
11797 /// `atom_text` below is for the other kind of use, where the atom is a key in the
11798 /// engine's own tables.
11799 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
11800 self.frame()
11801 .code
11802 .code
11803 .atoms
11804 .get(index)
11805 .map(|atom| match atom {
11806 Atom::Str(text) => text.clone(),
11807 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
11808 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
11809 Atom::Null => crate::value::Wtf8::new(String::new()),
11810 })
11811 .unwrap_or_default()
11812 }
11813
11814 fn atom_text(&self, index: usize) -> String {
11815 self.frame()
11816 .code
11817 .code
11818 .atoms
11819 .get(index)
11820 .map(|atom| match atom {
11821 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
11822 // compare it to an identifier, and a surrogate-bearing name is reachable
11823 // through `atom_wtf8` where it matters.
11824 Atom::Str(text) => text.to_string_lossy().into_owned(),
11825 Atom::Index(value) => value.to_string(),
11826 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
11827 // `throw_error`, `delete super.x`) never read it.
11828 Atom::Null => String::new(),
11829 })
11830 .unwrap_or_default()
11831 }
11832
11833 fn constant(&mut self, index: usize) -> JsResult<Value> {
11834 let constant = self.frame().code.code.cpool.get(index).cloned();
11835 Ok(match &constant {
11836 Some(Constant::Number(number)) => Value::Float(*number),
11837 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
11838 Some(Constant::BigInt { digits, radix }) => {
11839 match crate::bigint::BigInt::from_radix(digits, *radix) {
11840 Some(big) => self.bigint(big),
11841 // A literal the parser accepted is always parseable; a failure here
11842 // would be a compiler bug, so it reads as an `InternalError`.
11843 None => {
11844 return Err(Signal::Throw(
11845 self.make_error("InternalError", "unparseable bigint literal"),
11846 ));
11847 }
11848 }
11849 }
11850 Some(Constant::Function(_)) => {
11851 return Err(Signal::Throw(
11852 self.make_error("InternalError", "a bare function constant"),
11853 ));
11854 }
11855 // A tagged template's call site: a frozen array of the cooked chunks with a
11856 // frozen `raw` array beside it, which is what `String.raw` reads back.
11857 Some(Constant::Template { cooked, raw }) => {
11858 let cooked_values: Vec<Value> = cooked
11859 .iter()
11860 .map(|chunk| match chunk {
11861 Some(text) => self.string_wtf8(text.clone()),
11862 None => Value::Undefined,
11863 })
11864 .collect();
11865 let raw_values: Vec<Value> =
11866 raw.iter().map(|text| self.string(text.clone())).collect();
11867 let raw_array = self.new_array(raw_values);
11868 raw_array.set_extensible(false);
11869 let template = self.new_array(cooked_values);
11870 template.define(
11871 "raw",
11872 Property::with_attributes(Value::Object(raw_array), false, false),
11873 );
11874 template.set_extensible(false);
11875 Value::Object(template)
11876 }
11877 _ => Value::Undefined,
11878 })
11879 }
11880
11881 /// The reference cell a closure-variable slot names.
11882 ///
11883 /// Two kinds of binding share this addressing: a genuine closure variable
11884 /// (captured from an enclosing function) lives in this frame's environment,
11885 /// while a *declared global* lives in the realm so that a script, a function
11886 /// declaration and their uses all see one binding. A plain `Global` — an
11887 /// undeclared name that may be satisfied by the global object — has no cell at
11888 /// all, which is how `typeof x` still works for a name that does not exist.
11889 /// The reference cell a closure-variable slot names.
11890 ///
11891 /// The environment is resolved once, when the closure is built, and this is
11892 /// just the lookup afterwards. A *declared global* is in there too, pointing at
11893 /// the realm's cell, so a script, a hoisted function declaration and their uses
11894 /// all share one binding. A plain `Global` — a name the script never declared —
11895 /// is read and written through `get_var`/`put_var` by name instead, which is
11896 /// what lets the global object satisfy it.
11897 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
11898 self.frame().env.cells.get(slot).cloned()
11899 }
11900
11901 /// Whether `slot` refers to a global binding through the reference table.
11902 ///
11903 /// A global's cell in the closure environment only exists so the slot has
11904 /// something to point at; the binding itself lives on the global object (a `var`)
11905 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
11906 /// be routed, not performed on the placeholder.
11907 fn is_global_slot(&self, slot: usize) -> bool {
11908 self.frame()
11909 .code
11910 .code
11911 .closure_vars
11912 .get(slot)
11913 .is_some_and(|c| {
11914 // A module's declarations and imports are *not* globals: their cells are
11915 // the module environment's, filled by the host, so the placeholder routing
11916 // must not apply to them.
11917 matches!(
11918 c.closure_type,
11919 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
11920 )
11921 })
11922 }
11923
11924 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
11925 if self.is_global_slot(slot) {
11926 return self.get_global(slot);
11927 }
11928 Ok(self
11929 .var_ref_cell(slot)
11930 .map(|cell| cell.get())
11931 .unwrap_or(Value::Undefined))
11932 }
11933
11934 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
11935 // A function declaration is hoisted by storing into a global reference before
11936 // the body runs, so this path is also what puts it on the global object.
11937 if self.is_global_slot(slot) {
11938 return self.put_global(slot, value);
11939 }
11940 if let Some(cell) = self.var_ref_cell(slot) {
11941 cell.set(value);
11942 }
11943 Ok(())
11944 }
11945
11946 // -- closures -----------------------------------------------------------
11947
11948 /// Build the closure for the function constant `index`.
11949 ///
11950 /// Every entry in the child's closure table names where its binding lives in
11951 /// *this* frame: a local or argument slot that was marked captured, or a cell
11952 /// this frame is itself holding. That is how a variable three functions deep
11953 /// stays one binding.
11954 fn closure(&mut self, index: usize) -> JsResult<Value> {
11955 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
11956 else {
11957 return Err(Signal::Throw(
11958 self.make_error("InternalError", "fclosure of a non-function"),
11959 ));
11960 };
11961 let mut cells = Vec::with_capacity(function.closure_vars.len());
11962 for closure_var in &function.closure_vars {
11963 let cell = match closure_var.closure_type {
11964 ClosureType::Arg => {
11965 let slot = closure_var.var_idx as usize;
11966 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
11967 }
11968 ClosureType::Local => {
11969 let slot = closure_var.var_idx as usize;
11970 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
11971 }
11972 ClosureType::Ref | ClosureType::GlobalRef => {
11973 // A `Ref` names a cell in this frame's own closure table; a
11974 // `GlobalRef` also starts there, then resolves by name below.
11975 let slot = closure_var.var_idx as usize;
11976 if let Some(cell) = self.frame().env.cells.get(slot) {
11977 cells.push(cell.clone());
11978 continue;
11979 }
11980 -1
11981 }
11982 _ => -1,
11983 };
11984 if cell >= 0 {
11985 let cell = self.frame().cells[cell as usize].clone();
11986 cells.push(cell);
11987 continue;
11988 }
11989 // A global: the cell is created on demand and shared through the realm,
11990 // so every function sees one binding.
11991 let name = closure_var.name.clone();
11992 let cell = match self.realm.globals.get(&name) {
11993 Some(cell) => cell.clone(),
11994 None => {
11995 let cell = self.new_cell(Value::Undefined);
11996 self.realm.globals.insert(name.clone(), cell.clone());
11997 cell
11998 }
11999 };
12000 cells.push(cell);
12001 }
12002 let name = function.name.clone();
12003 // `.length` is the arity before any default or rest parameter, not the number
12004 // of slots a pattern parameter needs.
12005 let length = function.defined_args;
12006 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
12007 // function and an arrow function do not. A *method* also does not, but that is not
12008 // known here — the method is marked when the `[[HomeObject]]` is attached (see
12009 // `set_home_object`), which is the moment it becomes a method.
12010 let function_kind = function.kind;
12011 let constructible =
12012 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
12013 let code = Gc::new(self.heap, CompiledCode::new(*function));
12014 // A closure built inside an `eval` inherits the eval's view of the enclosing
12015 // bindings, so it can still read them once the eval has returned.
12016 let eval_scope = self
12017 .active_eval_scope
12018 .clone()
12019 .or_else(|| self.frame().env.eval_scope.clone());
12020 // A closure sees the variables a direct `eval` declared in the frame it was
12021 // created in — the ones declared before *and after* it, so the same object is
12022 // shared; only the phase bounds which of them are visible.
12023 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
12024 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
12025 let env = Gc::new(
12026 self.heap,
12027 ClosureEnv {
12028 cells,
12029 eval_scope,
12030 local_vars,
12031 local_phase,
12032 },
12033 );
12034 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
12035 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
12036 // the only thing that carries `Symbol.toStringTag`, so without it
12037 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
12038 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
12039 let proto = match function_kind {
12040 js_compile::bytecode::FunctionKind::AsyncGenerator => self
12041 .realm
12042 .async_generator_function_proto
12043 .clone()
12044 .or_else(|| self.realm.function_proto.clone().into()),
12045 js_compile::bytecode::FunctionKind::Generator => self
12046 .realm
12047 .generator_function_proto
12048 .clone()
12049 .or_else(|| self.realm.function_proto.clone().into()),
12050 js_compile::bytecode::FunctionKind::Async => self
12051 .realm
12052 .async_function_proto
12053 .clone()
12054 .or_else(|| self.realm.function_proto.clone().into()),
12055 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
12056 };
12057 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
12058 object.set_constructible(constructible);
12059 object.define(
12060 "length",
12061 Property::name_or_length(Value::Int(length as i32)),
12062 );
12063 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
12064 // that checks the own-property descriptor fails if the property is missing.
12065 object.define("name", Property::name_or_length(self.string(name)));
12066 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
12067 // when `[[Construct]]` is created, so an async function and an arrow function have
12068 // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
12069 // function) an own `prototype` property, which `builtin.js` checks for absence.
12070 //
12071 // A **generator** function is the exception that is not constructible: it still
12072 // gets a `prototype` field, because that object is what a generator *instance*
12073 // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
12074 // made `function* g(){}; g.prototype` `undefined` and every generator share
12075 // `%GeneratorPrototype%` as its direct prototype.
12076 if constructible {
12077 self.install_function_prototype(&object);
12078 } else if matches!(
12079 function_kind,
12080 js_compile::bytecode::FunctionKind::Generator
12081 | js_compile::bytecode::FunctionKind::AsyncGenerator
12082 ) {
12083 let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
12084 self.realm.generator_proto.clone()
12085 } else {
12086 self.realm
12087 .async_generator_proto
12088 .clone()
12089 .unwrap_or_else(|| self.realm.generator_proto.clone())
12090 };
12091 self.install_generator_prototype(&object, parent);
12092 }
12093 Ok(Value::Object(object))
12094 }
12095
12096 // -- conversions used by the operators ----------------------------------
12097
12098 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
12099 // `+x` is `ToNumber`, which for a string parses it and for an object runs
12100 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
12101 // string, which then behaves differently in every later comparison.
12102 match value {
12103 Value::Int(_) | Value::Float(_) => Ok(value),
12104 other => Ok(Value::Float(self.to_js_number(&other)?)),
12105 }
12106 }
12107
12108 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
12109 ///
12110 /// Returns the *converted* old value and the new one, because the two callers need
12111 /// different halves: `++x` yields the new value, while `x++` yields the old one and
12112 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
12113 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
12114 /// boolean.
12115 ///
12116 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
12117 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
12118 /// a bigint algorithm then ran exactly once.
12119 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
12120 if let Value::BigInt(big) = &value {
12121 let one = crate::bigint::BigInt::from_i64(1);
12122 let next = if up { big.add(&one) } else { big.sub(&one) };
12123 return Ok((value, self.bigint(next)));
12124 }
12125 let old = self.numeric(value)?;
12126 let new = if up {
12127 increment(old.clone())
12128 } else {
12129 decrement(old.clone())
12130 };
12131 Ok((old, new))
12132 }
12133
12134 fn numeric(&mut self, value: Value) -> JsResult<Value> {
12135 // `ToNumber` on an object runs `ToPrimitive` first, which is how
12136 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
12137 // heard at all. Reading the object's own tag instead (`other.to_number()`)
12138 // turned the whole operand into `NaN` and swallowed the exception.
12139 match value {
12140 Value::Int(_) | Value::Float(_) => Ok(value),
12141 other => Ok(Value::Float(self.to_js_number(&other)?)),
12142 }
12143 }
12144
12145 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
12146 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
12147 match value {
12148 Value::BigInt(big) => Ok((**big).clone()),
12149 // The reference words this the same way for every operator, so a failing
12150 // script reads identically; the operator itself adds nothing a caller can use.
12151 _ => Err(Signal::Throw(
12152 self.make_error("TypeError", "cannot convert bigint to number"),
12153 )),
12154 }
12155 }
12156
12157 /// Arithmetic where at least one operand is a `BigInt`.
12158 ///
12159 /// The two numeric types never mix, so a bigint paired with anything else is an error
12160 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
12161 /// that the relational operators handle it separately.
12162 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12163 use Opcode::*;
12164 let a = self.bigint_operand(&left)?;
12165 let b = self.bigint_operand(&right)?;
12166 let result = match op {
12167 Add => a.add(&b),
12168 Sub => a.sub(&b),
12169 Mul => a.mul(&b),
12170 Div | Mod => {
12171 let Some((quotient, remainder)) = a.div_rem(&b) else {
12172 return Err(Signal::Throw(
12173 self.make_error("RangeError", "division by zero"),
12174 ));
12175 };
12176 if op == Div { quotient } else { remainder }
12177 }
12178 Pow => {
12179 let Some(value) = a.pow(&b) else {
12180 return Err(Signal::Throw(self.make_error(
12181 "RangeError",
12182 "BigInt exponent must be non-negative and not absurdly large",
12183 )));
12184 };
12185 value
12186 }
12187 And => a.bitand(&b),
12188 Or => a.bitor(&b),
12189 Xor => a.bitxor(&b),
12190 Shl | Sar => {
12191 // A shift count is a `BigInt` here, and both directions are exact; a
12192 // negative count would be the other direction, which the spec forbids.
12193 let Some(count) = b.to_i64() else {
12194 return Err(Signal::Throw(
12195 self.make_error("RangeError", "BigInt shift count is too large"),
12196 ));
12197 };
12198 if count < 0 {
12199 return Err(Signal::Throw(self.make_error(
12200 "RangeError",
12201 "BigInt shift count must be non-negative",
12202 )));
12203 }
12204 if op == Shl {
12205 a.shl(count as u64)
12206 } else {
12207 a.shr(count as u64)
12208 }
12209 }
12210 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
12211 _ => {
12212 return Err(Signal::Throw(self.make_error(
12213 "TypeError",
12214 "BigInts have no unsigned right shift, use >> instead",
12215 )));
12216 }
12217 };
12218 Ok(self.bigint(result))
12219 }
12220
12221 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
12222 ///
12223 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
12224 /// is on the mathematical values, and nothing is rounded first.
12225 /// `<`, `<=`, `>`, `>=`.
12226 ///
12227 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
12228 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
12229 /// It is a `?`-returning function for exactly that reason: an object operand can run
12230 /// script, and script can throw. The old version compared `to_number` of the raw
12231 /// values, which answered `false` for every object instead of calling `valueOf` —
12232 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
12233 /// never ran.
12234 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12235 // The hot arm first: `i < n` with both sides already integers. No conversion, no
12236 // call, nothing that can throw.
12237 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12238 let ordering = Some(left.cmp(right));
12239 return Ok(ordering_answer(op, ordering));
12240 }
12241 // Anything that can run script has to be converted first, in this order.
12242 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
12243 {
12244 (
12245 self.to_primitive(left, Hint::Number)?,
12246 self.to_primitive(right, Hint::Number)?,
12247 )
12248 } else {
12249 (left, right)
12250 };
12251 let ordering = match (&left, &right) {
12252 // The loop condition `i < n` is integer against integer, and it runs once
12253 // per iteration of every loop in every program. Without this arm it took the
12254 // `to_number` path twice, which is a `match` plus a conversion each.
12255 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
12256 (Value::String(a), Value::String(b)) => {
12257 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
12258 }
12259 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
12260 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
12261 // is true even though `2.5` has no bigint form.
12262 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
12263 let b = other.to_number();
12264 if b.is_nan() {
12265 None
12266 } else {
12267 compare_bigint_and_f64(a, b)
12268 }
12269 }
12270 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
12271 let a = other.to_number();
12272 if a.is_nan() {
12273 None
12274 } else {
12275 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
12276 }
12277 }
12278 _ => left.to_number().partial_cmp(&right.to_number()),
12279 };
12280 Ok(ordering_answer(op, ordering))
12281 }
12282
12283 fn binary_add(&mut self) -> JsResult<()> {
12284 let right = self.pop();
12285 let left = self.pop();
12286 // Two integers add without any of the machinery below: no `ToPrimitive` (an
12287 // `Int` is already primitive), no string check, no bigint check, no allocation.
12288 // `x += 1` in a loop is the single most common instruction sequence in real
12289 // script, and it used to walk every one of those checks before reaching the
12290 // same `checked_add`.
12291 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12292 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
12293 return Ok(());
12294 }
12295 let left = self.primitive_of(left)?;
12296 let right = self.primitive_of(right)?;
12297 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
12298 // that check comes before the bigint one: `"" + 1n` is a string, not a
12299 // mixed-type error.
12300 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
12301 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
12302 // `TypeError`, the one place a symbol and a string do not mix.
12303 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
12304 // between a copy and a rope from their lengths, and a rope is what turns
12305 // `text += "abc"` in a loop from quadratic into linear.
12306 if let (Value::String(left), Value::String(right)) = (&left, &right) {
12307 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
12308 // reports as `InternalError: string too long`.
12309 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
12310 return Err(Signal::Throw(
12311 self.make_error("InternalError", "string too long"),
12312 ));
12313 };
12314 self.push(Value::String(Gc::new(self.heap, joined)));
12315 return Ok(());
12316 }
12317 // At least one operand was not a string, so `ToString` it. This rejects a
12318 // symbol, which is the one place a symbol and a string do not mix.
12319 let left = self.checked_to_wtf8(&left)?;
12320 let right = self.checked_to_wtf8(&right)?;
12321 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
12322 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
12323 let text = left.concat(&right);
12324 self.push(self.string_wtf8(text));
12325 return Ok(());
12326 }
12327 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
12328 // not a conversion.
12329 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
12330 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
12331 self.push(value);
12332 return Ok(());
12333 }
12334 let left = self.numeric(left)?;
12335 let right = self.numeric(right)?;
12336 self.push(add_numbers(left, right));
12337 Ok(())
12338 }
12339
12340 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
12341 self.to_primitive(value, Hint::Default)
12342 }
12343
12344 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
12345 ///
12346 /// The order depends on the hint: the "number" order tries `valueOf` first and
12347 /// `toString` second, the "string" order the other way round, and the default
12348 /// hint uses the number order. A result that is still an object is a `TypeError`,
12349 /// because no built-in `valueOf`/`toString` returns one.
12350 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
12351 let Value::Object(object) = &value else {
12352 return Ok(value);
12353 };
12354 // A Date overrides the default hint to mean "string", which is what
12355 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
12356 // this, `"" + new Date()` would print the milliseconds, not the date.
12357 let hint = if hint == Hint::Default && is_date_object(self, object) {
12358 Hint::String
12359 } else {
12360 hint
12361 };
12362 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
12363 // handed the hint as a string. This is the hook a Date uses for its default hint
12364 // and a script uses to take over conversion entirely.
12365 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
12366 // `GetMethod`, not "is it a callable object": the property has to be read and then
12367 // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
12368 // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
12369 // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
12370 // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
12371 // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
12372 // callable.
12373 match self.get_property_key(object, &key)? {
12374 None | Some(Value::Undefined) | Some(Value::Null) => {}
12375 Some(Value::Object(function)) if function.is_callable() => {
12376 let hint = match hint {
12377 Hint::String => "string",
12378 Hint::Number => "number",
12379 Hint::Default => "default",
12380 };
12381 let hint = self.string(hint);
12382 let result = self.call_value(
12383 Value::Object(function),
12384 Value::Object(object.clone()),
12385 vec![hint],
12386 )?;
12387 if !matches!(result, Value::Object(_)) {
12388 return Ok(result);
12389 }
12390 return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
12391 }
12392 Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
12393 }
12394 let order: [&str; 2] = match hint {
12395 Hint::String => ["toString", "valueOf"],
12396 Hint::Number | Hint::Default => ["valueOf", "toString"],
12397 };
12398 let receiver = object.clone();
12399 for method in order {
12400 if let Some(function) = self.get_property(&receiver, method)?
12401 && matches!(&function, Value::Object(object) if object.is_callable())
12402 {
12403 let result =
12404 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
12405 if !matches!(result, Value::Object(_)) {
12406 return Ok(result);
12407 }
12408 }
12409 }
12410 Err(self.type_error("cannot convert object to primitive value"))
12411 }
12412
12413 /// `ToString` with the object case going through `ToPrimitive`.
12414 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
12415 if matches!(value, Value::Object(_)) {
12416 let primitive = self.to_primitive(value.clone(), Hint::String)?;
12417 return Ok(primitive.to_js_string());
12418 }
12419 // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
12420 // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
12421 // callers that want that strictness call [`Interp::to_string_strict`] — putting the
12422 // check here broke `String(Symbol())` and 45 cases that print a symbol.
12423 Ok(value.to_js_string())
12424 }
12425
12426 /// `ToString(value)`, with §7.1.19's symbol refusal.
12427 ///
12428 /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
12429 /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
12430 /// operations and conflating them cost 45 cases in one direction and 6 in the other.
12431 pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
12432 if matches!(value, Value::Symbol(_)) {
12433 return Err(self.type_error("cannot convert a Symbol to a string"));
12434 }
12435 if matches!(value, Value::Object(_)) {
12436 let primitive = self.to_primitive(value.clone(), Hint::String)?;
12437 if matches!(primitive, Value::Symbol(_)) {
12438 return Err(self.type_error("cannot convert a Symbol to a string"));
12439 }
12440 return Ok(primitive.to_js_string());
12441 }
12442 Ok(value.to_js_string())
12443 }
12444
12445 /// `ToString` that keeps the string's code units instead of flattening them.
12446 ///
12447 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
12448 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
12449 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12450 if matches!(value, Value::Symbol(_)) {
12451 return Err(Signal::Throw(
12452 self.make_error("TypeError", "cannot convert symbol to string"),
12453 ));
12454 }
12455 // An object runs `ToPrimitive` first, which may itself produce a symbol.
12456 let value = self.to_primitive(value.clone(), Hint::String)?;
12457 match value {
12458 Value::Symbol(_) => Err(Signal::Throw(
12459 self.make_error("TypeError", "cannot convert symbol to string"),
12460 )),
12461 Value::String(text) => Ok(text.wtf8().clone()),
12462 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
12463 }
12464 }
12465
12466 /// `ToNumber` with the object case going through `ToPrimitive`.
12467 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
12468 let value = if matches!(value, Value::Object(_)) {
12469 self.to_primitive(value.clone(), Hint::Number)?
12470 } else {
12471 value.clone()
12472 };
12473 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
12474 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
12475 // `NaN` to stay total, and the operators check for the bigint themselves — but
12476 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
12477 // refuse, and answering `NaN` made them silently wrong instead.
12478 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
12479 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
12480 match value {
12481 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
12482 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
12483 other => Ok(other.to_number()),
12484 }
12485 }
12486
12487 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
12488 /// [`ElementType::write`].
12489 ///
12490 /// This is separated from the write because both conversions are observable script —
12491 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
12492 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
12493 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
12494 /// setters, and a plain `a[i] = v`.
12495 pub(crate) fn element_value(
12496 &mut self,
12497 element: crate::builtins::typedarray::ElementType,
12498 value: Value,
12499 ) -> JsResult<Value> {
12500 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
12501 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
12502 let primitive = match &value {
12503 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
12504 _ => value,
12505 };
12506 if element.is_bigint() {
12507 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
12508 Ok(Value::BigInt(Gc::new(self.heap, big)))
12509 } else {
12510 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
12511 Ok(Value::Float(self.to_js_number(&primitive)?))
12512 }
12513 }
12514
12515 /// `ToPropertyKey`: what a computed member access uses as its key.
12516 ///
12517 /// A symbol is returned as itself, never stringified — that is what keeps
12518 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
12519 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
12520 match value {
12521 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
12522 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
12523 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
12524 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
12525 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12526 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
12527 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
12528 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
12529 other.to_js_string(),
12530 ))),
12531 },
12532 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
12533 }
12534 }
12535
12536 /// `ToPropertyKey` for the callers that can only use a string key.
12537 ///
12538 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
12539 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
12540 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
12541 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
12542 /// program continues with a value nobody asked for.
12543 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12544 use crate::value::Wtf8;
12545 Ok(match value {
12546 // A string key keeps its code units. Going through a lossy `String` would make
12547 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
12548 Value::String(text) => text.wtf8().clone(),
12549 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
12550 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
12551 // falling back to its `ToString` would print `[object Object]`.
12552 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12553 Value::String(text) => text.wtf8().clone(),
12554 other => Wtf8::new(other.to_js_string()),
12555 },
12556 other => Wtf8::new(other.to_js_string()),
12557 })
12558 }
12559
12560 // -- object operations used by instructions -----------------------------
12561
12562 /// Read `object[key]`, returning `undefined` when the property is missing.
12563 ///
12564 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
12565 /// primitive (looking through its prototype) as well as an object — which is what
12566 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
12567 /// argument needs too.
12568 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
12569 self.read_field_key(object, &PropertyKey::from(key))
12570 }
12571
12572 /// [`Interp::read_field`] with a key that may be a symbol.
12573 ///
12574 /// A symbol key never reaches the string shortcuts: a string's `length` and its
12575 /// indices are string properties, and a symbol named `length` is a different
12576 /// property that a string primitive cannot have.
12577 /// [`Interp::read_field_key`], with an inline cache in front of it.
12578 ///
12579 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
12580 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
12581 /// without this the engine walked the chain and compared ~40 property names on each
12582 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
12583 ///
12584 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
12585 /// missing property. Those answers depend on running code or on state the guard below
12586 /// does not cover, and a wrong answer here is far more expensive than a lookup.
12587 ///
12588 /// A hit is re-validated against the *whole* walked chain, not just the level that
12589 /// answered: the receiver and every prototype down to that level must still be the same
12590 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
12591 /// property-table *lengths* — which is what catches a property appearing on an
12592 /// intermediate prototype and shadowing the cached one.
12593 pub fn read_field_cached(
12594 &mut self,
12595 object: &Value,
12596 key: &PropertyKey,
12597 slot: usize,
12598 ) -> JsResult<Value> {
12599 let index = Self::field_cache_slot(object, key, slot);
12600 let Value::Object(target) = object else {
12601 return self.read_field_key(object, key);
12602 };
12603 if target.proxy_state().is_some() {
12604 return self.read_field_key(object, key);
12605 }
12606 if let Some(cached) = &self.field_cache[index]
12607 && cached.key == *key
12608 && let Some(value) = Self::cached_hit(target, cached)
12609 {
12610 return Ok(value);
12611 }
12612 let value = self.read_field_key(object, key)?;
12613 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
12614 Ok(value)
12615 }
12616
12617 /// Whether a cache entry still describes this lookup, and if so the value.
12618 ///
12619 /// The guard is the whole point of the entry: identity plus property-table length for
12620 /// every level walked. Re-checked per level rather than once at the receiving end,
12621 /// because a shadowing property can appear anywhere along the chain.
12622 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
12623 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
12624 // starts with: a clone is a reference-count bump and a drop, and for
12625 // `property:monomorphic` every single hit takes only this arm.
12626 let (weak, len) = cached.chain[0].as_ref()?;
12627 if !target.upgrades_to(weak) {
12628 return None;
12629 }
12630 if cached.level == 0 {
12631 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
12632 return target.cached_property_at(cached.index, &cached.key, *len);
12633 }
12634 if target.props_len() != *len {
12635 return None;
12636 }
12637 let mut level = 1;
12638 let mut current = target.proto()?;
12639 loop {
12640 let (weak, len) = cached.chain[level].as_ref()?;
12641 if !current.upgrades_to(weak) || current.props_len() != *len {
12642 return None;
12643 }
12644 if level == cached.level as usize {
12645 // The level that answered: the value is only reusable while the key is
12646 // still there and still a plain data property.
12647 return current.cached_data_property(cached.index, &cached.key);
12648 }
12649 current = current.proto()?;
12650 level += 1;
12651 }
12652 }
12653
12654 /// Build a cache entry for a lookup that just went through the slow path.
12655 ///
12656 /// Records the chain only when the answer came from a plain data property at a level
12657 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
12658 /// costs the next lookup the walk it would have cost anyway.
12659 fn record_field_lookup(
12660 target: &Gc<JsObject>,
12661 key: &PropertyKey,
12662 _value: Value,
12663 ) -> Option<FieldCache> {
12664 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
12665 [None, None, None];
12666 let mut current = target.clone();
12667 for level in 0..MAX_CACHED_CHAIN {
12668 chain[level] = Some((current.downgrade(), current.props_len()));
12669 if let Some((found, _)) = current.own_property_index(key) {
12670 // `own_property_index` declines an accessor and a hole, which is exactly
12671 // the set that must not be cached.
12672 return Some(FieldCache {
12673 key: key.clone(),
12674 index: found,
12675 level: level as u8,
12676 chain,
12677 });
12678 }
12679 current = current.proto()?;
12680 }
12681 None
12682 }
12683
12684 /// Which cache slot a lookup uses.
12685 ///
12686 /// Mixes the object's address, the name and the site, so that two properties of one
12687 /// object, and one property of two objects, land in different slots — which is what lets
12688 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
12689 /// other iteration.
12690 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
12691 let mut hash = match object {
12692 Value::Object(object) => object.address(),
12693 _ => 0,
12694 };
12695 hash = hash
12696 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
12697 .rotate_left(17)
12698 .wrapping_add(key.hash_code());
12699 hash = hash.wrapping_add(site.wrapping_mul(31));
12700 // The table is a power of two, so the low bits are the slot.
12701 hash & (FIELD_CACHE_SLOTS - 1)
12702 }
12703
12704 /// Read `key` from `object`, without the inline cache.
12705 ///
12706 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
12707 /// prototype chain, while the cached form answers an own data property from memory.
12708 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
12709 let text = key.as_str().unwrap_or("");
12710 let Value::Object(object) = object else {
12711 // Reading a property of `undefined`/`null` is the classic TypeError.
12712 if object.is_nullish() {
12713 return Err(Signal::Throw(self.make_error(
12714 "TypeError",
12715 &format!("cannot read property '{key}' of {}", object.to_js_string()),
12716 )));
12717 }
12718 // A string has `length` and index access without being boxed.
12719 if let Value::String(value) = object {
12720 if text == "length" {
12721 return Ok(Value::Int(value.utf16_len() as i32));
12722 }
12723 if let Some(index) = array_index(text) {
12724 return Ok(match value.wtf8().unit_at(index as usize) {
12725 Some(unit) => self.string_wtf8(unit),
12726 None => Value::Undefined,
12727 });
12728 }
12729 }
12730 // A property of a primitive is looked up on its prototype: this is what
12731 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
12732 let prototype = match object {
12733 Value::String(_) => self.realm.string_proto.clone(),
12734 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
12735 Value::Bool(_) => self.realm.boolean_proto.clone(),
12736 // A symbol's methods live on `Symbol.prototype`, reached the same way —
12737 // `sym.description` reads through the prototype, not off the symbol.
12738 Value::Symbol(_) => self.realm.symbol_proto.clone(),
12739 // …and a bigint's on `BigInt.prototype`, which is how
12740 // `(255n).toString(16)` reaches its method.
12741 Value::BigInt(_) => self.realm.bigint_proto.clone(),
12742 _ => None,
12743 };
12744 if let Some(prototype) = prototype
12745 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
12746 {
12747 return Ok(value);
12748 }
12749 return Ok(Value::Undefined);
12750 };
12751 Ok(self
12752 .get_property_key(object, key)?
12753 .unwrap_or(Value::Undefined))
12754 }
12755
12756 /// The `#name` a private symbol stands for, for error messages.
12757 ///
12758 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
12759 /// was made from.
12760 fn private_name(symbol: &Value) -> Option<String> {
12761 match symbol {
12762 Value::Symbol(symbol) if symbol.is_private() => Some(
12763 symbol
12764 .description()
12765 .map(|text| text.to_string())
12766 .unwrap_or_default(),
12767 ),
12768 _ => None,
12769 }
12770 }
12771
12772 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
12773 ///
12774 /// Every private-field opcode takes the symbol the class stored in its own scope; a
12775 /// non-symbol here would be a compiler bug, and the reference guards it with
12776 /// `JS_ThrowTypeErrorNotASymbol`.
12777 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
12778 match symbol {
12779 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
12780 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
12781 }
12782 }
12783
12784 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
12785 ///
12786 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
12787 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
12788 /// would hit if the parser did not reject it first.
12789 fn define_private_field(
12790 &mut self,
12791 object: &Value,
12792 symbol: &Value,
12793 value: Value,
12794 ) -> JsResult<()> {
12795 let key = self.private_key(symbol)?;
12796 let Some(target) = object.as_object() else {
12797 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12798 };
12799 if !target.is_extensible() {
12800 return Err(Signal::Throw(
12801 self.make_error("TypeError", "object is not extensible"),
12802 ));
12803 }
12804 if target.own_property_key(&key).is_some() {
12805 let name = Self::private_name(symbol).unwrap_or_default();
12806 return Err(Signal::Throw(self.make_error(
12807 "TypeError",
12808 &format!("private class field '{name}' already exists"),
12809 )));
12810 }
12811 target.define_data_key(&key, value);
12812 Ok(())
12813 }
12814
12815 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
12816 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
12817 let key = self.private_key(symbol)?;
12818 let Some(target) = object.as_object() else {
12819 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12820 };
12821 match target.own_property_key(&key) {
12822 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
12823 None => {
12824 let name = Self::private_name(symbol).unwrap_or_default();
12825 Err(Signal::Throw(self.make_error(
12826 "TypeError",
12827 &format!("private class field '{name}' does not exist"),
12828 )))
12829 }
12830 }
12831 }
12832
12833 /// `JS_SetPrivateField`: the store half of the same rule.
12834 fn write_private_field(
12835 &mut self,
12836 object: &Value,
12837 symbol: &Value,
12838 value: Value,
12839 ) -> JsResult<()> {
12840 let key = self.private_key(symbol)?;
12841 let Some(target) = object.as_object() else {
12842 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12843 };
12844 if target.write_value_key(&key, value) {
12845 return Ok(());
12846 }
12847 let name = Self::private_name(symbol).unwrap_or_default();
12848 Err(Signal::Throw(self.make_error(
12849 "TypeError",
12850 &format!("private class field '{name}' does not exist"),
12851 )))
12852 }
12853
12854 /// The `in` half: does `object` have this private field?
12855 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
12856 ///
12857 /// The symbol is created once per class — the first `add_brand` on a given home object
12858 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
12859 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
12860 /// emit for the *instance* brand passes null because all it wants is the symbol.
12861 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
12862 let Some(home_object) = home.as_object() else {
12863 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12864 };
12865 let symbol = match home_object.private_brand() {
12866 Some(symbol) => symbol,
12867 None => {
12868 let symbol = Gc::new(
12869 self.heap,
12870 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
12871 );
12872 home_object.set_private_brand(symbol.clone());
12873 symbol
12874 }
12875 };
12876 let Some(target) = object.as_object() else {
12877 // Not an object: nothing to brand. The reference does the same, and `undefined`
12878 // here would otherwise turn a field initialiser into a TypeError.
12879 return Ok(());
12880 };
12881 if !target.is_extensible() {
12882 return Err(Signal::Throw(
12883 self.make_error("TypeError", "object is not extensible"),
12884 ));
12885 }
12886 if target.carries_brand(&symbol) {
12887 return Err(Signal::Throw(
12888 self.make_error("TypeError", "private method is already present"),
12889 ));
12890 }
12891 target.add_brand(symbol);
12892 Ok(())
12893 }
12894
12895 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
12896 ///
12897 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
12898 /// decides whether to throw.
12899 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
12900 let Some(function) = function.as_object() else {
12901 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12902 };
12903 let Some(home) = function.home_object() else {
12904 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12905 };
12906 let Some(brand) = home.private_brand() else {
12907 return Err(Signal::Throw(
12908 self.make_error("TypeError", "expecting <brand> private field"),
12909 ));
12910 };
12911 Ok(object.carries_brand(&brand))
12912 }
12913
12914 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
12915 let Value::Object(object) = object else {
12916 return Err(Signal::Throw(self.make_error(
12917 "TypeError",
12918 &format!("cannot set property '{key}' of {}", object.to_js_string()),
12919 )));
12920 };
12921 // The write half of the property inline cache, in effect: an own, writable,
12922 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
12923 // decide — no prototype walk (an own property shadows the chain before a setter
12924 // there could matter), no extensibility check (the object already has the key),
12925 // and no `[[DefineOwnProperty]]`.
12926 //
12927 // `this.value = …` inside a method is the whole write side of
12928 // `property:method-call`, and it was reaching `set_property_with_key` with its
12929 // proxy test, its typed-array test, its array-index test and finally a linear
12930 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
12931 //
12932 // Every disqualifier is checked here: a proxy traps the set, an array index and
12933 // `length` live outside the property table, and a typed array's element is stored
12934 // through its view's element type.
12935 if object.proxy_state().is_none()
12936 && !object.is_array()
12937 && object.typed_array_element_type().is_none()
12938 && object.write_value_key(key, value.clone())
12939 {
12940 return Ok(());
12941 }
12942 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
12943 let on_failure = if self.frame().code.code.strict {
12944 DeleteFailure::Throw
12945 } else {
12946 DeleteFailure::Ignore
12947 };
12948 self.set_property_with_key(object, key, value, on_failure)
12949 }
12950
12951 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
12952 ///
12953 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
12954 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
12955 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
12956 /// `Number.parseInt(sym)` — so those callers use this instead.
12957 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
12958 if matches!(value, Value::Symbol(_)) {
12959 return Err(Signal::Throw(
12960 self.make_error("TypeError", "cannot convert symbol to string"),
12961 ));
12962 }
12963 // An object runs `ToPrimitive` first, which may itself produce a symbol —
12964 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
12965 let value = self.to_primitive(value.clone(), Hint::String)?;
12966 if matches!(value, Value::Symbol(_)) {
12967 return Err(Signal::Throw(
12968 self.make_error("TypeError", "cannot convert symbol to string"),
12969 ));
12970 }
12971 Ok(value.to_js_string())
12972 }
12973
12974 /// `ToPropertyKey` for a builtin that takes a key argument.
12975 ///
12976 /// Fallible: a key whose `toString` throws has to propagate that error, both for
12977 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
12978 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
12979 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
12980 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
12981 self.propkey(value)
12982 }
12983
12984 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
12985 ///
12986 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
12987 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
12988 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
12989 /// `RangeError` — and why this cannot be a plain `ToNumber`.
12990 /// `ToNumber(value)` for `ArraySetLength`, which the spec performs **twice**.
12991 ///
12992 /// §10.4.2.4 steps 3–5 are `ToUint32(Desc.[[Value]])`, then `ToNumber(Desc.[[Value]])`,
12993 /// then a `RangeError` when they disagree. Two conversions rather than one is
12994 /// observable: a `valueOf` that runs the first time can make `length` non-writable
12995 /// before the second, which turns the store into a refused write
12996 /// (`length/define-own-prop-length-coercion-order`, `…-set`).
12997 pub fn coerce_array_length_twice(&mut self, value: &Value) -> JsResult<u32> {
12998 let first = self.array_length_of(value)?;
12999 let second = self.array_length_of(value)?;
13000 debug_assert_eq!(first, second);
13001 Ok(first)
13002 }
13003
13004 /// `ArraySetLength`'s `ToNumber(value)`, then the `ToUint32` round-trip check.
13005 ///
13006 /// Separate from [`Interp::coerce_array_length_twice`] so the callers that need one
13007 /// conversion can say so; a caller that needs the spec's two uses that instead.
13008 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
13009 let number = match value {
13010 Value::Int(number) => *number as f64,
13011 Value::Float(number) => *number,
13012 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
13013 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
13014 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
13015 // reference answers 0.
13016 Value::Null | Value::Bool(_) | Value::Undefined => value.to_number(),
13017 // A string goes through the full numeric-literal grammar: `"0x00B"` is 11 and
13018 // `" 5 "` is 5, which is exactly what `string_to_number` implements.
13019 Value::String(text) => crate::value::string_to_number(&text.to_string_lossy()),
13020 _ => {
13021 // The primitive comes back through this same conversion, so a wrapper of a
13022 // boolean (`new Boolean(false)`) is `0` rather than the `NaN` that
13023 // `ToNumber("false")` would give — `S15.4.5.1_A1.3_T1` walks every wrapper.
13024 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
13025 return self.array_length_of(&primitive);
13026 }
13027 };
13028 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
13029 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
13030 // is a `RangeError`, not `0`.
13031 if !number.is_finite()
13032 || number.fract() != 0.0
13033 || !(0.0..=u32::MAX as f64).contains(&number)
13034 {
13035 return Err(self.range_error("invalid array length"));
13036 }
13037 Ok(number as u32)
13038 }
13039
13040 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
13041 /// `Object.getOwnPropertySymbols` put in their result array.
13042 pub fn key_value(&self, key: &PropertyKey) -> Value {
13043 match key {
13044 PropertyKey::String(text) => self.string_wtf8(text.clone()),
13045 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
13046 }
13047 }
13048
13049 /// Fill in a String exotic object: `_value`, `length` and the index properties.
13050 ///
13051 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
13052 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
13053 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
13054 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
13055 /// the two paths had drifted; this is the one both now use.
13056 ///
13057 /// The indices are *code units*, so an astral character occupies two of them — the
13058 /// same rule `s.length` and `s[i]` follow.
13059 /// Give an already-created object the internal slot that makes it a wrapper of
13060 /// `value`, so the primitive's prototype methods work on it.
13061 ///
13062 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
13063 /// which are wrappers of their own type holding the empty value.
13064 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
13065 self.internal_set(object, "_value", value);
13066 }
13067
13068 pub(crate) fn init_string_wrapper(
13069 &mut self,
13070 object: &Gc<JsObject>,
13071 text: &Gc<crate::value::JsString>,
13072 ) {
13073 object.define(
13074 "length",
13075 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
13076 );
13077 for index in 0..text.utf16_len() {
13078 if let Some(unit) = text.wtf8().unit_at(index) {
13079 object.define(
13080 &index.to_string(),
13081 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
13082 Property::with_attributes(self.string_wtf8(unit), false, true),
13083 );
13084 }
13085 }
13086 object.define_key(
13087 &self.internal_slot("_value"),
13088 Property::with_attributes(Value::String(text.clone()), false, false),
13089 );
13090 }
13091
13092 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
13093 ///
13094 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
13095 /// throws. The wrapper carries its primitive in `_value` — the same slot
13096 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
13097 /// on a boxed value no constructor ever built.
13098 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13099 let (prototype, primitive) = match value {
13100 Value::Object(object) => return Ok(object.clone()),
13101 Value::String(text) => {
13102 let object = self.new_object(self.realm.string_proto.clone());
13103 self.init_string_wrapper(&object, text);
13104 return Ok(object);
13105 }
13106 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
13107 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
13108 // A symbol and a bigint box into wrappers whose methods live on
13109 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
13110 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
13111 // branch below instead produced an object with *no* prototype, so those
13112 // methods were unreachable on a box.
13113 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
13114 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
13115 Value::Undefined | Value::Null => {
13116 return Err(Signal::Throw(self.make_error(
13117 "TypeError",
13118 &format!("cannot convert {} to object", value.to_js_string()),
13119 )));
13120 }
13121 _ => (None, value.clone()),
13122 };
13123 let object = self.new_object(prototype);
13124 self.internal_set(&object, "_value", primitive);
13125 Ok(object)
13126 }
13127
13128 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
13129 ///
13130 /// Split out for a reader that has to create the object *before* it knows what it wraps:
13131 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
13132 /// written before its primitive, so the placeholder has to exist first and be filled in
13133 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
13134 /// than a second in the deserialiser.
13135 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
13136 let prototype = match value {
13137 Value::String(_) => self.realm.string_proto.clone(),
13138 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13139 Value::Bool(_) => self.realm.boolean_proto.clone(),
13140 Value::Symbol(_) => self.realm.symbol_proto.clone(),
13141 Value::BigInt(_) => self.realm.bigint_proto.clone(),
13142 _ => {
13143 return Err(Signal::Throw(self.make_error(
13144 "TypeError",
13145 &format!("cannot box {}", value.to_js_string()),
13146 )));
13147 }
13148 };
13149 object.set_proto(prototype);
13150 if let Value::String(text) = value {
13151 self.init_string_wrapper(object, text);
13152 return Ok(());
13153 }
13154 self.internal_set(object, "_value", value.clone());
13155 Ok(())
13156 }
13157
13158 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
13159 ///
13160 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
13161 /// through the `Symbol` function object, so the registry is reachable as a method rather
13162 /// than only from `builtins::symbol`.
13163 pub fn symbol_for(&mut self, key: &str) -> Value {
13164 if let Some(existing) = self.realm.symbol_registry.get(key) {
13165 return existing.clone();
13166 }
13167 let symbol = crate::builtins::symbol::symbol_value(
13168 self,
13169 crate::value::JsSymbol::registered(key.to_string()),
13170 );
13171 self.realm
13172 .symbol_registry
13173 .insert(key.to_string(), symbol.clone());
13174 symbol
13175 }
13176
13177 /// `a == b`, the coercing comparison.
13178 ///
13179 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
13180 /// which is what makes `[] == ""` true: `[]` becomes `""` via
13181 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
13182 /// because the conversion is allowed to call script code, so the two primitive
13183 /// operands are handed back to it.
13184 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
13185 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
13186 return Ok(left.loose_equals(&right));
13187 }
13188 // `null == undefined` holds even though neither is an object.
13189 if matches!(left, Value::Undefined | Value::Null)
13190 && matches!(right, Value::Undefined | Value::Null)
13191 {
13192 return Ok(true);
13193 }
13194 if matches!(left, Value::Undefined | Value::Null)
13195 || matches!(right, Value::Undefined | Value::Null)
13196 {
13197 return Ok(false);
13198 }
13199 // Two objects compare by identity. Only an object *against a primitive* is
13200 // converted, which is why `{} == {}` is false while `[] == ""` is true.
13201 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
13202 return Ok(a.ptr_eq(b));
13203 }
13204 let left = self.to_primitive(left, Hint::Default)?;
13205 let right = self.to_primitive(right, Hint::Default)?;
13206 Ok(left.loose_equals(&right))
13207 }
13208
13209 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
13210 let Value::Object(object) = object else {
13211 return Err(Signal::Throw(
13212 self.make_error("TypeError", "cannot use 'in' on a non-object"),
13213 ));
13214 };
13215 let key = self.propkey(key)?;
13216 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
13217 // trap. One implementation, so an array's derived `length` and its inherited holes
13218 // cannot be right in one caller and wrong in another.
13219 self.has_own_or_inherited(object, &key)
13220 }
13221
13222 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
13223 ///
13224 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
13225 /// whole reason the operator is a hook rather than a prototype walk.
13226 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13227 if let Value::Object(function) = constructor {
13228 let key = self.realm.well_known_key(WellKnown::HasInstance);
13229 let method = self.get_property_key(function, &key)?;
13230 if let Some(method) = method
13231 && !matches!(method, Value::Undefined)
13232 {
13233 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
13234 return Ok(answer.to_boolean());
13235 }
13236 }
13237 self.instance_of(object, constructor)
13238 }
13239
13240 /// `OrdinaryHasInstance`: the prototype walk on its own.
13241 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13242 self.instance_of(object, constructor)
13243 }
13244
13245 /// `IsArray`: an array, or a proxy whose target is one.
13246 ///
13247 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
13248 /// makes `Array.isArray(new Proxy([], {}))` true.
13249 pub fn is_array_value(&self, value: &Value) -> bool {
13250 match value {
13251 Value::Object(object) => {
13252 if let Some(state) = object.proxy_state() {
13253 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
13254 }
13255 object.is_array()
13256 }
13257 _ => false,
13258 }
13259 }
13260
13261 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
13262 ///
13263 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
13264 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
13265 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
13266 /// see [`Interp::enqueue_job_function`].
13267 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
13268 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
13269 // the handler is reported rather than lost — the same reason a `then` reaction needs a
13270 // promise to settle.
13271 let promise = self.new_promise();
13272 self.fulfill_promise(&promise, Value::Undefined);
13273 self.jobs.push_back(Job::Reaction {
13274 handler: Some(function),
13275 argument: Value::Undefined,
13276 rejected: false,
13277 promise,
13278 });
13279 Ok(())
13280 }
13281
13282 /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
13283 ///
13284 /// Four of its steps were missing or wrong, and each one is a test262 case in
13285 /// `Function/prototype/Symbol.hasInstance/`:
13286 ///
13287 /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
13288 /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
13289 /// `[[BoundThis]]` standing in for the object when that is an object), which is why
13290 /// `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
13291 /// `prototype` of its own, so without this step the walk below gives `false`;
13292 /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
13293 /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
13294 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13295 let Value::Object(function) = constructor else {
13296 return Ok(false);
13297 };
13298 if !function.is_callable() {
13299 return Ok(false);
13300 }
13301 // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
13302 // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
13303 // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
13304 if let Some((target, this)) = function.bound_target_and_this() {
13305 let object = if this.as_object().is_some() {
13306 this
13307 } else {
13308 object.clone()
13309 };
13310 return self.instance_of(&object, &target);
13311 }
13312 let Value::Object(target) = object else {
13313 return Ok(false);
13314 };
13315 let prototype = self.get_property(function, "prototype")?;
13316 let Some(Value::Object(prototype)) = prototype else {
13317 return Err(Signal::Throw(self.make_error(
13318 "TypeError",
13319 "function has non-object prototype in instanceof check",
13320 )));
13321 };
13322 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
13323 // which is also what makes `proxyOfInstance instanceof C` work.
13324 let mut current = Some(target.clone());
13325 while let Some(object) = current {
13326 if object.ptr_eq(&prototype) {
13327 return Ok(true);
13328 }
13329 current = self.object_prototype_of(&object)?;
13330 }
13331 Ok(false)
13332 }
13333
13334 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
13335 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
13336 if let Some(proto) = self.proxy_get_prototype_of(object)? {
13337 return Ok(proto);
13338 }
13339 if let Some(exotic) = object.exotic()
13340 && let Some(proto) = exotic.get_prototype(self, object)?
13341 {
13342 return Ok(proto);
13343 }
13344 Ok(object.proto())
13345 }
13346
13347 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
13348 pub fn object_set_prototype_of(
13349 &mut self,
13350 object: &Gc<JsObject>,
13351 proto: Option<Gc<JsObject>>,
13352 ) -> JsResult<bool> {
13353 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
13354 return Ok(answer);
13355 }
13356 if let Some(exotic) = object.exotic()
13357 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
13358 {
13359 return Ok(answer);
13360 }
13361 // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
13362 // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
13363 // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
13364 // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
13365 if self
13366 .internal_get(object, "_immutable_proto")
13367 .is_some_and(|flag| flag.to_boolean())
13368 && !same_proto(object.proto().as_ref(), proto.as_ref())
13369 {
13370 return Ok(false);
13371 }
13372 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
13373 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
13374 // inheriting from itself, which every later prototype walk then had to defend
13375 // against — and `Reflect.setPrototypeOf` reported success for an operation the
13376 // language says is impossible.
13377 if let Some(proto) = &proto {
13378 let mut current = Some(proto.clone());
13379 let mut guard = 0;
13380 while let Some(node) = current {
13381 if node.ptr_eq(object) {
13382 return Err(Signal::Throw(
13383 self.make_error("TypeError", "circular prototype chain"),
13384 ));
13385 }
13386 guard += 1;
13387 if guard > 1000 {
13388 break;
13389 }
13390 current = node.proto();
13391 }
13392 }
13393 // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
13394 // re-setting it to the *same* one is a no-op `true`. Missing this made
13395 // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
13396 // actually reparent the object — and it is what
13397 // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
13398 // forwarding path has nothing else left to refuse it.
13399 if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
13400 return Ok(false);
13401 }
13402 object.set_proto(proto);
13403 Ok(true)
13404 }
13405
13406 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
13407 ///
13408 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
13409 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
13410 /// already one.
13411 /// `HasProperty(O, P)`.
13412 ///
13413 /// One implementation, shared with the `in` operator. It used to be a second copy that
13414 /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
13415 /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
13416 /// proxy ran the wrong hook and could even disagree with `in`. The
13417 /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
13418 /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
13419 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
13420 self.has_own_or_inherited(object, key)
13421 }
13422
13423 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
13424 ///
13425 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
13426 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
13427 /// boolean as well, and it needs the receiver to be the one the caller named.
13428 pub fn set_property_with_key_receiver(
13429 &mut self,
13430 object: &Gc<JsObject>,
13431 key: &PropertyKey,
13432 value: Value,
13433 receiver: Option<&Value>,
13434 on_failure: DeleteFailure,
13435 ) -> JsResult<bool> {
13436 let receiver = receiver
13437 .cloned()
13438 .unwrap_or_else(|| Value::Object(object.clone()));
13439 if object.proxy_state().is_some() {
13440 return match self.proxy_set(object, key, value, &receiver)? {
13441 Some(accepted) => Ok(accepted),
13442 None => Ok(true),
13443 };
13444 }
13445 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
13446 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
13447 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
13448 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
13449 //
13450 // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
13451 //
13452 // * `SameValue(O, Receiver)` stores into the buffer, converting first;
13453 // * an *invalid* index with a different receiver answers `true` and does nothing,
13454 // not even converting `V` (`valueOfCalls` stays 0);
13455 // * a valid index with a different receiver falls through to
13456 // `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
13457 // value lands on the **receiver**, unconverted, and can be refused by a
13458 // non-extensible receiver, an accessor, or a read-only index there.
13459 //
13460 // The last one used to write into the view itself, which left `target[0]` changed
13461 // and `receiver[0]` untouched — backwards.
13462 if object.typed_array_element_type().is_some()
13463 && let Some(numeric) = canonical_numeric_index(key)
13464 {
13465 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13466 if same {
13467 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13468 return Ok(true);
13469 }
13470 if !typed_array_index_is_valid(object, numeric) {
13471 return Ok(true);
13472 }
13473 let Some(receiver) = receiver.as_object().cloned() else {
13474 return Ok(false);
13475 };
13476 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
13477 if existing.is_accessor() || !existing.writable {
13478 return Ok(false);
13479 }
13480 let property = Property {
13481 value: Some(value),
13482 ..existing
13483 };
13484 return self.object_define_own_property(&receiver, key, property);
13485 }
13486 return self.object_define_own_property(&receiver, key, Property::data(value));
13487 }
13488 // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
13489 // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
13490 // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
13491 // `Reflect.set` to *report* the refusal instead of raising.
13492 //
13493 // A receiver that is not the object turns the whole operation into
13494 // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
13495 // `[[Set]]` rather than a lookup — that is what makes
13496 // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
13497 // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
13498 // writes to `object`, so it cannot express that and is only used when the two are
13499 // the same.
13500 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13501 if !same {
13502 return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
13503 }
13504 // Same receiver: the plain path below writes into `object`, which is right, but it
13505 // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
13506 // boolean, so the two step-1 refusals have to be read off the own descriptor here.
13507 if let Some(existing) = self.object_get_own_property(object, key)? {
13508 if existing.is_accessor() {
13509 return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
13510 Some(setter) => {
13511 self.call_value(setter, receiver, vec![value])?;
13512 Ok(true)
13513 }
13514 None => Ok(false),
13515 };
13516 }
13517 if !existing.writable {
13518 return Ok(false);
13519 }
13520 }
13521 // Otherwise it is an ordinary create-or-write into `object` itself.
13522 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13523 Ok(true)
13524 }
13525
13526 /// `[[IsExtensible]]`, with the proxy trap when there is one.
13527 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13528 if let Some(answer) = self.proxy_is_extensible(object)? {
13529 return Ok(answer);
13530 }
13531 if let Some(exotic) = object.exotic()
13532 && let Some(answer) = exotic.is_extensible(self, object)?
13533 {
13534 return Ok(answer);
13535 }
13536 Ok(object.is_extensible())
13537 }
13538
13539 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
13540 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13541 if let Some(answer) = self.proxy_prevent_extensions(object)? {
13542 return Ok(answer);
13543 }
13544 // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
13545 //
13546 // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
13547 //
13548 // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
13549 // created with an explicit length, because the buffer can still move it. That is
13550 // what makes `Object.freeze` refuse every such view, including a zero-length one
13551 // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
13552 // plain buffer is allowed.
13553 if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
13554 && buffer
13555 .array_buffer_storage()
13556 .is_some_and(|storage| storage.borrow().is_resizable())
13557 {
13558 return Err(
13559 self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
13560 );
13561 }
13562 if let Some(exotic) = object.exotic()
13563 && let Some(answer) = exotic.prevent_extensions(self, object)?
13564 {
13565 return Ok(answer);
13566 }
13567 object.set_extensible(false);
13568 Ok(true)
13569 }
13570
13571 fn copy_properties(
13572 &mut self,
13573 target: &Value,
13574 source: &Value,
13575 exclusion: &Value,
13576 ) -> JsResult<()> {
13577 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
13578 // does contribute: its index properties are own, enumerable and writable, which
13579 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
13580 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
13581 // is a no-op.
13582 let Some(target) = target.as_object() else {
13583 return Ok(());
13584 };
13585 let source_object = match source {
13586 Value::Object(object) => object.clone(),
13587 Value::String(text) => {
13588 // Untaken keys are the string's indices, which are code units.
13589 for index in 0..text.utf16_len() {
13590 if let Some(unit) = text.wtf8().unit_at(index) {
13591 target.define_data(&index.to_string(), self.string_wtf8(unit));
13592 }
13593 }
13594 return Ok(());
13595 }
13596 _ => return Ok(()),
13597 };
13598 // An object *rest* element passes the keys already taken by the literal part as
13599 // an array of strings; a spread passes `null`, which excludes nothing. Only the
13600 // string keys of the exclusion array are meaningful, so an array is read by its
13601 // elements rather than by its own property names.
13602 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
13603 if let Value::Object(list) = exclusion
13604 && let Some(length) = list.array_length()
13605 {
13606 for index in 0..length {
13607 if let Some(value) = list.array_get(index) {
13608 excluded.push(self.propkey_of(&value)?);
13609 }
13610 }
13611 }
13612 let source = &source_object;
13613 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
13614 // Reading the property table directly made every spread of a proxy empty.
13615 let keys = self.object_own_property_keys(source)?;
13616 for as_key in keys {
13617 if as_key.is_symbol() {
13618 // A spread copies string-keyed properties only.
13619 continue;
13620 }
13621 if excluded.contains(&crate::value::Wtf8::new(
13622 as_key.as_str().unwrap_or_default(),
13623 )) {
13624 continue;
13625 }
13626 let enumerable = self
13627 .object_get_own_property(source, &as_key)?
13628 .is_some_and(|property| property.enumerable);
13629 if !enumerable {
13630 continue;
13631 }
13632 let value = self
13633 .get_property_key(source, &as_key)?
13634 .unwrap_or(Value::Undefined);
13635 target.define_data_key(&as_key, value);
13636 }
13637 Ok(())
13638 }
13639
13640 // -- iteration ---------------------------------------------------------
13641
13642 /// One object's own keys in enumeration order: array indices ascending, then the
13643 /// rest in insertion order.
13644 ///
13645 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
13646 /// whether the key is enumerable, which the caller resolves per key because an
13647 /// array's elements are not in the same store as its named properties.
13648 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
13649 // An index can arrive twice, once from the array's element store and once from
13650 // its property map, so the numeric keys go through a map that keeps the
13651 // enumerable answer if either source gave one.
13652 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
13653 for (key, enumerable) in &own {
13654 if let Some(index) = key.as_str().and_then(array_index) {
13655 let entry = numeric.entry(index).or_insert(false);
13656 *entry = *entry || *enumerable;
13657 }
13658 }
13659 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
13660 .into_iter()
13661 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
13662 .collect();
13663 ordered.extend(
13664 own.into_iter()
13665 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
13666 );
13667 ordered
13668 }
13669
13670 /// Build the key list a `for-in` loop walks.
13671 ///
13672 /// The order is the specification's: own properties before inherited ones, and
13673 /// within one object the integer-like keys in ascending numeric order ahead of the
13674 /// string keys in insertion order. A shadowed key only appears once, and a key that
13675 /// is a non-enumerable own property anywhere nearer is skipped entirely.
13676 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13677 let record = self.new_object(None);
13678 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
13679 // A proxy supplies its own key list, and — the reason this is not just another
13680 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
13681 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
13682 // descriptor there.
13683 if let Value::Object(object) = value
13684 && object.proxy_state().is_some()
13685 {
13686 let own = self
13687 .proxy_own_keys(object)?
13688 .unwrap_or_else(|| object.own_property_keys());
13689 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
13690 let mut numeric: Vec<u32> = Vec::new();
13691 let mut rest: Vec<PropertyKey> = Vec::new();
13692 for key in own {
13693 match key.as_str().and_then(array_index) {
13694 Some(index) => numeric.push(index),
13695 None => rest.push(key),
13696 }
13697 }
13698 numeric.sort_unstable();
13699 ordered.extend(
13700 numeric
13701 .into_iter()
13702 .map(|index| PropertyKey::from(index.to_string())),
13703 );
13704 ordered.extend(rest);
13705 for (index, key) in ordered.into_iter().enumerate() {
13706 record.define_data(&index.to_string(), self.key_value(&key));
13707 }
13708 record.define_data("__index", Value::Int(0));
13709 // The mark that makes `for_in_advance` re-ask the proxy per key.
13710 record.define_data("__proxy", Value::Object(object.clone()));
13711 return Ok(record);
13712 }
13713 if let Value::Object(object) = value {
13714 let mut chain = vec![object.clone()];
13715 chain.extend(object.chain());
13716 // Every own string key the walk has seen, enumerable or not. A
13717 // non-enumerable own property still hides a same-named enumerable one
13718 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
13719 // keeps `x` out of the loop even when the prototype has one.
13720 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
13721 for object in chain {
13722 let mut own: Vec<(crate::value::Wtf8, bool)> = object
13723 .own_property_keys()
13724 .iter()
13725 .filter_map(|key| key.as_wtf8().cloned())
13726 .map(|key| {
13727 let enumerable = object
13728 .own_property(&key.to_string_lossy())
13729 .map(|property| property.enumerable)
13730 .unwrap_or(false);
13731 (key, enumerable)
13732 })
13733 .collect();
13734 if let Some(length) = object.array_length() {
13735 own.retain(|(key, _)| key.as_str() != Some("length"));
13736 for index in 0..length {
13737 // A dense element is enumerable; a **hole** is not there at all —
13738 // and a hole is also what an index with a recorded descriptor
13739 // leaves behind, in which case the table entry above already
13740 // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
13741 // defines index 0 non-enumerable and `for…in` must skip it).
13742 if let Some(value) = object.array_get(index)
13743 && !matches!(value, Value::Hole)
13744 {
13745 own.push((crate::value::Wtf8::new(index.to_string()), true));
13746 }
13747 }
13748 }
13749 // Integer-like keys come first in ascending order, then the rest in
13750 // insertion order — and the ordering is *per object*, not for the chain
13751 // as a whole: one pass over every collected key lifted a prototype's
13752 // `"4"` above the target's own `x`/`y`, which is not the order
13753 // `for…in` reports.
13754 for (key, enumerable) in Self::order_own_keys(own) {
13755 if visited.contains(&key) {
13756 continue;
13757 }
13758 visited.push(key.clone());
13759 if enumerable {
13760 keys.push(key);
13761 }
13762 }
13763 }
13764 }
13765 for (index, key) in keys.into_iter().enumerate() {
13766 record.define_data(&index.to_string(), self.string_wtf8(key));
13767 }
13768 record.define_data("__index", Value::Int(0));
13769 Ok(record)
13770 }
13771
13772 /// The next key of a `for…in` record, `None` when the loop is done.
13773 ///
13774 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
13775 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
13776 /// the loop reaches it, so a handler that stops reporting a key partway through drops
13777 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
13778 /// key the handler had already withdrawn.
13779 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
13780 let Value::Object(record) = record else {
13781 return Ok(None);
13782 };
13783 let proxy = record
13784 .own_property("__proxy")
13785 .and_then(|property| property.value);
13786 loop {
13787 let index = record
13788 .own_property("__index")
13789 .and_then(|property| property.value)
13790 .map(|value| value.to_int32())
13791 .unwrap_or(0);
13792 let Some(candidate) = record
13793 .own_property(&index.to_string())
13794 .and_then(|property| property.value)
13795 else {
13796 return Ok(None);
13797 };
13798 record.define_data("__index", Value::Int(index + 1));
13799 let text = candidate.to_js_string();
13800 let Some(Value::Object(proxy)) = &proxy else {
13801 return Ok(Some(text));
13802 };
13803 // The candidate is already a key string here, so the lookup does not need a
13804 // second `ToPropertyKey` conversion.
13805 let key = PropertyKey::from(text.as_str());
13806 let live = match self.proxy_get_own_property(proxy, &key)? {
13807 Some(descriptor) => descriptor,
13808 // Not a proxy after all, or it lost its state: fall back to the target.
13809 None => proxy.own_property_key(&key),
13810 };
13811 if live.is_some_and(|property| property.enumerable) {
13812 return Ok(Some(text));
13813 }
13814 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
13815 // next one.
13816 }
13817 }
13818
13819 /// The iterator for `for-of`: the object and its `next` method.
13820 ///
13821 /// An object that already carries a `next` method is used as it is — that is what
13822 /// `arr.values()` returns — and only arrays and strings get the built-in
13823 /// sequence iterator.
13824 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
13825 ///
13826 /// Callers that must choose between the iterable and the array-like protocol — the
13827 /// typed-array constructor is the main one — need to ask *before* committing to one.
13828 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
13829 let key = self.realm.well_known_key(WellKnown::Iterator);
13830 let method = self.read_field_key(value, &key)?;
13831 if matches!(method, Value::Undefined | Value::Null) {
13832 return Ok(false);
13833 }
13834 if !matches!(&method, Value::Object(object) if object.is_callable()) {
13835 return Err(Signal::Throw(
13836 self.make_error("TypeError", "Symbol.iterator is not callable"),
13837 ));
13838 }
13839 Ok(true)
13840 }
13841
13842 /// Collect everything an iterable yields.
13843 ///
13844 /// The cap is a guard against a generator that never ends: an unbounded collect would
13845 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
13846 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
13847 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
13848 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
13849 const MAX_ITEMS: usize = 1 << 24;
13850 let iterator = self.get_iterator(value)?;
13851 let mut out = Vec::new();
13852 loop {
13853 let (element, done) = self.iterator_step(&iterator)?;
13854 if done {
13855 return Ok(out);
13856 }
13857 out.push(element);
13858 if out.len() > MAX_ITEMS {
13859 // Close before refusing: the walk is being abandoned, so the iterator's
13860 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
13861 // unrun and a locked resource unreleased.
13862 self.close_iterator_after_throw(&iterator)?;
13863 return Err(self.range_error("iterable is too long to collect"));
13864 }
13865 }
13866 }
13867
13868 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
13869 ///
13870 /// A native constructor calls this once it has validated its arguments, which is the
13871 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
13872 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
13873 /// never reached. The prototype comes from `new.target` when it is an object, and from
13874 /// `default_proto` otherwise.
13875 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
13876 let proto = self.ctor_prototype(default_proto)?;
13877 Ok(self.new_object(Some(proto)))
13878 }
13879
13880 /// An **array** whose prototype comes from `new.target`.
13881 ///
13882 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
13883 /// instance from `new.target.prototype`, and building a plain array instead made every
13884 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
13885 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
13886 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
13887 Ok(JsObject::array(self.heap, Some(proto), 0))
13888 }
13889
13890 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
13891 ///
13892 /// The `Option` form is for the constructors that build their instance in a helper which
13893 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
13894 /// from `await`'s internal promise, and only the first has a `new.target`.
13895 fn ctor_prototype_opt(
13896 &mut self,
13897 default_proto: Option<Gc<JsObject>>,
13898 ) -> JsResult<Option<Gc<JsObject>>> {
13899 // `active_new_target`: by the time a native constructor runs, `call_value` has
13900 // already consumed the parked value.
13901 let Some(target) = self
13902 .active_new_target
13903 .as_object()
13904 .cloned()
13905 .map(Value::Object)
13906 else {
13907 return Ok(default_proto);
13908 };
13909 let Some(target) = target.as_object().cloned() else {
13910 return Ok(default_proto);
13911 };
13912 match self.get_property(&target, "prototype")? {
13913 Some(Value::Object(proto)) => Ok(Some(proto)),
13914 _ => Ok(default_proto),
13915 }
13916 }
13917
13918 /// `new.target.prototype`, or `default_proto` when this is a plain call.
13919 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
13920 let Some(target) = self.active_new_target.as_object().cloned() else {
13921 return Ok(default_proto);
13922 };
13923 match self.get_property(&target, "prototype")? {
13924 Some(Value::Object(proto)) => Ok(proto),
13925 _ => Ok(default_proto),
13926 }
13927 }
13928
13929 /// `CreateDataPropertyOrThrow(O, key, value)`.
13930 ///
13931 /// A *definition*, not an assignment. The difference is visible the moment the target
13932 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
13933 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
13934 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
13935 /// refused (`configurable: false`).
13936 ///
13937 /// The fast path exists because this is called once per element by `map`, `filter`,
13938 /// `slice` and friends: a plain array with no custom element descriptors and a writable
13939 /// `length` can store straight into its element vector.
13940 pub fn create_data_property_or_throw(
13941 &mut self,
13942 object: &Gc<JsObject>,
13943 index: usize,
13944 value: Value,
13945 ) -> JsResult<()> {
13946 // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
13947 // an array (that is what `Array.isArray` must say), so the element fast path would
13948 // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
13949 // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
13950 // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
13951 // records the exact trap sequence.
13952 if object.proxy_state().is_none()
13953 && object.is_array()
13954 && object.elements_writable()
13955 && !object.has_element_descriptors()
13956 && object.is_extensible()
13957 && object.array_set(self.heap, index, value.clone())
13958 {
13959 return Ok(());
13960 }
13961 let key = PropertyKey::from(index.to_string());
13962 let property = Property {
13963 value: Some(value),
13964 writable: true,
13965 enumerable: true,
13966 configurable: true,
13967 ..Property::default()
13968 };
13969 // `CreateDataProperty` always asks for the default attributes, so it can only ever
13970 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
13971 // the rest. Checking here rather than inside `object_define_own_property` is
13972 // deliberate: that function receives a fully-populated `Property` and cannot tell
13973 // an omitted attribute from an explicit `false`, so the generic check it would need
13974 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
13975 // writable property (that cost eight `Object/defineProperty` tests).
13976 if object.proxy_state().is_none()
13977 && let Some(existing) = self.object_get_own_property(object, &key)?
13978 && !existing.configurable
13979 {
13980 return Err(self.type_error("cannot create the property"));
13981 }
13982 if self.object_define_own_property(object, &key, property)? {
13983 return Ok(());
13984 }
13985 Err(self.type_error("cannot create the property"))
13986 }
13987
13988 /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
13989 ///
13990 /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
13991 /// its callers have; this is the same operation for the named properties a built-in
13992 /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
13993 /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
13994 /// `Array.prototype` cannot see it — while `Set` would run that accessor.
13995 pub fn create_named_data_property_or_throw(
13996 &mut self,
13997 object: &Gc<JsObject>,
13998 key: &str,
13999 value: Value,
14000 ) -> JsResult<()> {
14001 let key = PropertyKey::from(key);
14002 let property = Property {
14003 value: Some(value),
14004 writable: true,
14005 enumerable: true,
14006 configurable: true,
14007 ..Property::default()
14008 };
14009 if object.proxy_state().is_none()
14010 && let Some(existing) = self.object_get_own_property(object, &key)?
14011 && !existing.configurable
14012 {
14013 return Err(self.type_error("cannot create the property"));
14014 }
14015 if self.object_define_own_property(object, &key, property)? {
14016 return Ok(());
14017 }
14018 Err(self.type_error("cannot create the property"))
14019 }
14020
14021 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
14022 ///
14023 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
14024 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
14025 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
14026 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
14027 /// run user code and both can throw.
14028 pub fn species_constructor(
14029 &mut self,
14030 object: &Gc<JsObject>,
14031 default: Value,
14032 ) -> JsResult<Value> {
14033 let Some(constructor) = self.get_property(object, "constructor")? else {
14034 return Ok(default);
14035 };
14036 let constructor = match constructor {
14037 Value::Undefined => return Ok(default),
14038 Value::Object(constructor) => constructor,
14039 _ => return Err(self.type_error("constructor is not an object")),
14040 };
14041 let key = self.realm.well_known_key(WellKnown::Species);
14042 let species = self.get_property_key(&constructor, &key)?;
14043 match species {
14044 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
14045 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
14046 Some(_) => Err(self.type_error("species is not a constructor")),
14047 }
14048 }
14049
14050 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
14051 ///
14052 /// The result is an array of `length` holes whose prototype comes from
14053 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
14054 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
14055 /// is why the `IsArray` check is the first step and not an optimisation.
14056 pub fn array_species_create(
14057 &mut self,
14058 original: &Value,
14059 length: usize,
14060 ) -> JsResult<Gc<JsObject>> {
14061 // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
14062 // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
14063 // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
14064 // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
14065 // `new_array_of_length` (`slice/create-non-array-invalid-len`).
14066 // `ArrayCreate(length)` is only reached when the result is a **plain array of this
14067 // realm** — the species may be a user function that ignores the length entirely, and
14068 // then `2**53 - 1` is not its problem
14069 // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
14070 // a short proxy and expects the copy loop to run).
14071 let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
14072 if length > ARRAY_CREATE_LIMIT {
14073 return Err(interp.range_error("invalid array length"));
14074 }
14075 Ok(interp.new_array_of_length(length))
14076 };
14077 let Some(object) = original.as_object().cloned() else {
14078 return default(self);
14079 };
14080 if !object.is_array() {
14081 return default(self);
14082 }
14083 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
14084 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
14085 let Some(constructor) = self.get_property(&object, "constructor")? else {
14086 return default(self);
14087 };
14088 let species = match constructor {
14089 Value::Undefined => return Ok(self.new_array_of_length(length)),
14090 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
14091 return default(self);
14092 }
14093 Value::Object(constructor) => {
14094 let key = self.realm.well_known_key(WellKnown::Species);
14095 match self.get_property_key(&constructor, &key)? {
14096 None | Some(Value::Undefined) | Some(Value::Null) => {
14097 return default(self);
14098 }
14099 Some(species) => species,
14100 }
14101 }
14102 // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
14103 // is a `TypeError`, not "the default". Treating it as the default made
14104 // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
14105 // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
14106 // `concat/create-ctor-non-object` are the same rule three times.
14107 _ => return Err(self.type_error("constructor is not an object")),
14108 };
14109 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
14110 // that is merely callable is the `create-species-non-ctor` case.
14111 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
14112 return Err(self.type_error("species is not a constructor"));
14113 }
14114 // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
14115 // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
14116 // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
14117 let created = self.construct(
14118 species.clone(),
14119 species,
14120 vec![crate::object::length_value(length)],
14121 )?;
14122 let Some(created) = created.as_object().cloned() else {
14123 return Err(self.type_error("species constructor did not answer an object"));
14124 };
14125 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
14126 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
14127 // object, and `create-species-with-non-writable-property` asserts exactly that.
14128 // The length is set for the array case; the generic case is the caller's
14129 // `Set(A, "length", …)`.
14130 if created.is_array() {
14131 created.array_set_length(self.heap, length);
14132 }
14133 Ok(created)
14134 }
14135
14136 /// Whether `object` is this realm's `%Array%`.
14137 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
14138 self.realm
14139 .array_constructor
14140 .as_ref()
14141 .is_some_and(|array| array.ptr_eq(object))
14142 }
14143
14144 /// A fresh `length`-hole array with the intrinsic prototype.
14145 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
14146 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
14147 array.array_set_length(self.heap, length);
14148 array
14149 }
14150
14151 /// Whether this call is a construction, i.e. `new.target` is defined.
14152 ///
14153 /// A native constructor receives `this = undefined` (it builds its own instance), so it
14154 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
14155 /// The native function currently executing, if any.
14156 pub fn current_native(&self) -> Option<Gc<JsObject>> {
14157 self.current_native.clone()
14158 }
14159
14160 /// Whether this call is a construction, i.e. `new.target` is defined.
14161 pub fn is_constructing(&self) -> bool {
14162 // `active_new_target`, not `pending_new_target`: the parked value is consumed by
14163 // `call_value` before a native runs, so by the time a constructor body asks, the
14164 // answer is only in the active slot.
14165 matches!(self.active_new_target, Value::Object(_))
14166 }
14167
14168 /// The `TypeError` a constructor too primitive to have a wrapper raises.
14169 ///
14170 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
14171 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
14172 /// happens inside the native function, which is why the trace carries an
14173 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
14174 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
14175 /// constructor`, and an unnamed one reports the leading space of `" is not a
14176 /// constructor"` because the reference formats the empty name as it is.
14177 ///
14178 /// It is also the answer for a `new.target` that cannot be named at all — not a
14179 /// function, or a throwing `name` getter — where the reference falls back to the bare
14180 /// `not a constructor`.
14181 pub fn not_a_constructor_error(&mut self) -> Signal {
14182 let target = self.active_new_target.clone();
14183 self.not_a_constructor_error_for(target)
14184 }
14185
14186 /// The same `TypeError` for an explicit target, for the callers that check
14187 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
14188 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
14189 let target = match target {
14190 Value::Object(target) if target.is_callable() => target,
14191 _ => return self.type_error("not a constructor"),
14192 };
14193 let name = match self.get_property(&target, "name") {
14194 Ok(Some(value)) => value.to_js_string(),
14195 _ => return self.type_error("not a constructor"),
14196 };
14197 self.type_error(format!("{name} is not a constructor"))
14198 }
14199
14200 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
14201 ///
14202 /// True whenever `new.target` is not the callee itself, or when it has no usable
14203 /// `prototype` — the cases where reading the property is observable at all.
14204 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
14205 match &self.active_new_target {
14206 Value::Object(target) => !target.ptr_eq(callee),
14207 Value::Undefined => false,
14208 _ => true,
14209 }
14210 }
14211
14212 /// The symbol key for one of the engine's own hidden slots.
14213 ///
14214 /// Cached on the realm, so every object of a kind shares one key and a slot can be
14215 /// read back by name.
14216 /// Whether any object on `object`'s **prototype chain** owns an array index.
14217 ///
14218 /// The one question the array methods' dense fast paths have to ask before touching the
14219 /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
14220 /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
14221 /// vector an unreliable answer. Walking the chain once per call is cheap because a
14222 /// prototype almost never holds an index.
14223 pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
14224 let mut current = object.proto();
14225 // Bounded, like every other prototype walk here: a proxy can answer a cycle.
14226 for _ in 0..10_000 {
14227 let Some(proto) = current else {
14228 return false;
14229 };
14230 if proto.has_indexed_own_property() {
14231 return true;
14232 }
14233 current = proto.proto();
14234 }
14235 false
14236 }
14237
14238 /// The hidden symbol a named internal slot is keyed by, created on first use.
14239 ///
14240 /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
14241 /// either keeping a table of its own.
14242 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
14243 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
14244 return PropertyKey::Symbol(symbol.clone());
14245 }
14246 let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
14247 self.realm
14248 .internal_slots
14249 .borrow_mut()
14250 .insert(name, Value::Symbol(symbol.clone()));
14251 PropertyKey::Symbol(symbol)
14252 }
14253
14254 /// Read a hidden slot, or `None` when the object has none of that name.
14255 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
14256 let slots = self.realm.internal_slots.borrow();
14257 let Value::Symbol(symbol) = slots.get(name)? else {
14258 return None;
14259 };
14260 object
14261 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
14262 .and_then(|property| property.value)
14263 }
14264
14265 /// Define a hidden slot.
14266 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
14267 let key = self.internal_slot(name);
14268 object.define_key(&key, Property::with_attributes(value, false, false));
14269 }
14270
14271 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
14272 ///
14273 /// The method is looked up on the value (through its prototype), called with no
14274 /// arguments, and its result becomes the iterator. A generator gets here through
14275 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
14276 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
14277 ///
14278 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
14279 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
14280 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
14281 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
14282 /// does, and a user-defined iterable works without a special case.
14283 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
14284 /// `Symbol.iterator`.
14285 ///
14286 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
14287 /// iterable is legal there, and each value it produces is simply already settled by
14288 /// the time the `await` around it runs.
14289 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14290 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
14291 let method = self.read_field_key(value, &async_key)?;
14292 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
14293 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
14294 // is *present but not callable* is a TypeError — it does not mean "try the other
14295 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
14296 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
14297 // guard is there to catch.
14298 let absent = matches!(method, Value::Undefined | Value::Null);
14299 if !absent {
14300 let Value::Object(object) = &method else {
14301 return Err(Signal::Throw(
14302 self.make_error("TypeError", "value is not iterable"),
14303 ));
14304 };
14305 if !object.is_callable() {
14306 return Err(Signal::Throw(
14307 self.make_error("TypeError", "value is not iterable"),
14308 ));
14309 }
14310 }
14311 if absent {
14312 return self.get_iterator(value);
14313 }
14314 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14315 if !matches!(iterator, Value::Object(_)) {
14316 return Err(Signal::Throw(
14317 self.make_error("TypeError", "iterator is not an object"),
14318 ));
14319 }
14320 // §7.4.2 `GetIteratorFromMethod` step 3.b: `GetIteratorDirect` reads `next` and
14321 // §7.4.1 requires it to be **callable** straight away — a throwing `return` must
14322 // not be reached, because the `TypeError` comes before any stepping
14323 // (`fromEntries/iterator-not-closed-for-uncallable-next`).
14324 let next = self.read_field(&iterator, "next")?;
14325 if !matches!(&next, Value::Object(function) if function.is_callable()) {
14326 return Err(Signal::Throw(
14327 self.make_error("TypeError", "iterator's next method is not callable"),
14328 ));
14329 }
14330 Ok(Iterator {
14331 object: iterator,
14332 next,
14333 })
14334 }
14335
14336 /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
14337 /// read — `@@iterator` is **not** consulted.
14338 ///
14339 /// The distinction is observable and test262 exercises it: a set-like object's `keys`
14340 /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
14341 /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
14342 /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
14343 /// refused it with "[object Object] is not iterable".
14344 pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
14345 if !matches!(value, Value::Object(_)) {
14346 return Err(self.type_error("iterator is not an object"));
14347 }
14348 let next = self.read_field(&value, "next")?;
14349 Ok(Iterator {
14350 object: value,
14351 next,
14352 })
14353 }
14354
14355 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14356 let key = self.realm.well_known_key(WellKnown::Iterator);
14357 let method = self.read_field_key(value, &key)?;
14358 let Value::Object(function) = &method else {
14359 return Err(Signal::Throw(self.make_error(
14360 "TypeError",
14361 &format!("{} is not iterable", value.to_js_string()),
14362 )));
14363 };
14364 if !function.is_callable() {
14365 return Err(Signal::Throw(self.make_error(
14366 "TypeError",
14367 &format!("{} is not iterable", value.to_js_string()),
14368 )));
14369 }
14370 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14371 // The spec requires an object here; a primitive iterator has no `next` to call
14372 // and would fail one step later with a confusing message.
14373 if !matches!(iterator, Value::Object(_)) {
14374 return Err(Signal::Throw(
14375 self.make_error("TypeError", "iterator is not an object"),
14376 ));
14377 }
14378 // `GetIteratorDirect` requires `next` to be **callable** right away, before any
14379 // stepping and therefore before any `return` can be reached
14380 // (`fromEntries/iterator-not-closed-for-uncallable-next`).
14381 let next = self.read_field(&iterator, "next")?;
14382 if !matches!(&next, Value::Object(function) if function.is_callable()) {
14383 return Err(Signal::Throw(
14384 self.make_error("TypeError", "iterator's next method is not callable"),
14385 ));
14386 }
14387 Ok(Iterator {
14388 object: iterator,
14389 next,
14390 })
14391 }
14392
14393 /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
14394 /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
14395 /// exception from `return` propagates normally instead of being swallowed. That is the
14396 /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
14397 /// because confusing them is exactly the bug both exist to avoid.
14398 pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
14399 let method = self.read_field(&iterator.object, "return")?;
14400 if matches!(method, Value::Undefined | Value::Null) {
14401 return Ok(());
14402 }
14403 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14404 return Err(self.type_error("iterator return is not a function"));
14405 }
14406 self.call_value(method, iterator.object.clone(), Vec::new())?;
14407 Ok(())
14408 }
14409
14410 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
14411 /// cannot replace it.
14412 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
14413 let method = self.read_field(&iterator.object, "return")?;
14414 if matches!(method, Value::Undefined | Value::Null) {
14415 return Ok(());
14416 }
14417 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14418 return Err(self.type_error("iterator return is not a function"));
14419 }
14420 self.call_value(method, iterator.object.clone(), Vec::new())?;
14421 Ok(())
14422 }
14423
14424 /// One step of an internal iterator: the value and whether it is exhausted.
14425 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
14426 // A real iterator (`next` is a function) answers with a result object.
14427 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
14428 let result =
14429 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
14430 let Some(result) = result.as_object().cloned() else {
14431 return Err(self.type_error("iterator result is not an object"));
14432 };
14433 let done = self
14434 .get_property(&result, "done")?
14435 .is_some_and(|value| value.to_boolean());
14436 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
14437 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
14438 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
14439 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
14440 // made an unrelated `value` getter observable after the loop was over.
14441 if done {
14442 return Ok((Value::Undefined, true));
14443 }
14444 let value = self
14445 .get_property(&result, "value")?
14446 .unwrap_or(Value::Undefined);
14447 return Ok((value, false));
14448 }
14449 // An iterator whose `next` is not callable is treated as exhausted, which is
14450 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
14451 // that are not iterable at all.
14452 Ok((Value::Undefined, true))
14453 }
14454
14455 /// `[...iterable]`: append everything the iterator yields, and answer the next
14456 /// index.
14457 ///
14458 /// This goes through the same iterator machinery `for-of` uses rather than copying
14459 /// an array's elements, because a spread source is any iterable: a string spreads
14460 /// into its characters and an array iterator spreads into its results. Handling
14461 /// only arrays made `[..."ab"]` come out empty with no error at all.
14462 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
14463 let Some(target) = array.as_object().cloned() else {
14464 return Ok(0);
14465 };
14466 let start = target.array_length().unwrap_or(0);
14467 let mut added = 0;
14468 let iterator = self.get_iterator(iterable)?;
14469 loop {
14470 let (value, done) = self.iterator_step(&iterator)?;
14471 if done {
14472 break;
14473 }
14474 target.array_set(self.heap, start + added, value);
14475 added += 1;
14476 }
14477 Ok((start + added) as i32)
14478 }
14479
14480 /// How an uncaught exception is reported.
14481 ///
14482 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
14483 /// with `ToString` — `js_std_dump_error` is three lines that end in
14484 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
14485 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
14486 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
14487 ///
14488 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
14489 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
14490 /// `toString`"; it does call it, but only for objects of a class it does not know how
14491 /// to walk, and never for errors, arrays or plain objects.
14492 ///
14493 /// A printer that fails must not take the reporter down with it, so that case falls
14494 /// back to the `ToString` rendering.
14495 pub fn describe_exception(&mut self, value: &Value) -> String {
14496 match crate::print::sprint(self, value) {
14497 Ok(text) => text,
14498 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
14499 }
14500 }
14501
14502 /// The file name of whatever is running, innermost frame first.
14503 ///
14504 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
14505 /// innermost frame's file name, without distinguishing a module body from a plain
14506 /// script. `import()` uses it as the base for a relative specifier, which is why
14507 /// `import('./x.js')` inside a script resolves next to the script and not next to the
14508 /// process's working directory.
14509 pub fn script_or_module_name(&self) -> Option<String> {
14510 self.script_or_module_name_at(0)
14511 }
14512
14513 /// [`Interp::script_or_module_name`] `level` frames further out.
14514 ///
14515 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
14516 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
14517 /// frame without a file name is skipped rather than counted, because a native call
14518 /// pushes no frame of its own and so cannot be a level.
14519 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
14520 self.frames
14521 .iter()
14522 .rev()
14523 .filter_map(|frame| frame.code.code.filename.clone())
14524 .nth(level)
14525 }
14526
14527 /// The current call stack, formatted the way `qjs` prints `error.stack`.
14528 ///
14529 /// One ` at name (file:line:col)` line per active frame, innermost first. The
14530 /// position is the one recorded for the instruction each frame is stopped on, which
14531 /// is why the compiler builds a pc-to-position table per function: without it a
14532 /// trace could only name the function, not the line inside it.
14533 ///
14534 /// A frame whose code has no positions prints just `(file)`, matching the
14535 /// reference's output for stripped bytecode.
14536 pub fn stack_trace(&self) -> String {
14537 self.stack_trace_skipping(0)
14538 }
14539
14540 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
14541 fn stack_trace_skipping(&self, skip: usize) -> String {
14542 // One ordered list, innermost first, so `skip` counts the same thing whether the
14543 // frames it leaves out are native or bytecode. Indices rather than references: a
14544 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
14545 let depth = self.frames.len();
14546 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
14547 // A native entered while `at` bytecode frames were live was called *from* the
14548 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
14549 // entered at the current depth are therefore innermost of all.
14550 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
14551 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
14552 if *at == wanted {
14553 order.push((true, index));
14554 }
14555 }
14556 };
14557 push_natives(&mut order, depth);
14558 for index in (0..depth).rev() {
14559 order.push((false, index));
14560 push_natives(&mut order, index);
14561 }
14562 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
14563 // barrier. Natives entered at exactly the barrier depth are the eval entry point
14564 // itself (`evalScript (native)`), and the reference leaves those out too.
14565 if let Some(barrier) = self.trace_barriers.last().copied() {
14566 order.retain(|(is_native, index)| match is_native {
14567 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
14568 false => *index >= barrier,
14569 });
14570 }
14571
14572 let mut out = String::new();
14573 for (is_native, index) in order.into_iter().skip(skip) {
14574 match is_native {
14575 true => {
14576 out.push_str(" at ");
14577 let (native, _) = &self.native_frames[index];
14578 let name = native
14579 .own_property("name")
14580 .and_then(|property| property.value)
14581 .map(|value| value.to_js_string())
14582 .unwrap_or_default();
14583 out.push_str(&name);
14584 out.push_str(" (native)\n");
14585 }
14586 false => {
14587 let frame = &self.frames[index];
14588 let code = &frame.code.code;
14589 let file = code.filename.as_deref().unwrap_or("<input>");
14590 // The name comes from the function *object*, not from the compiled code:
14591 // an anonymous function expression is named by the property it is stored
14592 // in (`{valueOf: function(){}}`), which only the object knows.
14593 let bound_name = match &frame.callee {
14594 Value::Object(object) => {
14595 object
14596 .own_property("name")
14597 .and_then(|property| match property.value {
14598 Some(Value::String(text)) if !text.wtf8().is_empty() => {
14599 Some(text.to_string_lossy().into_owned())
14600 }
14601 _ => None,
14602 })
14603 }
14604 _ => None,
14605 };
14606 // No callee object means the body was entered by the host, so the
14607 // name has to come from the compiled code. Two cases differ:
14608 //
14609 // * an *unnamed* function of any kind — the reference reads the
14610 // `name` property, finds it empty, and prints `<anonymous>`;
14611 // * a *module* body, which has no `name` property at all: the
14612 // reference builds that function object with `js_closure2` and
14613 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
14614 // so a trace reaching it also prints `<anonymous>` — while a
14615 // *script* body prints `<eval>`, its `name`.
14616 let unnamed = code.name.is_empty() || code.module.is_some();
14617 out.push_str(" at ");
14618 match bound_name.as_deref() {
14619 Some(name) => out.push_str(name),
14620 None if unnamed => out.push_str("<anonymous>"),
14621 None => out.push_str(&code.name),
14622 }
14623 match code.position_at(frame.at as u32) {
14624 Some((line, column)) => {
14625 out.push_str(&format!(" ({file}:{line}:{column})\n"));
14626 }
14627 None => out.push_str(&format!(" ({file})\n")),
14628 }
14629 }
14630 }
14631 }
14632 out
14633 }
14634
14635 /// Give an anonymous function the name of the property it is stored in.
14636 ///
14637 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
14638 /// enumerable and not configurable, and a function that already has a real name
14639 /// keeps it.
14640 ///
14641 /// "Already named" means a *non-empty* name: every function object is created with
14642 /// a `name` of `""` so the property exists on all of them, and treating that empty
14643 /// string as a name left every anonymous function nameless — which is how a stack
14644 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
14645 /// `SetFunctionName`, for a name that came from source text.
14646 fn set_function_name(&mut self, function: &Value, name: &str) {
14647 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
14648 }
14649
14650 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
14651 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
14652 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
14653 let Value::Object(object) = function else {
14654 return;
14655 };
14656 // `SetFunctionName` applies to *functions* and classes only, and only when they are
14657 // anonymous. Without the callability guard, `{value: someObject}` renamed
14658 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
14659 // on the right-hand side of a property. That is how a `zipKeyed` result object
14660 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
14661 // has no `NamedEvaluation` at all.
14662 if !object.is_callable() {
14663 return;
14664 }
14665 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
14666 && !existing.wtf8().is_empty()
14667 {
14668 return;
14669 }
14670 let text = self.string_wtf8(name.clone());
14671 object.define("name", Property::name_or_length(text));
14672 }
14673
14674 // -- global declarations -----------------------------------------------
14675
14676 /// Declare a global binding, creating its reference cell.
14677 /// Declare a `var` or function global, whose home is the global object.
14678 ///
14679 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
14680 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
14681 /// such as `print`, or a redeclaration — is left alone.
14682 pub fn declare_var_global(&mut self, name: &str) {
14683 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
14684 // global object is exactly the leak `typeof my_var === "undefined"` after
14685 // `eval("var my_var=2")` rules out.
14686 if let Some(scope) = self.eval_scope.as_mut() {
14687 scope.entry(name.to_string()).or_insert(Value::Undefined);
14688 return;
14689 }
14690 // A sloppy direct eval declares into its *caller's* variable environment. Doing
14691 // this on the global object instead made `eval("var c = 1")` inside a parameter
14692 // list overwrite a global `c`, and made two calls to the same function share one
14693 // binding.
14694 if let Some(cell) = self.declare_eval_local(name) {
14695 cell.set(Value::Undefined);
14696 return;
14697 }
14698 let global = self.realm.global.clone();
14699 if global.own_property(name).is_some() {
14700 return;
14701 }
14702 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
14703 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
14704 // whole point of that trick and what lets `Object.defineProperty` reshape it
14705 // afterwards. `eval_scope` is `Some` while an eval is running.
14706 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
14707 global.define(
14708 name,
14709 Property {
14710 value: Some(Value::Undefined),
14711 writable: true,
14712 enumerable: true,
14713 configurable: from_eval,
14714 ..Property::default()
14715 },
14716 );
14717 }
14718
14719 /// Declare a *lexical* global binding, which starts in its dead zone.
14720 ///
14721 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
14722 /// global object and is created when its initialiser runs.
14723 pub fn declare_global(&mut self, name: &str, is_const: bool) {
14724 if is_const {
14725 self.realm.lexical_consts.insert(name.to_string());
14726 }
14727 if !self.realm.globals.contains_key(name) {
14728 // `Uninitialized` rather than `Undefined`: the binding exists but is not
14729 // readable until its initialiser runs, and that is what `let x` before
14730 // `x = 1` has to observe.
14731 let cell = self.new_cell(Value::Uninitialized);
14732 self.realm.globals.insert(name.to_string(), cell);
14733 self.realm.declared.push(name.to_string());
14734 }
14735 }
14736}
14737
14738/// The bytecode and environment of a function object, if it is a bytecode function.
14739///
14740/// Extracted before a call so no borrow of the object is held across it.
14741fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
14742 function.with(|data| match &data.kind {
14743 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
14744 _ => None,
14745 })
14746}
14747
14748/// A native call target, extracted before the call so no borrow is held.
14749enum NativeCall {
14750 Native(NativeFn),
14751 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
14752 /// not hold that object's `RefCell` borrow.
14753 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
14754 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
14755 Bound {
14756 target: Value,
14757 this: Value,
14758 leading: Vec<Value>,
14759 },
14760 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
14761 Revoker(crate::object::ProxyRef),
14762 /// A promise's `resolve`.
14763 PromiseResolve(Gc<JsObject>),
14764 /// A promise's `reject`.
14765 PromiseReject(Gc<JsObject>),
14766 /// The executor `NewPromiseCapability(C)` hands a user constructor.
14767 CapabilityExecutor {
14768 state: Gc<JsObject>,
14769 },
14770 /// One leg of a `then` that settles through a user capability.
14771 ThenShim {
14772 handler: Option<Value>,
14773 resolve: Value,
14774 reject: Value,
14775 fulfilled: bool,
14776 },
14777 /// One continuation of an `await`.
14778 AwaitResume {
14779 coroutine: Gc<JsObject>,
14780 promise: Gc<JsObject>,
14781 kind: ResumeKind,
14782 },
14783 /// One element of a `Promise` combinator settling.
14784 CombinatorSettle {
14785 state: Gc<JsObject>,
14786 index: usize,
14787 fulfilled: bool,
14788 },
14789 /// One of `Promise.prototype.finally`'s two shims.
14790 FinallyShim {
14791 callback: Option<Value>,
14792 fulfilled: bool,
14793 constructor: Value,
14794 },
14795 /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
14796 ReturnValue(Value),
14797 /// A thunk that throws a fixed value, for `finally`'s `thrower`.
14798 ThrowValue(Value),
14799 /// Settle a promise with a fixed outcome.
14800 SettlePromise {
14801 promise: Gc<JsObject>,
14802 value: Value,
14803 rejected: bool,
14804 },
14805 /// Continue an async generator after its `await` settled.
14806 GeneratorResume {
14807 generator: Gc<JsObject>,
14808 promise: Gc<JsObject>,
14809 kind: ResumeKind,
14810 },
14811 /// Read a module namespace's binding out of its cell.
14812 ModuleBinding(Gc<Cell>),
14813 /// Finish a completed async generator's `return(v)` once `v` has settled.
14814 CompletedReturn {
14815 generator: Gc<JsObject>,
14816 promise: Gc<JsObject>,
14817 rejected: bool,
14818 },
14819 /// Answer a pending async-generator method with `{value, done}`.
14820 YieldResult {
14821 generator: Gc<JsObject>,
14822 promise: Gc<JsObject>,
14823 done: bool,
14824 },
14825 /// One step of `AsyncDisposableStack.disposeAsync`.
14826 DisposeStep {
14827 remaining: Gc<JsObject>,
14828 promise: Gc<JsObject>,
14829 error: Value,
14830 rejected: bool,
14831 },
14832}
14833
14834/// What a store does when the object refuses the write.
14835#[derive(Clone, Copy, PartialEq, Eq)]
14836pub enum DeleteFailure {
14837 /// Raise a `TypeError`, which is what strict mode and every built-in does.
14838 Throw,
14839 /// Ignore the write, which is what a sloppy-mode assignment does.
14840 Ignore,
14841}
14842
14843/// Whether `object` is a `Date` instance, by the class tag it carries.
14844///
14845/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
14846/// builtins module depending on the interpreter's conversion order.
14847fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
14848 interp
14849 .internal_get(object, "_class")
14850 .is_some_and(|value| value.to_js_string() == "Date")
14851}
14852
14853/// Which type `ToPrimitive` prefers when it converts an object.
14854#[derive(Clone, Copy, PartialEq, Eq)]
14855pub enum Hint {
14856 /// The default hint, which behaves like [`Hint::Number`].
14857 Default,
14858 /// `Number(obj)` and the arithmetic operators.
14859 Number,
14860 /// `String(obj)` and `ToPropertyKey`.
14861 String,
14862}
14863
14864/// Which table a binding slot indexes, for the messages that name it.
14865#[derive(Clone, Copy)]
14866enum VarSlot {
14867 Loc,
14868 Closure,
14869}
14870
14871/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
14872fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
14873 Ok(this)
14874}
14875
14876/// An internal iterator: the sequence plus a cursor.
14877pub(crate) struct Iterator {
14878 pub(crate) object: Value,
14879 pub(crate) next: Value,
14880}
14881
14882/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
14883/// and plain `a` for a method.
14884///
14885/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
14886/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
14887/// reads `at get a (file:1:2)`.
14888/// The same prefixing, for a name that may hold an unpaired surrogate.
14889fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
14890 let prefix = match flags & 3 {
14891 1 => "get ",
14892 2 => "set ",
14893 _ => return key.clone(),
14894 };
14895 let mut units: Vec<u16> = prefix.encode_utf16().collect();
14896 units.extend_from_slice(&key.to_units());
14897 crate::value::Wtf8::from_units(&units)
14898}
14899
14900fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
14901 match flags & 3 {
14902 1 => format!("get {key}"),
14903 2 => format!("set {key}"),
14904 _ => key.to_string(),
14905 }
14906}
14907
14908/// Define a method or accessor property, per the `define_method` flag byte.
14909///
14910/// The low two bits pick value/getter/setter and bit 2 marks the property
14911/// enumerable.
14912///
14913/// A getter and a setter arrive as two separate `define_method` instructions, and the
14914/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
14915/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
14916/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
14917/// `JS_DefineProperty`, which leaves the other half alone.
14918fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
14919 let enumerable = flags & 4 != 0;
14920 let kind = flags & 3;
14921 let existing = object.own_property_key(key);
14922 let property = match kind {
14923 1 => Property {
14924 getter: Some(function),
14925 // The setter half, if this literal already defined one.
14926 setter: existing
14927 .filter(Property::is_accessor)
14928 .and_then(|p| p.setter),
14929 enumerable,
14930 configurable: true,
14931 ..Property::default()
14932 },
14933 2 => Property {
14934 getter: existing
14935 .filter(Property::is_accessor)
14936 .and_then(|p| p.getter),
14937 setter: Some(function),
14938 enumerable,
14939 configurable: true,
14940 ..Property::default()
14941 },
14942 _ => Property {
14943 value: Some(function),
14944 writable: true,
14945 enumerable,
14946 configurable: true,
14947 ..Property::default()
14948 },
14949 };
14950 object.define_key(key, property);
14951}
14952
14953// ---------------------------------------------------------------------------
14954// Operand decoding
14955// ---------------------------------------------------------------------------
14956
14957/// How `print` renders a value: the reference's `JS_PrintValue`.
14958///
14959/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
14960/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
14961/// The format is reproduced closely because the test suite compares output text:
14962///
14963/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
14964/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
14965/// * a cycle prints `[circular N]` with `N` the stack index of the object;
14966/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
14967/// end print as `<N empty item(s)>`;
14968/// * a string is quoted inside a container but raw at the top level, which is why
14969/// `print("x")` and `print(["x"])` differ.
14970pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
14971 // A string argument is printed raw: `js_print` converts it with `ToString`
14972 // instead of dumping it, and the quoting only appears inside a container.
14973 if let Value::String(text) = value {
14974 return text.to_string_lossy().into_owned();
14975 }
14976 let mut printer = Printer {
14977 interp,
14978 out: String::new(),
14979 stack: Vec::new(),
14980 };
14981 printer.value(value, 0);
14982 printer.out
14983}
14984
14985/// The internal class name an object carries, when it has one.
14986fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
14987 interp
14988 .internal_get(object, "_class")
14989 .map(|value| value.to_js_string())
14990}
14991
14992/// A string property, looked up the way `GetProperty` does: own first, then the
14993/// prototype chain. Needed because the print formatter holds the interpreter
14994/// immutably and so cannot run getters.
14995fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
14996 let mut current = Some(object.clone());
14997 // Bounded, because a prototype cycle would otherwise loop forever.
14998 for _ in 0..100 {
14999 let node = current?;
15000 if let Some(property) = node.own_property(name)
15001 && let Some(value) = property.value
15002 {
15003 return Some(value.to_js_string());
15004 }
15005 current = node.with(|data| data.proto.clone());
15006 }
15007 None
15008}
15009
15010/// The `JS_PrintValue` state: output, and the objects currently being printed.
15011struct Printer<'a, 'rt> {
15012 /// Kept for the class-name lookups that typed arrays and `Date` will need.
15013 #[allow(dead_code)]
15014 interp: &'a Interp<'rt>,
15015 out: String,
15016 stack: Vec<Gc<JsObject>>,
15017}
15018
15019impl Printer<'_, '_> {
15020 /// Depth past which a container is summarised by its class name.
15021 const MAX_DEPTH: usize = 2;
15022
15023 fn value(&mut self, value: &Value, level: usize) {
15024 match value {
15025 Value::Undefined
15026 | Value::Uninitialized
15027 | Value::Hole
15028 | Value::CatchOffset(_)
15029 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
15030 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
15031 // The printer writes a bigint the way the language spells one, so a dump is
15032 // unambiguous about which kind of number it is showing.
15033 Value::BigInt(big) => {
15034 self.out.push_str(&big.to_decimal_string());
15035 self.out.push('n');
15036 }
15037 Value::Null => self.out.push_str("null"),
15038 Value::Bool(true) => self.out.push_str("true"),
15039 Value::Bool(false) => self.out.push_str("false"),
15040 Value::Int(number) => self.out.push_str(&number.to_string()),
15041 Value::Float(number) => {
15042 self.out
15043 .push_str(&crate::value::number_to_string_for_print(*number));
15044 }
15045 Value::String(text) => self.print_string(&text.to_string_lossy()),
15046 Value::Object(object) => self.object(object, level),
15047 }
15048 }
15049
15050 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
15051 // A cycle is reported rather than followed; the index is where the object
15052 // already sits in the print stack, which is what the reference shows.
15053 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
15054 self.out.push_str(&format!("[circular {index}]"));
15055 return;
15056 }
15057 if object.is_callable() {
15058 let name = object
15059 .own_property("name")
15060 .and_then(|property| property.value)
15061 .map(|value| value.to_js_string())
15062 .unwrap_or_default();
15063 if name.is_empty() {
15064 self.out.push_str("[Function (anonymous)]");
15065 } else {
15066 self.out.push_str(&format!("[Function {name}]"));
15067 }
15068 return;
15069 }
15070 if level >= Self::MAX_DEPTH {
15071 let class = if object.is_array() { "Array" } else { "Object" };
15072 self.out.push_str(&format!("[{class}]"));
15073 return;
15074 }
15075 // `Date` and `Error` print as themselves rather than as bags of properties:
15076 // the ISO string, and `Name: message` followed by the trace.
15077 if let Some(class) = class_of(self.interp, object) {
15078 if class == "Date" {
15079 self.date(object);
15080 return;
15081 }
15082 if class == "Error" {
15083 self.error(object);
15084 return;
15085 }
15086 }
15087 self.stack.push(object.clone());
15088 if object.is_array() {
15089 self.array(object, level);
15090 } else {
15091 self.plain_object(object, level);
15092 }
15093 self.stack.pop();
15094 }
15095
15096 /// A Date prints as its ISO string; an invalid one falls through to the plain
15097 /// object form, the way the reference falls back when `toISOString` throws.
15098 fn date(&mut self, object: &Gc<JsObject>) {
15099 let value = self
15100 .interp
15101 .internal_get(object, "_date_value")
15102 .map(|value| value.to_number());
15103 match value.and_then(crate::builtins::date::iso_string) {
15104 Some(text) => self.out.push_str(&text),
15105 None => self.plain_object(object, 0),
15106 }
15107 }
15108
15109 /// `Name: message`, then the trace with its trailing newline removed.
15110 fn error(&mut self, object: &Gc<JsObject>) {
15111 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
15112 self.out.push_str(&name);
15113 if let Some(message) = inherited(object, "message")
15114 && !message.is_empty()
15115 {
15116 self.out.push_str(": ");
15117 self.out.push_str(&message);
15118 }
15119 if let Some(stack) = inherited(object, "stack") {
15120 self.out.push('\n');
15121 self.out.push_str(stack.trim_end_matches('\n'));
15122 }
15123 }
15124
15125 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
15126 let elements = object.array_elements().unwrap_or_default();
15127 self.out.push_str("[ ");
15128 // An interior hole means the array is "sparse": the reference prints those
15129 // as `index: value` pairs and says nothing about the holes themselves, while
15130 // a hole run at the end becomes a single `<N empty items>` note.
15131 let last_present = elements
15132 .iter()
15133 .rposition(|value| !matches!(value, Value::Hole));
15134 let has_interior_hole = match last_present {
15135 Some(last) => elements[..last]
15136 .iter()
15137 .any(|value| matches!(value, Value::Hole)),
15138 None => false,
15139 };
15140 let mut first = true;
15141 if has_interior_hole {
15142 let mut index = 0;
15143 while index < elements.len() {
15144 let value = &elements[index];
15145 if matches!(value, Value::Hole) {
15146 index += 1;
15147 continue;
15148 }
15149 if !first {
15150 self.out.push_str(", ");
15151 }
15152 first = false;
15153 self.out.push_str(&format!("{index}: "));
15154 self.value(value, level + 1);
15155 index += 1;
15156 }
15157 } else {
15158 for (index, value) in elements.iter().enumerate() {
15159 if matches!(value, Value::Hole) {
15160 continue;
15161 }
15162 if !first {
15163 self.out.push_str(", ");
15164 }
15165 first = false;
15166 let _ = index;
15167 self.value(value, level + 1);
15168 }
15169 if let Some(last) = last_present {
15170 let trailing = elements.len() - last - 1;
15171 if trailing > 0 {
15172 if !first {
15173 self.out.push_str(", ");
15174 }
15175 self.out.push_str(&format!(
15176 "<{trailing} empty item{}>",
15177 if trailing > 1 { "s" } else { "" }
15178 ));
15179 }
15180 } else if !elements.is_empty() {
15181 let count = elements.len();
15182 self.out.push_str(&format!(
15183 "<{count} empty item{}>",
15184 if count > 1 { "s" } else { "" }
15185 ));
15186 }
15187 }
15188 self.out.push_str(" ]");
15189 }
15190
15191 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
15192 self.out.push_str("{ ");
15193 let mut first = true;
15194 for key in object.own_keys() {
15195 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
15196 continue;
15197 };
15198 if !property.enumerable {
15199 continue;
15200 }
15201 if !first {
15202 self.out.push_str(", ");
15203 }
15204 first = false;
15205 self.out
15206 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
15207 &key.to_string_lossy(),
15208 )));
15209 self.out.push_str(": ");
15210 // An accessor has no value to dump; the reference names the half that
15211 // exists instead of calling it.
15212 if property.is_accessor() {
15213 let text = match (property.getter.is_some(), property.setter.is_some()) {
15214 (true, true) => "[Getter/Setter]",
15215 (false, true) => "[Setter]",
15216 _ => "[Getter]",
15217 };
15218 self.out.push_str(text);
15219 } else {
15220 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
15221 }
15222 }
15223 self.out.push_str(" }");
15224 }
15225
15226 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
15227 fn print_string(&mut self, text: &str) {
15228 self.out.push('"');
15229 for character in text.chars() {
15230 match character {
15231 '"' => self.out.push_str("\\\""),
15232 '\\' => self.out.push_str("\\\\"),
15233 '\n' => self.out.push_str("\\n"),
15234 '\r' => self.out.push_str("\\r"),
15235 '\t' => self.out.push_str("\\t"),
15236 c if (c as u32) < 0x20 => {
15237 self.out.push_str(&format!("\\u{:04x}", c as u32));
15238 }
15239 c => self.out.push(c),
15240 }
15241 }
15242 self.out.push('"');
15243 }
15244}
15245
15246/// How `print` renders a value.
15247///
15248/// `ToString`, except that negative zero keeps its sign — the reference's host
15249/// printer does that while `String(-0)` is `"0"`.
15250pub fn display(value: &Value) -> String {
15251 match value {
15252 Value::Float(number) => crate::value::number_to_string_for_print(*number),
15253 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
15254 "undefined".to_string()
15255 }
15256 other => other.to_js_string(),
15257 }
15258}
15259
15260// ---------------------------------------------------------------------------
15261// Numeric operators
15262// ---------------------------------------------------------------------------
15263
15264/// `a + b` keeping the `Int` representation when it fits.
15265fn add_numbers(left: Value, right: Value) -> Value {
15266 match (&left, &right) {
15267 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
15268 Some(sum) => Value::Int(sum),
15269 None => Value::Float(*a as f64 + *b as f64),
15270 },
15271 _ => Value::Float(left.to_number() + right.to_number()),
15272 }
15273}
15274
15275/// The arithmetic operators other than `+`, which needs string concatenation.
15276fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15277 use Opcode::*;
15278 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
15279 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
15280 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
15281 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
15282 return Ok(match op {
15283 And => Value::Int(x & y),
15284 Or => Value::Int(x | y),
15285 Xor => Value::Int(x ^ y),
15286 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
15287 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
15288 Shr => match (*x as u32) >> ((*y as u32) & 31) {
15289 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
15290 shifted => Value::Float(shifted as f64),
15291 },
15292 Sub => match x.checked_sub(*y) {
15293 Some(value) => Value::Int(value),
15294 None => Value::Float(*x as f64 - *y as f64),
15295 },
15296 _ => return arithmetic_slow(op, left, right),
15297 });
15298 }
15299 arithmetic_slow(op, left, right)
15300}
15301
15302/// [`arithmetic`] for everything the integer fast path above does not take.
15303fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15304 use Opcode::*;
15305 let (a, b) = (left.to_number(), right.to_number());
15306 Ok(match op {
15307 Sub => match (&left, &right) {
15308 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
15309 Some(value) => Value::Int(value),
15310 None => Value::Float(a - b),
15311 },
15312 _ => Value::Float(a - b),
15313 },
15314 Mul => Value::Float(a * b),
15315 Div => Value::Float(a / b),
15316 Mod => Value::Float(js_mod(a, b)),
15317 Pow => Value::Float(a.powf(b)),
15318 And => Value::Int(left.to_int32() & right.to_int32()),
15319 Or => Value::Int(left.to_int32() | right.to_int32()),
15320 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
15321 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
15322 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
15323 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
15324 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
15325 // fits the small-integer representation stays an `Int`; the rest become a
15326 // float, which is how the reference keeps `n >>> 0` non-negative.
15327 Shr => {
15328 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
15329 match i32::try_from(shifted) {
15330 Ok(value) => Value::Int(value),
15331 Err(_) => Value::Float(shifted as f64),
15332 }
15333 }
15334 _ => Value::Float(a),
15335 })
15336}
15337
15338/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
15339///
15340/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
15341/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
15342/// slow path where the rules live.
15343fn is_number(value: &Value) -> bool {
15344 matches!(value, Value::Int(_) | Value::Float(_))
15345}
15346
15347/// The `Value::Bool` a comparison operator answers for `ordering`.
15348///
15349/// `None` is the unordered case — a `NaN` on either side — and every operator answers
15350/// false for it, including `<=` and `>=`.
15351fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
15352 use Opcode::*;
15353 let answer = match (op, ordering) {
15354 (_, None) => false,
15355 (Lt, Some(ordering)) => ordering.is_lt(),
15356 (Lte, Some(ordering)) => ordering.is_le(),
15357 (Gt, Some(ordering)) => ordering.is_gt(),
15358 (Gte, Some(ordering)) => ordering.is_ge(),
15359 _ => false,
15360 };
15361 Value::Bool(answer)
15362}
15363
15364/// `%`, which follows the sign of the dividend rather than Rust's.
15365fn js_mod(left: f64, right: f64) -> f64 {
15366 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
15367 return f64::NAN;
15368 }
15369 if right.is_infinite() {
15370 return left;
15371 }
15372 let remainder = left % right;
15373 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
15374 // the spec makes the sign match the dividend.
15375 if remainder == 0.0 {
15376 0.0f64.copysign(left)
15377 } else {
15378 remainder
15379 }
15380}
15381
15382fn negate(value: Value) -> Value {
15383 match value {
15384 Value::Int(0) => Value::Float(-0.0),
15385 Value::Int(i) => Value::Int(-i),
15386 other => Value::Float(-other.to_number()),
15387 }
15388}
15389
15390fn increment(value: Value) -> Value {
15391 match value {
15392 Value::Int(i) => match i.checked_add(1) {
15393 Some(next) => Value::Int(next),
15394 None => Value::Float(i as f64 + 1.0),
15395 },
15396 other => Value::Float(other.to_number() + 1.0),
15397 }
15398}
15399
15400fn decrement(value: Value) -> Value {
15401 match value {
15402 Value::Int(i) => match i.checked_sub(1) {
15403 Some(next) => Value::Int(next),
15404 None => Value::Float(i as f64 - 1.0),
15405 },
15406 other => Value::Float(other.to_number() - 1.0),
15407 }
15408}
15409
15410/// Compare a `BigInt` with an `f64` on their mathematical values.
15411///
15412/// Neither side is rounded to the other's precision: the number is split into its integer
15413/// part (compared as an exact bigint) and its fraction, which is what decides the answer
15414/// when the integer parts are equal. An infinite value is larger than every bigint.
15415fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
15416 use std::cmp::Ordering;
15417 if number.is_nan() {
15418 return None;
15419 }
15420 if number.is_infinite() {
15421 return Some(if number > 0.0 {
15422 Ordering::Less
15423 } else {
15424 Ordering::Greater
15425 });
15426 }
15427 let truncated = number.trunc();
15428 // A number wider than `i128` still has an exact integer part, but no bigint form we can
15429 // build cheaply; the sign of the difference is all that is needed, so compare against
15430 // the bigint's own magnitude instead.
15431 if truncated.abs() >= 1.7e38 {
15432 let big_as_f64 = big.to_f64();
15433 return big_as_f64.partial_cmp(&number);
15434 }
15435 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
15436 match big.cmp(&integer) {
15437 Ordering::Equal => {
15438 // Same integer part: the fraction decides, and a negative number's fraction is
15439 // below the integer (`-1.5` truncates to `-1`).
15440 if number > truncated {
15441 Some(Ordering::Less)
15442 } else if number < truncated {
15443 Some(Ordering::Greater)
15444 } else {
15445 Some(Ordering::Equal)
15446 }
15447 }
15448 other => Some(other),
15449 }
15450}
15451
15452/// `CanonicalNumericIndexString(argument)` (§7.1.21).
15453///
15454/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
15455/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
15456/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
15457/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
15458/// rather than treating it as `0`.
15459fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
15460 let PropertyKey::String(text) = key else {
15461 // A symbol is never an index.
15462 return None;
15463 };
15464 let text = text.to_string_lossy();
15465 if text == "-0" {
15466 return Some(-0.0);
15467 }
15468 let number: f64 = text.parse().ok()?;
15469 // The round-trip test *is* the definition: only the canonical spelling qualifies.
15470 // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
15471 // `"0.10"` does not.
15472 let rendered = Value::Float(number).to_js_string();
15473 (rendered == text).then_some(number)
15474}
15475
15476/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
15477///
15478/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
15479/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
15480/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
15481/// numeric and invalid, which is why they stop the prototype chain instead of falling
15482/// through it.
15483///
15484/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
15485/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
15486/// `in`, `delete` and `defineProperty` separately to make sure it does not.
15487fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
15488 numeric.is_finite()
15489 && numeric.fract() == 0.0
15490 && !(numeric == 0.0 && numeric.is_sign_negative())
15491 && numeric >= 0.0
15492 && object
15493 .typed_array_length()
15494 .is_some_and(|length| (numeric as usize) < length)
15495}
15496
15497/// `ArrayCreate`'s length bound, `2**32 - 1`.
15498///
15499/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
15500/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
15501/// through — can enforce it without depending on a builtin module.
15502const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;