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 /// `CreateAsyncFromSyncIterator`, as a script function.
223 ///
224 /// `GetIterator(obj, async)` has to wrap the synchronous iterator it falls back to, and
225 /// the wrapper's state machine is written in JavaScript (see
226 /// [`crate::builtins::async_from_sync`]). Holding the factory here is what lets the Rust
227 /// side call it without a global name a script could shadow.
228 pub async_from_sync: Option<Value>,
229 /// `Iterator.prototype`.
230 pub iterator_proto: Option<Gc<JsObject>>,
231 /// The `Iterator` constructor itself.
232 ///
233 /// `Iterator.prototype.constructor` is an accessor whose getter has to answer this
234 /// object, and the getter is a bare `fn` pointer that cannot capture it — so the only
235 /// place it can live is the realm.
236 pub iterator_ctor: Option<Gc<JsObject>>,
237 /// `%IteratorHelperPrototype%`, the prototype every lazy helper object gets.
238 ///
239 /// It sits between the helper and `Iterator.prototype`, which is how a helper is both
240 /// an `Iterator` and recognisable as a helper (`Object.prototype.toString` says
241 /// `[object Iterator Helper]`).
242 pub iterator_helper_proto: Option<Gc<JsObject>>,
243 /// `%WrapForValidIteratorPrototype%`, the prototype `Iterator.from` gives an iterable
244 /// that was not already an `Iterator`.
245 ///
246 /// Distinct from the helper prototype on purpose: it forwards `next` and `return`
247 /// untouched and does *not* override `@@toStringTag`, so
248 /// `Object.prototype.toString.call(Iterator.from(xs))` says `[object Iterator]`.
249 pub iterator_wrap_proto: Option<Gc<JsObject>>,
250 /// `%GeneratorFunction.prototype%` — what a generator function inherits from.
251 pub generator_function_proto: Option<Gc<JsObject>>,
252 /// `%AsyncFunction.prototype%`.
253 pub async_function_proto: Option<Gc<JsObject>>,
254 /// `%AsyncGeneratorFunction.prototype%`.
255 pub async_generator_function_proto: Option<Gc<JsObject>>,
256 /// One `%…IteratorPrototype%` per kind, keyed by its `@@toStringTag`.
257 ///
258 /// Cached because the *identity* is observable: `Object.getPrototypeOf([].values())`
259 /// has to equal `Object.getPrototypeOf([][Symbol.iterator]())`, and building a fresh
260 /// prototype per iterator made every array iterator's prototype distinct.
261 pub iterator_protos: std::collections::BTreeMap<String, Gc<JsObject>>,
262 /// `Symbol.iterator`, `Symbol.toPrimitive` and the other well-known symbols.
263 ///
264 /// Held as plain `Value`s rather than looked up on `Symbol` each time: the runtime
265 /// asks for them on every `for…of` and every `ToPrimitive`, and a realm field is
266 /// both faster and impossible to break from a script.
267 well_known_symbols: WellKnownSymbols,
268 /// The classes the host registered, and the prototype each one hands its instances.
269 pub host_classes: HostClasses,
270}
271
272/// The host's class registry: the `JS_NewClass` / `JS_SetClassProto` half of the class API.
273///
274/// One per realm, because a class id is only meaningful within the runtime that handed it
275/// out — the reference keeps one array per `JSRuntime` for the same reason, so a `Date` and
276/// a host class cannot collide.
277pub struct HostClasses {
278 /// The next id to hand out. Starts at 1: zero is `JS_INVALID_CLASS_ID`, and
279 /// `JS_GetOpaque(val, 0)` has to match nothing.
280 next_id: u32,
281 /// What each registered class does.
282 defs: std::collections::BTreeMap<ClassId, std::rc::Rc<ClassDef>>,
283 /// The prototype `JS_NewObjectClass` uses for each class, when the host installed one.
284 ///
285 /// A strong reference, so the prototype a host installed outlives every script
286 /// reference to it — which is what `JS_SetClassProto` promises.
287 protos: std::collections::BTreeMap<ClassId, Gc<JsObject>>,
288}
289
290impl HostClasses {
291 fn new() -> HostClasses {
292 HostClasses {
293 next_id: 1,
294 defs: std::collections::BTreeMap::new(),
295 protos: std::collections::BTreeMap::new(),
296 }
297 }
298
299 /// Allocate an id and register `def` under it (`JS_NewClassID` + `JS_NewClass`).
300 pub fn register(&mut self, def: ClassDef) -> ClassId {
301 let id = ClassId::from_raw(self.next_id);
302 self.next_id += 1;
303 self.defs.insert(id, std::rc::Rc::new(def));
304 id
305 }
306
307 /// Register `def` under an id the caller already has (`JS_NewClass`).
308 ///
309 /// The C API splits "get an id" from "register a class" because a module may be
310 /// initialised lazily; registering twice under one id replaces the definition, and an
311 /// object created under the old one keeps the old behaviour, since it carries its own
312 /// reference.
313 pub fn define(&mut self, id: ClassId, def: ClassDef) -> bool {
314 if !id.is_valid() {
315 return false;
316 }
317 // Keep the counter past any id handed out explicitly, so a later `register` cannot
318 // reuse one.
319 self.next_id = self.next_id.max(id.get() + 1);
320 self.defs.insert(id, std::rc::Rc::new(def));
321 true
322 }
323
324 /// What `id` was registered with.
325 pub fn def(&self, id: ClassId) -> Option<std::rc::Rc<ClassDef>> {
326 self.defs.get(&id).cloned()
327 }
328
329 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
330 pub fn set_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
331 self.protos.insert(id, proto);
332 }
333
334 /// The prototype installed for `id`, if the host installed one.
335 pub fn proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
336 self.protos.get(&id).cloned()
337 }
338
339 /// How many classes the host registered.
340 pub fn len(&self) -> usize {
341 self.defs.len()
342 }
343
344 /// Whether no class has been registered.
345 pub fn is_empty(&self) -> bool {
346 self.defs.is_empty()
347 }
348}
349
350impl Default for HostClasses {
351 fn default() -> HostClasses {
352 HostClasses::new()
353 }
354}
355
356/// One binding of the frame that called `eval`, so the eval'd code can read and
357/// write it by name.
358struct EvalBinding {
359 /// The name it was declared with.
360 name: String,
361 /// Which entry of [`Interp::frames`] owns it. An `eval` sees the whole chain of
362 /// calling frames, not only the innermost one: `function f(){ eval("a") }` inside
363 /// a function that declares `a` must find that `a`.
364 frame: usize,
365 /// Which table of that frame it lives in.
366 slot: EvalSlot,
367 /// The slot index within that table.
368 index: usize,
369}
370
371/// Which table of a frame an [`EvalBinding`] indexes.
372#[derive(Clone, Copy)]
373enum EvalSlot {
374 Arg,
375 Local,
376}
377
378/// One activation record.
379struct Frame {
380 /// The bytecode being run.
381 code: Gc<CompiledCode>,
382 /// The cells this closure captured.
383 env: Gc<ClosureEnv>,
384 /// The `this` binding.
385 this: Value,
386 /// Argument slots, sized to the declared parameter count.
387 args: Vec<Value>,
388 /// How many values the caller actually passed, which is what `arguments.length`
389 /// reports and what `...rest` slices from.
390 passed_count: usize,
391 /// The passed values, **only when they do not fit in [`Self::args`]**.
392 ///
393 /// `args` is sized to the declared parameters, so a call that passes no more than
394 /// that already holds every passed value in its first `passed_count` slots — copying
395 /// them here as well was two writes and a buffer per call, on the hottest path in
396 /// the engine (11.6% of `property:method-call` in `memmove`, plus the `Vec::resize`
397 /// beside it). `None` means exactly that, and [`Self::passed`] answers the slice of
398 /// `args`. A call with *extra* arguments — the ones `truncate` drops — has to keep
399 /// its own copy.
400 ///
401 /// Boxed to keep the field **8 bytes instead of 24**, which is the whole reason it is a
402 /// `Box<Vec<_>>` and not a `Vec<_>`: `Frame` is 216 bytes and `frames.push` copies the
403 /// whole struct on every call. Measured, 240 → 224 bytes is worth ~1% on `call:loop`
404 /// and `call:recursion`; the `u32` conversion that would have taken it to 216 was
405 /// worth *less than the casts it added* and was reverted. `Box<[Value]>` would be a
406 /// fat pointer (16 bytes), so it has to be `Box<Vec<_>>` — hence the silenced lint.
407 #[allow(clippy::box_collection)]
408 passed_overflow: Option<Box<Vec<Value>>>,
409 /// Local slots.
410 locals: Vec<Value>,
411 /// Reference cells for this frame's own captured bindings.
412 cells: Vec<Gc<Cell>>,
413 /// The operand stack.
414 stack: Vec<Value>,
415 /// Variables a direct `eval` has declared in this call; see [`LocalVars`].
416 local_vars: Option<Gc<LocalVars>>,
417
418 /// Index of the next instruction, not a byte offset.
419 ///
420 /// `u32` rather than `usize`: a jump target is already stored as `u32` (see
421 /// `Insn::a`), so this is the width the rest of the decoder assumes, and the field
422 /// was the only place that widened it. Two `usize` here cost 16 bytes of a 240-byte
423 /// `Frame`, and `frames.push` copies the whole struct on every call.
424 pc: usize,
425 /// Byte offset of the instruction being executed, which is what a stack trace
426 /// reports. `pc` has already moved past it by the time an instruction runs.
427 ///
428 /// Also `u32`, matching `Insn::offset`, which is where it is assigned from.
429 at: usize,
430 /// The callee, so a native builtin can tell which constructor it is.
431 callee: Value,
432 /// `new.target`: the constructor under `new`, `undefined` for a plain call.
433 new_target: Value,
434 /// What this frame costs against [`Interp::stack_limit`], in bytes.
435 ///
436 /// Cached rather than recomputed because it is charged on every call and a call is the
437 /// hottest thing in the interpreter.
438 cost: usize,
439 /// [`Interp::stack_used`] before this frame was pushed.
440 ///
441 /// Stored per frame so that *popping* needs no bookkeeping at all: the total is always
442 /// `top.stack_base + top.cost`, so a `pop`, a `truncate` or an unwinding loop cannot
443 /// leave the counter wrong. There are eight places that drop frames; one subtraction
444 /// forgotten in any of them would leak budget until the depth limit moved.
445 stack_base: usize,
446 /// Whether this frame's body ended in a `tail_call`.
447 ///
448 /// The reference's `tail_call` is not a frame-reusing tail call: it calls the callee
449 /// with its own frame just like `call` does and only skips storing the result
450 /// (`goto done` in `quickjs.c`). So a runaway tail recursion still hits
451 /// `InternalError: stack overflow` there, and the flag reproduces that: the frame is
452 /// pushed as usual, and this marker makes its return value the *caller's* return
453 /// value without running the instructions after the call.
454 tail: bool,
455}
456
457impl Frame {
458 /// Read a local slot, taking the frame as `self`.
459 ///
460 /// This lives on `Frame` rather than only on `Interp` so that an instruction that reads
461 /// **two** slots (`LtLocArgJump` reads the counter and the bound) pays for
462 /// `frames.last()` once instead of twice. That lookup is a length load, an `imul` by
463 /// `size_of::<Frame>()` and a panic branch; halving it in one fused arm measured 7.5%
464 /// on `dispatch:empty-loop`, which is the arm that makes up that whole loop.
465 #[inline]
466 fn read_loc(&self, slot: usize) -> Value {
467 let cell = self.code.loc_cell.get(slot).copied().unwrap_or(-1);
468 if cell == -1 {
469 return self.locals.get(slot).cloned().unwrap_or(Value::Undefined);
470 }
471 match self.cells.get(cell as usize) {
472 Some(cell) => cell.get(),
473 None => Value::Undefined,
474 }
475 }
476
477 /// [`Self::read_loc`] for an argument slot.
478 #[inline]
479 fn read_arg(&self, slot: usize) -> Value {
480 let cell = self.code.arg_cell.get(slot).copied().unwrap_or(-1);
481 if cell == -1 {
482 return self.args.get(slot).cloned().unwrap_or(Value::Undefined);
483 }
484 match self.cells.get(cell as usize) {
485 Some(cell) => cell.get(),
486 None => Value::Undefined,
487 }
488 }
489
490 /// The values the caller actually passed, which is what `arguments` exposes.
491 ///
492 /// Borrowed from `args` in the common case; see [`Self::passed_overflow`].
493 fn passed(&self) -> &[Value] {
494 match &self.passed_overflow {
495 Some(values) => values,
496 None => &self.args[..self.passed_count],
497 }
498 }
499
500 /// The decoded instructions of the function this frame runs.
501 ///
502 /// A method rather than `frame.code.insns` at the call site so that the borrow is
503 /// obviously of the frame — the dispatch loop holds one across a `get`.
504 fn insns(&self) -> &[crate::insn::Insn] {
505 &self.code.insns
506 }
507}
508
509impl js_gc::Trace for Frame {
510 fn trace(&self, tracer: &mut js_gc::Tracer) {
511 self.code.trace(tracer);
512 self.env.trace(tracer);
513 self.this.trace(tracer);
514 for value in &self.args {
515 value.trace(tracer);
516 }
517 for value in self.passed() {
518 value.trace(tracer);
519 }
520 for value in &self.locals {
521 value.trace(tracer);
522 }
523 for cell in &self.cells {
524 cell.trace(tracer);
525 }
526 if let Some(local_vars) = &self.local_vars {
527 tracer.visit(local_vars);
528 }
529 for value in &self.stack {
530 value.trace(tracer);
531 }
532 self.callee.trace(tracer);
533 self.new_target.trace(tracer);
534 }
535}
536
537/// The magic number `next()` resumes a `yield` with. `0` is falsy, which is the value the
538/// emitted `if_false` treats as "keep going".
539/// How many finished frames' value buffers are kept for reuse.
540const RECYCLE_SLOTS: usize = 8;
541
542/// The largest buffer worth keeping. See [`Interp::free_values`].
543const RECYCLE_MAX_CAPACITY: usize = 4096;
544
545const RESUME_NEXT: i32 = 0;
546/// The magic number `return()` resumes a `yield` with; any non-zero value makes the
547/// generator fall into its `return_async`.
548const RESUME_RETURN: i32 = 1;
549/// The magic number `throw()` resumes a `yield*` with. Unlike `return`, a throw cannot be
550/// folded into the same branch: the compiled delegation has to tell `2` apart to know it
551/// must forward the exception into the inner iterator rather than finish.
552const RESUME_THROW: i32 = 2;
553
554/// One microtask.
555///
556/// The queue holds *data* rather than closures because its contents are GC values: a
557/// closure would be invisible to the collector, and a pending reaction is exactly the
558/// kind of thing that must keep its handlers and its promise alive.
559pub enum Job {
560 /// A `then` reaction about to run.
561 Reaction {
562 /// The `onFulfilled`/`onRejected` to call, or `None` for the pass-through case.
563 handler: Option<Value>,
564 /// The value or reason to call it with.
565 argument: Value,
566 /// Whether the source promise rejected, which decides the pass-through kind.
567 rejected: bool,
568 /// The promise the answer settles.
569 promise: Gc<JsObject>,
570 },
571 /// Adopt a thenable: call its `then` with the adopting promise's resolve/reject.
572 Thenable {
573 /// The `then` that was found on the value.
574 then: Value,
575 /// The thenable itself, which becomes `then`'s `this`.
576 value: Value,
577 /// The promise being resolved.
578 promise: Gc<JsObject>,
579 },
580 /// A pending `import(specifier)`.
581 Import {
582 /// The specifier, already converted to a string.
583 specifier: String,
584 /// The module that asked, which the specifier resolves against.
585 referrer: String,
586 /// The promise `import()` handed back.
587 promise: Gc<JsObject>,
588 },
589 /// An async generator resuming after the value it awaited settled.
590 GeneratorResume {
591 /// The async generator to continue.
592 generator: Gc<JsObject>,
593 /// The promise the pending method returned.
594 promise: Gc<JsObject>,
595 /// Whether this delivers the value or raises the reason.
596 kind: ResumeKind,
597 /// The settled value, or the rejection reason.
598 value: Value,
599 },
600 /// An async function resuming after the value it awaited settled.
601 Resume {
602 /// The body, parked in a coroutine.
603 coroutine: Gc<JsObject>,
604 /// The promise the async function handed its caller.
605 promise: Gc<JsObject>,
606 /// Whether this resumption delivers a value or raises one.
607 kind: ResumeKind,
608 /// The settled value, or the rejection reason.
609 value: Value,
610 },
611}
612
613/// One macro-task: work the event loop owes the script but has not run yet.
614///
615/// The microtask queue ([`Job`]) is different: those run before the host regains control.
616/// A timer is the opposite — it is explicitly "later", and only an event loop can honour
617/// that. Keeping it here rather than in the host is what lets `run_one_turn` be pure
618/// logic: the engine decides *what* is due, the host decides *how to wait*.
619///
620/// The callback is a [`Value`], so the [`Gc`] inside it keeps the function alive by
621/// reference counting even though nothing else references it — the same rule the `HostFn`
622/// documentation states from the other side (a host closure must not hold a `Gc`, so the
623/// `Gc` lives here instead).
624pub enum Task {
625 /// A `setTimeout` that is due at `due_at`.
626 ///
627 /// There is no `setInterval` variant because the reference has no `os.setInterval` at
628 /// all: `quickjs-libc.c` defines only `setTimeout` and `clearTimeout`, and
629 /// `typeof os.setInterval` is `"undefined"` under `qjs --std`. A repeat field here
630 /// would give this engine a timer the reference cannot produce, with nothing to
631 /// compare it against.
632 Timer {
633 /// The id `setTimeout` returned, for `clearTimeout`.
634 id: i32,
635 /// What to call when it fires.
636 callback: Value,
637 /// When it becomes runnable, as a monotonic instant.
638 due_at: std::time::Instant,
639 },
640}
641
642/// A descriptor the host has to poll, and which directions have a handler.
643///
644/// The engine cannot poll for itself: `quickjs-pure` has no dependencies and no platform
645/// knowledge, and `poll(2)` is neither. So the loop hands this list to the host, the host
646/// blocks on it, and the host reports back through [`Interp::fire_fd`].
647#[derive(Debug, Clone, Copy, PartialEq, Eq)]
648pub struct FdInterest {
649 /// The descriptor to watch.
650 pub fd: i32,
651 /// Whether `os.setReadHandler` registered a callback.
652 pub read: bool,
653 /// Whether `os.setWriteHandler` registered a callback.
654 pub write: bool,
655}
656
657/// The callbacks registered for one descriptor, per direction.
658#[derive(Default)]
659pub(crate) struct FdHandlers {
660 /// `os.setReadHandler`'s callback.
661 pub read: Option<Value>,
662 /// `os.setWriteHandler`'s callback.
663 pub write: Option<Value>,
664}
665
666/// The file name `eval` reports, which the reference does not inherit from the caller.
667///
668/// Kept distinct from [`EVAL_SCRIPT_FILE`] because the two are named separately in the
669/// reference and the names show up in stack traces.
670/// The description of the private symbol a class brand is made from.
671///
672/// The reference builds it from `JS_ATOM_brand`, so it would print as `Symbol(brand)` — in a
673/// place no script can reach, since no expression can name a private symbol.
674const BRAND_DESCRIPTION: &str = "brand";
675
676/// One validated property lookup.
677///
678/// Covers both own-property hits and prototype hits. The second kind was deliberately left
679/// uncached at first ("a prototype hit depends on more than the object and the name"), and
680/// that is true — but it is checkable. What it costs is `array:push`: `a.push` lives on
681/// `Array.prototype`, so `get_field2 push` walked the chain and string-compared ~40 property
682/// names on every iteration (measured: 100 ns per call over an empty loop).
683pub struct FieldCache {
684 /// The name, so two different properties of one object do not collide.
685 key: PropertyKey,
686 /// Where the value was found, relative to the chain below.
687 index: usize,
688 /// Which level of [`Self::chain`] held it: 0 is the receiver, 1 its prototype, and so on.
689 level: u8,
690 /// The receiver and every prototype down to (and including) the level that answered,
691 /// each with the length of its property table at the time.
692 ///
693 /// That length is the whole guard, and it is sufficient for the ways the answer can
694 /// change without a lookup: adding or deleting any property moves it, and a
695 /// same-length rewrite is caught by `cached_data_property` re-checking the key and
696 /// refusing an accessor. Storing the *whole* chain — not just the object that answered
697 /// — is what catches a property appearing on an *intermediate* prototype and shadowing
698 /// the one that was cached.
699 ///
700 /// Fixed size because a chain longer than this (a deep `extends` hierarchy) simply does
701 /// not get cached: a miss costs a walk, which is what the uncached code did anyway.
702 chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN],
703}
704
705/// How many links of a prototype chain a [`FieldCache`] remembers.
706///
707/// Three covers the shape that matters — receiver → `Array.prototype` → `Object.prototype`
708/// — with one to spare. Raising it costs 16 bytes per cache slot (4096 slots), so it stays
709/// at three.
710const MAX_CACHED_CHAIN: usize = 3;
711
712/// A remembered global-variable lookup.
713///
714/// A `var` global is an ordinary property of the global object, so reading one walks the
715/// prototype chain — and `fib`'s recursive call is `get_var fib`, which made that walk 20%
716/// of `call:recursion` (`lookup_key` 19% under it). The binding cannot move: the name is
717/// fixed by the bytecode, and the slot in the object's table only changes if the global
718/// object is mutated, which the index-and-name check below catches.
719pub struct GlobalCache {
720 /// The global object the lookup was resolved on, weakly.
721 object: js_gc::WeakGc<JsObject>,
722 /// Index of the data property in the global object's table.
723 index: usize,
724}
725
726/// How many global lookups are remembered. Direct-mapped, like [`FieldCache`].
727const GLOBAL_CACHE_SLOTS: usize = 1024;
728
729/// How many property lookups are remembered.
730///
731/// Direct-mapped, so a collision costs a miss and nothing else. 4096 entries is 4096 × (a
732/// weak handle, a property key and a `usize`) ≈ 200 KB, which buys a hit rate high enough
733/// that `property:monomorphic` is dominated by the loop around the lookup rather than by the
734/// lookup itself. Making it bigger stops helping: the working set of a real program's
735/// property sites is bounded by its code size.
736const FIELD_CACHE_SLOTS: usize = 4096;
737
738/// How much the heap may grow past the last `out of memory` before saying it again.
739///
740/// The point is that the *handler* has to be able to run: `catch (e) { print(e.message) }`
741/// allocates a few hundred bytes, and re-throwing on the very next instruction made the
742/// error unobservable from script — a `catch` that cannot catch is worse than no limit,
743/// because it looks like it works. The reference gets this for free: it fails inside
744/// `js_malloc`, and its printing path happens not to allocate.
745///
746/// 64 KiB is chosen to be far below any limit worth setting (so a script that keeps
747/// allocating is stopped within a rounding error of the limit) and far above what a
748/// handler needs.
749const OOM_HYSTERESIS: usize = 64 * 1024;
750
751/// The stack budget when the host sets none: the reference's `JS_DEFAULT_STACK_SIZE`.
752pub const DEFAULT_STACK_SIZE: usize = 1024 * 1024;
753
754/// How many instructions run between polls of [`Interp::interrupt`].
755///
756/// The reference's `JS_INTERRUPT_COUNTER_INIT`, so a handler that counts polls sees the same
757/// order of magnitude on both implementations — which is what lets a C driver compare its
758/// output byte for byte (see `scripts/m15-capi.sh --embed`).
759pub const INTERRUPT_POLL_INTERVAL: u32 = 10_000;
760
761/// The frame-count ceiling that backs up [`DEFAULT_STACK_SIZE`].
762///
763/// Chosen so that the byte budget is what actually decides for every ordinary
764/// `--stack-size` (a frame costs a few hundred bytes, so 1 MB buys a few thousand frames and
765/// 32 MB buys tens of thousands), while a deliberately huge budget still cannot allocate
766/// millions of frames.
767pub const MAX_FRAMES: usize = 200_000;
768
769const EVAL_FILE: &str = "<input>";
770
771/// The file name `std.evalScript` reports.
772const EVAL_SCRIPT_FILE: &str = "<evalScript>";
773
774/// A delay in milliseconds as a `Duration`, clamped to something `Instant` accepts.
775///
776/// Negative and `NaN` both mean "as soon as possible": the reference runs the delay through
777/// `JS_ToInt64`, so `setTimeout(f, NaN)` fires immediately rather than being rejected.
778fn clamp_delay(delay_ms: f64) -> std::time::Duration {
779 // `is_nan()` spelled out rather than `!(x > 0.0)`: the latter is a negated comparison
780 // on a float, which reads as a typo even when it is deliberate. Both NaN and a
781 // non-positive delay mean "due now".
782 if delay_ms.is_nan() || delay_ms <= 0.0 {
783 return std::time::Duration::ZERO;
784 }
785 std::time::Duration::from_secs_f64(delay_ms / 1000.0)
786}
787
788impl js_gc::Trace for Task {
789 fn trace(&self, tracer: &mut js_gc::Tracer) {
790 let Task::Timer { callback, .. } = self;
791 callback.trace(tracer);
792 }
793}
794
795/// What one turn of the event loop did, so the caller cannot spin by accident.
796///
797/// A bare `bool` invites the mistake of looping on it without sleeping, which burns a
798/// core until the timer is due. Naming the three cases makes the wait explicit.
799#[derive(Debug, Clone, Copy, PartialEq, Eq)]
800pub enum Turn {
801 /// Something ran. Call again immediately — there may be more ready work.
802 Ran,
803 /// Nothing is runnable, but descriptors are registered: the host must poll
804 /// [`Interp::pending_fds`] for at most this long, then report readiness with
805 /// [`Interp::fire_fd`].
806 ///
807 /// A separate variant from [`Turn::Wait`] on purpose. Sleeping instead of polling is
808 /// the failure this project treats as worst — a handler that silently never fires —
809 /// so the two cannot be confused by accident.
810 Poll(std::time::Duration),
811 /// Nothing is runnable yet, but something is pending. Block at most this long, then
812 /// call again.
813 Wait(std::time::Duration),
814 /// Nothing is pending at all: the loop is done.
815 Done,
816}
817
818impl js_gc::Trace for Job {
819 fn trace(&self, tracer: &mut js_gc::Tracer) {
820 match self {
821 Job::Reaction {
822 handler,
823 argument,
824 promise,
825 ..
826 } => {
827 if let Some(handler) = handler {
828 handler.trace(tracer);
829 }
830 argument.trace(tracer);
831 tracer.visit(promise);
832 }
833 Job::Thenable {
834 then,
835 value,
836 promise,
837 } => {
838 then.trace(tracer);
839 value.trace(tracer);
840 tracer.visit(promise);
841 }
842 Job::Resume {
843 coroutine,
844 promise,
845 value,
846 ..
847 } => {
848 tracer.visit(coroutine);
849 tracer.visit(promise);
850 value.trace(tracer);
851 }
852 Job::Import { promise, .. } => tracer.visit(promise),
853 Job::GeneratorResume {
854 generator,
855 promise,
856 value,
857 ..
858 } => {
859 tracer.visit(generator);
860 tracer.visit(promise);
861 value.trace(tracer);
862 }
863 }
864 }
865}
866
867/// Which of `%GeneratorPrototype%`'s three methods resumed a generator.
868#[derive(Debug, Clone, Copy, PartialEq, Eq)]
869pub enum ResumeKind {
870 /// The generator was just created and is being run to its first suspension.
871 Start,
872 /// `next(v)`.
873 Next,
874 /// `return(v)`.
875 Return,
876 /// `throw(e)`.
877 Throw,
878}
879
880/// A generator object's saved execution.
881///
882/// The reference keeps this as a `JSAsyncFunctionState` hanging off the object; the shape
883/// here is the same, with a whole [`Frame`] standing in for its `JSStackFrame` plus the
884/// separately allocated buffers.
885pub struct GeneratorState {
886 /// The detached frame, or `None` once the generator has finished or while it runs.
887 frame: Option<Frame>,
888 /// How far it got.
889 phase: GeneratorPhase,
890 /// Whether the last suspension was an `await` rather than a `yield`.
891 ///
892 /// The two resume with *different stack shapes*: a `yield` is re-entered with the
893 /// value and a magic number, because the emitted code branches on which method
894 /// resumed it, while an `await` simply continues with its value. Getting this wrong
895 /// leaves an extra value on the operand stack that the next instruction then
896 /// consumes — a wrong answer rather than a crash.
897 parked_on_await: bool,
898 /// Whether the last suspension was a `yield*` rather than a plain `yield`.
899 ///
900 /// It decides what a `throw()` from the caller means. At a plain `yield` the exception
901 /// is raised *at* the yield, so the body's own `try`/`catch` sees it. At a `yield*` it
902 /// has to be forwarded into the inner iterator's `throw` method instead — which is the
903 /// `rethrow` branch the compiled delegation emits — because that is the whole point of
904 /// delegating. Tracking it as part of the phase, the way the reference splits
905 /// `SUSPENDED_YIELD` from `SUSPENDED_YIELD_STAR`, is what makes the two cases
906 /// distinguishable; without it `try { yield* xs } catch (e)` swallowed the caller's
907 /// exception and never reached `xs.throw`.
908 parked_on_yield_star: bool,
909 /// Pending `next`/`return`/`throw` calls, oldest first.
910 ///
911 /// An async generator is a queue, not a re-entrant function: `it.next(); it.next(v)`
912 /// called back to back must answer in that order, with the second call's value
913 /// arriving at the *second* `yield`. Running each call straight into the body — which
914 /// is what this engine did before — delivered the last queued value to whichever
915 /// suspension happened to be live, so `var a = yield 1; var b = yield a` saw
916 /// `a === b ===` the final argument.
917 ///
918 /// The front entry is the one being served; it stays there (with `async_busy` set)
919 /// until its promise settles, because an `await` inside the body is a suspension of
920 /// the *driver*, not the end of the request.
921 requests: std::collections::VecDeque<AsyncRequest>,
922 /// Whether the front request is in flight.
923 async_busy: bool,
924 /// Whether this came from an `async function*`.
925 ///
926 /// A sync generator and an async one share `ObjectKind::Generator`, so without this
927 /// flag `%AsyncGeneratorPrototype%.next` happily ran a sync generator's body:
928 /// `AsyncGeneratorValidate` has to tell them apart
929 /// (`AsyncGeneratorPrototype/next/this-val-not-async-generator.js`).
930 pub is_async: bool,
931}
932
933/// How one async-generator request ended.
934enum AsyncOutcome {
935 /// The method answered this `{value, done}`.
936 Value(Value),
937 /// The body threw.
938 Error(Value),
939}
940
941/// One queued `next`/`return`/`throw` on an async generator: the reference's
942/// `JSAsyncGeneratorRequest`.
943pub struct AsyncRequest {
944 /// Which method was called.
945 kind: ResumeKind,
946 /// Its argument.
947 value: Value,
948 /// The promise the method answered.
949 promise: Gc<JsObject>,
950}
951
952/// Which of §27.5.3.3's states a generator is in.
953#[derive(Debug, Clone, Copy, PartialEq, Eq)]
954enum GeneratorPhase {
955 /// Created, `initial_yield` reached, body not entered.
956 SuspendedStart,
957 /// Parked at a `yield`.
958 SuspendedYield,
959 /// Between a resume and its suspension, which a re-entrant `next()` must refuse.
960 Executing,
961 /// Finished; the frame is gone.
962 Completed,
963}
964
965impl js_gc::Trace for GeneratorState {
966 fn trace(&self, tracer: &mut js_gc::Tracer) {
967 if let Some(frame) = &self.frame {
968 frame.trace(tracer);
969 }
970 for request in &self.requests {
971 request.value.trace(tracer);
972 tracer.visit(&request.promise);
973 }
974 }
975}
976
977/// The realm's well-known symbols, indexed by the order [`builtins::symbol`] creates
978/// them in.
979///
980/// Each is a field rather than a map entry because the runtime reads them on hot paths
981/// (`for…of`, `ToPrimitive`) and because a missing one would be a bug, not a lookup
982/// failure — reaching a default here means the builtin did not install, and every
983/// accessor panics rather than silently answering `undefined`.
984///
985/// [`builtins::symbol`]: crate::builtins::symbol
986#[derive(Default)]
987pub struct WellKnownSymbols {
988 /// The symbol values, positionally. Empty until `Symbol` installs.
989 symbols: Vec<Value>,
990}
991
992/// Which well-known symbol a caller wants.
993///
994/// A typed accessor beats passing a name around: a typo is a compile error rather than
995/// an `undefined` key that quietly matches nothing.
996#[derive(Debug, Clone, Copy, PartialEq, Eq)]
997pub enum WellKnown {
998 /// `Symbol.toPrimitive`.
999 ToPrimitive,
1000 /// `Symbol.iterator`.
1001 Iterator,
1002 /// `Symbol.match`.
1003 Match,
1004 /// `Symbol.matchAll`.
1005 MatchAll,
1006 /// `Symbol.replace`.
1007 Replace,
1008 /// `Symbol.search`.
1009 Search,
1010 /// `Symbol.split`.
1011 Split,
1012 /// `Symbol.toStringTag`.
1013 ToStringTag,
1014 /// `Symbol.isConcatSpreadable`.
1015 IsConcatSpreadable,
1016 /// `Symbol.hasInstance`.
1017 HasInstance,
1018 /// `Symbol.species`.
1019 Species,
1020 /// `Symbol.unscopables`.
1021 Unscopables,
1022 /// `Symbol.asyncIterator`.
1023 AsyncIterator,
1024 /// `Symbol.dispose` — the well-known name of a disposable resource's disposer.
1025 Disposable,
1026 /// `Symbol.asyncDispose` — the awaited form.
1027 AsyncDisposable,
1028}
1029
1030impl WellKnown {
1031 /// The index `Symbol`'s installer creates this symbol at.
1032 fn index(self) -> usize {
1033 match self {
1034 WellKnown::ToPrimitive => 0,
1035 WellKnown::Iterator => 1,
1036 WellKnown::Match => 2,
1037 WellKnown::MatchAll => 3,
1038 WellKnown::Replace => 4,
1039 WellKnown::Search => 5,
1040 WellKnown::Split => 6,
1041 WellKnown::ToStringTag => 7,
1042 WellKnown::IsConcatSpreadable => 8,
1043 WellKnown::HasInstance => 9,
1044 WellKnown::Species => 10,
1045 WellKnown::Unscopables => 11,
1046 WellKnown::AsyncIterator => 12,
1047 WellKnown::Disposable => 13,
1048 WellKnown::AsyncDisposable => 14,
1049 }
1050 }
1051}
1052
1053impl Realm {
1054 /// Record the well-known symbols, in the order `Symbol`'s installer made them.
1055 pub fn set_well_known_symbols(&mut self, symbols: Vec<Value>) {
1056 self.well_known_symbols.symbols = symbols;
1057 }
1058
1059 /// A well-known symbol.
1060 pub fn well_known(&self, which: WellKnown) -> Value {
1061 self.well_known_symbols
1062 .symbols
1063 .get(which.index())
1064 .cloned()
1065 .unwrap_or(Value::Undefined)
1066 }
1067
1068 /// The well-known symbol as a property key.
1069 pub fn well_known_key(&self, which: WellKnown) -> PropertyKey {
1070 match self.well_known(which) {
1071 Value::Symbol(symbol) => PropertyKey::Symbol(symbol),
1072 // Unreachable once `Symbol` has installed; an empty string key matches
1073 // nothing, which degrades to "the object has no such method".
1074 _ => PropertyKey::from(String::new()),
1075 }
1076 }
1077}
1078
1079/// The interpreter: a realm plus a frame stack.
1080pub struct Interp<'a> {
1081 /// The heap everything is allocated on.
1082 pub heap: &'a Heap,
1083 /// The realm.
1084 pub realm: Realm,
1085 /// Active frames, outermost first.
1086 frames: Vec<Frame>,
1087 /// Value buffers from frames that have finished, reused by the next call.
1088 ///
1089 /// A call used to allocate four `Vec`s — the argument slots, the `arguments` copy,
1090 /// the locals and the operand stack — and free all four on return. `call:recursion`
1091 /// is 400k calls to a function that is 27 deep, so the work was 400k allocations to
1092 /// keep 27 frames alive. Recycling makes it proportional to *depth*.
1093 ///
1094 /// Bounded in both directions: a few buffers per kind, and none larger than
1095 /// [`RECYCLE_MAX_CAPACITY`] — a frame that pushed ten thousand operands is a one-off,
1096 /// and keeping its buffer would pin that memory for the rest of the run.
1097 free_values: Vec<Vec<Value>>,
1098 /// A strict-mode `eval`'s own variable scope, while its script runs.
1099 ///
1100 /// Strict eval gets a *fresh* variable environment, so a `var` inside it does not
1101 /// become a global. Name lookups still fall through to the realm, which is why
1102 /// `eval("a")` sees a global `a` and `eval("a = 3")` writes it.
1103 eval_scope: Option<BTreeMap<String, Value>>,
1104 /// How deep the interpreter currently is inside an `eval`, so a `var` it declares can
1105 /// be created configurable — the distinction `(1, eval)("var g")` exists to exploit.
1106 eval_depth: usize,
1107 /// The calling frame's own bindings, which the running `eval` can read and write.
1108 ///
1109 /// Held separately from [`Interp::eval_scope`] because these already exist: reads
1110 /// come from the frame, and a write is applied back to the frame (or to the cell
1111 /// the frame captured) when the eval finishes. That is what makes
1112 /// `f("a = 3")` visible to the caller as `a === 3`.
1113 eval_bindings: Vec<EvalBinding>,
1114 /// The calling frame's `arguments`, while an `eval` runs.
1115 ///
1116 /// Kept apart from [`Interp::eval_scope`] because a sloppy eval has no scope of its
1117 /// own yet still has to see the caller's `arguments`.
1118 eval_arguments: Option<Value>,
1119 /// The `with` objects live at the moment the running `eval` started, innermost first.
1120 ///
1121 /// `None` outside an eval, which is what keeps a finished block's object from
1122 /// shadowing ordinary bytecode reads.
1123 eval_with: Option<Vec<Gc<JsObject>>>,
1124 /// The bindings the running direct `eval` makes visible, as name → cell.
1125 ///
1126 /// Set for the duration of an eval and then restored, but every closure created
1127 /// during it keeps a handle (see [`ClosureEnv::eval_scope`]), which is what lets
1128 /// `eval("f = () => i")` work after the eval has returned.
1129 active_eval_scope: Option<Gc<EvalScope>>,
1130 /// The frame that called the direct `eval` currently running, if any.
1131 ///
1132 /// A sloppy eval declares its `var`s in that frame's variable environment rather than
1133 /// on the global object, which is what keeps
1134 /// `function f(){ eval("var x=1") } f(); x` from defining a global `x` — and what
1135 /// gives each call its own `x`.
1136 eval_caller: Option<Option<usize>>,
1137 /// The caller's `new.target`, while an `eval` runs.
1138 ///
1139 /// The eval'd code is a script with no constructor of its own, so it inherits the
1140 /// one the enclosing function was called with.
1141 eval_new_target: Option<Value>,
1142 /// `new.target` for the frame about to be pushed.
1143 ///
1144 /// `construct` parks the constructor here and `push_frame` takes it, which is how the
1145 /// value reaches the frame without threading a parameter through every call site.
1146 ///
1147 /// A **native** has no frame, so `call_value` takes it the same way and moves it to
1148 /// [`Interp::active_new_target`] for the duration of the call. Without that, a plain
1149 /// `native()` made from inside a constructor body saw the enclosing `new.target` — the
1150 /// value was parked for the outer call and never consumed.
1151 pending_new_target: Option<Value>,
1152 /// `new.target` of the call currently running, for [`Interp::current_new_target`].
1153 ///
1154 /// `undefined` outside a `new` call.
1155 active_new_target: Value,
1156 /// Names of the native functions currently executing, outermost first.
1157 ///
1158 /// A native has no [`Frame`] — it runs on the Rust stack — but the reference's
1159 /// trace still names it with `(native)` instead of a position, so the names are
1160 /// tracked separately and stitched into [`Interp::stack_trace`].
1161 ///
1162 /// The third field is how many bytecode frames were live when the native was entered,
1163 /// which is what places it *among* them rather than before all of them. Native
1164 /// functions used to be emitted up front on the grounds that they never re-enter
1165 /// JavaScript; `std.evalScript` does, so that reasoning no longer holds.
1166 /// The natives currently running, innermost last: the function object and the
1167 /// depth it was entered at.
1168 ///
1169 /// The *name* is deliberately not stored. It used to be, read with
1170 /// `own_property("name")` plus `to_js_string` on **every** native call, which is a
1171 /// property lookup and a `String` allocation per `values.push(i)` — 5% of the push
1172 /// benchmark. A stack trace is built rarely; it can read the name then.
1173 native_frames: Vec<(Gc<JsObject>, usize)>,
1174 /// The native function currently executing, for the ones that have to know *which*
1175 /// function they are — a typed-array constructor reads its element type off itself.
1176 ///
1177 /// `current_callee` cannot answer this: a native call pushes no frame of its own, so it
1178 /// reports whatever the enclosing bytecode frame was called with.
1179 current_native: Option<Gc<JsObject>>,
1180 /// Text written by `print` and friends, in order.
1181 ///
1182 /// Buffered rather than streamed so a test can inspect it; the CLI flushes it
1183 /// once at the end, which is also when upstream's line buffering becomes
1184 /// visible for the cases compared here.
1185 pub output: String,
1186 /// Where `print` also writes, as it goes. `output` keeps the full log for
1187 /// [`crate::Context::output`]; this is the live copy, flushed per line.
1188 ///
1189 /// Both exist on purpose. A host that gives a script a sink sees output *when it
1190 /// happens* — which is what a timer callback's `console.log` has to do, and what the
1191 /// reference does with `fputs` + `fflush` — while embedders and the 595 assertions in
1192 /// this repository keep reading the accumulated `String`. Buffering only (no sink)
1193 /// would show a script's output all at once when it finished.
1194 pub output_sink: Option<Box<dyn std::io::Write>>,
1195 /// Where recent property reads found their value.
1196 ///
1197 /// An inline cache, in the only form that is safe without hidden classes: a direct-mapped
1198 /// table remembering *which object* and *which entry of its property table* answered a
1199 /// given name. The entry is re-validated on every hit (the table is a `Vec`, so an index
1200 /// can move; the property can become an accessor), which is what makes a stale entry a
1201 /// miss rather than a wrong answer.
1202 ///
1203 /// The object is held weakly: a cache that held it strongly would keep up to
1204 /// `FIELD_CACHE_SLOTS` objects alive for the life of the interpreter, which is a leak a
1205 /// program cannot see and cannot work around.
1206 pub field_cache: Vec<Option<FieldCache>>,
1207 /// Global lookups, by binding slot. See [`GlobalCache`].
1208 global_cache: Vec<Option<GlobalCache>>,
1209 /// The heap total at which `out of memory` was last raised, or 0 when the heap is
1210 /// under its limit. See [`Interp::check_memory`].
1211 pub oom_reported_at: usize,
1212 /// A host hook that may abort execution, polled every [`INTERRUPT_POLL_INTERVAL`]
1213 /// instructions. `Some` asks for the poll; the closure answers `true` to abort.
1214 ///
1215 /// This is where the C API's `JS_SetInterruptHandler` lands. The reference polls the same
1216 /// way (`js_poll_interrupts`, whose counter starts at 10000) and for the same reason: a
1217 /// host that wants to stop a runaway script must not have to wait for it to return.
1218 ///
1219 /// Two things this cannot do, both of them differences a host can observe:
1220 ///
1221 /// * **The abort is catchable.** The reference marks its `InternalError: interrupted`
1222 /// uncatchable, so a `catch` cannot swallow it there and can here. Implementing that
1223 /// needs a signal that the `catch` machinery does not see, which is a change to
1224 /// [`Signal`]'s shape and every handler of it — not worth it while the only caller is
1225 /// a host that stops the script itself.
1226 /// * **The poll is per instruction, not at the sites the reference picks.** The reference
1227 /// also polls at calls and at loop back-edges; a counter over the dispatch loop covers
1228 /// both, so the difference is when the counter hits zero, not whether it will.
1229 pub interrupt: Option<Box<dyn FnMut() -> bool>>,
1230 /// Instructions until the next [`Interp::interrupt`] poll.
1231 pub interrupt_counter: u32,
1232 /// A request that the *next* throw be uncatchable: `JS_SetUncatchableException(true)`.
1233 ///
1234 /// A separate field from [`Interp::uncatchable`] because the two live for different
1235 /// spans. This one is the host's standing request; it survives the start of an
1236 /// evaluation (a host sets it and *then* calls `JS_Eval`), and is consumed by the first
1237 /// throw, which promotes it to `uncatchable` for the duration of that unwind. One field
1238 /// for both was the first attempt and it did nothing at all: the outermost `execute`
1239 /// cleared it before the script it was set for had a chance to throw.
1240 pub uncatchable_next: bool,
1241 /// Whether the exception now unwinding may be caught by a `catch`.
1242 ///
1243 /// This is what `JS_SetInterruptHandler` needs to match the reference: there, an
1244 /// interrupted script fails with an `InternalError` that no `try`/`catch` can swallow, so
1245 /// a host stopping a runaway loop is not fought by the loop.
1246 ///
1247 /// Read in exactly one place — the unwind in `execute` — and cleared when the outermost
1248 /// evaluation starts, so a throw that reaches the host ends the mode. Deliberately not
1249 /// part of [`Signal::Throw`]: that type is threaded through 115 match arms, and a flag
1250 /// consulted at that one choke point buys the same behaviour for a fraction of the churn.
1251 pub uncatchable: bool,
1252 /// The most stack a JavaScript call chain may use, in bytes of frame state.
1253 ///
1254 /// The reference rations the **C stack** here: each call `alloca`s its value slots and
1255 /// `js_check_stack_overflow` compares the stack pointer against `rt->stack_limit`. This
1256 /// interpreter does not recurse in Rust — a call pushes a [`Frame`] instead (see the
1257 /// module comment) — so there is no C stack to run out of, and the C stack is the wrong
1258 /// thing to measure. What a deep recursion actually costs here is *frame state*, so
1259 /// that is what the budget counts: `size_of::<Frame>()` plus the frame's own slots.
1260 ///
1261 /// The numbers come out close for the same reason a C frame and a heap frame of this
1262 /// shape cost about the same (both are a few hundred bytes, dominated by the value
1263 /// slots): `qjs --stack-size 1M` bottoms out at depth 1985 on `function f(){ d++; f() }`
1264 /// and this engine lands in the same neighbourhood — measured, not fudged, by
1265 /// `crates/quickjs-cli/tests/limits.rs`.
1266 pub stack_limit: usize,
1267 /// The most frames that may be live at once, whatever the byte budget says.
1268 ///
1269 /// A second bound for a reason the reference does not have: our frames cost less than
1270 /// its C frames, so a large `--stack-size` would otherwise buy an unbounded number of
1271 /// them and a `Vec<Frame>` in the hundreds of megabytes. This cap is what keeps
1272 /// `--stack-size 1G` from being a memory bomb.
1273 pub max_frames: usize,
1274 /// The microtask queue, but see `Interp::jobs` — shared with the module machinery.
1275 ///
1276 /// Script execution does not return until this has drained, which is what makes
1277 /// `Promise.resolve().then(f)` run `f` before the next statement of the *host* rather
1278 /// than never. Reactions append to it while it drains, so the loop is a `while` and
1279 /// not a `for`.
1280 pub(crate) jobs: std::collections::VecDeque<Job>,
1281 /// Macrotasks: the timers an event loop has to wait for. See [`Task`].
1282 ///
1283 /// A `Vec` rather than a heap because the queue is short (a script rarely has more than
1284 /// a handful) and `run_one_turn` has to scan it anyway to find the earliest deadline.
1285 pub(crate) tasks: Vec<Task>,
1286 /// Active `backtrace_barrier` depths: how many bytecode frames were live when the
1287 /// barrier'd evaluation started.
1288 ///
1289 /// A trace is truncated to the frames at or inside the innermost barrier, which is what
1290 /// lets a REPL report an error from the line it just evaluated without also reporting
1291 /// its own readline loop.
1292 trace_barriers: Vec<usize>,
1293 /// `os.signal` handlers, keyed by signal number.
1294 ///
1295 /// Kept here for the same reason as `fd_handlers`: the collector walks these values, so
1296 /// a handler cannot be freed while it is still registered.
1297 pub(crate) signal_handlers: std::collections::BTreeMap<i32, Value>,
1298 /// `os.setReadHandler`/`os.setWriteHandler` callbacks, keyed by descriptor.
1299 ///
1300 /// Kept here rather than in a closure so the collector walks the callbacks: a handler
1301 /// that is only reachable from a host closure could be freed while still registered.
1302 pub(crate) fd_handlers: std::collections::BTreeMap<i32, FdHandlers>,
1303 /// The next timer id.
1304 ///
1305 /// Starts at 1 and wraps back to 1 at `INT32_MAX`, matching `js_os_setTimeout`, because
1306 /// the id reaches the script as an `Int32` and `clearTimeout(0)` must never match.
1307 next_timer_id: i32,
1308 /// Errors thrown by timer callbacks, already rendered.
1309 ///
1310 /// Kept apart from `unhandled`: that list is rejected promises, and a timer callback
1311 /// that throws has no promise behind it. Both are reported by the host at the end of
1312 /// the loop, but only one is fixed up by a later `.catch`.
1313 timer_errors: Vec<String>,
1314 /// The module registry, keyed by canonical name.
1315 pub modules: std::collections::BTreeMap<String, Gc<crate::module::ModuleRecord>>,
1316 /// How the host turns a specifier into bytes.
1317 pub module_loader: Option<Box<dyn crate::module::ModuleLoader>>,
1318 /// The module the host was asked to run, for `import.meta.main`.
1319 pub main_module_name: Option<String>,
1320 /// The name to register the *entry* module under, when the host supplies one.
1321 ///
1322 /// The entry's bytes come from a path on disk; this is the name the module graph should
1323 /// know it by. They differ for a host that evaluates a file it did not write — a test
1324 /// runner that prepends a harness, a bundler, a REPL — and getting it wrong is visible:
1325 /// a module importing *itself* resolves the specifier against the real path, finds no
1326 /// record under that name, and loads a second copy with its own bindings.
1327 pub entry_module_name: Option<String>,
1328 /// Module bodies currently running, innermost last.
1329 ///
1330 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1331 /// this is the only place that knows which module that is.
1332 pub module_stack: Vec<String>,
1333 /// Rejections that no handler has claimed, with the promise they belong to.
1334 ///
1335 /// A `then` registered later prunes its entry, which is why the promise is kept: the
1336 /// reason alone cannot say whether somebody eventually listened.
1337 unhandled: Vec<(Gc<JsObject>, Value)>,
1338}
1339
1340impl<'a> Interp<'a> {
1341 /// Build an interpreter over `heap`, with a fresh realm.
1342 pub fn new(heap: &'a Heap) -> Interp<'a> {
1343 let object_proto = JsObject::ordinary(heap, None);
1344 let function_proto = JsObject::function(
1345 heap,
1346 Some(object_proto.clone()),
1347 Callable::Native {
1348 func: |_, _, _| Ok(Value::Undefined),
1349 own_instance: false,
1350 },
1351 );
1352 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1353 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1354 let mut interp = Interp {
1355 heap,
1356 realm: Realm {
1357 global,
1358 object_proto,
1359 function_proto,
1360 array_proto,
1361 array_constructor: None,
1362 promise_constructor: None,
1363 object_proto_to_string: None,
1364 globals: BTreeMap::new(),
1365 declared: Vec::new(),
1366 lexical_consts: BTreeSet::new(),
1367 errors: BTreeMap::new(),
1368 string_proto: None,
1369 number_proto: None,
1370 boolean_proto: None,
1371 bigint_proto: None,
1372 error_proto: JsObject::ordinary(heap, None),
1373 date_proto: JsObject::ordinary(heap, None),
1374 throw_type_error: None,
1375 generator_proto: JsObject::ordinary(heap, None),
1376 promise_proto: None,
1377 async_generator_proto: None,
1378 async_iterator_proto: None,
1379 symbol_proto: None,
1380 symbol_registry: BTreeMap::new(),
1381 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1382 regexp_proto: None,
1383 regexp_ctor: None,
1384 suppressed_error_proto: None,
1385 disposable_stack_proto: None,
1386 map_proto: None,
1387 set_proto: None,
1388 finalization_registries: Vec::new(),
1389 array_buffer_proto: None,
1390 typed_array_proto: None,
1391 typed_array_protos: Vec::new(),
1392 data_view_proto: None,
1393 async_disposable_stack_proto: None,
1394 async_from_sync: None,
1395 iterator_proto: None,
1396 iterator_ctor: None,
1397 iterator_helper_proto: None,
1398 iterator_wrap_proto: None,
1399 generator_function_proto: None,
1400 async_function_proto: None,
1401 async_generator_function_proto: None,
1402 iterator_protos: std::collections::BTreeMap::new(),
1403 well_known_symbols: WellKnownSymbols::default(),
1404 host_classes: HostClasses::new(),
1405 },
1406 frames: Vec::new(),
1407 free_values: Vec::new(),
1408 global_cache: {
1409 let mut cache = Vec::new();
1410 cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1411 cache
1412 },
1413 eval_scope: None,
1414 eval_depth: 0,
1415 eval_bindings: Vec::new(),
1416 eval_arguments: None,
1417 eval_with: None,
1418 active_eval_scope: None,
1419 eval_caller: None,
1420 pending_new_target: None,
1421 active_new_target: Value::Undefined,
1422 eval_new_target: None,
1423 native_frames: Vec::new(),
1424 current_native: None,
1425 output: String::new(),
1426 output_sink: None,
1427 field_cache: {
1428 let mut cache = Vec::new();
1429 cache.resize_with(FIELD_CACHE_SLOTS, || None);
1430 cache
1431 },
1432 oom_reported_at: 0,
1433 interrupt: None,
1434 interrupt_counter: INTERRUPT_POLL_INTERVAL,
1435 uncatchable_next: false,
1436 uncatchable: false,
1437 // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1438 // absent.
1439 stack_limit: DEFAULT_STACK_SIZE,
1440 max_frames: MAX_FRAMES,
1441 jobs: std::collections::VecDeque::new(),
1442 tasks: Vec::new(),
1443 trace_barriers: Vec::new(),
1444 signal_handlers: std::collections::BTreeMap::new(),
1445 fd_handlers: std::collections::BTreeMap::new(),
1446 next_timer_id: 1,
1447 timer_errors: Vec::new(),
1448 modules: std::collections::BTreeMap::new(),
1449 module_loader: None,
1450 main_module_name: None,
1451 entry_module_name: None,
1452 module_stack: Vec::new(),
1453 unhandled: Vec::new(),
1454 };
1455 crate::builtins::install(&mut interp);
1456 interp
1457 }
1458
1459 // -- allocation helpers -------------------------------------------------
1460
1461 /// A new string value.
1462 /// A `BigInt` value from a computed big integer.
1463 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1464 Value::BigInt(Gc::new(self.heap, value))
1465 }
1466
1467 /// A string value from bytes that are already WTF-8, which is how a string with an
1468 /// unpaired surrogate reaches a `Value`.
1469 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1470 Value::string_wtf8(self.heap, text)
1471 }
1472
1473 /// A new string value, from text that is valid UTF-8.
1474 pub fn string(&self, text: impl Into<String>) -> Value {
1475 Value::string(self.heap, text)
1476 }
1477
1478 /// A new ordinary object with the given prototype.
1479 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1480 JsObject::ordinary(self.heap, proto)
1481 }
1482
1483 // -- host classes -------------------------------------------------------
1484
1485 /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1486 pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1487 self.realm.host_classes.register(def)
1488 }
1489
1490 /// Register `def` under an id the host already holds (`JS_NewClass`).
1491 ///
1492 /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1493 /// `JS_NewClass`.
1494 pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1495 self.realm.host_classes.define(id, def)
1496 }
1497
1498 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1499 pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1500 self.realm.host_classes.set_proto(id, proto);
1501 }
1502
1503 /// The prototype installed for `id`, if any.
1504 pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1505 self.realm.host_classes.proto(id)
1506 }
1507
1508 /// A new instance of `id` (`JS_NewObjectProtoClass`).
1509 ///
1510 /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1511 /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1512 /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1513 /// host installed none.
1514 ///
1515 /// Answers `None` for an id that was never registered: the C API would return an
1516 /// exception, and silently making an ordinary object instead would move the failure to
1517 /// the first `JS_GetOpaque` that no longer matches.
1518 pub fn new_host_object(
1519 &mut self,
1520 proto: Option<Gc<JsObject>>,
1521 class_id: ClassId,
1522 ) -> Option<Gc<JsObject>> {
1523 let class = self.realm.host_classes.def(class_id)?;
1524 let proto = proto
1525 .or_else(|| self.realm.host_classes.proto(class_id))
1526 .or_else(|| Some(self.realm.object_proto.clone()));
1527 Some(JsObject::host_object(self.heap, proto, class_id, class))
1528 }
1529
1530 /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1531 ///
1532 /// `None` covers both answers the C API gives as a null pointer — the value is not an
1533 /// object, it is an object of another class, or the class never got a payload. A host
1534 /// that has to tell them apart uses [`JsObject::host_class_id`].
1535 pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1536 let object = value.as_object()?;
1537 if object.host_class_id()? != class_id {
1538 return None;
1539 }
1540 object.host_opaque()
1541 }
1542
1543 /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1544 pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1545 match value.as_object() {
1546 Some(object) => object.set_host_opaque(opaque),
1547 None => false,
1548 }
1549 }
1550
1551 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1552 ///
1553 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1554 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1555 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1556 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1557 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1558 /// said `[object Object]` instead of `[object Array Iterator]`.
1559 ///
1560 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1561 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1562 /// its own.
1563 pub fn new_iterator_prototype(
1564 &mut self,
1565 tag: &str,
1566 next: crate::object::NativeFn,
1567 ) -> Gc<JsObject> {
1568 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1569 return existing.clone();
1570 }
1571 let parent = self.realm.iterator_proto.clone();
1572 let proto = self.new_object(parent);
1573 let next = self.new_native("next", 0, next);
1574 proto.define(
1575 "next",
1576 Property::with_attributes(Value::Object(next), true, false),
1577 );
1578 let key = self.realm.well_known_key(WellKnown::Iterator);
1579 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1580 proto.define_key(
1581 &key,
1582 Property::with_attributes(Value::Object(identity), true, false),
1583 );
1584 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1585 let tag_value = self.string(tag);
1586 // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1587 // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1588 // checks it.
1589 proto.define_key(&tag_key, Property::configurable_only(tag_value));
1590 self.realm
1591 .iterator_protos
1592 .insert(tag.to_string(), proto.clone());
1593 proto
1594 }
1595
1596 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1597 ///
1598 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1599 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1600 /// produced. That is why the two branches are not merged.
1601 pub fn object_own_property_keys(
1602 &mut self,
1603 object: &Gc<JsObject>,
1604 ) -> JsResult<Vec<PropertyKey>> {
1605 if let Some(keys) = self.proxy_own_keys(object)? {
1606 return Ok(keys);
1607 }
1608 // Integer-like keys ascending, then the string keys in insertion order, then the
1609 // symbols — the order every schema that walks an object expects.
1610 let entries = object.property_entries();
1611 let mut numeric: Vec<u32> = Vec::new();
1612 // An integer-indexed exotic object reports its indices as own keys even though they
1613 // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1614 // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1615 // order). The length is asked per call, so a resizable buffer's view reports the
1616 // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1617 if object.typed_array_parts().is_some() {
1618 for index in 0..object.typed_array_length().unwrap_or(0) {
1619 // `u32::try_from` cannot fail for a real length, but the length is a
1620 // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1621 // as an array index and one element beyond is not.
1622 match u32::try_from(index) {
1623 Ok(index) => numeric.push(index),
1624 Err(_) => break,
1625 }
1626 }
1627 }
1628 let mut strings: Vec<PropertyKey> = Vec::new();
1629 let mut symbols: Vec<PropertyKey> = Vec::new();
1630 for (key, _) in entries {
1631 match &key {
1632 // A class-private name is never reported by any enumeration: that is the
1633 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1634 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1635 // symbol skip, `Object.assign`) therefore cannot see it.
1636 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1637 PropertyKey::Symbol(_) => symbols.push(key),
1638 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1639 Some(index) => {
1640 if !numeric.contains(&index) {
1641 numeric.push(index);
1642 }
1643 }
1644 None => strings.push(key),
1645 },
1646 }
1647 }
1648 // An array's `length` is an own property from the moment the array exists, so it
1649 // sits **before** every string key added afterwards — `arr.a = 1; arr.length` lists
1650 // as `["length", "a"]`, not `["a", "length"]`
1651 // (`getOwnPropertyNames/order-after-define-property`). It is synthesised rather
1652 // than stored in the property table, which is why it has to be placed here.
1653 if object.is_array() && object.proxy_state().is_none() {
1654 // Unconditionally: `Object.defineProperty(arr, "length", …)` files `length` in
1655 // the property table, at whatever position the *define* happened, but the key
1656 // lists it as the array's oldest string property because that is what it is.
1657 if let Some(position) = strings
1658 .iter()
1659 .position(|key| key.as_str() == Some("length"))
1660 {
1661 strings.remove(position);
1662 }
1663 strings.insert(0, PropertyKey::from("length"));
1664 }
1665 numeric.sort_unstable();
1666 let mut keys: Vec<PropertyKey> = numeric
1667 .into_iter()
1668 .map(|index| PropertyKey::from(index.to_string()))
1669 .collect();
1670 keys.extend(strings);
1671 keys.extend(symbols);
1672 Ok(keys)
1673 }
1674
1675 /// The state behind a promise object, or `None` when `object` is not one.
1676 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1677 object.with(|data| match &data.kind {
1678 ObjectKind::Promise(state) => Some(state.clone()),
1679 _ => None,
1680 })
1681 }
1682
1683 /// A new pending promise.
1684 pub fn new_promise(&mut self) -> Gc<JsObject> {
1685 // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1686 // the one place every promise is built, and a subclass that builds its instances
1687 // somewhere else would be invisible to `instanceof`.
1688 let default = self.realm.promise_proto.clone();
1689 // A throwing `new.target.prototype` getter cannot be reported from here — this is
1690 // the raw promise constructor and its result is not `JsResult` — so the rejection is
1691 // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1692 // `prototype` getter therefore still gets a working promise; the alternative is a
1693 // panic, and the throwing path is covered by `Promise`'s own argument validation.
1694 let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1695 Self::make_promise_object(self.heap, proto)
1696 }
1697
1698 /// A promise object with an explicit prototype, and nothing else.
1699 ///
1700 /// Separate from [`Interp::new_promise`] for the callers that have to *report* an abrupt
1701 /// `Get(newTarget, "prototype")` — `new Promise(executor)` is specified as
1702 /// `OrdinaryCreateFromConstructor`, so a throwing `prototype` getter on `new.target` is an
1703 /// exception rather than a reason to fall back (`Promise/get-prototype-abrupt`).
1704 pub fn make_promise_object(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1705 let promise = JsObject::ordinary(heap, proto);
1706 promise.with_mut(|data| {
1707 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1708 crate::object::PromiseState::default(),
1709 )));
1710 });
1711 promise
1712 }
1713
1714 /// Fulfil `promise`, unless it has already settled.
1715 ///
1716 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1717 /// after `reject`, changes nothing.
1718 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1719 let Some(state) = self.promise_state(promise) else {
1720 return;
1721 };
1722 let reactions = {
1723 let mut state = state.borrow_mut();
1724 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1725 return;
1726 }
1727 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1728 std::mem::take(&mut state.reactions)
1729 };
1730 self.queue_reactions(reactions, value, false);
1731 }
1732
1733 /// Reject `promise`, unless it has already settled.
1734 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1735 let Some(state) = self.promise_state(promise) else {
1736 return;
1737 };
1738 let reactions = {
1739 let mut state = state.borrow_mut();
1740 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1741 return;
1742 }
1743 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1744 std::mem::take(&mut state.reactions)
1745 };
1746 // Remember it only when nothing is listening *now*; a `then` registered later
1747 // prunes the entry in `perform_then`.
1748 if reactions.is_empty() {
1749 self.unhandled.push((promise.clone(), reason.clone()));
1750 }
1751 self.queue_reactions(reactions, reason, true);
1752 }
1753
1754 /// Queue one job per reaction.
1755 ///
1756 /// This is what makes `then` asynchronous even on an already-settled promise:
1757 /// `p.then(f); g()` calls `g` first.
1758 fn queue_reactions(
1759 &mut self,
1760 reactions: Vec<crate::object::PromiseReaction>,
1761 argument: Value,
1762 rejected: bool,
1763 ) {
1764 for reaction in reactions {
1765 let handler = if rejected {
1766 reaction.on_rejected.clone()
1767 } else {
1768 reaction.on_fulfilled.clone()
1769 };
1770 self.jobs.push_back(Job::Reaction {
1771 handler,
1772 argument: argument.clone(),
1773 rejected,
1774 promise: reaction.promise,
1775 });
1776 }
1777 }
1778
1779 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1780 /// resolve/reject pair.
1781 ///
1782 /// The pair are callable objects rather than Rust closures, because the script gets
1783 /// them and may stash them for later.
1784 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1785 let promise = self.new_promise();
1786 // Both handlers are built-ins with an empty name and length 1, in
1787 // `length`-then-`name` order — `reject-function-property-order` reads the order back
1788 // off `Object.getOwnPropertyNames`.
1789 let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1790 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1791 (promise, Value::Object(resolve), Value::Object(reject))
1792 }
1793
1794 /// §27.2.1.5 `NewPromiseCapability(C)`.
1795 ///
1796 /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1797 /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1798 /// decide what capability it hands back. That is the whole mechanism behind subclassing
1799 /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1800 /// silently ignored argument.
1801 ///
1802 /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1803 /// the engine's own executor is exactly what `new_promise_capability` builds.
1804 pub fn new_promise_capability_for(
1805 &mut self,
1806 constructor: &Value,
1807 ) -> JsResult<(Value, Value, Value)> {
1808 let Some(object) = constructor.as_object().cloned() else {
1809 return Err(self.type_error("promise constructor is not a constructor"));
1810 };
1811 if !object.is_constructor() {
1812 return Err(self.type_error("promise constructor is not a constructor"));
1813 }
1814 if self
1815 .realm
1816 .promise_constructor
1817 .as_ref()
1818 .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1819 {
1820 let (promise, resolve, reject) = self.new_promise_capability();
1821 return Ok((Value::Object(promise), resolve, reject));
1822 }
1823 let state = self.new_object(Some(self.realm.object_proto.clone()));
1824 // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1825 // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1826 // which only a *custom* constructor can observe, and none of the combinator tests
1827 // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1828 let executor = self.builtin_function(
1829 "",
1830 2,
1831 Callable::CapabilityExecutor {
1832 state: state.clone(),
1833 },
1834 );
1835 let promise = self.construct(
1836 Value::Object(object.clone()),
1837 Value::Object(object),
1838 vec![Value::Object(executor)],
1839 )?;
1840 // The pair is read *after* the constructor returns, so a constructor that never
1841 // called its executor, or called it with non-callables, is the spec's step 11
1842 // `TypeError` — not something the engine can paper over.
1843 let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1844 return Err(self.type_error("promise executor never ran"));
1845 };
1846 let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1847 return Err(self.type_error("promise executor never ran"));
1848 };
1849 for handler in [&resolve, &reject] {
1850 if !matches!(handler, Value::Object(object) if object.is_callable()) {
1851 return Err(self.type_error("promise capability handler is not callable"));
1852 }
1853 }
1854 Ok((promise, resolve, reject))
1855 }
1856
1857 /// §27.2.3.1 `PromiseResolve(C, x)`.
1858 ///
1859 /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1860 /// an `x` that is already a promise of exactly this constructor is handed back
1861 /// unchanged, and anything else gets a fresh capability from `C`.
1862 pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1863 if let Value::Object(object) = &value
1864 && self.promise_state(object).is_some()
1865 {
1866 // `x.constructor === C` means "already the right kind", so no capability is
1867 // built — which is observable through a `resolve` that counts its calls.
1868 let x_constructor = self.get_property(object, "constructor")?;
1869 let same = match (
1870 x_constructor.as_ref().and_then(Value::as_object),
1871 constructor.as_object(),
1872 ) {
1873 (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1874 _ => false,
1875 };
1876 if same {
1877 return Ok(value);
1878 }
1879 }
1880 let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1881 // §27.2.4.6 step 5: `? Call(resolve, undefined, «x»)` — an exception from a
1882 // *user* resolve function propagates (`resolve/capability-invocation-error`), while
1883 // the intrinsic one swallows its own self-resolution error.
1884 self.call_value(resolve, Value::Undefined, vec![value])?;
1885 Ok(promise)
1886 }
1887
1888 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1889 /// promise, as `{ value: completion }`.
1890 ///
1891 /// The three cases are the reference's, and they differ on purpose:
1892 ///
1893 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1894 /// exception before any promise exists;
1895 /// * a **runtime** error rejects the returned promise;
1896 /// * success resolves it with `{ value }`, where the value is the script's completion
1897 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1898 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1899 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1900 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1901 ///
1902 /// # What this does not do
1903 ///
1904 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1905 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1906 /// the parser and the suspension machinery to accept a suspended top-level script, and
1907 /// is not implemented — such source is a syntax error here. Everything else about the
1908 /// flag is reproduced.
1909 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1910 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1911 // too, and the reference truncates that one at the same place as a runtime failure.
1912 if barrier {
1913 let depth = self.frames.len();
1914 self.trace_barriers.push(depth);
1915 }
1916 // Compiled before the promise exists, so a parse failure propagates as a throw
1917 // instead of being folded into a rejection.
1918 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1919 Ok(compiled) => compiled,
1920 Err(error) => {
1921 if barrier {
1922 self.trace_barriers.pop();
1923 }
1924 return Err(error);
1925 }
1926 };
1927 // An async body answers its own promise, and that promise is what the reference
1928 // hands back — the same object, not a wrapper around it. Its resolution value is
1929 // the `{value}` object the compiled epilogue built.
1930 if compiled.kind.is_async() {
1931 let strict = compiled.strict;
1932 let promise = self.run_eval_script(compiled, strict)?;
1933 if barrier {
1934 self.trace_barriers.pop();
1935 }
1936 return Ok(promise);
1937 }
1938 let (promise, resolve, reject) = self.new_promise_capability();
1939 let strict = compiled.strict;
1940 match self.run_eval_script(compiled, strict) {
1941 Ok(value) => {
1942 // `{ value }` is a plain object, so resolving with it adopts nothing even
1943 // when the completion value is itself a promise.
1944 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1945 self.set_property(&wrapped, "value", value)?;
1946 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1947 }
1948 Err(Signal::Throw(error)) => {
1949 self.call_value(reject, Value::Undefined, vec![error])?;
1950 }
1951 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1952 }
1953 if barrier {
1954 self.trace_barriers.pop();
1955 }
1956 Ok(Value::Object(promise))
1957 }
1958
1959 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1960 ///
1961 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1962 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1963 /// timer table, where the collector already scans it.
1964 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1965 let (promise, resolve, _reject) = self.new_promise_capability();
1966 let resolve = self.new_host_function(
1967 "resolve",
1968 1,
1969 Box::new(
1970 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1971 let value = args.first().cloned().unwrap_or(Value::Undefined);
1972 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1973 },
1974 ),
1975 );
1976 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1977 // timer table is part of what the collector walks.
1978 self.schedule_timer(Value::Object(resolve), delay_ms);
1979 Ok(Value::Object(promise))
1980 }
1981
1982 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1983 /// new promise resolved with it.
1984 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1985 if let Value::Object(object) = &value
1986 && self.promise_state(object).is_some()
1987 {
1988 return Ok(value);
1989 }
1990 let promise = self.new_promise();
1991 self.resolve_promise_with(&promise, value)?;
1992 Ok(Value::Object(promise))
1993 }
1994
1995 /// §27.2.4.7 `PromiseResolve(%Promise%, value)`.
1996 ///
1997 /// The difference from [`Interp::promise_resolve_value`] is step 1.a: when `value` is
1998 /// already a promise, its **`constructor` is read**, and only if that is the intrinsic
1999 /// `%Promise%` is `value` returned unchanged. A getter placed on `constructor` is
2000 /// therefore observable — which is exactly what
2001 /// `AsyncGeneratorPrototype/return/return-*-broken-promise*.js` use to check that the
2002 /// `AsyncGeneratorAwaitReturn` path goes through `PromiseResolve` rather than a private
2003 /// shortcut.
2004 pub fn promise_resolve_intrinsic(&mut self, value: Value) -> JsResult<Value> {
2005 if let Value::Object(object) = &value
2006 && self.promise_state(object).is_some()
2007 {
2008 let constructor = self.get_property(object, "constructor")?;
2009 let same = match (&constructor, &self.realm.promise_constructor) {
2010 (Some(Value::Object(found)), Some(intrinsic)) => found.ptr_eq(intrinsic),
2011 _ => false,
2012 };
2013 if same {
2014 return Ok(value);
2015 }
2016 }
2017 let promise = self.new_promise();
2018 self.resolve_promise_with(&promise, value)?;
2019 Ok(Value::Object(promise))
2020 }
2021
2022 /// Claim `[[AlreadyResolved]]` for `promise`: `true` for the first caller, `false` after.
2023 ///
2024 /// The pair of resolving functions a promise hands to its executor shares this record, so
2025 /// whichever runs first wins and the other is a silent no-op. Promise *status* is not a
2026 /// substitute: resolving with a thenable leaves the promise `Pending` for a whole job.
2027 pub fn claim_resolution(&mut self, promise: &Gc<JsObject>) -> bool {
2028 let Some(state) = self.promise_state(promise) else {
2029 return true;
2030 };
2031 let mut state = state.borrow_mut();
2032 if state.resolved {
2033 return false;
2034 }
2035 state.resolved = true;
2036 true
2037 }
2038
2039 /// Clear `[[AlreadyResolved]]`, for the job that hands out a fresh pair.
2040 fn forget_resolution(&mut self, promise: &Gc<JsObject>) {
2041 let Some(state) = self.promise_state(promise) else {
2042 return;
2043 };
2044 state.borrow_mut().resolved = false;
2045 }
2046
2047 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
2048 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
2049 // Resolving a promise with itself is a `TypeError`. The check exists because the
2050 // alternative is a chain of self-reactions that never settles.
2051 if let Value::Object(object) = &value
2052 && object.ptr_eq(promise)
2053 {
2054 // The spec rejects *and* throws, so both the promise and the caller see it.
2055 let thrown = self.type_error("cannot resolve a promise with itself");
2056 let Signal::Throw(error) = thrown.clone() else {
2057 unreachable!("type_error always throws")
2058 };
2059 self.reject_promise(promise, error);
2060 return Err(thrown);
2061 }
2062 // §27.2.1.3.1 `NewPromiseResolveThenableJob` step 3: `Get(resolution, "then")` is a
2063 // `Completion`, and an abrupt one **rejects** the promise rather than throwing to
2064 // whoever resolved it — a poisoned `then` getter is the case every
2065 // `*-poisoned-then` test is written against.
2066 let then = match &value {
2067 Value::Object(object) => match self.get_property(object, "then") {
2068 Ok(then) => then,
2069 Err(signal) => {
2070 if let Signal::Throw(reason) = signal {
2071 self.reject_promise(promise, reason);
2072 return Ok(());
2073 }
2074 return Err(signal);
2075 }
2076 },
2077 _ => None,
2078 };
2079 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
2080 if !callable_then {
2081 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
2082 self.fulfill_promise(promise, value);
2083 return Ok(());
2084 }
2085 // Adopting a thenable is asynchronous — `then` is called from a job, never from
2086 // inside `resolve`, so a script cannot make a promise settle synchronously.
2087 self.jobs.push_back(Job::Thenable {
2088 then: then.expect("checked callable"),
2089 value,
2090 promise: promise.clone(),
2091 });
2092 Ok(())
2093 }
2094
2095 /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
2096 ///
2097 /// `C.resolve` is user code and may answer a plain thenable rather than one of this
2098 /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
2099 ///
2100 /// The property read is **not** short-circuitable even for a real promise: the spec says
2101 /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
2102 /// expects it to run. Skipping the read for promises not only lost the throw, it made
2103 /// the combinator's loop infinite — the test's iterator never sets `done`.
2104 pub fn invoke_then(
2105 &mut self,
2106 thenable: Value,
2107 on_fulfilled: Value,
2108 on_rejected: Value,
2109 ) -> JsResult<()> {
2110 let then = match &thenable {
2111 Value::Object(object) => self.get_property(object, "then")?,
2112 primitive => {
2113 let boxed = self.object_from(primitive)?;
2114 self.get_property(&boxed, "then")?
2115 }
2116 };
2117 let Some(then) = then else {
2118 return Err(self.type_error("thenable has no then method"));
2119 };
2120 if !matches!(&then, Value::Object(object) if object.is_callable()) {
2121 return Err(self.type_error("then is not a function"));
2122 }
2123 self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
2124 Ok(())
2125 }
2126
2127 /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
2128 ///
2129 /// `Promise.prototype.then` in one step: register a reaction and answer the derived
2130 /// promise.
2131 pub fn perform_then(
2132 &mut self,
2133 promise: &Gc<JsObject>,
2134 on_fulfilled: Option<Value>,
2135 on_rejected: Option<Value>,
2136 ) -> JsResult<Value> {
2137 let Some(state) = self.promise_state(promise) else {
2138 return Err(self.type_error("not a promise"));
2139 };
2140 // Whether a rejection handler is being attached decides whether a recorded
2141 // rejection stops being unhandled, so it is read before the values are moved.
2142 let has_rejection_handler = on_rejected.is_some();
2143 let derived = self.new_promise();
2144 let reaction = crate::object::PromiseReaction {
2145 on_fulfilled,
2146 on_rejected,
2147 promise: derived.clone(),
2148 };
2149 let settled = {
2150 let mut state = state.borrow_mut();
2151 // A rejection somebody reacts to is no longer unhandled.
2152 state.handled = true;
2153 match &state.status {
2154 crate::object::PromiseStatus::Pending => {
2155 state.reactions.push(reaction.clone());
2156 None
2157 }
2158 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2159 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2160 }
2161 };
2162 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2163 // later, means somebody is listening after all.
2164 if has_rejection_handler {
2165 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2166 }
2167 if let Some((argument, rejected)) = settled {
2168 let handler = if rejected {
2169 reaction.on_rejected
2170 } else {
2171 reaction.on_fulfilled
2172 };
2173 self.jobs.push_back(Job::Reaction {
2174 handler,
2175 argument,
2176 rejected,
2177 promise: reaction.promise,
2178 });
2179 }
2180 Ok(Value::Object(derived))
2181 }
2182
2183 /// The rejections nobody listened to, formatted the way the reference reports them.
2184 ///
2185 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2186 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2187 /// unhandled at the point the queue drains, because a `then` may still be attached
2188 /// before the host acts on it.
2189 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2190 let entries = std::mem::take(&mut self.unhandled);
2191 // Somebody may have attached a handler after the rejection was recorded, so the
2192 // promise is the authority rather than the list.
2193 let still_unhandled: Vec<Value> = entries
2194 .into_iter()
2195 .filter_map(|(promise, reason)| {
2196 let handled = self
2197 .promise_state(&promise)
2198 .map(|state| state.borrow().handled)
2199 .unwrap_or(true);
2200 (!handled).then_some(reason)
2201 })
2202 .collect();
2203 still_unhandled
2204 .into_iter()
2205 .map(|reason| {
2206 let text = self.describe_exception(&reason);
2207 let stack = match &reason {
2208 Value::Object(object) => self
2209 .get_property(object, "stack")
2210 .ok()
2211 .flatten()
2212 .map(|value| value.to_js_string())
2213 // `stack` carries a trailing newline of its own, which would leave
2214 // a blank line between two reported rejections.
2215 .map(|text| text.trim_end().to_string())
2216 .unwrap_or_default(),
2217 _ => String::new(),
2218 };
2219 if stack.is_empty() {
2220 format!("Possibly unhandled promise rejection: {text}")
2221 } else {
2222 format!("Possibly unhandled promise rejection: {text}\n{stack}")
2223 }
2224 })
2225 .collect()
2226 }
2227
2228 /// Run the microtask queue to exhaustion.
2229 ///
2230 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2231 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2232 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2233 ///
2234 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2235 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2236 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2237 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2238 crate::builtins::json::parse_text(self, text, true)
2239 }
2240
2241 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2242 ///
2243 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2244 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2245 /// immediately, and `setTimeout(f, -1)` is ordinary code.
2246 ///
2247 /// The callback is called with **no arguments**. The reference stores only the function
2248 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2249 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2250 /// extra arguments arrive as `undefined`.
2251 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2252 let id = self.next_timer_id;
2253 // Wrap rather than grow: the id reaches the script as an `Int32`.
2254 self.next_timer_id = if self.next_timer_id == i32::MAX {
2255 1
2256 } else {
2257 self.next_timer_id + 1
2258 };
2259 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2260 self.tasks.push(Task::Timer {
2261 id,
2262 callback,
2263 due_at,
2264 });
2265 id
2266 }
2267
2268 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2269 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2270 pub fn cancel_timer(&mut self, id: i32) -> bool {
2271 let before = self.tasks.len();
2272 self.tasks.retain(|task| match task {
2273 Task::Timer { id: task_id, .. } => *task_id != id,
2274 });
2275 self.tasks.len() != before
2276 }
2277
2278 /// How long until the earliest pending timer, or `None` when none is pending.
2279 pub fn next_timeout(&self) -> Option<std::time::Duration> {
2280 let now = std::time::Instant::now();
2281 self.tasks
2282 .iter()
2283 .map(|task| match task {
2284 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2285 })
2286 .min()
2287 }
2288
2289 /// Run one turn of the event loop.
2290 ///
2291 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2292 /// run at most one due timer, then drain again. The blocking belongs to the caller
2293 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2294 /// is how it asks.
2295 ///
2296 /// One timer per turn rather than all of them: a timer callback may schedule another
2297 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2298 /// starve the microtask queue.
2299 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2300 self.drain_jobs()?;
2301 let now = std::time::Instant::now();
2302 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2303 // followed by `setTimeout(g, 1)` must run `g` first.
2304 let due = self
2305 .tasks
2306 .iter()
2307 .enumerate()
2308 .filter(|(_, task)| match task {
2309 Task::Timer { due_at, .. } => *due_at <= now,
2310 })
2311 .min_by_key(|(_, task)| match task {
2312 Task::Timer { due_at, .. } => *due_at,
2313 })
2314 .map(|(index, _)| index);
2315 let Some(index) = due else {
2316 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2317 // descriptor is registered but no timer is closer, so a script that never
2318 // touches the descriptor still gets control back. Without a cap a handler on a
2319 // descriptor that is never ready would block for as long as the host allows.
2320 let timeout = self
2321 .next_timeout()
2322 .unwrap_or(std::time::Duration::from_secs(10))
2323 .min(std::time::Duration::from_secs(10));
2324 if !self.fd_handlers.is_empty() {
2325 // Blocking on a timer while descriptors are registered would starve them,
2326 // and blocking on the descriptors while a timer is due would delay it; the
2327 // host polls with the earlier of the two deadlines, which this timeout is.
2328 return Ok(Turn::Poll(timeout));
2329 }
2330 return Ok(match self.next_timeout() {
2331 Some(wait) => Turn::Wait(wait),
2332 None => Turn::Done,
2333 });
2334 };
2335 let Task::Timer { callback, .. } = self.tasks.remove(index);
2336 let this = Value::Undefined;
2337 // A throwing timer callback must not stop the loop: the reference reports it and
2338 // keeps going, because the alternative is that one bad timer silently stops every
2339 // later one.
2340 // No arguments: see `schedule_timer` — the reference calls the callback bare.
2341 match self.call_value(callback, this, 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(Turn::Ran)
2351 }
2352
2353 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2354 ///
2355 /// `callback` of `None` unregisters that direction, and an entry with neither direction
2356 /// left is removed — the reference does the same, so a script can rely on
2357 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2358 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2359 let entry = self.fd_handlers.entry(fd).or_default();
2360 if readable {
2361 entry.read = callback;
2362 } else {
2363 entry.write = callback;
2364 }
2365 if entry.read.is_none() && entry.write.is_none() {
2366 self.fd_handlers.remove(&fd);
2367 }
2368 }
2369
2370 /// Register or clear an `os.signal` handler.
2371 ///
2372 /// `None` removes it; the host separately restores the default disposition or sets
2373 /// ignore, because which of those happened is the script's choice (`null` versus
2374 /// `undefined`) and not something this table can express.
2375 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2376 match handler {
2377 Some(handler) => {
2378 self.signal_handlers.insert(signal, handler);
2379 }
2380 None => {
2381 self.signal_handlers.remove(&signal);
2382 }
2383 }
2384 }
2385
2386 /// Run the handler for `signal`, reporting whether one ran.
2387 ///
2388 /// A throwing handler is reported and the loop continues, like a timer's.
2389 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2390 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2391 return Ok(false);
2392 };
2393 match self.call_value(handler, 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 /// The descriptors the host has to poll, and in which direction.
2406 ///
2407 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2408 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2409 /// `os_poll` asks for.
2410 pub fn pending_fds(&self) -> Vec<FdInterest> {
2411 self.fd_handlers
2412 .iter()
2413 .map(|(fd, entry)| FdInterest {
2414 fd: *fd,
2415 read: entry.read.is_some(),
2416 write: entry.write.is_some(),
2417 })
2418 .collect()
2419 }
2420
2421 /// Call the handler registered for `fd`, reporting whether one ran.
2422 ///
2423 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2424 /// poll iteration and then restarts the loop, because the handler may have changed the
2425 /// registration list underneath it; doing the same here keeps a handler that
2426 /// unregisters itself from being called with stale state.
2427 ///
2428 /// A throwing handler is reported and the loop continues — a bad handler must not stop
2429 /// every later one, exactly as with timers.
2430 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2431 let Some(entry) = self.fd_handlers.get(&fd) else {
2432 return Ok(false);
2433 };
2434 let callback = if readable {
2435 entry.read.clone()
2436 } else if writable {
2437 entry.write.clone()
2438 } else {
2439 None
2440 };
2441 let Some(callback) = callback else {
2442 return Ok(false);
2443 };
2444 self.drain_jobs()?;
2445 match self.call_value(callback, Value::Undefined, Vec::new()) {
2446 Ok(_) => {}
2447 Err(Signal::Throw(value)) => {
2448 let text = self.describe_exception(&value);
2449 self.timer_errors.push(text);
2450 }
2451 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2452 }
2453 self.drain_jobs()?;
2454 Ok(true)
2455 }
2456
2457 /// Take the errors timer callbacks threw, leaving the list empty.
2458 pub fn take_timer_errors(&mut self) -> Vec<String> {
2459 std::mem::take(&mut self.timer_errors)
2460 }
2461
2462 /// Whether anything is still pending: a microtask or a timer.
2463 pub fn has_pending_work(&self) -> bool {
2464 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2465 }
2466
2467 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2468 pub fn has_pending_timers_or_jobs(&self) -> bool {
2469 !self.jobs.is_empty() || !self.tasks.is_empty()
2470 }
2471
2472 /// Run every queued microtask, including ones queued while draining.
2473 pub fn drain_jobs(&mut self) -> JsResult<()> {
2474 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2475 // would spin forever, so the drain is bounded the way the call stack is.
2476 let mut budget = 1_000_000usize;
2477 while let Some(job) = self.jobs.pop_front() {
2478 if budget == 0 {
2479 return Err(Signal::Throw(
2480 self.make_error("InternalError", "promise job queue did not drain"),
2481 ));
2482 }
2483 budget -= 1;
2484 self.run_job(job)?;
2485 // `FinalizationRegistry` at the job boundary: this is the safe point where the
2486 // engine may run script that the script itself did not ask for. Doing it here
2487 // rather than from a drop hook is what keeps the callback out of arbitrary
2488 // engine bookkeeping — see `builtins::weak`'s header.
2489 crate::builtins::weak::drain_finalizers(self)?;
2490 }
2491 // A script that queued no jobs may still have dropped targets, so the checkpoint
2492 // runs once more after the queue empties.
2493 crate::builtins::weak::drain_finalizers(self)?;
2494 Ok(())
2495 }
2496
2497 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2498 ///
2499 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2500 /// `None` and is swept out here. This is also where the realm learns that a registry
2501 /// died, which is why it is a mutation rather than a read.
2502 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2503 let handles = std::mem::take(&mut self.realm.finalization_registries);
2504 let mut live = Vec::with_capacity(handles.len());
2505 for handle in handles {
2506 let Some(object) = handle.upgrade() else {
2507 continue;
2508 };
2509 let Some(state) = object.finalization_state() else {
2510 continue;
2511 };
2512 live.push((object.clone(), *state));
2513 self.realm.finalization_registries.push(object.downgrade());
2514 }
2515 live
2516 }
2517
2518 /// Run one microtask.
2519 fn run_job(&mut self, job: Job) -> JsResult<()> {
2520 match job {
2521 Job::Reaction {
2522 handler: None,
2523 argument,
2524 rejected,
2525 promise,
2526 } => {
2527 // No handler: the settlement passes straight through to the derived
2528 // promise, which is why `p.catch(f)` ignores fulfilments.
2529 if rejected {
2530 self.reject_promise(&promise, argument);
2531 } else {
2532 self.fulfill_promise(&promise, argument);
2533 }
2534 Ok(())
2535 }
2536 Job::Reaction {
2537 handler: Some(handler),
2538 argument,
2539 promise,
2540 ..
2541 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2542 Ok(answer) => {
2543 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2544 self.reject_promise(&promise, error);
2545 }
2546 Ok(())
2547 }
2548 Err(Signal::Throw(reason)) => {
2549 self.reject_promise(&promise, reason);
2550 Ok(())
2551 }
2552 Err(other) => Err(other),
2553 },
2554 Job::Thenable {
2555 then,
2556 value,
2557 promise,
2558 } => {
2559 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2560 // the value it produces settles `promise`.
2561 // The thenable's `then` gets this promise's own pair, so whatever it
2562 // produces settles `promise`.
2563 // `length: 1`, `name: ""` — a resolve/reject function is a
2564 // `%Promise.prototype.then%`-style pair, not a bare native. Building them
2565 // with `JsObject::function` left `length` at 0, which a test reads straight
2566 // off the function (`finally/resolved-observable-then-calls-argument`
2567 // requires `resolve.length === 1` for the pair handed to a thenable).
2568 let resolve =
2569 self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
2570 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
2571 // §27.2.2.2 step 1: the job builds a **fresh** pair of resolving functions,
2572 // so the one-shot record starts over. Without the reset the pair above was
2573 // already spent by the `resolve` that queued this job, and a thenable that
2574 // calls `reject` left the promise pending forever
2575 // (`Promise/all/reject-immed`).
2576 self.forget_resolution(&promise);
2577 let reject = Value::Object(reject);
2578 match self.call_value(then, value, vec![Value::Object(resolve), reject.clone()]) {
2579 Ok(_) => Ok(()),
2580 // Step 3.a is `Call(resolvingFunctions.[[Reject]], …)` — **through** the
2581 // reject function, whose one-shot record makes this a no-op once `then`
2582 // has already resolved the promise
2583 // (`exception-after-resolve-in-thenable-job`).
2584 Err(Signal::Throw(reason)) => {
2585 self.call_value(reject, Value::Undefined, vec![reason])?;
2586 Ok(())
2587 }
2588 Err(other) => Err(other),
2589 }
2590 }
2591 Job::Resume {
2592 coroutine,
2593 promise,
2594 kind,
2595 value,
2596 } => self.drive_async(&coroutine, &promise, kind, value),
2597 Job::GeneratorResume {
2598 generator,
2599 promise,
2600 kind,
2601 value,
2602 } => self.step_async_generator(&generator, &promise, kind, value),
2603 Job::Import {
2604 specifier,
2605 referrer,
2606 promise,
2607 } => {
2608 self.run_dynamic_import(&specifier, &referrer, &promise);
2609 Ok(())
2610 }
2611 }
2612 }
2613
2614 /// One element of a `Promise` combinator settled.
2615 ///
2616 /// The shared state object holds the result array, the number still outstanding, and
2617 /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2618 /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2619 /// to settle, only whatever `Sub` said a capability is.
2620 ///
2621 /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2622 /// and `any` must ignore every later settlement, and `all` must not report a second
2623 /// rejection after the first.
2624 fn settle_combinator(
2625 &mut self,
2626 state: &Gc<JsObject>,
2627 index: usize,
2628 fulfilled: bool,
2629 value: Value,
2630 ) -> JsResult<()> {
2631 let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2632 // Each element settles at most once: a thenable may call `onFulfilled` twice
2633 // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2634 // call a no-op. Without it the second call decremented `remaining` again and settled
2635 // `all` with a short values array (`call-resolve-element-items`).
2636 let done = field("done");
2637 let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2638 let settled = field("settled").is_some_and(|value| value.to_boolean());
2639 if settled {
2640 return Ok(());
2641 }
2642 if let Some(Value::Object(done)) = &done {
2643 if done
2644 .array_get(index)
2645 .is_some_and(|value| value.to_boolean())
2646 {
2647 return Ok(());
2648 }
2649 done.array_set(self.heap, index, Value::Bool(true));
2650 }
2651 let resolve = field("resolve");
2652 let reject = field("reject");
2653 let keys = field("keys");
2654 let results = field("results").and_then(|value| value.as_object().cloned());
2655 // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2656 // promise: the handler is a plain function the constructor chose.
2657 let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2658 if let Some(handler) = handler {
2659 interp.call_value(handler, Value::Undefined, vec![value])?;
2660 }
2661 Ok(())
2662 };
2663 match kind {
2664 // `race`: the first settlement wins and stops the rest.
2665 3 => {
2666 state.define_data("settled", Value::Bool(true));
2667 let handler = if fulfilled { resolve } else { reject };
2668 settle_with(self, handler, value)?;
2669 return Ok(());
2670 }
2671 // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2672 // the first rejection wins outright.
2673 0 | 4 if !fulfilled => {
2674 state.define_data("settled", Value::Bool(true));
2675 settle_with(self, reject, value)?;
2676 return Ok(());
2677 }
2678 // `any`: the first fulfilment wins.
2679 2 if fulfilled => {
2680 state.define_data("settled", Value::Bool(true));
2681 settle_with(self, resolve, value)?;
2682 return Ok(());
2683 }
2684 _ => {}
2685 }
2686 let Some(results) = &results else {
2687 return Ok(());
2688 };
2689 match kind {
2690 4 => {
2691 results.array_set(self.heap, index, value);
2692 }
2693 0 => {
2694 results.array_set(self.heap, index, value);
2695 }
2696 // `allSettled` (and its keyed twin) never rejects; each slot records what
2697 // happened.
2698 1 | 5 => {
2699 let record = self.new_object(Some(self.realm.object_proto.clone()));
2700 if fulfilled {
2701 record.define_data("status", self.string("fulfilled"));
2702 record.define_data("value", value);
2703 } else {
2704 record.define_data("status", self.string("rejected"));
2705 record.define_data("reason", value);
2706 }
2707 results.array_set(self.heap, index, Value::Object(record));
2708 }
2709 // `any`: a rejection is parked in the errors array and the sweep continues.
2710 2 => {
2711 results.array_set(self.heap, index, value);
2712 }
2713 _ => {}
2714 }
2715 let remaining = field("remaining")
2716 .map(|value| value.to_int32())
2717 .unwrap_or(0);
2718 let left = remaining - 1;
2719 state.define_data("remaining", Value::Int(left));
2720 if left != 0 {
2721 return Ok(());
2722 }
2723 state.define_data("settled", Value::Bool(true));
2724 match kind {
2725 0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2726 // The keyed result: an ordinary object with a **null** prototype, holding the
2727 // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2728 4 | 5 => {
2729 let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2730 settle_with(self, resolve, keyed)?;
2731 }
2732 2 => {
2733 // The rejection is an `AggregateError` whose `errors` is the results array
2734 // itself — the slots are the reasons, in input order.
2735 let errors = results.array_elements().unwrap_or_default();
2736 let error = self.aggregate_error(errors, "all promises were rejected");
2737 settle_with(self, reject, error)?;
2738 }
2739 _ => {}
2740 }
2741 Ok(())
2742 }
2743
2744 /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2745 ///
2746 /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2747 /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2748 /// prototype is load-bearing in both directions: a key called `toString` must not
2749 /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2750 /// (`resolves-empty-object.js`).
2751 pub(crate) fn keyed_result_object(
2752 &mut self,
2753 keys: Option<&Value>,
2754 values: &Gc<JsObject>,
2755 ) -> JsResult<Value> {
2756 let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2757 return Ok(Value::Object(self.new_object(None)));
2758 };
2759 let result = self.new_object(None);
2760 let count = values.array_length().unwrap_or(0);
2761 for index in 0..count {
2762 let Some(key) = keys.array_get(index) else {
2763 continue;
2764 };
2765 let Some(value) = values.array_get(index) else {
2766 continue;
2767 };
2768 let property = Property::with_attributes(value, true, true);
2769 match &key {
2770 Value::Symbol(symbol) => {
2771 result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2772 }
2773 other => {
2774 let text = self.to_js_string(other)?;
2775 result.define_key(&PropertyKey::from(text.as_str()), property);
2776 }
2777 }
2778 }
2779 Ok(Value::Object(result))
2780 }
2781
2782 /// Build an async function's result: a promise whose body runs as a coroutine.
2783 pub fn new_async_function(
2784 &mut self,
2785 function: Value,
2786 this: Value,
2787 args: Vec<Value>,
2788 ) -> JsResult<Value> {
2789 let promise = self.new_promise();
2790 let coroutine = self.new_coroutine(function, this, args)?;
2791 if let Err(Signal::Throw(reason)) =
2792 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2793 {
2794 self.reject_promise(&promise, reason);
2795 }
2796 Ok(Value::Object(promise))
2797 }
2798
2799 /// The coroutine an async body runs in.
2800 ///
2801 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2802 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2803 /// than growing a second state machine. The difference is only in the ending — a
2804 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2805 /// Run `code` as an async function body, answering the promise it settles.
2806 ///
2807 /// Used for a module with top-level `await`: its body is an async function whose
2808 /// caller is the host, so there is no function object to pass through
2809 /// [`Interp::new_async_function`].
2810 pub fn run_async_body(
2811 &mut self,
2812 code: Gc<CompiledCode>,
2813 env: Gc<ClosureEnv>,
2814 this: Value,
2815 ) -> JsResult<Value> {
2816 let promise = self.new_promise();
2817 let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2818 if let Err(Signal::Throw(reason)) =
2819 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2820 {
2821 self.reject_promise(&promise, reason);
2822 }
2823 Ok(Value::Object(promise))
2824 }
2825
2826 fn new_coroutine(
2827 &mut self,
2828 function: Value,
2829 this: Value,
2830 args: Vec<Value>,
2831 ) -> JsResult<Gc<JsObject>> {
2832 let Some(object) = function.as_object().cloned() else {
2833 return Err(self.type_error("not a function"));
2834 };
2835 let Some((code, env)) = bytecode_of(&object) else {
2836 return Err(self.type_error("not a function"));
2837 };
2838 self.new_coroutine_from(code, env, this, args)
2839 }
2840
2841 /// Build a coroutine over an already-resolved body.
2842 fn new_coroutine_from(
2843 &mut self,
2844 code: Gc<CompiledCode>,
2845 env: Gc<ClosureEnv>,
2846 this: Value,
2847 args: Vec<Value>,
2848 ) -> JsResult<Gc<JsObject>> {
2849 let function = Value::Undefined;
2850 self.push_frame(code, env, this, args, function)?;
2851 let frame = self.frames.pop().expect("push_frame just pushed it");
2852 let state = GeneratorState {
2853 frame: Some(frame),
2854 phase: GeneratorPhase::SuspendedStart,
2855 parked_on_await: false,
2856 parked_on_yield_star: false,
2857 requests: std::collections::VecDeque::new(),
2858 async_busy: false,
2859 // An `async function` body is driven by `drive_async`, never by the generator
2860 // protocol, and the object is not reachable from script.
2861 is_async: false,
2862 };
2863 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2864 coroutine.with_mut(|data| {
2865 data.kind = ObjectKind::Generator(Box::new(state));
2866 });
2867 Ok(coroutine)
2868 }
2869
2870 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2871 /// `await` and `value` is what it awaited.
2872 fn resume_coroutine(
2873 &mut self,
2874 coroutine: &Gc<JsObject>,
2875 kind: ResumeKind,
2876 value: Value,
2877 ) -> JsResult<(Value, bool)> {
2878 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2879 ObjectKind::Generator(state) => {
2880 let is_async = state.is_async;
2881 Some(std::mem::replace(
2882 state.as_mut(),
2883 GeneratorState {
2884 frame: None,
2885 phase: GeneratorPhase::Executing,
2886 parked_on_await: false,
2887 parked_on_yield_star: false,
2888 requests: std::collections::VecDeque::new(),
2889 async_busy: false,
2890 is_async,
2891 },
2892 ))
2893 }
2894 _ => None,
2895 }) else {
2896 return Err(self.type_error("not a coroutine"));
2897 };
2898 let result = self.step_generator(&mut state, kind, value);
2899 coroutine.with_mut(|data| {
2900 data.kind = ObjectKind::Generator(Box::new(state));
2901 });
2902 let (value, done, _ready, _reason) = result?;
2903 Ok((value, done))
2904 }
2905
2906 /// Advance an async body and settle its promise with the outcome.
2907 fn drive_async(
2908 &mut self,
2909 coroutine: &Gc<JsObject>,
2910 promise: &Gc<JsObject>,
2911 kind: ResumeKind,
2912 value: Value,
2913 ) -> JsResult<()> {
2914 match self.resume_coroutine(coroutine, kind, value) {
2915 Ok((value, true)) => {
2916 // `Ok` with `done` means the body finished *normally*, even when it was
2917 // resumed by a `throw` — `try { await p } catch {}` completes by
2918 // returning. Only the `Err` arm below is a rejection.
2919 //
2920 // Resolving rather than fulfilling matters: `return promise` in an async
2921 // body adopts the inner promise, so `async function f(){ return
2922 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2923 // promise.
2924 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2925 self.reject_promise(promise, reason);
2926 }
2927 Ok(())
2928 }
2929 Ok((value, false)) => {
2930 // Parked on `await`: follow what it awaited and resume with the outcome.
2931 let awaited = match self.promise_resolve_value(value) {
2932 Ok(awaited) => awaited,
2933 Err(Signal::Throw(error)) => {
2934 self.reject_promise(promise, error);
2935 return Ok(());
2936 }
2937 Err(other) => return Err(other),
2938 };
2939 self.hook_await(awaited, coroutine, promise)
2940 }
2941 Err(Signal::Throw(reason)) => {
2942 self.reject_promise(promise, reason);
2943 Ok(())
2944 }
2945 Err(other) => Err(other),
2946 }
2947 }
2948
2949 /// Arrange for `coroutine` to resume when `awaited` settles.
2950 fn hook_await(
2951 &mut self,
2952 awaited: Value,
2953 coroutine: &Gc<JsObject>,
2954 promise: &Gc<JsObject>,
2955 ) -> JsResult<()> {
2956 let resumed = JsObject::function(
2957 self.heap,
2958 Some(self.realm.function_proto.clone()),
2959 Callable::AwaitResume {
2960 coroutine: coroutine.clone(),
2961 promise: promise.clone(),
2962 kind: ResumeKind::Next,
2963 },
2964 );
2965 let raised = JsObject::function(
2966 self.heap,
2967 Some(self.realm.function_proto.clone()),
2968 Callable::AwaitResume {
2969 coroutine: coroutine.clone(),
2970 promise: promise.clone(),
2971 kind: ResumeKind::Throw,
2972 },
2973 );
2974 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2975 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2976 let Value::Object(awaited) = &awaited else {
2977 self.jobs.push_back(Job::Resume {
2978 coroutine: coroutine.clone(),
2979 promise: promise.clone(),
2980 kind: ResumeKind::Next,
2981 value: awaited,
2982 });
2983 return Ok(());
2984 };
2985 self.perform_then(
2986 awaited,
2987 Some(Value::Object(resumed)),
2988 Some(Value::Object(raised)),
2989 )?;
2990 Ok(())
2991 }
2992
2993 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2994 /// things an engine keeps outside it — array elements and an array's `length`.
2995 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2996 if let Some(property) = object.own_property_key(key) {
2997 return Some(property);
2998 }
2999 // A typed array's indices are bytes in its buffer, so a descriptor for one has to
3000 // be synthesized too — and every one of them is a plain writable, enumerable,
3001 // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
3002 // `undefined` before this, which made `key-is-numericindex` fail on its own
3003 // side effect check.
3004 //
3005 // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
3006 // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
3007 // likewise not elements however numeric they look.
3008 if object.typed_array_element_type().is_some()
3009 && let Some(numeric) = canonical_numeric_index(key)
3010 && numeric.is_finite()
3011 && numeric.fract() == 0.0
3012 && !(numeric == 0.0 && numeric.is_sign_negative())
3013 && numeric >= 0.0
3014 && (numeric as usize) < object.typed_array_length().unwrap_or(0)
3015 {
3016 let value = object.typed_array_element(numeric as usize)?;
3017 return Some(Property::data(value));
3018 }
3019 // An array's elements live in their own vector rather than the property table, so
3020 // a descriptor for one has to be synthesized — with the attributes an element has.
3021 if let Some(index) = key.as_str().and_then(array_index)
3022 && let Some(value) = object.array_get(index as usize)
3023 && !matches!(value, Value::Hole)
3024 {
3025 return Some(Property::data(value));
3026 }
3027 // `length` is an own property of an array that is not in its property table
3028 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
3029 // and non-enumerable.
3030 if key.as_str() == Some("length")
3031 && let Some(length) = object.array_length()
3032 {
3033 return Some(Property {
3034 value: Some(crate::object::length_value(length)),
3035 writable: object.length_writable(),
3036 enumerable: false,
3037 configurable: false,
3038 getter: None,
3039 setter: None,
3040 descriptor_fields: None,
3041 });
3042 }
3043 None
3044 }
3045
3046 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
3047 pub fn object_get_own_property(
3048 &mut self,
3049 object: &Gc<JsObject>,
3050 key: &PropertyKey,
3051 ) -> JsResult<Option<Property>> {
3052 if let Some(answer) = self.proxy_get_own_property(object, key)? {
3053 return Ok(answer);
3054 }
3055 if let Some(exotic) = object.exotic()
3056 && let Some(answer) = exotic.get_own_property(self, object, key)?
3057 {
3058 return Ok(answer);
3059 }
3060 // A module namespace's bindings are accessors internally and data properties to
3061 // script; see `namespace_own_property`.
3062 if object.module_namespace_marker() {
3063 return self.namespace_own_property(object, key);
3064 }
3065 // A mapped `arguments` index is a data property as far as script can see: the
3066 // accessor pair that aliases the parameter is plumbing, and exposing it would
3067 // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
3068 // report a `get` where the spec has a `[[Value]]`.
3069 if let Some(index) = key.as_str().and_then(crate::object::array_index)
3070 && let Some(cell) = object.mapped_argument_cell(index as usize)
3071 {
3072 // Non-configurable is *not* the default: an ordinary mapped index is
3073 // configurable, and only becomes non-configurable once something
3074 // redefines it. Preserve whatever the property table currently says.
3075 // The attributes come from whatever the property table holds, because they
3076 // can be changed independently of the mapping; only the *value* and the
3077 // data-property *kind* are the accessor's secret.
3078 let flags = Self::ordinary_own_property(object, key);
3079 if let Some(existing) = &flags
3080 && !existing.is_accessor()
3081 {
3082 // Already demapped: the table entry is the answer, not the cell.
3083 return Ok(flags);
3084 }
3085 return Ok(Some(Property {
3086 value: Some(cell.get()),
3087 writable: true,
3088 enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
3089 configurable: flags.as_ref().is_some_and(|p| p.configurable),
3090 ..Property::default()
3091 }));
3092 }
3093 Ok(Self::ordinary_own_property(object, key))
3094 }
3095
3096 /// Whether `object` is a module namespace exotic object (§10.4.6).
3097 ///
3098 /// Recognised by shape rather than by a flag: a namespace is the only object whose
3099 /// properties are all accessors over a `ModuleBinding` cell. That is the same
3100 /// identification `Set`/`Add` membership tests use on function objects, and it keeps the
3101 /// distinction in one place instead of adding a boolean every constructor has to
3102 /// remember to set.
3103 pub fn is_module_namespace(&self, object: &Gc<JsObject>) -> bool {
3104 object.module_namespace_marker()
3105 }
3106
3107 /// `[[GetOwnProperty]]` for a module namespace exotic object.
3108 ///
3109 /// The bindings are stored as getters — that is the only way a live binding can be read
3110 /// through the namespace — but §10.4.6.5 says the *observable* descriptor is a data
3111 /// descriptor:
3112 ///
3113 /// ```text
3114 /// { [[Value]]: current value, [[Writable]]: true,
3115 /// [[Enumerable]]: true, [[Configurable]]: false }
3116 /// ```
3117 ///
3118 /// So `Object.getOwnPropertyDescriptor(ns, "x").writable` is `true`, and `.get` is
3119 /// `undefined`. Reporting the accessor instead — which is what the property table holds
3120 /// — made every one of test262's namespace descriptor assertions fail, in both the
3121 /// `await-ns-*` and `promise-then-ns-*` families.
3122 ///
3123 /// `[[Configurable]]: false` is why `Reflect.defineProperty(ns, "x", {value: 1})` answers
3124 /// `true` only when the new value is `SameValue` the current one (`await-ns-define-own-
3125 /// property`); the ordinary descriptor machinery derives that from these attributes.
3126 pub fn namespace_own_property(
3127 &mut self,
3128 object: &Gc<JsObject>,
3129 key: &PropertyKey,
3130 ) -> JsResult<Option<Property>> {
3131 let Some(stored) = Self::ordinary_own_property(object, key) else {
3132 return Ok(None);
3133 };
3134 let Some(Property {
3135 getter: Some(getter),
3136 ..
3137 }) = Some(&stored)
3138 else {
3139 return Ok(Some(stored));
3140 };
3141 // Reading the binding is what a namespace `[[Get]]` does, and it can run script
3142 // (`export let x` assigned by a getter elsewhere), so the value is materialised here
3143 // rather than stored.
3144 let value = self.call_value(getter.clone(), Value::Object(object.clone()), Vec::new())?;
3145 Ok(Some(Property {
3146 value: Some(value),
3147 writable: true,
3148 enumerable: true,
3149 configurable: false,
3150 ..Property::default()
3151 }))
3152 }
3153
3154 /// `[[DefineOwnProperty]]` for a module namespace exotic object (§10.4.6.6).
3155 ///
3156 /// Modelled as "does this descriptor describe the property that is already there?",
3157 /// because a namespace property's attributes are fixed and its value cannot be changed
3158 /// through the namespace. The three ways to succeed:
3159 ///
3160 /// * a descriptor that names no field at all (`Reflect.defineProperty(ns, k, {})`);
3161 /// * one whose `[[Value]]` is `SameValue` the current binding value;
3162 /// * one whose attribute fields all restate `{writable: true, enumerable: true,
3163 /// configurable: false}`.
3164 ///
3165 /// `@@toStringTag` is a real own property of the namespace (a data property, writable
3166 /// false), so it goes through the same check against its stored value — which is what
3167 /// makes `{value: "Module", writable: false, enumerable: false, configurable: false}`
3168 /// answer `true` while `{value: "Other"}` answers `false`.
3169 fn namespace_define_own_property(
3170 &mut self,
3171 object: &Gc<JsObject>,
3172 key: &PropertyKey,
3173 property: &Property,
3174 ) -> JsResult<bool> {
3175 let Some(current) = self.namespace_own_property(object, key)? else {
3176 // A name the namespace does not export cannot be added to it.
3177 return Ok(false);
3178 };
3179 if let Some(value) = &property.value {
3180 let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3181 if !self.same_value(value, current_value)? {
3182 return Ok(false);
3183 }
3184 }
3185 Ok(true)
3186 }
3187
3188 /// `[[DefineOwnProperty]]` for a namespace, driven by the *descriptor object*.
3189 ///
3190 /// §10.4.6.6 is worded entirely in terms of which fields the descriptor **has**: "If
3191 /// Desc has [[Value]] and SameValue(Desc.[[Value]], current) is false, return false",
3192 /// then the same for [[Writable]], [[Enumerable]] and [[Configurable]], then true. A
3193 /// descriptor with no fields at all therefore succeeds, which is what
3194 /// `Reflect.defineProperty(ns, k, {})` checks.
3195 ///
3196 /// Taking the *merged* `Property` instead cannot work: the merge inherits from the
3197 /// stored property, and a namespace stores its bindings as accessors, so every
3198 /// definition looked like "accessor → data kind changed" or carried `writable: false`
3199 /// from the accessor's own entry. Presence is only available here, before the merge.
3200 pub fn namespace_define_from_descriptor(
3201 &mut self,
3202 object: &Gc<JsObject>,
3203 key: &PropertyKey,
3204 descriptor: &Gc<JsObject>,
3205 ) -> JsResult<bool> {
3206 let Some(current) = self.namespace_own_property(object, key)? else {
3207 return Ok(false);
3208 };
3209 // An accessor descriptor can never describe a namespace binding.
3210 if self.get_property(descriptor, "get")?.is_some()
3211 || self.get_property(descriptor, "set")?.is_some()
3212 {
3213 return Ok(false);
3214 }
3215 if let Some(value) = self.get_property(descriptor, "value")? {
3216 let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3217 if !self.same_value(&value, current_value)? {
3218 return Ok(false);
3219 }
3220 }
3221 // The three attribute fields, when named, must restate what the property already
3222 // has. Not a fixed shape: an exported binding reports
3223 // `{writable: true, enumerable: true, configurable: false}` while `@@toStringTag`
3224 // is a real own data property with `{false, false, false}`, and both are namespace
3225 // properties. Comparing against `current` is what makes one rule cover both.
3226 for (name, have) in [
3227 ("writable", current.writable),
3228 ("enumerable", current.enumerable),
3229 ("configurable", current.configurable),
3230 ] {
3231 if let Some(named) = self.get_property(descriptor, name)?
3232 && named.to_boolean() != have
3233 {
3234 return Ok(false);
3235 }
3236 }
3237 Ok(true)
3238 }
3239
3240 /// `SameValue` (§7.2.9), exposed because the namespace's `[[DefineOwnProperty]]` needs to
3241 /// compare a requested value against a live binding.
3242 pub fn same_value(&mut self, a: &Value, b: &Value) -> JsResult<bool> {
3243 Ok(a.same_value(b))
3244 }
3245
3246 ///
3247 /// Written for `Error.prototype.stack`'s setter and the exact mechanism
3248 /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
3249 /// abstract operation here rather than a private helper in `error.rs`.
3250 ///
3251 /// The name is the whole point: the setter must behave as if the prototype were not
3252 /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3253 /// the accessor for every error object in the realm. Everything below follows from that:
3254 ///
3255 /// 1. `thisValue` must be an object — otherwise `TypeError`.
3256 /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3257 /// accessor's own home an error rather than a self-shadow.
3258 /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3259 /// either has a string or has made a mistake.
3260 /// 4. An existing *own* property decides the path — an own setter is called, an own
3261 /// non-writable data property is a `TypeError` — and only a missing own property
3262 /// falls through to defining one.
3263 /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3264 /// traps and a non-extensible receiver is a `TypeError`.
3265 ///
3266 /// The installed shape is writable + configurable, not enumerable.
3267 pub fn setter_that_ignores_prototype_properties(
3268 &mut self,
3269 this_value: Value,
3270 home: &Gc<JsObject>,
3271 property_key: &str,
3272 args: &[Value],
3273 ) -> JsResult<Value> {
3274 self.setter_that_ignores_prototype_properties_key(
3275 this_value,
3276 home,
3277 &PropertyKey::from(property_key),
3278 args,
3279 )
3280 }
3281
3282 /// [`Interp::setter_that_ignores_prototype_properties`] for a key that may be a symbol.
3283 ///
3284 /// `Iterator.prototype[@@toStringTag]`'s setter is the symbol-keyed caller.
3285 pub fn setter_that_ignores_prototype_properties_key(
3286 &mut self,
3287 this_value: Value,
3288 home: &Gc<JsObject>,
3289 key: &PropertyKey,
3290 args: &[Value],
3291 ) -> JsResult<Value> {
3292 let Some(receiver) = this_value.as_object().cloned() else {
3293 return Err(self.type_error("setter called on a non-object"));
3294 };
3295 if Gc::ptr_eq(&receiver, home) {
3296 return Err(self.type_error("cannot assign to the accessor's own home object"));
3297 }
3298 // No type check here: §7.3.40 takes an arbitrary `v`, and
3299 // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3300 // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3301 // before calling this.
3302 let value = args.first().cloned().unwrap_or(Value::Undefined);
3303 // Step 4: an own property on the receiver changes what happens, and there are three
3304 // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3305 // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3306 // `Set` with `throw = true`, and a test exists for each.
3307 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
3308 if existing.is_accessor() && existing.setter.is_none() {
3309 // A getter-only own accessor cannot be written through.
3310 return Err(self.type_error("no setter for the own property"));
3311 }
3312 // Everything else — an own data property, or an own accessor *with* a setter —
3313 // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3314 // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3315 // an own user setter receives the value (`setter-own-accessor`), because
3316 // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3317 // setter directly is the difference between one code path and two that can
3318 // disagree.
3319 self.set_property_with_key(
3320 &receiver,
3321 key,
3322 value.clone(),
3323 crate::interp::DeleteFailure::Throw,
3324 )?;
3325 return Ok(Value::Undefined);
3326 }
3327 let property = Property {
3328 value: Some(value.clone()),
3329 writable: true,
3330 // Enumerable, despite the accessor it shadows not being. The reference installs
3331 // it that way and six cases check it (`setter-creates-own-property` and friends).
3332 enumerable: true,
3333 configurable: true,
3334 ..Property::default()
3335 };
3336 if !self.object_define_own_property(&receiver, key, property)? {
3337 return Err(self.type_error("the receiver refused the definition"));
3338 }
3339 Ok(Value::Undefined)
3340 }
3341
3342 /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3343 ///
3344 /// The indices of a typed array are not properties at all — they are bytes in the
3345 /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3346 /// fly. That makes their descriptor shape fixed: every valid index is writable,
3347 /// enumerable and configurable, so a definition can only ever change the *value*, and
3348 /// every other descriptor is refused rather than applied.
3349 ///
3350 /// The order of the checks is the spec's, and two of them are load-bearing:
3351 ///
3352 /// * the index is validated **before** the value is converted, because the conversion
3353 /// itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3354 /// detaches from a `valueOf` and still expects `true` with no store, which only
3355 /// happens when the index was valid on the way in;
3356 /// * the store is attempted even when the index has gone out of bounds by the time the
3357 /// conversion finishes, because the store is a silent no-op rather than a failure —
3358 /// the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3359 /// the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3360 ///
3361 /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3362 /// the existing element, which is harmless here: every valid index is already
3363 /// writable, enumerable and configurable, so a `false` in the merged property can only
3364 /// have come from the descriptor having named `false`.
3365 fn integer_indexed_define_own_property(
3366 &mut self,
3367 object: &Gc<JsObject>,
3368 numeric: f64,
3369 property: &Property,
3370 ) -> JsResult<bool> {
3371 // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3372 // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3373 if !typed_array_index_is_valid(object, numeric) {
3374 return Ok(false);
3375 }
3376 // Step 6: the indices are data properties, so an accessor descriptor is refused
3377 // rather than converted. `Object.defineProperty` turns the `false` into a
3378 // `TypeError`; `Reflect.defineProperty` reports it.
3379 if property.is_accessor() {
3380 return Ok(false);
3381 }
3382 // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3383 // definition that asks for anything else cannot be honoured.
3384 if !property.writable || !property.enumerable || !property.configurable {
3385 return Ok(false);
3386 }
3387 // Step 10: only a descriptor that names a value stores anything.
3388 let Some(value) = property.value.clone() else {
3389 return Ok(true);
3390 };
3391 let Some(element) = object.typed_array_element_type() else {
3392 return Ok(false);
3393 };
3394 let stored = self.element_value(element, value)?;
3395 if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3396 return Err(self.type_error(reason));
3397 }
3398 Ok(true)
3399 }
3400
3401 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3402 pub fn object_define_own_property(
3403 &mut self,
3404 object: &Gc<JsObject>,
3405 key: &PropertyKey,
3406 property: Property,
3407 ) -> JsResult<bool> {
3408 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3409 return Ok(accepted);
3410 }
3411 // §10.4.6.6 `[[DefineOwnProperty]]` for a module namespace.
3412 //
3413 // The only definitions that can succeed are ones describing the property the
3414 // namespace *already* has: `Reflect.defineProperty(ns, "x", {})` asks for no change
3415 // and answers `true`; so does `{value: <SameValue current>}` or the exact attribute
3416 // set `{writable: true, enumerable: true, configurable: false}`. A different value,
3417 // `writable: false`, `configurable: true`, or any name the namespace does not
3418 // export is `false`.
3419 //
3420 // The ordinary path gets the no-change case right by accident — it compares against
3421 // `[[GetOwnProperty]]` — but cannot describe a namespace binding, because the binding
3422 // is an accessor internally while the definition script writes is a data descriptor.
3423 // Answering here is what makes that attribute-only definition a no-op rather than a
3424 // refusal (`namespace/await-ns-define-own-property`).
3425 if object.module_namespace_marker() {
3426 return self.namespace_define_own_property(object, key, &property);
3427 }
3428 // A proxy always answers above — with `Some` from its trap, or with `None` when
3429 // the trap is absent, and then the definition belongs to the **target**
3430 // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3431 // when there is no trap). Falling through to the ordinary path here defined the
3432 // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3433 // property the target never saw.
3434 if object.proxy_state().is_some() {
3435 let Some((target, _handler)) = self.proxy_parts(object)? else {
3436 return Err(self.type_error("cannot use a proxy that has been revoked"));
3437 };
3438 return self.object_define_own_property(&target, key, property);
3439 }
3440 // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3441 // they accept exactly one descriptor shape. This has to happen before the
3442 // ordinary path, which would happily store a data property next to the buffer —
3443 // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3444 // and `TypedArray/prototype/set` are about this section.
3445 if object.typed_array_element_type().is_some()
3446 && let Some(index) = canonical_numeric_index(key)
3447 {
3448 return self.integer_indexed_define_own_property(object, index, &property);
3449 }
3450 // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3451 // non-extensible object. The check lives here rather than in the callers because
3452 // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3453 // `Array.prototype.filter` uses to store its result, and a species object made
3454 // non-extensible by its own constructor must make that a `TypeError`
3455 // (`target-array-non-extensible`).
3456 // Note the `is_none()`: an already-present property may still be **redefined** on a
3457 // non-extensible object, and only *adding* one is refused (as Distinct from
3458 // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3459 // properties — testing extensibility before looking for the property made every
3460 // `Object.freeze` of an ordinary object refuse its own second step).
3461 if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3462 return Ok(false);
3463 }
3464 // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3465 // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3466 // an omitted field is left alone). Merging here rather than at each call site is
3467 // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3468 // the value and `enumerable` in place.
3469 //
3470 // The merge is a no-op when the property is absent: there is nothing to keep.
3471 let was_partial = property.descriptor_fields.is_some();
3472 let property = match property.descriptor_fields {
3473 None => property,
3474 Some(fields) => {
3475 let base = self.object_get_own_property(object, key)?;
3476 let mut merged = base.clone().unwrap_or_default();
3477 // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3478 // descriptor names, and switching kind discards the other half —
3479 // `{set: f}` on a data property is an accessor with no getter, not a data
3480 // property whose `get` happens to be absent.
3481 let wants_accessor = fields.get || fields.set;
3482 let wants_data = fields.value || fields.writable;
3483 if wants_accessor {
3484 merged.value = None;
3485 merged.writable = false;
3486 merged.getter = property.getter.clone();
3487 merged.setter = property.setter.clone();
3488 } else if wants_data {
3489 merged.getter = None;
3490 merged.setter = None;
3491 if fields.value {
3492 merged.value = property.value.clone();
3493 }
3494 if fields.writable {
3495 merged.writable = property.writable;
3496 }
3497 }
3498 if fields.enumerable {
3499 merged.enumerable = property.enumerable;
3500 }
3501 if fields.configurable {
3502 merged.configurable = property.configurable;
3503 }
3504 merged.descriptor_fields = None;
3505 merged
3506 }
3507 };
3508 // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3509 // descriptor. `define_property_on` runs the same check before it calls here, so an
3510 // ordinary object is already covered; what is *not* is the forwarding a proxy does
3511 // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3512 // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3513 // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3514 // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3515 // own define would have refused.
3516 //
3517 // Only partial descriptors are validated here. A whole `Property` passed by an
3518 // internal caller (`Property::data(…)`) carries attributes that say nothing about
3519 // what the descriptor "named", and those callers rely on the write landing.
3520 if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3521 // Every branch below is gated on `!existing.configurable`: a *configurable*
3522 // property may be reshaped however the descriptor likes, which is why an
3523 // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3524 // must succeed. Testing only `writable` refused that and broke
3525 // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3526 let same_kind = existing.is_accessor() == property.is_accessor();
3527 if !same_kind {
3528 // Step 4: a non-configurable property may not change kind.
3529 if !existing.configurable {
3530 return Ok(false);
3531 }
3532 } else if existing.is_accessor() {
3533 // Step 6: an accessor's halves are its value.
3534 if !existing.configurable
3535 && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3536 || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3537 {
3538 return Ok(false);
3539 }
3540 } else if !existing.configurable && !existing.writable {
3541 // Step 7: a non-configurable *and* non-writable data property's value is
3542 // fixed, and it may not become writable again.
3543 if property.writable {
3544 return Ok(false);
3545 }
3546 let current = existing.value.clone().unwrap_or(Value::Undefined);
3547 let requested = property.value.clone().unwrap_or(Value::Undefined);
3548 if !current.same_value(&requested) {
3549 return Ok(false);
3550 }
3551 }
3552 // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3553 // is frozen with it.
3554 if !existing.configurable
3555 && (property.configurable || property.enumerable != existing.enumerable)
3556 {
3557 return Ok(false);
3558 }
3559 }
3560 // A host class that intercepts definitions owns the attributes of the properties it
3561 // defines: `_class`-style storage on the native side is the usual reason.
3562 if let Some(exotic) = object.exotic()
3563 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3564 {
3565 return Ok(accepted);
3566 }
3567 // An array index is stored in the element vector, which can hold a plain value and
3568 // nothing else. An accessor — or a data property with non-default attributes —
3569 // therefore has to live in the property table, and the element slot is blanked so
3570 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3571 // {get})` stored the accessor where no read ever looked, and the array kept
3572 // answering its old value.
3573 // An array's `length` is not stored in the property table, so defining it has to
3574 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3575 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3576 // {value: 1})` reported success and changed nothing.
3577 if key.as_str() == Some("length") && object.is_array() {
3578 // `{writable: false}` on `length` does not change the length, but it does make
3579 // it read-only — after which neither a later `{writable: true}` nor a store
3580 // past the end may succeed.
3581 if property.value.is_none() {
3582 if !object.length_writable() && property.writable {
3583 return Ok(false);
3584 }
3585 object.set_length_writable(property.writable);
3586 return Ok(true);
3587 }
3588 if !object.length_writable() {
3589 return Ok(false);
3590 }
3591 }
3592 if key.as_str() == Some("length")
3593 && object.is_array()
3594 && let Some(value) = property.value.clone()
3595 {
3596 let requested = value.to_number();
3597 let valid = requested.is_finite()
3598 && requested >= 0.0
3599 && requested.fract() == 0.0
3600 && requested <= u32::MAX as f64;
3601 if !valid {
3602 return Err(self.range_error("invalid array length"));
3603 }
3604 // Truncating deletes the elements above the new length, and a non-configurable
3605 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3606 // makes `a.length = 2` fail rather than quietly drop it.
3607 let current = object.array_length().unwrap_or(0);
3608 let requested = requested as usize;
3609 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3610 // §10.4.2.4 `ArraySetLength` step 3.i.2: the refusal still applies
3611 // `[[Writable]]: false` when the descriptor asked for it — the length is
3612 // left at its old value but locked. Returning `false` alone left it
3613 // writable, which `verifyProperty` catches
3614 // (`defineProperties/15.2.3.7-6-a-164`).
3615 if property
3616 .descriptor_fields
3617 .is_some_and(|fields| fields.writable)
3618 && !property.writable
3619 && object.length_writable()
3620 {
3621 object.set_length_writable(false);
3622 }
3623 return Ok(false);
3624 }
3625 object.array_set_length(self.heap, requested);
3626 return Ok(true);
3627 }
3628 let plain = property.writable
3629 && property.enumerable
3630 && property.configurable
3631 && !property.is_accessor();
3632 if let Some(index) = key.as_str().and_then(array_index)
3633 && object.is_array()
3634 {
3635 // Growing the array needs a writable `length`: after
3636 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3637 // be added.
3638 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3639 return Ok(false);
3640 }
3641 if plain && property.value.is_some() {
3642 // An ordinary element: the vector is where a read looks first, so it has
3643 // to be the vector that changes — unless the index is too far out to be
3644 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3645 // one property, because past its own limit it stores the index as an
3646 // ordinary key. Falling through to `define_key` below is the same choice,
3647 // and the alternative was worse: the store used to be *dropped* and the
3648 // length left at 0, which is a silent wrong answer.
3649 let value = property.value.clone().unwrap_or(Value::Undefined);
3650 object.delete_key(key);
3651 if object.array_set(self.heap, index as usize, value) {
3652 return Ok(true);
3653 }
3654 // Past the dense limit the element lives in the table like any property.
3655 object.note_element_descriptor();
3656 object.define_key(key, property);
3657 // A sparse store past the dense limit still extends `length`, which is what
3658 // `a[a.length] = v` relies on — but only extends: shortening would delete
3659 // the sparse properties above the index, including this one.
3660 if index as usize + 1 > object.array_length().unwrap_or(0) {
3661 object.array_set_length(self.heap, index as usize + 1);
3662 }
3663 return Ok(true);
3664 }
3665 // A non-plain element — an accessor, or an attribute that is not the default —
3666 // lives in the table while the slot becomes a hole. Recording it keeps every
3667 // later `a[i] = v` off the dense path, where the write would have shadowed the
3668 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3669 // replace the accessor with a plain data property.
3670 object.note_element_descriptor();
3671 object.define_key(key, property);
3672 // The slot stays, so `length` does not shrink; a hole is not an element, so
3673 // the table entry is now what a read finds.
3674 object.array_set(self.heap, index as usize, Value::Hole);
3675 // `ArraySetLength` step 2 of `OrdinaryDefineOwnProperty`'s index branch —
3676 // `length = index + 1` — applies whatever the descriptor's *attributes* are,
3677 // not just to a plain one: `Object.defineProperty(a, 4294967294, {value: 100})`
3678 // makes `a.length` 4294967295 (`defineProperty/15.2.3.6-4-183`).
3679 if index as usize + 1 > object.array_length().unwrap_or(0) {
3680 object.array_set_length(self.heap, index as usize + 1);
3681 }
3682 return Ok(true);
3683 }
3684 object.define_key(key, property);
3685 Ok(true)
3686 }
3687
3688 /// Build a proxy object over `target`, with its traps read from `handler`.
3689 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3690 JsObject::proxy(self.heap, target, handler)
3691 }
3692
3693 /// The `revoke` function for a proxy's slots.
3694 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3695 let revoke = JsObject::function(
3696 self.heap,
3697 Some(self.realm.function_proto.clone()),
3698 Callable::Revoker(slots),
3699 );
3700 // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3701 // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3702 // inherited from `Function.prototype` reads the same but fails the three cases that
3703 // check the own-property list (`revocation-function-{length,name,property-order}`).
3704 revoke.define("length", Property::name_or_length(Value::Int(0)));
3705 revoke.define("name", Property::name_or_length(self.string("")));
3706 revoke
3707 }
3708
3709 /// A new array.
3710 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3711 let array = JsObject::array(
3712 self.heap,
3713 Some(self.realm.array_proto.clone()),
3714 elements.len(),
3715 );
3716 for (index, element) in elements.into_iter().enumerate() {
3717 array.array_set(self.heap, index, element);
3718 }
3719 array
3720 }
3721
3722 /// A new native function object.
3723 ///
3724 /// The observable `name` and `length` are installed as properties here, which is
3725 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3726 /// so `f.name = "x"` behaves like the writable property it is.
3727 /// A native constructor that builds its own instance after validating its arguments.
3728 ///
3729 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3730 /// check runs before `new.target.prototype` is read.
3731 pub fn new_native_ctor(
3732 &self,
3733 name: impl Into<String>,
3734 length: u32,
3735 func: NativeFn,
3736 ) -> Gc<JsObject> {
3737 let function = JsObject::function(
3738 self.heap,
3739 Some(self.realm.function_proto.clone()),
3740 Callable::Native {
3741 func,
3742 own_instance: true,
3743 },
3744 );
3745 function.set_constructible(true);
3746 function.define(
3747 "length",
3748 Property::name_or_length(Value::Int(length as i32)),
3749 );
3750 function.define("name", Property::name_or_length(self.string(name)));
3751 function
3752 }
3753
3754 /// A native constructor that lets `new` build the instance first.
3755 ///
3756 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3757 /// validation that must precede reading `new.target.prototype`, so the object can be
3758 /// created before the implementation runs. Distinct from [`Interp::new_native`],
3759 /// which makes a *method* and therefore not a constructor at all.
3760 pub fn new_native_constructor(
3761 &self,
3762 name: impl Into<String>,
3763 length: u32,
3764 func: NativeFn,
3765 ) -> Gc<JsObject> {
3766 let function = self.new_native(name, length, func);
3767 function.set_constructible(true);
3768 function
3769 }
3770
3771 /// A new host function object: a native closure that carries its own state.
3772 ///
3773 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3774 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3775 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3776 /// this safe: the closure must not capture a `Gc`.
3777 pub fn new_host_function(
3778 &self,
3779 name: impl Into<String>,
3780 length: u32,
3781 func: crate::object::HostFn,
3782 ) -> Gc<JsObject> {
3783 self.new_host_inner(name.into(), length, func, false)
3784 }
3785
3786 /// A host constructor: `new` hands it `this = undefined`, so it validates its
3787 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3788 pub fn new_host_ctor(
3789 &self,
3790 name: impl Into<String>,
3791 length: u32,
3792 func: crate::object::HostFn,
3793 ) -> Gc<JsObject> {
3794 let function = self.new_host_inner(name.into(), length, func, true);
3795 function.set_constructible(true);
3796 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3797 // installs its own methods on it, so it starts as a plain object.
3798 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3799 function.define(
3800 "prototype",
3801 Property {
3802 value: Some(Value::Object(proto)),
3803 writable: true,
3804 enumerable: false,
3805 configurable: false,
3806 ..Property::default()
3807 },
3808 );
3809 function
3810 }
3811
3812 fn new_host_inner(
3813 &self,
3814 name: String,
3815 length: u32,
3816 func: crate::object::HostFn,
3817 own_instance: bool,
3818 ) -> Gc<JsObject> {
3819 let function = JsObject::function(
3820 self.heap,
3821 Some(self.realm.function_proto.clone()),
3822 Callable::Host {
3823 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3824 own_instance,
3825 },
3826 );
3827 function.define(
3828 "length",
3829 Property::name_or_length(Value::Int(length as i32)),
3830 );
3831 function.define("name", Property::name_or_length(self.string(name)));
3832 function
3833 }
3834
3835 /// A callable object with the `length`/`name` a built-in function has, in that order.
3836 ///
3837 /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3838 /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3839 /// [`JsObject::function`] defines neither, which is why every capability helper built
3840 /// with it reported no own `length` and no own `name` at all.
3841 ///
3842 /// The attributes are the spec's for a built-in: not writable, not enumerable,
3843 /// configurable.
3844 pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3845 let function =
3846 JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3847 function.define(
3848 "length",
3849 Property::name_or_length(Value::Int(length as i32)),
3850 );
3851 function.define("name", Property::name_or_length(self.string(name)));
3852 function
3853 }
3854
3855 /// A new native function object.
3856 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3857 let function = JsObject::function(
3858 self.heap,
3859 Some(self.realm.function_proto.clone()),
3860 Callable::Native {
3861 func,
3862 own_instance: false,
3863 },
3864 );
3865 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3866 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3867 // `length,name` and this listed `name,length`. A bytecode function already gets it
3868 // the right way round; only native ones were built backwards.
3869 function.define(
3870 "length",
3871 Property::name_or_length(Value::Int(length as i32)),
3872 );
3873 function.define("name", Property::name_or_length(self.string(name)));
3874 function
3875 }
3876
3877 /// A new bound function.
3878 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3879 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3880 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3881 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3882 let constructible = target
3883 .as_object()
3884 .is_some_and(|target| target.is_constructor());
3885 let bound = JsObject::function(
3886 self.heap,
3887 Some(self.realm.function_proto.clone()),
3888 Callable::Bound { target, this, args },
3889 );
3890 bound.set_constructible(constructible);
3891 bound
3892 }
3893
3894 /// A new reference cell.
3895 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3896 Gc::new(self.heap, Cell::new(value))
3897 }
3898
3899 // -- running ------------------------------------------------------------
3900
3901 /// Evaluate `code` as a script body and return its completion value.
3902 /// Compile and run `source` for the engine's own use, returning its completion value.
3903 ///
3904 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3905 /// needs to be a real async function, and the engine already runs those as coroutines,
3906 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3907 ///
3908 /// Differences from [`Self::eval_in_global`], both deliberate:
3909 ///
3910 /// * It does **not** drain the microtask queue. Install runs while the realm is still
3911 /// being built, and the source is an IIFE that only constructs a closure, so there
3912 /// is nothing to drain — and draining here would run script-queued jobs in the
3913 /// middle of `install`.
3914 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3915 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3916 /// and it should not look like the user wrote something wrong.
3917 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3918 let program = match js_parse::parse_script(source) {
3919 Ok(program) => program,
3920 Err(error) => {
3921 let message = format!("builtin source does not parse: {error}");
3922 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3923 }
3924 };
3925 let mut code = match js_compile::compile_script_with_source(&program, source) {
3926 Ok(code) => code,
3927 Err(error) => {
3928 let message = format!("builtin source does not compile: {}", error.message);
3929 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3930 }
3931 };
3932 // The frame has to name something, and `<builtin>` is what a stack trace through
3933 // this code should say.
3934 code.set_filename("<builtin>");
3935 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3936 let closure_vars = compiled.code.closure_vars.clone();
3937 let env = self.global_env(&closure_vars);
3938 let this = Value::Object(self.realm.global.clone());
3939 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3940 }
3941
3942 /// Run an already-parsed script and drain the microtasks it queued.
3943 ///
3944 /// The drain is what lets an `async` function's body advance past its first `await`
3945 /// before the host sees the result: nothing else pumps the job queue.
3946 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3947 let this = Value::Object(self.realm.global.clone());
3948 self.run_script_with_this(code, this)
3949 }
3950
3951 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3952 ///
3953 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3954 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3955 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3956 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3957 /// state the next script evaluation tripped over.
3958 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3959 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3960 let closure_vars = compiled.code.closure_vars.clone();
3961 let env = self.global_env(&closure_vars);
3962 let callee = Value::Undefined;
3963 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3964 // The script is done, so the microtasks it queued run before the host sees the
3965 // result. Without this an `async` function's body would never advance past its
3966 // first `await`, because nothing else drains the queue.
3967 self.drain_jobs()?;
3968 Ok(result)
3969 }
3970
3971 /// Compile and run `source` in global scope, returning its completion value.
3972 ///
3973 /// This is what `eval` and `new Function` use. Running it as a script means it
3974 /// sees the global object and nothing else, which is right for `eval("1+1")` and
3975 /// for a `Function` body; a *direct* eval that reads a local variable would need
3976 /// the compiler to hand its variable environment over, which is not implemented.
3977 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3978 self.eval_in_global_named(source, EVAL_FILE, false)
3979 }
3980
3981 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3982 ///
3983 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3984 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3985 /// through the code, so they cannot share one constant.
3986 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3987 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3988 }
3989
3990 /// Evaluate `source` as a global script, reported under `file`.
3991 ///
3992 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3993 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3994 /// from inside a C callback, where the interpreter is the running one rather than a
3995 /// context's own.
3996 pub fn eval_in_global_named(
3997 &mut self,
3998 source: &str,
3999 file: &str,
4000 barrier: bool,
4001 ) -> JsResult<Value> {
4002 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
4003 // eval-created global binding — configurable, unlike a script's own `var`.
4004 self.eval_depth += 1;
4005 if barrier {
4006 let depth = self.frames.len();
4007 self.trace_barriers.push(depth);
4008 }
4009 let result = self.eval_in_global_inner(source, file);
4010 if barrier {
4011 self.trace_barriers.pop();
4012 }
4013 self.eval_depth -= 1;
4014 result
4015 }
4016
4017 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
4018 let compiled = self.compile_global_script(source, file, false)?;
4019 let strict = compiled.strict;
4020 self.run_eval_script(compiled, strict)
4021 }
4022
4023 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
4024 ///
4025 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
4026 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
4027 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
4028 /// direct eval's is.
4029 pub fn eval_script_with_this(
4030 &mut self,
4031 source: &str,
4032 file: &str,
4033 this: Value,
4034 ) -> JsResult<Value> {
4035 let program = match js_parse::parse_script(source) {
4036 Ok(program) => program,
4037 Err(error) => {
4038 return Err(Signal::Throw(self.syntax_error_at(
4039 file,
4040 error.span.start.line,
4041 error.span.start.column,
4042 &error.message,
4043 )));
4044 }
4045 };
4046 let mut compiled = match js_compile::compile_script(&program) {
4047 Ok(compiled) => compiled,
4048 Err(error) => {
4049 return Err(Signal::Throw(self.syntax_error_at(
4050 file,
4051 error.span.start.line,
4052 error.span.start.column,
4053 &error.message,
4054 )));
4055 }
4056 };
4057 compiled.set_filename(file);
4058 self.run_script_with_this(compiled, this)
4059 }
4060
4061 /// Parse and compile `source` as a global script, without running it.
4062 ///
4063 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
4064 /// before a promise exists to reject — while still evaluating in the same eval context
4065 /// (direct-eval strictness, `new.target`, `super`).
4066 fn compile_global_script(
4067 &mut self,
4068 source: &str,
4069 file: &str,
4070 async_body: bool,
4071 ) -> JsResult<CompiledFunction> {
4072 // A *direct* eval inherits the strictness of the code that called it, which is
4073 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
4074 // implicit global. The caller's frame is the innermost one here, because a
4075 // native function does not push a frame of its own.
4076 let strict = self.current_strict();
4077 // `eval` runs in the caller's function context, so `new.target` is legal here
4078 // even though the source is a bare script — and so is `super.x` when the caller
4079 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
4080 // caller's, which is what `special_object 4` already does.
4081 // Nothing of the caller's is inherited by an *indirect* eval: `(0, eval)('super.x')`
4082 // and `(0, eval)('arguments')` are both `SyntaxError`s because there is no caller
4083 // context at all. The site is what tells the two apart — an indirect call leaves no
4084 // site behind, since only a bare `eval(...)` is recorded.
4085 let site = self.eval_site_at_cursor();
4086 let private = site
4087 .map(|site| site.private_names.clone())
4088 .unwrap_or_default();
4089 let context = js_parse::EvalContext {
4090 in_method: site.is_some() && self.enclosing_home_object().is_some(),
4091 // `super()` belongs to a derived constructor, and an eval'd body is not a
4092 // constructor at all: the caller frame's `this` is already built.
4093 in_derived_constructor: false,
4094 // Private names are lexically scoped, so a direct `eval` inside a class body
4095 // can see them; see `Interp::eval_private_names`.
4096 private_names: private.iter().map(|entry| entry.name.clone()).collect(),
4097 arguments_allowed: site.is_none_or(|site| site.arguments_allowed),
4098 new_target_allowed: site.is_some(),
4099 };
4100 // A *global* eval is not a function body: `new.target` and `super` are out of
4101 // reach there. Its `{async: true}` form differs in the other direction — the body
4102 // may `await` — so the two flags are independent and the reference sets both from
4103 // the eval type rather than from the caller.
4104 let parsed = if async_body {
4105 js_parse::parse_suspensible_global_eval(source, strict)
4106 } else {
4107 js_parse::parse_eval_script_in(source, strict, context)
4108 };
4109 let program = match parsed {
4110 Ok(program) => program,
4111 Err(error) => {
4112 // The message is bare: the position lives in `fileName`,
4113 // `lineNumber`, `columnNumber` and the stack frame above, which is where
4114 // the reference puts it. An `invalid source: L:C: ` prefix made
4115 // `e.message` differ from the reference while the stack already agreed.
4116 return Err(Signal::Throw(self.syntax_error_at(
4117 file,
4118 error.span.start.line,
4119 error.span.start.column,
4120 &error.message,
4121 )));
4122 }
4123 };
4124 let mut compiled = match if async_body {
4125 js_compile::compile_eval_with_private(&program, &private, true)
4126 } else {
4127 js_compile::compile_eval_with_private(&program, &private, false)
4128 } {
4129 Ok(compiled) => compiled,
4130 // A construct the compiler does not handle yet is reported the same way a
4131 // parse error is: it happens before anything runs, so the trace is the
4132 // position in the source followed by the caller.
4133 Err(error) => {
4134 return Err(Signal::Throw(self.syntax_error_at(
4135 file,
4136 error.span.start.line,
4137 error.span.start.column,
4138 &error.message,
4139 )));
4140 }
4141 };
4142 compiled.set_filename(file);
4143 Ok(compiled)
4144 }
4145
4146 /// The private names the code at the current position can see, innermost first.
4147 ///
4148 /// Private names are lexically scoped (§15.10.2 `AllPrivateIdentifiersValid`), and a
4149 /// direct `eval` runs inside its caller's scope, so
4150 /// `class C { #m = 44; f() { return eval("this.#m") } }` is legal. The names belong to the
4151 /// *call site's* compilation unit, so they are recorded on the `EvalSite` and read back
4152 /// here rather than being derivable from the eval'd source.
4153 ///
4154 /// An indirect `eval` gets nothing: `(0, eval)("this.#m")` outside a class is a
4155 /// `SyntaxError`, and an indirect call leaves no site behind, which is exactly the test
4156 /// [`Interp::run_eval_script`] uses for "direct".
4157 fn eval_site_at_cursor(&self) -> Option<&js_compile::bytecode::EvalSite> {
4158 let frame = self.frames.last()?;
4159 let (line, column) = frame
4160 .code
4161 .code
4162 .position_at(frame.at as u32)
4163 .unwrap_or_default();
4164 // The nearest site at or before the current position: the recorded position of the
4165 // `call` instruction is the callee's, which sits a few columns inside the call
4166 // expression the compiler recorded, so an exact match would never be found.
4167 frame
4168 .code
4169 .code
4170 .eval_sites
4171 .iter()
4172 .filter(|site| (site.line, site.column) <= (line, column))
4173 .max_by_key(|site| (site.line, site.column))
4174 }
4175
4176 /// Run an `eval`'d script in the caller's scope.
4177 ///
4178 /// Three things have to come from the calling frame, because the eval'd code is a
4179 /// script and would otherwise see only the global object:
4180 ///
4181 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
4182 /// * `arguments`, exposed as a binding of the eval's own scope, so
4183 /// `f("arguments.length", 1)` sees the caller's arguments;
4184 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
4185 /// `eval("var v = 1")` into the global object.
4186 ///
4187 /// Locals of the calling function are *not* reachable: that needs the compiler to
4188 /// hand its variable environment over, which this milestone does not do.
4189 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
4190 // `this` and `arguments` come from the innermost frame only — those are not
4191 // lexical — while the name bindings come from the whole chain of frames, part
4192 // of it being ordinary scope resolution.
4193 // An arrow has no `this` of its own, so an `eval` inside one inherits the
4194 // enclosing function's receiver — the lexical `this` the arrow was compiled to
4195 // read from its closure.
4196 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
4197 // variable environment is the innermost frame of all: an arrow's own body is where
4198 // `var`s declared by an `eval` inside it belong.
4199 let caller_index = self
4200 .frames
4201 .iter()
4202 .rposition(|frame| !frame.code.code.is_arrow)
4203 .or_else(|| self.frames.len().checked_sub(1));
4204 let env_index = self.frames.len().checked_sub(1);
4205 let caller = caller_index.and_then(|index| self.frames.get(index));
4206 let (this, passed) = match caller {
4207 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
4208 // No frame at all: the eval is running at the top level, so there is
4209 // nothing to inherit and the global receiver is right.
4210 None => (Value::Object(self.realm.global.clone()), Vec::new()),
4211 };
4212 // Innermost frame first, so the first binding found for a name is the one that
4213 // shadows the rest. A script frame (`<eval>`) contributes nothing.
4214 let mut bindings: Vec<EvalBinding> = Vec::new();
4215 // The calling function's own bindings, resolved by the compiler at the call
4216 // site. That table is the only reliable answer when a name is declared twice in
4217 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
4218 // body means, and guessing by declaration order picks the wrong one as soon as
4219 // two loops in a row use the same name.
4220 // Only a *direct* eval sees the caller's scope. The compiler records a site for
4221 // every direct call — a bare `eval(...)` callee — so finding one at the current
4222 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
4223 // callee to a value first and leave no site behind.
4224 let mut direct = false;
4225 let mut resolved_here = false;
4226 if let Some(frame) = self.frames.last() {
4227 let (line, column) = frame
4228 .code
4229 .code
4230 .position_at(frame.at as u32)
4231 .unwrap_or_default();
4232 // The nearest site at or before the current position, not an exact match:
4233 // the recorded position of the `call` instruction is the callee's, which
4234 // sits a few columns inside the call expression the compiler recorded. A
4235 // site is unique per call, so "the closest one behind us" identifies it.
4236 if let Some(site) = frame
4237 .code
4238 .code
4239 .eval_sites
4240 .iter()
4241 .filter(|site| (site.line, site.column) <= (line, column))
4242 .max_by_key(|site| (site.line, site.column))
4243 {
4244 direct = true;
4245 resolved_here = true;
4246 for binding in &site.bindings {
4247 // An enclosing function's frame sits `owner` levels below the one
4248 // running the call.
4249 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
4250 else {
4251 continue;
4252 };
4253 bindings.push(EvalBinding {
4254 name: binding.name.clone(),
4255 frame,
4256 slot: if binding.is_arg {
4257 EvalSlot::Arg
4258 } else {
4259 EvalSlot::Local
4260 },
4261 index: binding.index as usize,
4262 });
4263 }
4264 }
4265 }
4266 for frame_index in (0..self.frames.len()).rev() {
4267 // Skip the innermost frame's flat scan when the compiler already answered
4268 // for it; an enclosing frame still needs one, because the eval resolves
4269 // those names dynamically.
4270 if resolved_here && frame_index == self.frames.len() - 1 {
4271 continue;
4272 }
4273 let frame = &self.frames[frame_index];
4274 for (index, arg) in frame.code.code.args.iter().enumerate() {
4275 bindings.push(EvalBinding {
4276 name: arg.name.clone(),
4277 frame: frame_index,
4278 slot: EvalSlot::Arg,
4279 index,
4280 });
4281 }
4282 for (index, local) in frame.code.code.vars.iter().enumerate() {
4283 bindings.push(EvalBinding {
4284 name: local.name.clone(),
4285 frame: frame_index,
4286 slot: EvalSlot::Local,
4287 index,
4288 });
4289 }
4290 }
4291 let mut seen = BTreeSet::new();
4292 bindings.retain(|binding| seen.insert(binding.name.clone()));
4293
4294 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4295 // elements is all the spec's ordinary uses need.
4296 //
4297 // Known divergence: this is bound for a *global* eval too, where there is no
4298 // caller and the reference throws `'arguments' is not defined`. Deciding properly
4299 // needs "does the calling frame have an `arguments` of its own", which is not
4300 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4301 // script or eval body does not, and `eval(b)` passes the callee as a value so even
4302 // the call-site detection does not answer it. Modelled as a binding in the caller's
4303 // variable environment, this would fall out; that is a larger change than the one
4304 // this comment is attached to.
4305 let arguments = Value::Object(self.new_array(passed));
4306
4307 // Only a *strict* eval gets a variable environment of its own. A sloppy one
4308 // declares its `var`s in the caller's — which for a top-level eval is the global
4309 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4310 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4311 // vanish into a scope nobody reads back from.
4312 let previous_scope = if code_strict {
4313 self.eval_scope.replace(BTreeMap::new())
4314 } else {
4315 None
4316 };
4317 // Only a *direct* eval inherits the caller's arguments object. An indirect one runs
4318 // in global scope, where `arguments` means whatever the global object says — which
4319 // is why `var arguments = 1; class C { x = (0, eval)('arguments;') }` answers `1`
4320 // (`indirect-eval-contains-arguments`). Binding the caller's array there made it
4321 // answer the array instead.
4322 let previous_arguments = if direct {
4323 self.eval_arguments.replace(arguments)
4324 } else {
4325 None
4326 };
4327 let previous_with = self.eval_with.replace(self.with_objects());
4328 let inherited_new_target = self
4329 .frames
4330 .iter()
4331 .rev()
4332 .find(|frame| !frame.code.code.is_arrow)
4333 .map(|frame| frame.new_target.clone());
4334 let previous_new_target = self
4335 .eval_new_target
4336 .replace(inherited_new_target.unwrap_or(Value::Undefined));
4337 let eval_cells = self.eval_cells_for(&bindings);
4338 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4339 // A sloppy direct eval declares its `var`s in the caller's variable environment;
4340 // `declare_eval_local` needs to know which frame that is.
4341 // An indirect eval gets the global environment, so nothing of the caller's is
4342 // recorded as the place its `var`s belong.
4343 let previous_caller = self
4344 .eval_caller
4345 .replace(if direct { env_index } else { None });
4346 // The cell-based view of the same bindings, which is what a closure created
4347 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4348 // whose compiler did not put a binding in a cell simply does not appear here —
4349 // reads and writes still work through `eval_bindings`, they just cannot outlive
4350 // the eval.
4351 let previous_eval_scope = self
4352 .active_eval_scope
4353 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4354 let compiled = Gc::new(self.heap, CompiledCode::new(code));
4355 let closure_vars = compiled.code.closure_vars.clone();
4356 // Declaration instantiation is where this belongs: the check needs the caller frame
4357 // (recorded just above) and the eval's own var names, and it raises before any of
4358 // the eval's code runs.
4359 self.check_eval_var_named_arguments(&closure_vars, code_strict)?;
4360 let env = self.global_env(&closure_vars);
4361 let callee = Value::Undefined;
4362 // An async body does not run here: it becomes a coroutine and answers a promise,
4363 // which is what makes `await` legal in it. `this` still has to be the caller's
4364 // (for a global eval, the global object), because `this` is not part of `await`.
4365 let result = if compiled.code.kind.is_async() {
4366 self.run_async_body(compiled, env, this)
4367 } else {
4368 self.execute(compiled, env, this, Vec::new(), callee)
4369 };
4370 self.eval_scope = previous_scope;
4371 self.eval_arguments = previous_arguments;
4372 self.eval_with = previous_with;
4373 self.eval_new_target = previous_new_target;
4374 self.eval_bindings = previous_bindings;
4375 self.eval_caller = previous_caller;
4376 self.active_eval_scope = previous_eval_scope;
4377 result
4378 }
4379
4380 /// The declarations an eval cannot instantiate: they are `SyntaxError`/`TypeError`
4381 /// rather than bindings.
4382 ///
4383 /// Two rules, both from `EvalDeclarationInstantiation` (§19.2.1.3) and both about a
4384 /// declaration that cannot exist:
4385 ///
4386 /// * **`var arguments` in a function's parameter scope.** §10.2.1.3 gives a function with
4387 /// parameter expressions a separate parameter environment, and `arguments` is bound
4388 /// implicitly there, so a `var` of that name collides. An arrow that binds no
4389 /// `arguments` of its own has nothing to collide with and is allowed — see the table in
4390 /// [`Interp::check_eval_var_named_arguments`].
4391 /// * **A global `var` on a non-extensible global object**, where `CanDeclareGlobalVar` is
4392 /// false; the operation is a `TypeError`, and `eval("var x")` with
4393 /// `Object.preventExtensions(this)` must raise rather than quietly do nothing
4394 /// (`non-definable-global-var` and its four siblings).
4395 fn check_eval_var_named_arguments(
4396 &self,
4397 closure_vars: &[js_compile::bytecode::ClosureVar],
4398 strict: bool,
4399 ) -> JsResult<()> {
4400 if strict {
4401 return Ok(());
4402 }
4403 // A `var` this eval would declare on the global object, where there is no room for it.
4404 let global = &self.realm.global;
4405 if !global.is_extensible() {
4406 for var in closure_vars {
4407 if var.is_lexical || var.name == "*default*" {
4408 continue;
4409 }
4410 let declare = matches!(
4411 var.closure_type,
4412 js_compile::bytecode::ClosureType::GlobalDecl
4413 );
4414 if declare && global.own_property(&var.name).is_none() {
4415 return Err(Signal::Throw(self.make_error(
4416 "TypeError",
4417 "cannot declare a global in a non-extensible global object",
4418 )));
4419 }
4420 }
4421 }
4422 // Only a *direct* eval declares into a caller's environment; an indirect one gets the
4423 // global environment, where `var arguments` is an ordinary global.
4424 let Some(caller) = self.eval_caller.flatten() else {
4425 return Ok(());
4426 };
4427 if !closure_vars
4428 .iter()
4429 .any(|var| var.name == "arguments" && !var.is_lexical)
4430 {
4431 return Ok(());
4432 }
4433 // The body of a function is a different environment from its parameter list, and only
4434 // the parameter list is separate from `arguments`.
4435 if !self.in_parameter_list_at(caller) {
4436 return Ok(());
4437 }
4438 let caller_is_arrow = self
4439 .frames
4440 .get(caller)
4441 .is_some_and(|frame| frame.code.code.is_arrow);
4442 // A *parameter* named `arguments`, not merely a binding of that name: a body
4443 // `let arguments` is in the body's environment, which is the one that is separate and
4444 // therefore cannot collide. The slot tells them apart — an argument lives in
4445 // `EvalSlot::Arg`, a lexical in `EvalSlot::Local`.
4446 let parameter_scope_binds_arguments = self.eval_bindings.iter().any(|binding| {
4447 binding.frame == caller
4448 && binding.name == "arguments"
4449 && matches!(binding.slot, EvalSlot::Arg)
4450 });
4451 if caller_is_arrow && !parameter_scope_binds_arguments {
4452 return Ok(());
4453 }
4454 Err(Signal::Throw(self.make_error(
4455 "SyntaxError",
4456 "eval declares 'arguments' in a function's parameter scope",
4457 )))
4458 }
4459
4460 /// The cell-backed subset of `bindings`, in the same priority order.
4461 ///
4462 /// Both lookup routes have to agree — the eval's own reads go through
4463 /// [`Interp::eval_binding_value`] and the closures it builds go through
4464 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4465 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4466 /// is not in a cell simply does not appear: reads and writes still work, they just
4467 /// cannot be handed to a closure that outlives the eval.
4468 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4469 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4470 for binding in bindings {
4471 let Some(frame) = self.frames.get(binding.frame) else {
4472 continue;
4473 };
4474 let cell = match binding.slot {
4475 EvalSlot::Arg => frame
4476 .code
4477 .arg_cell
4478 .get(binding.index)
4479 .copied()
4480 .unwrap_or(-1),
4481 EvalSlot::Local => frame
4482 .code
4483 .loc_cell
4484 .get(binding.index)
4485 .copied()
4486 .unwrap_or(-1),
4487 };
4488 if cell < 0 {
4489 continue;
4490 }
4491 if let Some(cell) = frame.cells.get(cell as usize) {
4492 names.push((binding.name.clone(), cell.clone()));
4493 }
4494 }
4495 names
4496 }
4497
4498 /// A `SyntaxError` that reports where in the source it happened.
4499 ///
4500 /// Compile-time failures never run, so they have no frame of their own; the
4501 /// reference still puts the position first in the trace, with no function name and
4502 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4503 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4504 /// reference borrows), which is how a script reads the position without parsing
4505 /// the trace.
4506 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4507 ///
4508 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4509 /// `columnNumber`, which is how the reference prints one. A positionless error
4510 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4511 /// the reference raises it from `js_resolve_module`, where there is no position.
4512 pub(crate) fn syntax_error_plain(
4513 &mut self,
4514 error: &js_parse::SyntaxError,
4515 file: &str,
4516 ) -> Value {
4517 if error.positionless {
4518 return self.make_error("SyntaxError", &error.message);
4519 }
4520 self.syntax_error_at(
4521 file,
4522 error.span.start.line,
4523 error.span.start.column,
4524 &error.message,
4525 )
4526 }
4527
4528 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4529 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
4530 let value = self.make_error("SyntaxError", message);
4531 if let Value::Object(object) = &value {
4532 let text = self.string(blamed);
4533 // `stack` is an own data property, and the reference keeps it
4534 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4535 object.define("stack", Property::with_attributes(text, true, false));
4536 let name = self.string(file);
4537 object.define("fileName", Property::with_attributes(name, true, true));
4538 object.define(
4539 "lineNumber",
4540 Property::with_attributes(Value::Int(line as i32), true, true),
4541 );
4542 object.define(
4543 "columnNumber",
4544 Property::with_attributes(Value::Int(column as i32), true, true),
4545 );
4546 }
4547 value
4548 }
4549
4550 /// Run a compiled script whose completion value is a function, returning it.
4551 ///
4552 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4553 /// get the closure out, which keeps the constant-pool plumbing in one place.
4554 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4555 self.run_script(code)
4556 }
4557
4558 /// The environment of a script or of any function compiled at global scope:
4559 /// every entry is a global binding, so each one resolves to the realm's cell.
4560 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4561 let mut cells = Vec::with_capacity(closure_vars.len());
4562 for closure_var in closure_vars {
4563 let cell = match closure_var.closure_type {
4564 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4565 if closure_var.is_lexical =>
4566 {
4567 // A lexical declaration: the cell is created here holding the
4568 // dead-zone marker, which is what makes the binding exist and
4569 // unreadable before its initialiser runs.
4570 self.declare_global(&closure_var.name, closure_var.is_const);
4571 self.realm.globals[&closure_var.name].clone()
4572 }
4573 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4574 // A `var` or function declaration becomes a property of the global
4575 // object, and it exists from here on — which is why
4576 // `print(v); var v = 1` prints `undefined` instead of raising.
4577 // Declaring it at instantiation time (rather than at the
4578 // initialiser) is also what makes it non-configurable: the store
4579 // then lands on an existing property instead of creating one.
4580 self.declare_var_global(&closure_var.name);
4581 // The cell is a placeholder that nothing indexes; it cannot be
4582 // omitted because the slot has to hold something.
4583 self.new_cell(Value::Undefined)
4584 }
4585 _ => {
4586 // An undeclared global is read by name; the cell is a
4587 // placeholder that nothing indexes.
4588 self.new_cell(Value::Undefined)
4589 }
4590 };
4591 cells.push(cell);
4592 }
4593 Gc::new(
4594 self.heap,
4595 ClosureEnv {
4596 cells,
4597 eval_scope: None,
4598 local_vars: None,
4599 local_phase: 1,
4600 },
4601 )
4602 }
4603
4604 /// Push a frame and run until it returns.
4605 pub(crate) fn execute(
4606 &mut self,
4607 code: Gc<CompiledCode>,
4608 env: Gc<ClosureEnv>,
4609 this: Value,
4610 args: Vec<Value>,
4611 callee: Value,
4612 ) -> JsResult<Value> {
4613 let depth = self.frames.len();
4614 if depth == 0 {
4615 // A throw that reached the host ends the *active* mode: the next one is catchable
4616 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4617 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4618 // for the throw that evaluation will raise.
4619 self.uncatchable = false;
4620 }
4621 self.push_frame(code, env, this, args, callee)?;
4622 loop {
4623 // The fast loop first: it runs whole runs of records with `pc` in a register.
4624 //
4625 // `step`'s `pc` lives in the frame, so every instruction writes it back and
4626 // reads it again — a store, a load and two bounds checks that a loop body does
4627 // not need, because nothing outside the loop can run in between. This is the
4628 // classic split: advance a register, and only spill it when leaving.
4629 //
4630 // `Some(value)` means the function ended by running off the end of its
4631 // instruction array, which is a normal return.
4632 let step = match self.run_fast() {
4633 Ok(Some(value)) => Ok(Step::Return(value)),
4634 Ok(None) => self.step(),
4635 Err(signal) => Err(signal),
4636 };
4637 match step {
4638 Ok(Step::Continue) => {}
4639 Ok(Step::Return(value)) => {
4640 self.pop_frame();
4641 // A frame that ended in a `tail_call` hands its value straight to
4642 // its caller: nothing after the call can run, so every frame above
4643 // the callee unwinds with the same value. See [`Frame::tail`] —
4644 // the reference does not reuse frames either, so recursion depth
4645 // and the stack-overflow limit behave the same way.
4646 while self.frames.len() > depth && self.frame().tail {
4647 self.pop_frame();
4648 }
4649 if self.frames.len() == depth {
4650 return Ok(value);
4651 }
4652 // The caller resumes with the value on its stack.
4653 self.frames
4654 .last_mut()
4655 .expect("a caller is live")
4656 .stack
4657 .push(value);
4658 }
4659 Err(Signal::Throw(value)) => {
4660 // The host's standing request becomes the active mode for this unwind,
4661 // and is consumed here so it does not leak into the next throw.
4662 if self.uncatchable_next {
4663 self.uncatchable_next = false;
4664 self.uncatchable = true;
4665 }
4666 // An uncatchable throw walks past every `catch` on the way out. The
4667 // frames are still popped, because the values they hold have to be
4668 // dropped — only the search for a handler is skipped.
4669 if self.uncatchable {
4670 while self.frames.len() > depth {
4671 self.frames.pop();
4672 }
4673 return Err(Signal::Throw(value));
4674 }
4675 // A handler lives on the stack of the frame that is throwing —
4676 // `catch` pushed it there — so this frame gets the first chance
4677 // to catch before it is popped.
4678 let mut value = value;
4679 loop {
4680 if self.frames.len() <= depth {
4681 return Err(Signal::Throw(value));
4682 }
4683 if self.catch_here(&mut value).is_some() {
4684 break;
4685 }
4686 self.frames.pop();
4687 }
4688 }
4689 // A `yield` in a frame that `execute` is running directly means a
4690 // generator body was entered as an ordinary call, which only happens if
4691 // the generator check in `call_or_push` was bypassed.
4692 Ok(Step::Suspend(_)) => {
4693 return Err(Signal::Throw(self.make_error(
4694 "InternalError",
4695 "a generator body ran as an ordinary call",
4696 )));
4697 }
4698 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4699 }
4700 }
4701 }
4702
4703 /// Install a handler for `value` if this frame has one, resuming at it.
4704 ///
4705 /// The scan is the reference's: walk the frame's stack downwards looking for the
4706 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset `0` is an
4707 /// enumerator marker rather than a handler — `for of` keeps one under its record so
4708 /// that `break` and `return` can find the iterator — and an exception reaching one
4709 /// **closes that iterator** before the unwinding continues.
4710 ///
4711 /// Skipping the marker instead leaked the iterator of every `for of` whose body threw:
4712 /// `for (const x of xs) { throw new Error }` never called `return`. It was also the
4713 /// whole of a nineteen-case `dstr` cluster, where `[ {}[thrower()] ] = iterable` has to
4714 /// close the iterator while the reference to store into is being worked out.
4715 ///
4716 /// `value` is `&mut` because closing the iterator may replace it: see
4717 /// [`Interp::close_iterator_on_throw`] for which of the two exceptions wins.
4718 fn catch_here(&mut self, value: &mut Value) -> Option<()> {
4719 loop {
4720 // Popped one at a time so no frame borrow is held across the close below.
4721 let top = self.frames.last_mut()?.stack.pop()?;
4722 let Value::CatchOffset(offset) = top else {
4723 continue;
4724 };
4725 if offset != 0 {
4726 let frame = self.frames.last_mut().expect("the frame was just read");
4727 frame.stack.push(value.clone());
4728 frame.pc = offset as usize;
4729 return Some(());
4730 }
4731 // The record's `iter` and `next` sit directly below the marker.
4732 let close = {
4733 let frame = self.frames.last_mut().expect("the frame was just read");
4734 let next = frame.stack.pop();
4735 let iterator = frame.stack.pop();
4736 match (iterator, next) {
4737 (Some(iterator), Some(_next)) => Some(iterator),
4738 // A malformed record cannot be closed, but unwinding still has to go
4739 // on: this is not a handler, so there is nothing to resume at.
4740 _ => None,
4741 }
4742 };
4743 if let Some(iterator) = close {
4744 self.close_iterator_on_throw(iterator);
4745 }
4746 }
4747 }
4748
4749 /// `IteratorClose` on the exception path — §7.4.6 reached with a *throw* completion.
4750 ///
4751 /// Two things differ from the ordinary close, both from the spec's step ordering:
4752 ///
4753 /// * the original exception **wins**. Step 4 (`If completion is a throw completion,
4754 /// return ? completion`) comes before step 5, so an exception raised by `return()`
4755 /// itself — or by reading it — is discarded;
4756 /// * a non-object result is **not** a `TypeError`, because step 6 is never reached.
4757 ///
4758 /// The reference does exactly this in `JS_IteratorClose(…, is_exception_pending=TRUE)`:
4759 /// it saves the pending exception, clears the slot, and re-throws the saved one from
4760 /// `done:` no matter what happened in between.
4761 fn close_iterator_on_throw(&mut self, iterator: Value) {
4762 if matches!(iterator, Value::Undefined) {
4763 return;
4764 }
4765 let Ok(method) = self.read_field(&iterator, "return") else {
4766 return;
4767 };
4768 if matches!(method, Value::Undefined | Value::Null) {
4769 return;
4770 }
4771 // A throw from `return()` replaces nothing: the exception already being unwound is
4772 // the one that propagates.
4773 let _ = self.call_value(method, iterator, Vec::new());
4774 }
4775
4776 fn push_frame(
4777 &mut self,
4778 code: Gc<CompiledCode>,
4779 env: Gc<ClosureEnv>,
4780 this: Value,
4781 mut args: Vec<Value>,
4782 callee: Value,
4783 ) -> JsResult<()> {
4784 // Two bounds, and the byte budget is the one that decides in practice. The
4785 // reference's message is `stack overflow` on an `InternalError`, not V8's
4786 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4787 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4788 let frame_cost = Self::frame_cost(&code);
4789 let stack_base = self.stack_used();
4790 if self.frames.len() >= self.max_frames
4791 || stack_base.saturating_add(frame_cost) > self.stack_limit
4792 {
4793 return Err(Signal::Throw(
4794 self.make_error("InternalError", "stack overflow"),
4795 ));
4796 }
4797 let arg_count = code.code.args.len();
4798 // How many were actually passed, which `arguments.length` reports and
4799 // `assert(x)` depends on: a call with one argument must not look like a call
4800 // with one argument and an explicit `undefined`.
4801 let passed = args.len();
4802 // Missing arguments are `undefined` in their slots; extra ones are dropped
4803 // from the slots but still reachable through `arguments`.
4804 //
4805 // A call that passes no more than the declared parameters needs **no** copy:
4806 // after the resize below, `args[..passed]` *is* the passed values. Only the
4807 // extra ones — which `truncate` is about to drop — have to be kept, and they are
4808 // the rare case. This used to copy every call: one `Value` clone per argument
4809 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4810 let passed_overflow = (passed > arg_count).then(|| {
4811 let mut values = self.take_values(passed, Value::Undefined);
4812 values[..passed].clone_from_slice(&args[..passed]);
4813 values
4814 });
4815 // Only when the counts differ, which for the overwhelmingly common call — as many
4816 // arguments as parameters — is never. `resize` followed by `truncate` on equal
4817 // lengths is two length compares and nothing else, but this is the hottest few
4818 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4819 if passed != arg_count {
4820 args.resize(arg_count, Value::Undefined);
4821 args.truncate(arg_count);
4822 }
4823 let cell_count = code.code.var_ref_count as usize;
4824 let mut cells = Vec::with_capacity(cell_count);
4825 for _ in 0..cell_count {
4826 cells.push(self.new_cell(Value::Undefined));
4827 }
4828 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4829 // A captured argument lives in its cell, not in the argument slot, so the
4830 // incoming value has to be moved there before the body runs.
4831 for (slot, cell) in code.arg_cell.iter().enumerate() {
4832 if *cell >= 0
4833 && let Some(value) = args.get(slot).cloned()
4834 {
4835 cells[*cell as usize].set(value);
4836 }
4837 }
4838 // Sloppy mode substitutes the global object for a missing receiver and boxes a
4839 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4840 // reports `object`. Strict mode passes the value through untouched.
4841 let this = if code.code.strict {
4842 this
4843 } else if this.is_nullish() {
4844 Value::Object(self.realm.global.clone())
4845 } else if matches!(this, Value::Object(_)) {
4846 this
4847 } else {
4848 match crate::builtins::this_object(self, &this) {
4849 Ok(boxed) => Value::Object(boxed),
4850 Err(_) => this,
4851 }
4852 };
4853 let stack_depth = code.code.stack_size as usize + 1;
4854 // Taken before the `push` borrows `self.frames`, because the operand stack comes
4855 // out of the same recycle pool the locals did.
4856 let stack = self.take_values(stack_depth, Value::Undefined);
4857 self.frames.push(Frame {
4858 code,
4859 env,
4860 this,
4861 args,
4862 passed_count: passed,
4863 passed_overflow: passed_overflow.map(Box::new),
4864 locals,
4865 cells,
4866 local_vars: None,
4867 // Exactly the depth the compiler computed, so the operand stack never
4868 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4869 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4870 // the buffer between calls, so "exactly" costs nothing after the first one.
4871 stack,
4872 pc: 0,
4873 at: 0,
4874 callee,
4875 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4876 cost: frame_cost,
4877 stack_base,
4878 tail: false,
4879 });
4880 Ok(())
4881 }
4882
4883 /// A value buffer of `len` slots, from the recycle pool when there is one.
4884 ///
4885 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4886 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4887 // A frame with no locals asks for nothing, and that is most frames: taking a
4888 // buffer out of the pool, clearing it and resizing it to zero is four operations
4889 // and a pool pop for an empty `Vec`, which is free to construct.
4890 if len == 0 {
4891 return Vec::new();
4892 }
4893 let mut buffer = self.free_values.pop().unwrap_or_default();
4894 buffer.clear();
4895 buffer.resize(len, fill);
4896 buffer
4897 }
4898
4899 /// Return a finished frame's value buffers for the next call to reuse.
4900 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4901 for mut buffer in [
4902 std::mem::take(&mut frame.locals),
4903 frame
4904 .passed_overflow
4905 .take()
4906 .map(|buffer| *buffer)
4907 .unwrap_or_default(),
4908 std::mem::take(&mut frame.stack),
4909 ] {
4910 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4911 // GC root: it kept every value the frame held reachable, which is invisible
4912 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4913 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4914 // exactly that within one run — the target `{}` of a finished IIFE was still
4915 // in its operand stack, in the pool.
4916 buffer.clear();
4917 // A buffer with no capacity is what `Vec::new` is; putting it back would just
4918 // fill the pool with nothing to offer.
4919 if free_values.len() < RECYCLE_SLOTS
4920 && buffer.capacity() > 0
4921 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4922 {
4923 free_values.push(buffer);
4924 }
4925 }
4926 }
4927
4928 /// Pop a finished frame and keep its buffers.
4929 ///
4930 /// Every place that drops a frame goes through here: a recycled buffer is also where
4931 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4932 /// nothing but the reuse.
4933 fn pop_frame(&mut self) -> Option<()> {
4934 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4935 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4936 let last = self.frames.len().checked_sub(1)?;
4937 Self::recycle(&mut self.free_values, &mut self.frames[last]);
4938 self.frames.truncate(last);
4939 Some(())
4940 }
4941
4942 /// Poll the host's interrupt handler, if one is installed.
4943 ///
4944 /// The counter is what keeps this off the hot path when nobody asked: the early return is
4945 /// one `Option` test, and with no handler installed the whole function is that test —
4946 /// `check_memory` next door already costs more, so this cannot be what shows up in a
4947 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4948 #[inline]
4949 fn check_interrupt(&mut self) -> JsResult<()> {
4950 if self.interrupt.is_none() {
4951 return Ok(());
4952 }
4953 if self.interrupt_counter > 0 {
4954 self.interrupt_counter -= 1;
4955 return Ok(());
4956 }
4957 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4958 // The closure is taken out for the duration so that a handler which re-enters the
4959 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4960 let mut handler = self.interrupt.take().expect("checked above");
4961 let abort = handler();
4962 self.interrupt = Some(handler);
4963 if abort {
4964 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4965 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4966 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4967 // documentation says.
4968 self.uncatchable = true;
4969 return Err(Signal::Throw(
4970 self.make_error("InternalError", "interrupted"),
4971 ));
4972 }
4973 Ok(())
4974 }
4975
4976 /// A memory checkpoint: does the heap still fit under its limit?
4977 ///
4978 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4979 /// a `Cell` read and a predictable branch, and the point of asking that often is that
4980 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4981 /// only at calls would let it run until the machine died, which is the exact failure
4982 /// `--memory-limit` exists to prevent.
4983 ///
4984 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4985 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4986 /// script that catches it, drops the reference and carries on is legitimate: measured
4987 /// on `qjs --memory-limit 1M`, the engine recovers.
4988 fn check_memory(&mut self) -> JsResult<()> {
4989 // One `Cell` read and a predictable branch when no limit is set, and an integer
4990 // compare when one is. Containers report their own growth as it happens
4991 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4992 // walking it here was the first version and it was O(live) per 256 instructions,
4993 // which turned a 100k-element push loop into a five-minute one.
4994 let Some(limit) = self.heap.memory_limit() else {
4995 return Ok(());
4996 };
4997 let used = self.heap.used_bytes();
4998 if used <= limit {
4999 // Back under the limit — a collection or a dropped reference did it. The next
5000 // time it goes over is a new failure, not a repeat of this one.
5001 self.oom_reported_at = 0;
5002 return Ok(());
5003 }
5004 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
5005 // block runs normally after `out of memory` — it allocates nothing, so nothing
5006 // fails. A check that re-fired on every instruction made the handler itself throw,
5007 // which is a dead end: the error became unobservable from script.
5008 //
5009 // Comparing against the total at the last report gives the same behaviour: the
5010 // handler runs while the total is unchanged, and the very next allocation over the
5011 // limit fails.
5012 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
5013 {
5014 return Ok(());
5015 }
5016 self.oom_reported_at = used;
5017 Err(Signal::Throw(
5018 self.make_error("InternalError", "out of memory"),
5019 ))
5020 }
5021
5022 /// Fail before allocating `payload` bytes, if they would not fit.
5023 ///
5024 /// For the allocations whose size comes from script data — `new Array(n)`,
5025 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
5026 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
5027 /// answering NULL for the one big request.
5028 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
5029 if self.heap.fits(payload) {
5030 return Ok(());
5031 }
5032 Err(Signal::Throw(
5033 self.make_error("InternalError", "out of memory"),
5034 ))
5035 }
5036
5037 /// Bytes of frame state the live call chain accounts for.
5038 pub fn stack_used(&self) -> usize {
5039 match self.frames.last() {
5040 Some(frame) => frame.stack_base + frame.cost,
5041 None => 0,
5042 }
5043 }
5044
5045 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
5046 ///
5047 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
5048 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
5049 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
5050 /// instead. That is the whole difference between the two models: it rations C stack, we
5051 /// ration frame state, and both quantities are dominated by the value slots — which is
5052 /// why the two depths come out comparable rather than merely proportional.
5053 fn frame_cost(code: &CompiledCode) -> usize {
5054 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
5055 std::mem::size_of::<Frame>()
5056 + std::mem::size_of::<Value>() * slots
5057 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
5058 }
5059
5060 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
5061 ///
5062 /// Only names the eval created are here: a name the frame already declared statically
5063 /// is written through to its own slot instead, so this cannot shadow a real local.
5064 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
5065 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
5066 let (local_vars, phase) = self.visible_local_vars()?;
5067 if !local_vars.contains(name) {
5068 return None;
5069 }
5070 local_vars.get(name, phase)
5071 }
5072
5073 /// The variables a direct `eval` declared, as the code currently running sees them.
5074 ///
5075 /// Inside an eval that is the *caller's* set — the eval's own variable environment
5076 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
5077 /// else it is the current frame's, falling back to the frame the closure was created
5078 /// in.
5079 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
5080 ///
5081 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
5082 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
5083 /// refcount operations (the clone out of the frame, the drop at the end of the match)
5084 /// just to be asked `is_none`.
5085 fn has_visible_local_vars(&self) -> bool {
5086 let index = match self.eval_caller.flatten() {
5087 Some(caller) => caller,
5088 None => match self.frames.len().checked_sub(1) {
5089 Some(top) => top,
5090 None => return false,
5091 },
5092 };
5093 match self.frames.get(index) {
5094 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
5095 None => false,
5096 }
5097 }
5098
5099 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
5100 // While an `eval` runs, its own frame is on top but its variable environment is
5101 // the *caller's* — so the caller is what the lookup has to start from.
5102 let (index, phase) = match self.eval_caller.flatten() {
5103 Some(caller) => (
5104 caller,
5105 if self.in_parameter_list_at(caller) {
5106 0
5107 } else {
5108 1
5109 },
5110 ),
5111 None => (
5112 self.frames.len().checked_sub(1)?,
5113 if self.in_parameter_list() { 0 } else { 1 },
5114 ),
5115 };
5116 let frame = self.frames.get(index)?;
5117 // The frame's own variables, or — for an arrow, which has no variable environment
5118 // of its own — the one it was created in, which `ClosureEnv` carries.
5119 if let Some(local_vars) = frame.local_vars.clone() {
5120 return Some((local_vars, phase));
5121 }
5122 frame
5123 .env
5124 .local_vars
5125 .clone()
5126 .map(|local_vars| (local_vars, frame.env.local_phase))
5127 }
5128
5129 /// Whether the innermost frame is still evaluating its parameter list.
5130 ///
5131 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
5132 /// and a closure created there may only see that much of [`LocalVars`].
5133 fn in_parameter_list(&self) -> bool {
5134 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
5135 }
5136
5137 /// [`Interp::in_parameter_list`] for a specific frame.
5138 fn in_parameter_list_at(&self, frame: usize) -> bool {
5139 let Some(frame) = self.frames.get(frame) else {
5140 return false;
5141 };
5142 let code = &frame.code.code;
5143 if !code.has_parameter_expressions {
5144 return false;
5145 }
5146 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
5147 // function as its body and let a direct `eval` act accordingly.
5148 if code.body_start == (0, 0) {
5149 return false;
5150 }
5151 match code.position_at(frame.at as u32) {
5152 Some(position) => position < code.body_start,
5153 None => false,
5154 }
5155 }
5156
5157 fn frame(&self) -> &Frame {
5158 self.frames.last().expect("a frame is live")
5159 }
5160
5161 fn frame_mut(&mut self) -> &mut Frame {
5162 self.frames.last_mut().expect("a frame is live")
5163 }
5164
5165 // -- slot access --------------------------------------------------------
5166
5167 /// Move a local's value out, leaving `undefined` in the slot.
5168 ///
5169 /// `None` for a captured slot: its value lives in a cell shared with every closure
5170 /// that closed over it, so it can never be exclusively ours and must not be taken.
5171 ///
5172 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
5173 /// for every read and fatal for this one — a clone is exactly the second handle that
5174 /// rules out growing the string in place.
5175 fn take_loc(&mut self, slot: usize) -> Option<Value> {
5176 let frame = self.frames.last_mut()?;
5177 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
5178 return None;
5179 }
5180 frame
5181 .locals
5182 .get_mut(slot)
5183 .map(|value| std::mem::replace(value, Value::Undefined))
5184 }
5185
5186 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
5187 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
5188 ///
5189 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
5190 /// it** — the value is put back before the general path runs — so a `valueOf` that
5191 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
5192 /// error as it would have without the fusion. This is why the in-place attempt is a
5193 /// `take` and not a `get`: an optimisation that changes what an exception observes is
5194 /// a wrong answer with a good excuse.
5195 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
5196 // The take is `matches!`-guarded on the *right* operand only, and the taken value
5197 // is put back on every path that does not append. An earlier version wrote the two
5198 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
5199 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
5200 // through with its value already taken and dropped: the general path below then
5201 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
5202 // A wrong answer, from an optimisation, with every test green.
5203 if matches!(right, Value::String(_))
5204 && let Some(taken) = self.take_loc(slot)
5205 {
5206 if let Value::String(mut left) = taken {
5207 let appended = match left.get_mut() {
5208 Some(string) => string.append_in_place(
5209 // The pattern is the one `matches!` just checked.
5210 match &right {
5211 Value::String(text) => text,
5212 _ => unreachable!("guarded above"),
5213 },
5214 ),
5215 None => None,
5216 };
5217 self.put_loc(slot, Value::String(left));
5218 if let Some(added) = appended {
5219 // The buffer grew where it stood, so the heap's running total has to
5220 // be told: `measure_used` would report the new length, and the two must
5221 // agree or the subtraction at free time leaves the counter wrong.
5222 self.heap.adjust_payload(added as isize);
5223 return Ok(());
5224 }
5225 } else {
5226 self.put_loc(slot, taken);
5227 }
5228 }
5229 // The two-number case, without an operand stack round trip. Everything below
5230 // this point is the *general* path: push both, call `binary_add`, pop the answer,
5231 // store it — five operations and two `Value` clones for what is one integer add.
5232 // `AddImmLoc` already answers this shape that way; the fusion above it was written
5233 // for string append and never got the numeric half, so `t += i` — a counting loop
5234 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
5235 let left = self.get_loc(slot);
5236 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
5237 self.put_loc(
5238 slot,
5239 match a.checked_add(*b) {
5240 Some(sum) => Value::Int(sum),
5241 None => Value::Float(*a as f64 + *b as f64),
5242 },
5243 );
5244 return Ok(());
5245 }
5246 self.push(left);
5247 self.push(right);
5248 self.binary_add()?;
5249 let value = self.pop();
5250 self.put_loc(slot, value);
5251 Ok(())
5252 }
5253
5254 fn get_arg(&self, slot: usize) -> Value {
5255 self.frame().read_arg(slot)
5256 }
5257
5258 fn put_arg(&mut self, slot: usize, value: Value) {
5259 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
5260 if cell == -1 {
5261 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
5262 *slot = value;
5263 }
5264 } else {
5265 self.frame().cells[cell as usize].set(value);
5266 }
5267 }
5268
5269 fn get_loc(&self, slot: usize) -> Value {
5270 // The cell mapping is `-1` for every slot that was not captured — which is all of
5271 // them in a function that creates no closure. `Frame::read_loc` tests that first,
5272 // so the common case is one array read and a clone: 20% of every loop iteration
5273 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
5274 // sample of `dispatch:arith`).
5275 self.frame().read_loc(slot)
5276 }
5277
5278 fn put_loc(&mut self, slot: usize, value: Value) {
5279 // One borrow instead of three, and the cell check on the frame we already hold.
5280 let frame = self.frames.last_mut().expect("a frame is live");
5281 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
5282 if cell < 0 {
5283 if let Some(slot) = frame.locals.get_mut(slot) {
5284 *slot = value;
5285 }
5286 } else if let Some(cell) = frame.cells.get(cell as usize) {
5287 cell.set(value);
5288 }
5289 }
5290
5291 // -- globals ------------------------------------------------------------
5292
5293 /// The name a global-slot operand refers to.
5294 fn global_name(&self, slot: usize) -> String {
5295 self.frame()
5296 .code
5297 .code
5298 .closure_vars
5299 .get(slot)
5300 .map(|c| c.name.clone())
5301 .unwrap_or_default()
5302 }
5303
5304 /// The facts about a global binding that decide where it lives.
5305 ///
5306 /// A script's globals split in two, and the split is observable: `var` and
5307 /// function declarations become properties of the global object (`globalThis.v`
5308 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
5309 /// declarations live in the global *lexical* environment and are invisible there
5310 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
5311 /// `is_lexical` flag means the answer is already in the bytecode.
5312 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
5313 let name = self.global_name(slot);
5314 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
5315 // while forwarding a reference through a nested function is built with the
5316 // flags cleared, so `const c` would look like an ordinary `var` from inside a
5317 // closure. Presence in the realm's lexical table is the same fact, recorded
5318 // once, and every slot sees it.
5319 let lexical = self.realm.globals.contains_key(&name);
5320 let is_const = self.realm.lexical_consts.contains(&name);
5321 (name, lexical, is_const)
5322 }
5323
5324 /// The value of `name` in the innermost active `with` object, if any.
5325 ///
5326 /// The active objects are the [`VarKind::With`] locals of every frame still running,
5327 /// innermost frame first and innermost block first within one. Walking frames rather
5328 /// than keeping a separate stack is what makes a closure called from inside a `with`
5329 /// see it, and what keeps the object alive only as long as the block is.
5330 /// The innermost active `with` object that has `name`, if any.
5331 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
5332 let objects = self.eval_with.clone().unwrap_or_default();
5333 for object in objects {
5334 let key = self.string(name.to_string());
5335 if self
5336 .has_property(&key, &Value::Object(object.clone()))
5337 .ok()?
5338 {
5339 return Some(object);
5340 }
5341 }
5342 None
5343 }
5344
5345 /// Every active `with` object, innermost first.
5346 fn with_objects(&self) -> Vec<Gc<JsObject>> {
5347 let mut objects = Vec::new();
5348 for frame in self.frames.iter().rev() {
5349 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
5350 if var.kind != js_compile::VarKind::With {
5351 continue;
5352 }
5353 // A captured binding lives in its cell and not in the slot list, so the
5354 // cell is consulted first — a closure created inside the block is exactly
5355 // what makes the object captured. Before the store runs the slot still
5356 // holds `undefined`, and a `with` object is always boxed, so a non-object
5357 // entry is simply not in scope yet.
5358 let value = frame
5359 .code
5360 .loc_cell
5361 .get(index)
5362 .copied()
5363 .filter(|cell| *cell >= 0)
5364 .and_then(|cell| frame.cells.get(cell as usize))
5365 .map(|cell| cell.get())
5366 .or_else(|| frame.locals.get(index).cloned());
5367 if let Some(Value::Object(object)) = value {
5368 objects.push(object);
5369 }
5370 }
5371 }
5372 objects
5373 }
5374
5375 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
5376 for object in self.eval_with.clone().unwrap_or_default() {
5377 let key = self.string(name.to_string());
5378 if self.has_property(&key, &Value::Object(object.clone()))? {
5379 return Ok(Some(self.read_field(&Value::Object(object), name)?));
5380 }
5381 }
5382 Ok(None)
5383 }
5384
5385 /// Whether every scope between here and the global object is an ordinary one.
5386 ///
5387 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
5388 /// bytecode resolved; when any is live the general path has to run in full order. When
5389 /// none is — every ordinary program — a global read is a property read and nothing
5390 /// else, and that is worth caching.
5391 fn scopes_are_plain(&self) -> bool {
5392 self.eval_caller.is_none()
5393 && self.eval_with.is_none()
5394 && self.eval_arguments.is_none()
5395 && self.eval_bindings.is_empty()
5396 && self.eval_scope.is_none()
5397 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
5398 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
5399 // its `ClosureEnv`, so the test has to be the same one the general path makes.
5400 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
5401 // upstream corpus caught and no unit test did.
5402 && !self.has_visible_local_vars()
5403 && self.frame().env.eval_scope.is_none()
5404 }
5405
5406 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
5407 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
5408 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
5409 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
5410 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
5411 // borrow outlive the `&mut self` the lookup needs.
5412 //
5413 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
5414 // forwarded through a nested function has its flags cleared, so the flag cannot
5415 // be believed.
5416 let code = self.frame().code.clone();
5417 let name = code
5418 .code
5419 .closure_vars
5420 .get(slot)
5421 .map(|c| c.name.as_str())
5422 .unwrap_or_default();
5423 let lexical = self.realm.globals.contains_key(name);
5424 // The common case, first: an ordinary global `var`, with a cache in front of the
5425 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
5426 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
5427 // cache hit and return without touching any of it.
5428 if !lexical && self.scopes_are_plain() {
5429 return self.get_plain_global(name, slot);
5430 }
5431 if name == "arguments"
5432 && let Some(arguments) = &self.eval_arguments
5433 {
5434 return Ok(arguments.clone());
5435 }
5436 // A `with` block around the *call site* is part of the scope an `eval` sees, so
5437 // the objects live when the eval started are consulted before anything else. The
5438 // snapshot is taken at entry rather than scanning the frames on every read: a
5439 // block that has already finished still leaves its object in the slot, and a
5440 // bytecode read outside the block must not see it.
5441 if let Some(value) = self.with_lookup(name)? {
5442 return Ok(value);
5443 }
5444 // A variable a direct `eval` declared shadows everything the compiler resolved,
5445 // including an enclosing function's binding: the eval put it in the caller's own
5446 // variable environment, which is nearer than any captured scope.
5447 if let Some((local_vars, phase)) = self.visible_local_vars()
5448 && let Some(cell) = local_vars.get(name, phase)
5449 {
5450 return Ok(cell.get());
5451 }
5452 // The frame that called `eval` is the innermost scope the eval'd code sees, so
5453 // its local `a` wins over a global `a`.
5454 if let Some(value) = self.eval_binding_value(name) {
5455 return Ok(value);
5456 }
5457 // A closure created by an `eval` resolves its free names against the bindings
5458 // that eval saw, even after the eval (and its frames) are gone.
5459 if let Some(cell) = self
5460 .frame()
5461 .env
5462 .eval_scope
5463 .as_ref()
5464 .and_then(|scope| scope.get(name))
5465 {
5466 let value = cell.get();
5467 if matches!(value, Value::Uninitialized) {
5468 return Err(self.throw_reference(name));
5469 }
5470 return Ok(value);
5471 }
5472 // A binding declared by the strict `eval` currently running shadows anything
5473 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5474 if let Some(scope) = &self.eval_scope
5475 && let Some(value) = scope.get(name)
5476 {
5477 return Ok(value.clone());
5478 }
5479 if lexical {
5480 // A lexical global is a binding in a side table, so the dead zone is
5481 // visible and it is nowhere on the global object.
5482 if let Some(cell) = self.realm.globals.get(name) {
5483 let value = cell.get();
5484 if matches!(value, Value::Uninitialized) {
5485 return Err(self.throw_reference(name));
5486 }
5487 return Ok(value);
5488 }
5489 return Err(self.throw_reference(name));
5490 }
5491 // A `var` global is an ordinary property, so the prototype chain and the
5492 // global object's own builtins are all reachable through it.
5493 match self.get_property(&self.realm.global.clone(), name)? {
5494 Some(value) => Ok(value),
5495 None => Err(self.throw_reference(name)),
5496 }
5497 }
5498
5499 /// Read a plain global `var`: a cached own data property, or the full lookup.
5500 ///
5501 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5502 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5503 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5504 let object = self.realm.global.clone();
5505 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5506 if let Some(cached) = &self.global_cache[site]
5507 && object.upgrades_to(&cached.object)
5508 && let Some(value) = object.data_property_at(cached.index, name)
5509 {
5510 return Ok(value);
5511 }
5512 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5513 // chain exactly as before, then remember the answer if it is worth remembering.
5514 let Some(value) = self.get_property(&object, name)? else {
5515 return Err(self.throw_reference(name));
5516 };
5517 if let Some(index) = object.own_data_index(name) {
5518 self.global_cache[site] = Some(GlobalCache {
5519 object: object.downgrade(),
5520 index,
5521 });
5522 }
5523 Ok(value)
5524 }
5525
5526 /// Store to a global binding.
5527 ///
5528 /// Returns a signal when the store is refused: a `const` global may only be
5529 /// written by its initialiser, and a non-configurable `var` global may not be
5530 /// deleted but is always writable.
5531 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5532 let (name, lexical, is_const) = self.global_binding(slot);
5533
5534 // An assignment inside a `with` writes through to the object that supplies the
5535 // name, which for an `eval` means consulting the same chain `get_global` does.
5536 if let Some(owner) = self.with_owner(&name) {
5537 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5538 return Ok(());
5539 }
5540 // A variable the running eval *declared* takes the write before any caller
5541 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5542 // environment even when an enclosing function has a `var c` of its own.
5543 if self.eval_caller.flatten().is_some()
5544 && let Some((local_vars, phase)) = self.visible_local_vars()
5545 && local_vars.contains(&name)
5546 && let Some(cell) = local_vars.get(&name, phase)
5547 {
5548 cell.set(value);
5549 return Ok(());
5550 }
5551 // A binding of the frame that called `eval` takes the write, which is what
5552 // makes `f("a = 3")` change the caller's `a`.
5553 if self.set_eval_binding(&name, &value)? {
5554 return Ok(());
5555 }
5556 // A closure that outlived its `eval` writes through to the same cell it reads.
5557 if let Some(cell) = self
5558 .frame()
5559 .env
5560 .eval_scope
5561 .as_ref()
5562 .and_then(|scope| scope.get(&name))
5563 .cloned()
5564 {
5565 cell.set(value);
5566 return Ok(());
5567 }
5568 // Inside a strict `eval`, a name it declared itself is stored there. An
5569 // *assignment* to a name nobody declared is not a declaration, so it falls
5570 // through: strict mode raises `ReferenceError` for it, which is what
5571 // `eval("1 + (@not_def = 1)")` has to do.
5572 if let Some(scope) = self.eval_scope.as_mut()
5573 && scope.contains_key(&name)
5574 {
5575 scope.insert(name, value);
5576 return Ok(());
5577 }
5578 if lexical {
5579 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5580 // A lexical global starts out `Uninitialized` and only `init_global` ends
5581 // that, so a store reaching here is either a plain assignment to a slot
5582 // still in its dead zone — `x = 1; let x` at the top level, a
5583 // `ReferenceError` — or a write to a `const` whose initialiser already ran.
5584 if matches!(cell.get(), Value::Uninitialized) {
5585 return Err(self.dead_zone_global(&name));
5586 }
5587 if is_const {
5588 return Err(self.read_only_global(&name));
5589 }
5590 cell.set(value);
5591 return Ok(());
5592 }
5593 // Writing an undeclared lexical global is a `ReferenceError` in strict
5594 // mode and a silent global creation otherwise; creating the cell here
5595 // keeps both paths from losing the value.
5596 let cell = self.new_cell(value);
5597 self.realm.globals.insert(name, cell);
5598 return Ok(());
5599 }
5600 // A variable a direct `eval` declared in this call shadows the global object, even
5601 // when the global already has a property of that name — `var c = "global"` at the
5602 // top level must not capture `eval("var c = 1")` inside a function.
5603 if let Some((local_vars, phase)) = self.visible_local_vars()
5604 && local_vars.contains(&name)
5605 && let Some(cell) = local_vars.get(&name, phase)
5606 {
5607 cell.set(value);
5608 return Ok(());
5609 }
5610 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5611 // remembered a global's slot index since M12b, but the *store* side never did: it
5612 // converted the name to a `PropertyKey` (two allocations) and then scanned the
5613 // global object's whole table — which holds every builtin — on every assignment to
5614 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5615 // full global lookup per iteration; measured with a counter, `s` as a global made
5616 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5617 //
5618 // Re-validated exactly like the read: same object, same index, still the name, and
5619 // — the one extra check a store needs — still writable. A global that is an
5620 // accessor, non-writable, or inherited fails here and falls through to the full
5621 // path below, which reports the failure the way it always did.
5622 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5623 let global = self.realm.global.clone();
5624 if let Some(cached) = &self.global_cache[site]
5625 && global.upgrades_to(&cached.object)
5626 && global.write_data_at(cached.index, &name, value.clone())
5627 {
5628 return Ok(());
5629 }
5630 match global.own_property(&name) {
5631 // A `var` global is writable, so the store goes straight through — but
5632 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5633 // store (a non-writable or accessor-without-setter global) is a silent
5634 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5635 // split every other assignment has.
5636 Some(_) => {
5637 let on_failure = if self.current_strict() {
5638 DeleteFailure::Throw
5639 } else {
5640 DeleteFailure::Ignore
5641 };
5642 let result = self.set_property_with(&global, &name, value, on_failure);
5643 // Teach the cache the slot for a plain writable own data property, which is
5644 // what a declared `var` is. Without this the fast path above could never
5645 // fire for a global that is only ever *written* — its entry would have to
5646 // be put there by a read of the same slot, and a write-only loop has none.
5647 if result.is_ok()
5648 && let Some(index) = global.own_data_index(&name)
5649 {
5650 self.global_cache[site] = Some(GlobalCache {
5651 object: global.downgrade(),
5652 index,
5653 });
5654 }
5655 result
5656 }
5657 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5658 // declaration creates a *configurable* property, which is what makes it
5659 // deletable and is the one way a global differs from a declared `var`.
5660 // In strict mode the same store is a `ReferenceError` instead: that is the
5661 // whole point of strict mode, and creating the global silently meant
5662 // `"use strict"; x = 1` looked like it worked.
5663 None => {
5664 if self.current_strict() {
5665 return Err(self.throw_reference(&name));
5666 }
5667 // A direct eval declares here rather than on the global object: its
5668 // `var`s belong to the caller's variable environment. `declare_eval_local`
5669 // also covers a plain assignment to a variable an earlier eval made.
5670 if let Some(cell) = self.declare_eval_local(&name) {
5671 cell.set(value);
5672 return Ok(());
5673 }
5674 global.define_data(&name, value);
5675 Ok(())
5676 }
5677 }
5678 }
5679
5680 /// The value of a binding of the frame that called `eval`, if there is one.
5681 fn eval_binding_value(&self, name: &str) -> Option<Value> {
5682 let binding = self
5683 .eval_bindings
5684 .iter()
5685 .find(|binding| binding.name == name)?;
5686 let owner = self.frames.get(binding.frame)?;
5687 let (slot, index) = (binding.slot, binding.index);
5688 Some(match slot {
5689 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5690 cell if cell >= 0 => owner
5691 .cells
5692 .get(cell as usize)
5693 .map(|cell| cell.get())
5694 .unwrap_or(Value::Undefined),
5695 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5696 },
5697 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5698 cell if cell >= 0 => owner
5699 .cells
5700 .get(cell as usize)
5701 .map(|cell| cell.get())
5702 .unwrap_or(Value::Undefined),
5703 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5704 },
5705 })
5706 }
5707
5708 /// Write to a binding of the frame that called `eval`.
5709 ///
5710 /// `Ok(false)` means no binding matched and the caller should keep looking. A
5711 /// matched binding can still refuse the store, which is why this is fallible: a
5712 /// `const` is read-only everywhere, and a named function expression's own name is
5713 /// read-only in strict mode.
5714 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5715 let Some(binding) = self
5716 .eval_bindings
5717 .iter()
5718 .find(|binding| binding.name == name)
5719 else {
5720 return Ok(false);
5721 };
5722 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5723 let strict = self.current_strict();
5724 let Some(owner) = self.frames.get_mut(frame) else {
5725 return Ok(false);
5726 };
5727 match slot {
5728 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5729 cell if cell >= 0 => {
5730 if let Some(cell) = owner.cells.get(cell as usize) {
5731 cell.set(value.clone());
5732 }
5733 }
5734 _ => {
5735 if let Some(slot) = owner.args.get_mut(index) {
5736 *slot = value.clone();
5737 }
5738 }
5739 },
5740 EvalSlot::Local => {
5741 let declared = owner.code.code.vars.get(index);
5742 // A `const` is read-only even through `eval`. The realm records this for
5743 // globals (see `lexical_consts`), but a local's `const`-ness is only in
5744 // the bytecode, so this is where it has to be enforced.
5745 if declared.is_some_and(|var| var.is_const) {
5746 return Err(self.read_only_local(name));
5747 }
5748 // The name of a named function expression is read-only too, but only
5749 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5750 // such a name is ignored, the same as a direct store would be.
5751 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5752 return if strict {
5753 Err(self.read_only_local(name))
5754 } else {
5755 Ok(true)
5756 };
5757 }
5758 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5759 cell if cell >= 0 => {
5760 if let Some(cell) = owner.cells.get(cell as usize) {
5761 cell.set(value.clone());
5762 }
5763 }
5764 _ => {
5765 if let Some(slot) = owner.locals.get_mut(index) {
5766 *slot = value.clone();
5767 }
5768 }
5769 }
5770 }
5771 }
5772 Ok(true)
5773 }
5774
5775 /// The `TypeError` an assignment to a read-only binding raises.
5776 fn read_only_local(&self, name: &str) -> Signal {
5777 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5778 }
5779
5780 /// Declare `name` as a variable of the frame that called the running `eval`.
5781 ///
5782 /// `None` when there is no direct eval in progress, or it was called from the top
5783 /// level — then the caller's variable environment *is* the global one and the
5784 /// existing path is right.
5785 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5786 let caller = self.eval_caller.flatten()?;
5787 // The bottom frame is the top-level script, whose variable environment *is* the
5788 // global one — so `eval("var x = 1")` at the top level still creates a global.
5789 if caller == 0 {
5790 return None;
5791 }
5792 // A name the eval's *own* variable environment already binds is not a new
5793 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5794 // `arguments`, and creating a second binding would leave the first — the one
5795 // closures read — untouched. A binding of an *outer* frame does not count: a
5796 // declaration shadows it rather than writing through.
5797 if self
5798 .eval_bindings
5799 .iter()
5800 .any(|binding| binding.name == name && binding.frame == caller)
5801 {
5802 return None;
5803 }
5804 let phase = if self.in_parameter_list_at(caller) {
5805 0
5806 } else {
5807 1
5808 };
5809 self.frame_local_vars(caller)?;
5810 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5811 if let Some(cell) = local_vars.get(name, 1) {
5812 return Some(cell);
5813 }
5814 let cell = self.new_cell(Value::Undefined);
5815 Some(local_vars.declare(name, phase, cell))
5816 }
5817
5818 /// Make sure `frame` has a `LocalVars`, creating it on demand.
5819 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5820 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5821 return Some(local_vars.clone());
5822 }
5823 let local_vars = Gc::new(self.heap, LocalVars::new());
5824 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5825 Some(local_vars)
5826 }
5827
5828 /// Whether the realm already has a binding for `name`, lexically or as an *own*
5829 /// property of the global object. Used to decide whether a store inside an
5830 /// `eval` writes through to the realm or declares a binding of its own.
5831 ///
5832 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5833 /// write to `Object.prototype.toString`, and must not shadow it either.
5834 fn global_knows(&mut self, name: &str) -> bool {
5835 if self.realm.globals.contains_key(name) {
5836 return true;
5837 }
5838 self.realm.global.own_property(name).is_some()
5839 }
5840
5841 /// Whether the code currently running is strict.
5842 ///
5843 /// Read off the frame's function, which is where the parser's answer ended up; a
5844 /// native function never runs strict-only checks, and there is no frame at all
5845 /// before the first script.
5846 pub fn current_strict(&self) -> bool {
5847 self.frames
5848 .last()
5849 .is_some_and(|frame| frame.code.code.strict)
5850 }
5851
5852 /// Initialise a declared global, which is what ends its dead zone.
5853 ///
5854 /// A `var` global becomes a property of the global object: writable, so a later
5855 /// assignment goes through, and non-configurable, so `delete` refuses.
5856 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5857 let (name, lexical, _) = self.global_binding(slot);
5858 // A `var` declared by the strict `eval` currently running belongs to the
5859 // eval's scope, not to the global object: `eval("var v = 1")` must not make
5860 // `typeof v` answer `"number"` afterwards. A name the realm already has is
5861 // initialised in place, which is what a re-declaration inside eval does.
5862 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5863 self.eval_scope
5864 .as_mut()
5865 .expect("checked above")
5866 .insert(name, value);
5867 return Ok(());
5868 }
5869 if let Some(scope) = self.eval_scope.as_mut()
5870 && scope.contains_key(&name)
5871 {
5872 scope.insert(name, value);
5873 return Ok(());
5874 }
5875 if lexical {
5876 // The cell exists (created at declaration time) holding the dead-zone
5877 // marker; storing the value is what makes the binding readable.
5878 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5879 cell.set(value);
5880 return Ok(());
5881 }
5882 let cell = self.new_cell(value);
5883 self.realm.globals.insert(name, cell);
5884 return Ok(());
5885 }
5886 let global = self.realm.global.clone();
5887 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5888 // to answer `false` and leave the binding in place. `with_attributes` ties
5889 // `configurable` to `writable`, so the property is built field by field.
5890 global.define(
5891 &name,
5892 Property {
5893 value: Some(value),
5894 writable: true,
5895 enumerable: true,
5896 configurable: false,
5897 ..Property::default()
5898 },
5899 );
5900 Ok(())
5901 }
5902
5903 /// The `TypeError` a store to a `const` global raises.
5904 fn read_only_global(&self, name: &str) -> Signal {
5905 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5906 }
5907
5908 /// The `ReferenceError` a store to a not-yet-initialised lexical global raises.
5909 fn dead_zone_global(&self, name: &str) -> Signal {
5910 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not initialized")))
5911 }
5912
5913 // -- properties ---------------------------------------------------------
5914
5915 /// Read `object[key]`, following the prototype chain.
5916 ///
5917 /// An inherited accessor runs with the *receiver* as `this`, which is why the
5918 /// lookup returns the owner rather than just the value.
5919 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5920 self.get_property_key(object, &PropertyKey::from(key))
5921 }
5922
5923 /// [`Interp::get_property`] with a key that may be a symbol.
5924 pub fn get_property_key(
5925 &mut self,
5926 object: &Gc<JsObject>,
5927 key: &PropertyKey,
5928 ) -> JsResult<Option<Value>> {
5929 self.get_property_key_for(object, None, key)
5930 }
5931
5932 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5933 ///
5934 /// The receiver matters when the property is found on a *prototype*: a getter has to
5935 /// see the object the read started from. For a primitive that is the primitive
5936 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5937 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5938 /// the owner.
5939 pub fn get_property_key_for(
5940 &mut self,
5941 object: &Gc<JsObject>,
5942 receiver: Option<&Value>,
5943 key: &PropertyKey,
5944 ) -> JsResult<Option<Value>> {
5945 // A proxy answers for itself, before any of the shortcuts below: `new
5946 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5947 // have.
5948 if object.proxy_state().is_some() {
5949 let receiver = receiver
5950 .cloned()
5951 .unwrap_or_else(|| Value::Object(object.clone()));
5952 return self.proxy_get(object, &receiver, key);
5953 }
5954 // A host class's `get_property` trap replaces the whole read, prototype walk
5955 // included — that is what makes a native accessor free rather than a JavaScript
5956 // getter call.
5957 if let Some(exotic) = object.exotic() {
5958 let receiver_value = receiver
5959 .cloned()
5960 .unwrap_or_else(|| Value::Object(object.clone()));
5961 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5962 return Ok(Some(value));
5963 }
5964 // With no `get_property` trap, a `get_own_property` trap still answers for the
5965 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5966 // and the hook lives exactly there. A key the trap reports as absent is still
5967 // looked for on the prototype, which is why the search resumes *above*.
5968 if let Some(property) = exotic.get_own_property(self, object, key)? {
5969 return match property {
5970 Some(property) => self.read_property(property, object, receiver),
5971 None => match lookup_key_above(object, key) {
5972 Some((_, property)) => self.read_property(property, object, receiver),
5973 None => Ok(None),
5974 },
5975 };
5976 }
5977 }
5978 // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
5979 // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
5980 // The `[[Get]]` short-circuit therefore belongs to this one arm.
5981 //
5982 // Constructibility is exactly the split the reference makes: `function f(){}` and
5983 // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
5984 // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
5985 // function" — it *is* the predicate, which is why no extra marker is needed.
5986 if let Some(text) = key.as_str()
5987 && (text == "caller" || text == "arguments")
5988 && object.is_constructor()
5989 && object.is_callable()
5990 && !object.is_bound_function()
5991 // …and only when the body is **sloppy**. A strict body reaches the
5992 // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
5993 // whole `Function/15.3.5.4_2-*gs` family is written against
5994 // (`onlyStrict`, so every function in them is strict).
5995 && !object.function_is_strict()
5996 && object.own_property(text).is_none()
5997 {
5998 return Ok(Some(Value::Undefined));
5999 }
6000 // The element-vector and `length` shortcuts are string-only: an array index
6001 // has no symbol spelling.
6002 if let Some(text) = key.as_str() {
6003 if let Some(value) = self.own_element(object, text) {
6004 return Ok(Some(value));
6005 }
6006 // `length` is not stored as a property: an array's length is its element
6007 // count, and keeping one copy of it is what makes `push`/`pop` and
6008 // `a.length = n` agree.
6009 if let Some(length) = object.array_length()
6010 && text == "length"
6011 {
6012 // Not `Value::Int(length as i32)`: see [`length_value`].
6013 return Ok(Some(crate::object::length_value(length)));
6014 }
6015 }
6016 // A proxy or a hooked exotic object anywhere above `object` makes the static
6017 // table walk below wrong: a proxy's own table is *empty by design* (the properties
6018 // live on its target), so the walk skipped that link entirely and everything behind
6019 // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
6020 // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
6021 // -target-is-proxy.js` are the four.
6022 if Self::chain_needs_dispatch(object) {
6023 return self.walk_get(object, receiver, key);
6024 }
6025 match lookup_key(object, key) {
6026 Some((_, property)) => self.read_property(property, object, receiver),
6027 None => Ok(None),
6028 }
6029 }
6030
6031 /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
6032 /// answer for itself.
6033 ///
6034 /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
6035 /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
6036 /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
6037 /// an inherited getter the object the read started from.
6038 fn walk_get(
6039 &mut self,
6040 start: &Gc<JsObject>,
6041 receiver: Option<&Value>,
6042 key: &PropertyKey,
6043 ) -> JsResult<Option<Value>> {
6044 let receiver = receiver
6045 .cloned()
6046 .unwrap_or_else(|| Value::Object(start.clone()));
6047 let mut current = Some(start.clone());
6048 while let Some(holder) = current {
6049 // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
6050 // has to ask it, not read its (empty) own-property table. `Object.create(new
6051 // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
6052 // instead found nothing.
6053 if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
6054 return Ok(Some(value));
6055 }
6056 // A host class's `get_property` trap replaces the whole read for that holder,
6057 // prototype walk included — the same rule `get_property_key_for` applies to the
6058 // first object.
6059 if let Some(exotic) = holder.exotic()
6060 && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
6061 {
6062 return Ok(Some(value));
6063 }
6064 if let Some(property) = self.object_get_own_property(&holder, key)? {
6065 return self.read_property(property, &holder, Some(&receiver));
6066 }
6067 current = self.object_prototype_of(&holder)?;
6068 }
6069 Ok(None)
6070 }
6071
6072 /// Whether `object` or anything above it has properties that cannot be read out of a
6073 /// property table — a proxy, or an exotic object with a `get_own_property` hook.
6074 ///
6075 /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
6076 /// is the hot path for every property read; this is the check that decides whether it
6077 /// is safe to take it.
6078 fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
6079 object
6080 .chain()
6081 .iter()
6082 .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
6083 }
6084
6085 /// The value a property read answers.
6086 ///
6087 /// One place rather than three, because an accessor has to run with the *receiver* as
6088 /// `this` whether the descriptor came from the property table, an exotic
6089 /// `get_own_property` trap, or a prototype above one.
6090 fn read_property(
6091 &mut self,
6092 property: Property,
6093 object: &Gc<JsObject>,
6094 receiver: Option<&Value>,
6095 ) -> JsResult<Option<Value>> {
6096 if property.is_accessor() {
6097 match &property.getter {
6098 Some(getter) if !matches!(getter, Value::Undefined) => {
6099 let receiver = receiver
6100 .cloned()
6101 .unwrap_or_else(|| Value::Object(object.clone()));
6102 self.call_value(getter.clone(), receiver, Vec::new())
6103 .map(Some)
6104 }
6105 // An accessor with no getter reads as `undefined`.
6106 _ => Ok(Some(Value::Undefined)),
6107 }
6108 } else {
6109 Ok(property.value)
6110 }
6111 }
6112
6113 /// `super.key` — start the search at `proto`, but report to `receiver`.
6114 ///
6115 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
6116 /// found on the prototype of a class has to see the *instance* as `this`, and a
6117 /// plain property read off `proto` would lose that.
6118 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
6119 let start = self.require_object(proto)?;
6120 let key = self.propkey(key)?;
6121 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
6122 if matches!(proto, Value::Null) {
6123 return Ok(Value::Undefined);
6124 }
6125 match lookup_key(&start, &key) {
6126 Some((_, property)) if property.is_accessor() => match &property.getter {
6127 Some(getter) if !matches!(getter, Value::Undefined) => {
6128 self.call_value(getter.clone(), receiver.clone(), Vec::new())
6129 }
6130 _ => Ok(Value::Undefined),
6131 },
6132 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
6133 None => Ok(Value::Undefined),
6134 }
6135 }
6136
6137 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
6138 ///
6139 /// A setter found on the prototype runs with `receiver` as `this`; a data property
6140 /// is shadowed by a new own property on the receiver, the same rule an ordinary
6141 /// assignment follows.
6142 fn super_write(
6143 &mut self,
6144 receiver: &Value,
6145 proto: &Value,
6146 key: &Value,
6147 value: Value,
6148 ) -> JsResult<()> {
6149 let target = self.require_object(receiver)?;
6150 let key = self.propkey(key)?;
6151 if !matches!(proto, Value::Null)
6152 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
6153 {
6154 if property.is_accessor() {
6155 if let Some(setter) = &property.setter
6156 && !matches!(setter, Value::Undefined)
6157 {
6158 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
6159 }
6160 return Ok(());
6161 }
6162 // A data property on the prototype is writable or not; reading `owner` at
6163 // all is only for the attribute check.
6164 if !property.writable {
6165 return Err(self.type_error(format!("'{key}' is read-only")));
6166 }
6167 let _ = owner;
6168 }
6169 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
6170 }
6171
6172 /// The object a `super` operation needs, or the `TypeError` the spec raises.
6173 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
6174 match value.as_object() {
6175 Some(object) => Ok(object.clone()),
6176 None => Err(Signal::Throw(
6177 self.make_error("TypeError", "value is not an object"),
6178 )),
6179 }
6180 }
6181
6182 /// Build the class object `define_class` produces.
6183 ///
6184 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
6185 /// whose prototype property is a fresh object inheriting from the parent's
6186 /// prototype, and whose own prototype is the parent constructor — which is what makes
6187 /// a static method inherited too.
6188 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
6189 let ctor = self.pop();
6190 let parent = self.pop();
6191 let Value::Object(function) = &ctor else {
6192 return Err(Signal::Throw(
6193 self.make_error("TypeError", "class constructor must be a function"),
6194 ));
6195 };
6196 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
6197 // but gives the instances no prototype at all.
6198 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
6199 match &parent {
6200 Value::Null => (Some(self.realm.function_proto.clone()), None),
6201 Value::Object(parent_class) => {
6202 if !parent_class.is_callable() {
6203 return Err(Signal::Throw(
6204 self.make_error("TypeError", "parent class must be constructor"),
6205 ));
6206 }
6207 let proto = self.get_property(parent_class, "prototype")?;
6208 match proto {
6209 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
6210 Some(Value::Null) => (Some(parent_class.clone()), None),
6211 _ => {
6212 return Err(Signal::Throw(self.make_error(
6213 "TypeError",
6214 "parent prototype must be an object or null",
6215 )));
6216 }
6217 }
6218 }
6219 _ => {
6220 return Err(Signal::Throw(
6221 self.make_error("TypeError", "parent class must be constructor"),
6222 ));
6223 }
6224 }
6225 } else {
6226 (
6227 Some(self.realm.function_proto.clone()),
6228 Some(self.realm.object_proto.clone()),
6229 )
6230 };
6231 let proto = self.new_object(parent_proto);
6232 function.set_proto(parent_ctor);
6233 // A class is not callable without `new`, and its `prototype` is not writable —
6234 // both follow from being a class and are what `class A {}; A()` throws on.
6235 function.set_class_constructor(true);
6236 function.set_home_object(None);
6237 self.set_function_name(&ctor, name);
6238 self.define_class_properties(function, &ctor, &proto)?;
6239 Ok((ctor, proto))
6240 }
6241
6242 /// Give the constructor its `prototype` and `length`, and the prototype its
6243 /// `constructor` back-pointer.
6244 fn define_class_properties(
6245 &mut self,
6246 function: &Gc<JsObject>,
6247 ctor: &Value,
6248 proto: &Gc<JsObject>,
6249 ) -> JsResult<()> {
6250 proto.define(
6251 "constructor",
6252 Property::with_attributes(ctor.clone(), true, false),
6253 );
6254 function.define(
6255 "prototype",
6256 Property::prototype_of(Value::Object(proto.clone()), false),
6257 );
6258 if let Some((code, _)) = bytecode_of(function) {
6259 let length = code.code.defined_args;
6260 function.define(
6261 "length",
6262 Property::name_or_length(Value::Int(length as i32)),
6263 );
6264 }
6265 Ok(())
6266 }
6267
6268 /// The own array element `key` names, if this object has one.
6269 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
6270 // A typed array's elements live in its buffer, not in a property list: reading one
6271 // goes through the view's element type so a bounds check and a detached buffer are
6272 // both handled there.
6273 //
6274 // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
6275 // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
6276 // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
6277 // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
6278 // consulted. Testing with `array_index` rejected all three, which let a throwing
6279 // getter installed on `TypedArray.prototype["-1"]` run.
6280 if object.typed_array_parts().is_some() {
6281 let property_key = PropertyKey::from(key);
6282 let numeric = canonical_numeric_index(&property_key)?;
6283 if typed_array_index_is_valid(object, numeric) {
6284 return object.typed_array_element(numeric as usize);
6285 }
6286 // Canonical, but not a valid index: `undefined`, and *final*.
6287 return Some(Value::Undefined);
6288 }
6289 let index = array_index(key)?;
6290 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
6291 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
6292 // search early, which is why `Array.prototype[1] = 9` could not be seen through
6293 // `[1,,3][1]`.
6294 match object.array_get(index as usize) {
6295 Some(Value::Hole) | None => None,
6296 other => other,
6297 }
6298 }
6299
6300 /// Store `object[key] = value`, honouring setters and inherited properties.
6301 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
6302 self.set_property_with(object, key, value, DeleteFailure::Throw)
6303 }
6304
6305 /// Store a property, choosing what to do when the object refuses.
6306 ///
6307 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
6308 /// mode, which is the one place assignment differs by mode. Native code (the array
6309 /// methods, `JSON`) always asks for the throw.
6310 pub fn set_property_with(
6311 &mut self,
6312 object: &Gc<JsObject>,
6313 key: &str,
6314 value: Value,
6315 on_failure: DeleteFailure,
6316 ) -> JsResult<()> {
6317 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
6318 }
6319
6320 /// [`Interp::set_property_with`] with a key that may be a symbol.
6321 pub fn set_property_with_key(
6322 &mut self,
6323 object: &Gc<JsObject>,
6324 key: &PropertyKey,
6325 value: Value,
6326 on_failure: DeleteFailure,
6327 ) -> JsResult<()> {
6328 self.set_property_with_key_receiver_aware(object, key, value, on_failure)
6329 }
6330
6331 /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
6332 ///
6333 /// The receiver split lives one level up, in
6334 /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
6335 /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
6336 /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
6337 /// stores into `object` itself, which is why the element branch below converts `V`
6338 /// before asking whether the index is valid: `V` may put it back in bounds
6339 /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
6340 fn set_property_with_key_receiver_aware(
6341 &mut self,
6342 object: &Gc<JsObject>,
6343 key: &PropertyKey,
6344 value: Value,
6345 on_failure: DeleteFailure,
6346 ) -> JsResult<()> {
6347 // §10.4.6.7: a module namespace's `[[Set]]` **always** returns false — for an
6348 // exported name, for a name that is not exported, and for `@@toStringTag` alike.
6349 // Nothing about the receiver or the value changes that, so the whole operation is
6350 // one answer.
6351 //
6352 // Not implementing it explicitly left the ordinary algorithm in charge, and that
6353 // says "true" for names the namespace does not own as soon as the value matches or
6354 // the key is writable, so `Reflect.set(ns, 'local1', …)` answered `true` and strict
6355 // assignment stopped throwing (`await-ns-set-strict`).
6356 if object.module_namespace_marker() {
6357 return match on_failure {
6358 DeleteFailure::Ignore => Ok(()),
6359 DeleteFailure::Throw => Err(self.type_error(format!(
6360 "cannot assign to property '{key}' of a module namespace object"
6361 ))),
6362 };
6363 }
6364 // A proxy's `set` trap decides, and its `false` means the same thing an
6365 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
6366 if object.proxy_state().is_some() {
6367 let receiver = Value::Object(object.clone());
6368 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
6369 return match (accepted, on_failure) {
6370 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6371 (false, DeleteFailure::Throw) => {
6372 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
6373 }
6374 };
6375 }
6376 }
6377 // A host class's `set_property` trap decides for itself. `Some(false)` is a
6378 // refusal and means exactly what a proxy's `false` means.
6379 if let Some(exotic) = object.exotic() {
6380 let receiver = Value::Object(object.clone());
6381 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
6382 return match (accepted, on_failure) {
6383 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6384 (false, DeleteFailure::Throw) => {
6385 Err(self.type_error(format!("property '{key}' is read-only")))
6386 }
6387 };
6388 }
6389 }
6390 // The element and `length` shortcuts only exist for string keys: an array
6391 // index has no symbol spelling, and a symbol named `length` is an ordinary
6392 // property.
6393 let text = key.as_str();
6394 // A typed array's elements are a window onto its buffer: the store has to go
6395 // through the view's element type so the value is wrapped (or clamped) and so an
6396 // out-of-range or detached write is a silent no-op, as the spec says.
6397 //
6398 // The key test is `CanonicalNumericIndexString`, like every other index operation
6399 // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
6400 // does not exist, so they do nothing and leave no own property behind
6401 // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
6402 // path, which created a property named `"-0"`.
6403 //
6404 // The conversion comes **first**, before the index is checked at all, and that
6405 // order is observable twice over:
6406 //
6407 // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
6408 // has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
6409 // then store the converted value;
6410 // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
6411 // `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
6412 // run and its exception to escape.
6413 //
6414 // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
6415 // validity check, not a validity check that skips the conversion. The store itself
6416 // is a no-op when the index is invalid by then, which is why no extra guard is
6417 // needed around `typed_array_set`.
6418 if let Some(element) = object.typed_array_element_type()
6419 && let Some(numeric) = canonical_numeric_index(key)
6420 {
6421 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
6422 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
6423 // in `Interp`, because it is script-observable and the storage borrow inside
6424 // `typed_array_set` must not be held across it.
6425 let stored = self.element_value(element, value)?;
6426 if typed_array_index_is_valid(object, numeric)
6427 && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
6428 {
6429 return Err(self.type_error(reason));
6430 }
6431 return Ok(());
6432 }
6433 if let Some(text) = text
6434 && let Some(index) = array_index(text)
6435 && object.is_array()
6436 {
6437 // An accessor defined on an index lives in the property table while the
6438 // element slot is a hole, so the store has to go through the property first.
6439 // Writing the vector directly skipped the setter entirely.
6440 if let Some(existing) = object.own_property_key(key) {
6441 if existing.is_accessor() {
6442 return match existing.setter.clone() {
6443 Some(setter) if !matches!(setter, Value::Undefined) => {
6444 let receiver = Value::Object(object.clone());
6445 self.call_value(setter, receiver, vec![value]).map(|_| ())
6446 }
6447 _ => match on_failure {
6448 DeleteFailure::Throw => Err(self.type_error(format!(
6449 "cannot set property '{text}', it has only a getter"
6450 ))),
6451 DeleteFailure::Ignore => Ok(()),
6452 },
6453 };
6454 }
6455 if !existing.writable {
6456 return match on_failure {
6457 DeleteFailure::Throw => {
6458 Err(self.type_error(format!("'{text}' is read-only")))
6459 }
6460 DeleteFailure::Ignore => Ok(()),
6461 };
6462 }
6463 }
6464 {
6465 // Growing the array needs a writable `length`.
6466 if (index as usize) >= object.array_length().unwrap_or(0)
6467 && !object.length_writable()
6468 {
6469 return match on_failure {
6470 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6471 DeleteFailure::Ignore => Ok(()),
6472 };
6473 }
6474 // Adding an index past the end makes the array longer, which a
6475 // non-extensible array refuses.
6476 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6477 return match on_failure {
6478 DeleteFailure::Throw => Err(self.type_error(format!(
6479 "cannot add property '{key}', object is not extensible"
6480 ))),
6481 DeleteFailure::Ignore => Ok(()),
6482 };
6483 }
6484 if object.element_is_locked(index) {
6485 return match on_failure {
6486 DeleteFailure::Throw => {
6487 Err(self.type_error(format!("'{key}' is read-only")))
6488 }
6489 DeleteFailure::Ignore => Ok(()),
6490 };
6491 }
6492 // The element vector is only half of `[[Set]]` for an index: the
6493 // prototype chain is consulted first, and a setter there answers instead
6494 // of the element store. This branch used to write the element directly, so
6495 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6496 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6497 // the reference calls the setter and the array keeps no own index.
6498 //
6499 // An *exotic* prototype has no entry to find, because its indices live
6500 // outside the property table — `Object.setPrototypeOf([], typedArray)`
6501 // then looked like "nothing on the chain" and the store created the
6502 // element, where the view's `[[Set]]` answers `true` and does nothing for
6503 // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6504 // checks the array's `length` stays 0). So the dispatch comes first.
6505 if !object.has_own_key(key)
6506 && let Some(proto) = object.proto()
6507 && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6508 {
6509 let receiver = Value::Object(object.clone());
6510 let accepted =
6511 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6512 return if accepted {
6513 Ok(())
6514 } else {
6515 match on_failure {
6516 DeleteFailure::Throw => {
6517 Err(self.type_error(format!("'{key}' is read-only")))
6518 }
6519 DeleteFailure::Ignore => Ok(()),
6520 }
6521 };
6522 }
6523 if let Some((owner, property)) = lookup_key(object, key)
6524 && !owner.ptr_eq(object)
6525 {
6526 match &property {
6527 property if property.is_accessor() => {
6528 match &property.setter {
6529 Some(setter) if !matches!(setter, Value::Undefined) => {
6530 let receiver = Value::Object(object.clone());
6531 self.call_value(setter.clone(), receiver, vec![value])?;
6532 }
6533 _ => {
6534 return match on_failure {
6535 DeleteFailure::Throw => Err(self.type_error(format!(
6536 "cannot set property '{text}', it has only a getter"
6537 ))),
6538 DeleteFailure::Ignore => Ok(()),
6539 };
6540 }
6541 }
6542 return Ok(());
6543 }
6544 property if !property.writable => {
6545 return match on_failure {
6546 DeleteFailure::Throw => {
6547 Err(self.type_error(format!("'{text}' is read-only")))
6548 }
6549 DeleteFailure::Ignore => Ok(()),
6550 };
6551 }
6552 _ => {}
6553 }
6554 }
6555 if object.array_set(self.heap, index as usize, value.clone()) {
6556 return Ok(());
6557 }
6558 // Past the dense limit the slot is too far out to be worth one `Value`
6559 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6560 // constant time by keeping the index as an ordinary property. The store
6561 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6562 // to a legal program.
6563 object.define_key(key, Property::with_attributes(value, true, true));
6564 // Extend, never shorten: the index may be *inside* the current length (a
6565 // huge `length` with a sparse store), and shortening would delete the
6566 // sparse properties above it — including the one just stored.
6567 if index as usize + 1 > object.array_length().unwrap_or(0) {
6568 object.array_set_length(self.heap, index as usize + 1);
6569 }
6570 return Ok(());
6571 }
6572 }
6573 if text == Some("length") && object.is_array() {
6574 // §10.4.2.4 steps 3–5: **two** `ToNumber` conversions, then the writability
6575 // test. A `valueOf` that locks `length` on its second call therefore turns the
6576 // store into a refused write rather than a silent success
6577 // (`length/define-own-prop-length-coercion-order-set`).
6578 let rounded = self.coerce_array_length_twice(&value)?;
6579 if !object.length_writable() {
6580 return match on_failure {
6581 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6582 DeleteFailure::Ignore => Ok(()),
6583 };
6584 }
6585 // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6586 // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6587 // answered `NaN`, which left the assignment silently ignored
6588 // (`S15.4.5.2_A3_T2`).
6589 let _ = rounded;
6590 let length = self.to_js_number(&value)?;
6591 // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6592 // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6593 // `RangeError`s; the old code only tested "finite and non-negative" and then
6594 // truncated, so `[].length = 4294967297` quietly produced a length no array can
6595 // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6596 let valid = length.is_finite()
6597 && length >= 0.0
6598 && length.fract() == 0.0
6599 && length <= u32::MAX as f64;
6600 if !valid {
6601 return Err(self.range_error("invalid array length"));
6602 }
6603 {
6604 let length = length as usize;
6605 // `a.length = n` with `n` below a non-configurable element cannot
6606 // drop that element, so the whole assignment fails. The spec makes
6607 // this a `TypeError` rather than a silent no-op, in any mode.
6608 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6609 // Sloppy mode stops the truncation at the blocking element
6610 // instead of failing; strict mode raises.
6611 // Both modes stop at the blocking element; they differ in
6612 // whether that is reported. The reference truncates *then*
6613 // throws, so the array is left in the shortened state.
6614 object.array_truncate(self.heap, blocked + 1);
6615 return match on_failure {
6616 DeleteFailure::Throw => {
6617 Err(self.type_error(format!("cannot delete property '{blocked}'")))
6618 }
6619 DeleteFailure::Ignore => Ok(()),
6620 };
6621 }
6622 object.array_set_length(self.heap, length);
6623 return Ok(());
6624 }
6625 }
6626 // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6627 // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6628 // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6629 //
6630 // The prototype step is a dispatch, not a lookup. Walking the chain here and
6631 // applying whatever came back is the same thing for an ordinary prototype and
6632 // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6633 // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6634 // answers "not mine, the receiver is not me" without touching the buffer. This
6635 // code used to find nothing owned by `o`, find no property on the view either,
6636 // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6637 // object and never converted (`key-is-valid-index-prototype-chain-set`,
6638 // `key-is-canonical-invalid-index-prototype-chain-set`).
6639 //
6640 // The read-only and accessor rules of step 1 are what make
6641 // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6642 // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6643 let own = match self.lookup_for_write(object, key)? {
6644 Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6645 _ => None,
6646 };
6647 if let Some(property) = own {
6648 if property.is_accessor() {
6649 return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6650 Some(setter) => {
6651 let receiver = Value::Object(object.clone());
6652 self.call_value(setter, receiver, vec![value])?;
6653 Ok(())
6654 }
6655 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6656 // Sloppy code swallows that refusal, strict code raises — the same
6657 // rule the read-only *data* property below follows, and skipping it
6658 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6659 // return silently. The reference answers `TypeError: 'x' is
6660 // read-only`.
6661 None => match on_failure {
6662 DeleteFailure::Throw => {
6663 Err(self.type_error(format!("'{key}' is read-only")))
6664 }
6665 DeleteFailure::Ignore => Ok(()),
6666 },
6667 };
6668 }
6669 // An own non-writable data property stops here: nothing may change it.
6670 if !property.writable {
6671 return match on_failure {
6672 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6673 DeleteFailure::Ignore => Ok(()),
6674 };
6675 }
6676 // An existing writable own property keeps its attributes: only the value
6677 // moves. Redefining instead would reset them, which is how a
6678 // non-configurable global `var` used to become deletable.
6679 if object.write_value_key(key, value.clone()) {
6680 return Ok(());
6681 }
6682 }
6683 // Step 2: hand the store to the prototype, with `object` as the receiver.
6684 if let Some(proto) = object.proto() {
6685 let receiver = Value::Object(object.clone());
6686 let accepted =
6687 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6688 return if accepted {
6689 Ok(())
6690 } else {
6691 match on_failure {
6692 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6693 DeleteFailure::Ignore => Ok(()),
6694 }
6695 };
6696 }
6697 // Step 3: create one, and a non-extensible object cannot.
6698 if !object.is_extensible() {
6699 return match on_failure {
6700 DeleteFailure::Throw => Err(self.type_error(format!(
6701 "cannot add property {key}, object is not extensible"
6702 ))),
6703 DeleteFailure::Ignore => Ok(()),
6704 };
6705 }
6706 object.define_data_key(key, value);
6707 Ok(())
6708 }
6709
6710 /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6711 ///
6712 /// The distinction the fast path above does not need: it is called with the store's
6713 /// receiver already being the object it writes to. Here `object` is the one whose
6714 /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6715 /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6716 /// and not a write to `object`.
6717 ///
6718 /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6719 /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6720 /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6721 /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6722 /// descriptor on the prototype refuses instead, which is the same rule that keeps
6723 /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6724 ///
6725 /// Answers `false` where the spec says `false`; the caller turns that into the
6726 /// strict-mode `TypeError` or the sloppy-mode silence.
6727 fn ordinary_set_with_receiver(
6728 &mut self,
6729 object: &Gc<JsObject>,
6730 receiver: &Value,
6731 key: &PropertyKey,
6732 value: Value,
6733 on_failure: DeleteFailure,
6734 ) -> JsResult<bool> {
6735 // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6736 if object.proxy_state().is_some() {
6737 return Ok(self
6738 .proxy_set(object, key, value, receiver)?
6739 .unwrap_or(true));
6740 }
6741 // A host class decides for itself, with the receiver the caller named.
6742 if let Some(exotic) = object.exotic()
6743 && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6744 {
6745 return Ok(accepted);
6746 }
6747 // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6748 // rather than the receiver, but the receiver may still *be* the view:
6749 // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6750 // itself as receiver, and then the first half applies — convert `V` once, store
6751 // if the index is valid, answer `true` either way. The conversion is the observable
6752 // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6753 //
6754 // Only the second half, a view that is *not* the receiver, skips the conversion
6755 // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6756 // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6757 // below with the value still unconverted.
6758 if object.typed_array_element_type().is_some()
6759 && let Some(numeric) = canonical_numeric_index(key)
6760 {
6761 if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6762 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6763 return Ok(true);
6764 }
6765 if !typed_array_index_is_valid(object, numeric) {
6766 return Ok(true);
6767 }
6768 }
6769 let own = self.object_get_own_property(object, key)?;
6770 if let Some(own) = own {
6771 if own.is_accessor() {
6772 return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6773 Some(setter) => {
6774 self.call_value(setter, receiver.clone(), vec![value])?;
6775 Ok(true)
6776 }
6777 None => Ok(false),
6778 };
6779 }
6780 // A non-writable data descriptor refuses, own or inherited. Either way the
6781 // receiver must not gain a shadowing property.
6782 if !own.writable {
6783 return Ok(false);
6784 }
6785 // Step 1.d: the *receiver's* own descriptor decides whether it can be
6786 // created or written, and it is created as an ordinary data property.
6787 let Some(receiver_object) = receiver.as_object().cloned() else {
6788 return Ok(false);
6789 };
6790 return match self.object_get_own_property(&receiver_object, key)? {
6791 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6792 Some(existing) => self.object_define_own_property(
6793 &receiver_object,
6794 key,
6795 Property {
6796 value: Some(value),
6797 ..existing
6798 },
6799 ),
6800 None => {
6801 self.object_define_own_property(&receiver_object, key, Property::data(value))
6802 }
6803 };
6804 }
6805 // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6806 if let Some(proto) = object.proto() {
6807 return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6808 }
6809 // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6810 // *default* data descriptor here, so control falls into step 2 exactly as if the
6811 // target had owned a writable property — which means the **receiver's** own
6812 // descriptor is asked for before the write. Skipping that question went straight to
6813 // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6814 // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6815 // exactly those calls).
6816 let Some(receiver_object) = receiver.as_object().cloned() else {
6817 return Ok(false);
6818 };
6819 match self.object_get_own_property(&receiver_object, key)? {
6820 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6821 Some(existing) => self.object_define_own_property(
6822 &receiver_object,
6823 key,
6824 Property {
6825 value: Some(value),
6826 ..existing
6827 },
6828 ),
6829 None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6830 }
6831 }
6832
6833 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6834 ///
6835 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6836 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6837 /// a virtual accessor gets its setter run without implementing `set_property` at all.
6838 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6839 /// the prototype, so the walk resumes above the object.
6840 fn lookup_for_write(
6841 &mut self,
6842 object: &Gc<JsObject>,
6843 key: &PropertyKey,
6844 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6845 let Some(exotic) = object.exotic() else {
6846 return Ok(lookup_key(object, key));
6847 };
6848 Ok(match exotic.get_own_property(self, object, key)? {
6849 Some(Some(property)) => Some((object.clone(), property)),
6850 Some(None) => lookup_key_above(object, key),
6851 None => lookup_key(object, key),
6852 })
6853 }
6854
6855 /// Delete `object[key]`.
6856 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6857 self.delete_property_key(object, &PropertyKey::from(key))
6858 }
6859
6860 /// [`Interp::delete_property`] with a key that may be a symbol.
6861 pub fn delete_property_key(
6862 &mut self,
6863 object: &Gc<JsObject>,
6864 key: &PropertyKey,
6865 ) -> JsResult<bool> {
6866 // A proxy decides for itself, and may even throw; the invariant checks live in
6867 // `proxy_delete`.
6868 if let Some(answer) = self.proxy_delete(object, key)? {
6869 return Ok(answer);
6870 }
6871 // A host class's `delete_property` trap decides; `false` is a refusal, which the
6872 // caller reports as a failed delete.
6873 if let Some(exotic) = object.exotic()
6874 && let Some(answer) = exotic.delete_property(self, object, key)?
6875 {
6876 return Ok(answer);
6877 }
6878 // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6879 // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6880 // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6881 // one answers `false` because the elements are non-configurable. The prototype
6882 // chain is not consulted either, which is what makes a throwing getter on
6883 // `TypedArray.prototype["-1"]` stay unrun.
6884 if object.typed_array_parts().is_some()
6885 && object.proxy_state().is_none()
6886 && let Some(numeric) = canonical_numeric_index(key)
6887 {
6888 return Ok(!typed_array_index_is_valid(object, numeric));
6889 }
6890 let mapped_index = key.as_str().and_then(array_index);
6891 if let Some(index) = mapped_index
6892 && let Some(length) = object.array_length()
6893 && (index as usize) < length
6894 {
6895 // An accessor defined on an index lives in the property table rather than the
6896 // element vector, so both have to be cleared: `delete` after
6897 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6898 object.delete_key(key);
6899 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6900 // index stops answering `in`.
6901 if object.element_is_undeletable(index) {
6902 return Ok(false);
6903 }
6904 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6905 // so a later `defineProperty(arguments, "0", {value})` writes to the object
6906 // and no longer through to the parameter. A refused delete leaves the
6907 // mapping alone.
6908 object.drop_mapped_argument(index as usize);
6909 object.array_set(self.heap, index as usize, Value::Hole);
6910 return Ok(true);
6911 }
6912 // An array's `length` is a non-configurable own property that lives outside the
6913 // property table, so `delete_key` finds nothing and reports success — `Reflect
6914 // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6915 // §10.4.4.1 step 3 refuses it.
6916 if key.as_str() == Some("length") && object.array_length().is_some() {
6917 return Ok(false);
6918 }
6919 // The same for an object that is not an array: only a delete that actually
6920 // removed the property ends the alias.
6921 let deleted = object.delete_key(key);
6922 if deleted && let Some(index) = mapped_index {
6923 object.drop_mapped_argument(index as usize);
6924 }
6925 Ok(deleted)
6926 }
6927
6928 // -- proxy traps --------------------------------------------------------
6929 //
6930 // A proxy's internal methods all look the same: ask the handler for the trap, call it
6931 // with the target and the operation's own arguments, then check the answer against
6932 // the target. The checks are not decoration — they are what stops a proxy from
6933 // reporting a `non-configurable` property as missing, which would let a frozen object
6934 // be rewritten by standing in front of it.
6935
6936 /// The target and handler of `object`, or `None` when it is not a proxy.
6937 ///
6938 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6939 /// one has to fail: the slots the traps would have been read from are gone.
6940 pub(crate) fn proxy_parts(
6941 &mut self,
6942 object: &Gc<JsObject>,
6943 ) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6944 let Some(state) = object.proxy_state() else {
6945 return Ok(None);
6946 };
6947 let state = state.borrow();
6948 match (&state.target, &state.handler) {
6949 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
6950 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
6951 }
6952 }
6953
6954 /// Call `handler[name]`, or answer `None` when the trap is absent.
6955 ///
6956 /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
6957 /// and only a value that is neither is `IsCallable`-checked and refused. Treating
6958 /// `null` as "present but not callable" made every `{ get: null }` proxy throw
6959 /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
6960 /// one per trap plus the `target-is-proxy` variants.
6961 ///
6962 /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
6963 /// this cannot simply be "any non-callable means no trap".
6964 fn proxy_trap(
6965 &mut self,
6966 handler: &Value,
6967 name: &str,
6968 args: Vec<Value>,
6969 ) -> JsResult<Option<Value>> {
6970 let Value::Object(table) = handler else {
6971 return Err(self.type_error("proxy handler is not an object"));
6972 };
6973 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
6974 match trap {
6975 Value::Undefined | Value::Null => Ok(None),
6976 Value::Object(function) if function.is_callable() => {
6977 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
6978 Ok(Some(answer))
6979 }
6980 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
6981 }
6982 }
6983
6984 /// Whether the target's own property `key` is one it refuses to lose.
6985 ///
6986 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
6987 /// its value behind the target's back.
6988 ///
6989 /// A **method**, not a free function, because §10.5.1's invariants say
6990 /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
6991 /// property table directly finds nothing (a proxy's table is empty by design), so every
6992 /// invariant check silently passed for a proxy target. That is what
6993 /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
6994 /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
6995 /// where an array's elements and its `length` — both fixed, both outside the table —
6996 /// are covered.
6997 fn fixed_property(
6998 &mut self,
6999 target: &Gc<JsObject>,
7000 key: &PropertyKey,
7001 ) -> JsResult<Option<Property>> {
7002 Ok(self
7003 .object_get_own_property(target, key)?
7004 .filter(|property| !property.configurable))
7005 }
7006
7007 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
7008 fn proxy_get(
7009 &mut self,
7010 object: &Gc<JsObject>,
7011 receiver: &Value,
7012 key: &PropertyKey,
7013 ) -> JsResult<Option<Value>> {
7014 let Some((target, handler)) = self.proxy_parts(object)? else {
7015 return Ok(None);
7016 };
7017 let key_value = self.key_value(key);
7018 let Some(result) = self.proxy_trap(
7019 &handler,
7020 "get",
7021 vec![Value::Object(target.clone()), key_value, receiver.clone()],
7022 )?
7023 else {
7024 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
7025 // inherited getter still sees the proxy.
7026 return Ok(Some(
7027 self.get_property_key_for(&target, Some(receiver), key)?
7028 .unwrap_or(Value::Undefined),
7029 ));
7030 };
7031 if let Some(fixed) = self.fixed_property(&target, key)? {
7032 if fixed.is_accessor() {
7033 // A fixed accessor with no getter must read as `undefined`.
7034 let has_getter = fixed
7035 .getter
7036 .as_ref()
7037 .is_some_and(|getter| !matches!(getter, Value::Undefined));
7038 if !has_getter && !matches!(result, Value::Undefined) {
7039 return Err(self.type_error(format!(
7040 "proxy 'get' must report undefined for the non-configurable property '{key}'"
7041 )));
7042 }
7043 } else if !fixed.writable {
7044 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7045 if !fixed_value.same_value(&result) {
7046 return Err(self.type_error(format!(
7047 "proxy 'get' disagrees with the non-configurable property '{key}'"
7048 )));
7049 }
7050 }
7051 }
7052 Ok(Some(result))
7053 }
7054
7055 /// `[[Set]]` on a proxy.
7056 ///
7057 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
7058 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
7059 /// read-only store has.
7060 fn proxy_set(
7061 &mut self,
7062 object: &Gc<JsObject>,
7063 key: &PropertyKey,
7064 value: Value,
7065 receiver: &Value,
7066 ) -> JsResult<Option<bool>> {
7067 let Some((target, handler)) = self.proxy_parts(object)? else {
7068 return Ok(None);
7069 };
7070 let key_value = self.key_value(key);
7071 let Some(result) = self.proxy_trap(
7072 &handler,
7073 "set",
7074 vec![
7075 Value::Object(target.clone()),
7076 key_value,
7077 value.clone(),
7078 receiver.clone(),
7079 ],
7080 )?
7081 else {
7082 // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
7083 // given — not the target. `OrdinarySet` step 3 is
7084 // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
7085 // object whose prototype is a typed array has to reach the proxy's own
7086 // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
7087 // calls and expects exactly one. Storing on the target instead put the value
7088 // in the target and never consulted the trap.
7089 let accepted = self.ordinary_set_with_receiver(
7090 &target,
7091 receiver,
7092 key,
7093 value,
7094 DeleteFailure::Ignore,
7095 )?;
7096 return Ok(Some(accepted));
7097 };
7098 if !result.to_boolean() {
7099 return Ok(Some(false));
7100 }
7101 if let Some(fixed) = self.fixed_property(&target, key)? {
7102 if fixed.is_accessor() {
7103 let has_setter = fixed
7104 .setter
7105 .as_ref()
7106 .is_some_and(|setter| !matches!(setter, Value::Undefined));
7107 if !has_setter {
7108 return Err(self.type_error(format!(
7109 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
7110 )));
7111 }
7112 } else if !fixed.writable {
7113 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7114 if !fixed_value.same_value(&value) {
7115 return Err(self.type_error(format!(
7116 "proxy 'set' changed the non-configurable property '{key}'"
7117 )));
7118 }
7119 }
7120 }
7121 // A new property cannot appear on a target that refuses new properties.
7122 if self.object_get_own_property(&target, key)?.is_none()
7123 && !self.object_is_extensible(&target)?
7124 {
7125 return Err(self.type_error(format!(
7126 "proxy 'set' added '{key}' to a non-extensible target"
7127 )));
7128 }
7129 Ok(Some(true))
7130 }
7131
7132 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
7133 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7134 let Some((target, handler)) = self.proxy_parts(object)? else {
7135 return Ok(None);
7136 };
7137 let key_value = self.key_value(key);
7138 let Some(result) = self.proxy_trap(
7139 &handler,
7140 "has",
7141 vec![Value::Object(target.clone()), key_value],
7142 )?
7143 else {
7144 return Ok(Some(self.has_own_or_inherited(&target, key)?));
7145 };
7146 if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7147 return Err(self.type_error(format!(
7148 "proxy 'has' denied the non-configurable property '{key}'"
7149 )));
7150 }
7151 // A non-extensible target cannot grow, so every own property it *has* is fixed.
7152 if !result.to_boolean()
7153 && !self.object_is_extensible(&target)?
7154 && self.object_get_own_property(&target, key)?.is_some()
7155 {
7156 return Err(self.type_error(format!(
7157 "proxy 'has' denied the own property '{key}' of a non-extensible target"
7158 )));
7159 }
7160 Ok(Some(result.to_boolean()))
7161 }
7162
7163 /// `[[Delete]]` on a proxy.
7164 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7165 let Some((target, handler)) = self.proxy_parts(object)? else {
7166 return Ok(None);
7167 };
7168 let key_value = self.key_value(key);
7169 let Some(result) = self.proxy_trap(
7170 &handler,
7171 "deleteProperty",
7172 vec![Value::Object(target.clone()), key_value],
7173 )?
7174 else {
7175 return Ok(Some(self.delete_property_key(&target, key)?));
7176 };
7177 if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7178 return Err(self.type_error(format!(
7179 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
7180 )));
7181 }
7182 if result.to_boolean()
7183 && !self.object_is_extensible(&target)?
7184 && self.object_get_own_property(&target, key)?.is_some()
7185 {
7186 return Err(self.type_error(format!(
7187 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
7188 )));
7189 }
7190 Ok(Some(result.to_boolean()))
7191 }
7192
7193 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
7194 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
7195 let Some((target, handler)) = self.proxy_parts(object)? else {
7196 return Ok(None);
7197 };
7198 let Some(result) =
7199 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
7200 else {
7201 // No trap: the target's own keys, already in the order an object reports.
7202 return Ok(Some(self.object_own_property_keys(&target)?));
7203 };
7204 // `CreateListFromArrayLike` with the string-or-symbol restriction.
7205 let list = self.list_from_array_like(&result, true)?;
7206 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
7207 for value in list {
7208 let key = self.propkey(&value)?;
7209 if keys.contains(&key) {
7210 return Err(self.type_error(format!(
7211 "proxy 'ownKeys' returned the duplicate key '{key}'"
7212 )));
7213 }
7214 keys.push(key);
7215 }
7216 // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
7217 // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
7218 // table is empty, which made every check below vacuous.
7219 let target_keys = self.object_own_property_keys(&target)?;
7220 let extensible = self.object_is_extensible(&target)?;
7221 for key in &target_keys {
7222 if keys.contains(key) {
7223 continue;
7224 }
7225 if self.fixed_property(&target, key)?.is_some() {
7226 return Err(self.type_error(format!(
7227 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
7228 )));
7229 }
7230 if !extensible {
7231 return Err(self.type_error(format!(
7232 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
7233 )));
7234 }
7235 }
7236 if !extensible {
7237 // §10.5.11 step 12: the lists must match one for one, in any order.
7238 if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
7239 {
7240 return Err(
7241 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
7242 );
7243 }
7244 }
7245 Ok(Some(keys))
7246 }
7247
7248 /// `[[GetOwnProperty]]` on a proxy.
7249 fn proxy_get_own_property(
7250 &mut self,
7251 object: &Gc<JsObject>,
7252 key: &PropertyKey,
7253 ) -> JsResult<Option<Option<Property>>> {
7254 let Some((target, handler)) = self.proxy_parts(object)? else {
7255 return Ok(None);
7256 };
7257 let key_value = self.key_value(key);
7258 let Some(result) = self.proxy_trap(
7259 &handler,
7260 "getOwnPropertyDescriptor",
7261 vec![Value::Object(target.clone()), key_value],
7262 )?
7263 else {
7264 // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
7265 // property table. Two things ride on that choice: a target that is itself a
7266 // proxy has to re-dispatch (its own table is empty, so reading it reported
7267 // `undefined` for every key, `Object.keys` then dropped them all), and an array's
7268 // indices and `length` live outside the table and need the ordinary synthesis.
7269 // `object_get_own_property` does both.
7270 return Ok(Some(self.object_get_own_property(&target, key)?));
7271 };
7272 // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
7273 // `ToPropertyDescriptor` runs, because that operation would box the primitive
7274 // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
7275 // empty descriptor instead of refusing.
7276 if !matches!(result, Value::Undefined | Value::Object(_)) {
7277 return Err(self.type_error(
7278 "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
7279 ));
7280 }
7281 let target_desc = self.object_get_own_property(&target, key)?;
7282 let extensible = self.object_is_extensible(&target)?;
7283 let Some(descriptor) = (match result {
7284 Value::Undefined => None,
7285 _ => Some(self.property_from_descriptor(&result)?),
7286 }) else {
7287 // Steps 12.a–12.d: reporting absent is allowed only when the target's own
7288 // descriptor is configurable *and* the target can still grow back.
7289 if let Some(target_desc) = &target_desc {
7290 if !target_desc.configurable {
7291 return Err(self.type_error(format!(
7292 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
7293 )));
7294 }
7295 if !extensible {
7296 return Err(self.type_error(format!(
7297 "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
7298 )));
7299 }
7300 }
7301 return Ok(Some(None));
7302 };
7303 // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
7304 // which is a stronger requirement than "the target is not contradicting it" — the
7305 // four branches below are each one test262 case.
7306 if !descriptor.configurable {
7307 let Some(target_desc) = &target_desc else {
7308 return Err(self.type_error(format!(
7309 "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
7310 )));
7311 };
7312 if target_desc.configurable {
7313 return Err(self.type_error(format!(
7314 "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
7315 )));
7316 }
7317 let target_is_data = !target_desc.is_accessor();
7318 let result_is_data = !descriptor.is_accessor();
7319 if result_is_data && !target_is_data {
7320 return Err(self.type_error(format!(
7321 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7322 )));
7323 }
7324 if target_is_data && !target_desc.writable {
7325 if !result_is_data {
7326 return Err(self.type_error(format!(
7327 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7328 )));
7329 }
7330 if descriptor.writable {
7331 return Err(self.type_error(format!(
7332 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7333 )));
7334 }
7335 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7336 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
7337 if !fixed_value.same_value(&reported) {
7338 return Err(self.type_error(format!(
7339 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
7340 )));
7341 }
7342 }
7343 // Step 16.d: a reported *read-only* data property needs a real read-only data
7344 // property behind it. Missing this let a trap bolt a frozen property onto a
7345 // writable target intent (`resultdesc-is-not-configurable-not-writable-
7346 // targetdesc-is-writable`).
7347 if result_is_data && !descriptor.writable {
7348 if !target_is_data {
7349 return Err(self.type_error(format!(
7350 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7351 )));
7352 }
7353 if target_desc.writable {
7354 return Err(self.type_error(format!(
7355 "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
7356 )));
7357 }
7358 }
7359 if descriptor.is_accessor() {
7360 // Step 16.e: a getter the target does not have may not be invented, and
7361 // vice versa.
7362 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7363 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7364 (Some(a), Some(b)) => a.same_value(b),
7365 _ => false,
7366 };
7367 if !same(&target_desc.getter, &descriptor.getter)
7368 || !same(&target_desc.setter, &descriptor.setter)
7369 {
7370 return Err(self.type_error(format!(
7371 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7372 )));
7373 }
7374 }
7375 }
7376 // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
7377 // where the target's own is locked. Without it a handler could advertise
7378 // `{value: 1, configurable: true}` for a non-configurable property, and a caller
7379 // that believed it would try to redefine something it cannot.
7380 if descriptor.configurable
7381 && let Some(target_desc) = &target_desc
7382 && !target_desc.configurable
7383 {
7384 return Err(self.type_error(format!(
7385 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
7386 )));
7387 }
7388 // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
7389 // through the trap either, however well-formed the descriptor is. This is the
7390 // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
7391 // the frozen target does not own.
7392 if !extensible {
7393 let Some(target_desc) = &target_desc else {
7394 return Err(self.type_error(format!(
7395 "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
7396 )));
7397 };
7398 if target_desc.is_accessor() == descriptor.is_accessor() {
7399 let target_is_data = !target_desc.is_accessor();
7400 let result_is_data = !descriptor.is_accessor();
7401 if target_is_data && !target_desc.writable && descriptor.writable {
7402 return Err(self.type_error(format!(
7403 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7404 )));
7405 }
7406 if !result_is_data && !target_is_data {
7407 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7408 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7409 (Some(a), Some(b)) => a.same_value(b),
7410 _ => false,
7411 };
7412 if !same(&target_desc.getter, &descriptor.getter)
7413 || !same(&target_desc.setter, &descriptor.setter)
7414 {
7415 return Err(self.type_error(format!(
7416 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7417 )));
7418 }
7419 }
7420 }
7421 }
7422 Ok(Some(Some(descriptor)))
7423 }
7424
7425 /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
7426 ///
7427 /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
7428 /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
7429 /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
7430 /// for a data property. `Property` cannot express "this field is absent", so the whole
7431 /// property path is skipped and the descriptor is assembled here field by field.
7432 ///
7433 /// `current` is the property the trap reported, used only to tell a data property from
7434 /// an accessor.
7435 pub fn proxy_seal_property(
7436 &mut self,
7437 object: &Gc<JsObject>,
7438 key: &PropertyKey,
7439 frozen: bool,
7440 current: &Property,
7441 ) -> JsResult<bool> {
7442 let Some((_target, handler)) = self.proxy_parts(object)? else {
7443 return Err(self.type_error("not a proxy"));
7444 };
7445 let descriptor = self.new_object(None);
7446 descriptor.define_data("configurable", Value::Bool(false));
7447 if frozen && !current.is_accessor() {
7448 descriptor.define_data("writable", Value::Bool(false));
7449 }
7450 let key_value = self.key_value(key);
7451 let target = object
7452 .proxy_state()
7453 .and_then(|state| state.borrow().target.clone());
7454 let Some(target) = target else {
7455 return Err(self.type_error("cannot use a proxy that has been revoked"));
7456 };
7457 let Some(result) = self.proxy_trap(
7458 &handler,
7459 "defineProperty",
7460 vec![Value::Object(target), key_value, Value::Object(descriptor)],
7461 )?
7462 else {
7463 // No trap means the definition belongs to the target; `false` is its answer.
7464 return Ok(false);
7465 };
7466 Ok(result.to_boolean())
7467 }
7468
7469 /// `[[DefineOwnProperty]]` on a proxy.
7470 fn proxy_define_property(
7471 &mut self,
7472 object: &Gc<JsObject>,
7473 key: &PropertyKey,
7474 property: Property,
7475 ) -> JsResult<Option<bool>> {
7476 let Some((target, handler)) = self.proxy_parts(object)? else {
7477 return Ok(None);
7478 };
7479 let key_value = self.key_value(key);
7480 let descriptor = self.descriptor_from_property(&property);
7481 let Some(result) = self.proxy_trap(
7482 &handler,
7483 "defineProperty",
7484 vec![Value::Object(target.clone()), key_value, descriptor],
7485 )?
7486 else {
7487 // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7488 // going" answer and `object_define_own_property` turns it into exactly that
7489 // forwarding — see the note there. (Reading it as "not a proxy" would define
7490 // the property on the proxy object itself, whose table is empty and which no
7491 // read ever consults.)
7492 return Ok(None);
7493 };
7494 if !result.to_boolean() {
7495 return Ok(Some(false));
7496 }
7497 // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7498 // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7499 // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7500 // and treating them alike made four cases pass a descriptor the target contradicts.
7501 let target_desc = self.object_get_own_property(&target, key)?;
7502 let extensible = self.object_is_extensible(&target)?;
7503 let named = property
7504 .descriptor_fields
7505 .unwrap_or(crate::object::DescriptorFields {
7506 value: false,
7507 writable: false,
7508 enumerable: false,
7509 configurable: false,
7510 get: false,
7511 set: false,
7512 });
7513 if named.configurable && !property.configurable {
7514 let Some(target_desc) = &target_desc else {
7515 return Err(self.type_error(format!(
7516 "proxy 'defineProperty' invented the non-configurable '{key}'"
7517 )));
7518 };
7519 if target_desc.configurable {
7520 return Err(self.type_error(format!(
7521 "proxy 'defineProperty' made '{key}' non-configurable"
7522 )));
7523 }
7524 }
7525 // Step 11's other half: reporting that a property was made *configurable* needs a
7526 // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7527 // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7528 // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7529 // target`).
7530 if named.configurable
7531 && property.configurable
7532 && let Some(target_desc) = &target_desc
7533 && !target_desc.configurable
7534 {
7535 return Err(
7536 self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7537 );
7538 }
7539 // Step 12: a property cannot be reported *made writable* when the target's copy is
7540 // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7541 // the trap is allowed to claim a definition it did not perform, as long as the
7542 // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7543 // legal, and refusing it broke the commonest way to seed a proxy).
7544 if named.writable
7545 && property.writable
7546 && let Some(target_desc) = &target_desc
7547 && !target_desc.writable
7548 {
7549 return Err(self.type_error(format!(
7550 "proxy 'defineProperty' made the read-only '{key}' writable"
7551 )));
7552 }
7553 // Step 13: making a property read-only needs an existing read-only property.
7554 if named.writable
7555 && !property.writable
7556 && let Some(target_desc) = &target_desc
7557 && !target_desc.is_accessor()
7558 && target_desc.writable
7559 {
7560 return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7561 }
7562 // Step 14: a non-writable, non-configurable property's value is fixed.
7563 if named.value
7564 && let Some(target_desc) = &target_desc
7565 && !target_desc.is_accessor()
7566 && !target_desc.writable
7567 && !target_desc.configurable
7568 {
7569 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7570 let reported = property.value.clone().unwrap_or(Value::Undefined);
7571 if !fixed_value.same_value(&reported) {
7572 return Err(self.type_error(format!(
7573 "proxy 'defineProperty' changed the value of '{key}'"
7574 )));
7575 }
7576 }
7577 // Step 15: a non-extensible target cannot grow.
7578 if target_desc.is_none() && !extensible {
7579 return Err(self.type_error(format!(
7580 "proxy 'defineProperty' added '{key}' to a non-extensible target"
7581 )));
7582 }
7583 Ok(Some(true))
7584 }
7585
7586 /// `[[GetPrototypeOf]]` on a proxy.
7587 fn proxy_get_prototype_of(
7588 &mut self,
7589 object: &Gc<JsObject>,
7590 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7591 let Some((target, handler)) = self.proxy_parts(object)? else {
7592 return Ok(None);
7593 };
7594 let Some(result) = self.proxy_trap(
7595 &handler,
7596 "getPrototypeOf",
7597 vec![Value::Object(target.clone())],
7598 )?
7599 else {
7600 // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7601 // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7602 // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7603 // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7604 // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7605 return Ok(Some(self.object_prototype_of(&target)?));
7606 };
7607 let proto = match &result {
7608 Value::Null => None,
7609 Value::Object(proto) => Some(proto.clone()),
7610 _ => {
7611 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7612 }
7613 };
7614 if !self.object_is_extensible(&target)? {
7615 let actual = self.object_prototype_of(&target)?;
7616 if !same_proto(proto.as_ref(), actual.as_ref()) {
7617 return Err(self.type_error(
7618 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7619 ));
7620 }
7621 }
7622 Ok(Some(proto))
7623 }
7624
7625 /// `[[SetPrototypeOf]]` on a proxy.
7626 fn proxy_set_prototype_of(
7627 &mut self,
7628 object: &Gc<JsObject>,
7629 proto: Option<Gc<JsObject>>,
7630 ) -> JsResult<Option<bool>> {
7631 let Some((target, handler)) = self.proxy_parts(object)? else {
7632 return Ok(None);
7633 };
7634 let proto_value = match &proto {
7635 Some(proto) => Value::Object(proto.clone()),
7636 None => Value::Null,
7637 };
7638 let Some(result) = self.proxy_trap(
7639 &handler,
7640 "setPrototypeOf",
7641 vec![Value::Object(target.clone()), proto_value],
7642 )?
7643 else {
7644 // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7645 // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7646 // its stored prototype overwritten behind its back.
7647 return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7648 };
7649 if result.to_boolean()
7650 && !self.object_is_extensible(&target)?
7651 && !same_proto(
7652 Some(&proto).and_then(|p| p.clone()).as_ref(),
7653 self.object_prototype_of(&target)?.as_ref(),
7654 )
7655 {
7656 return Err(self.type_error(
7657 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7658 ));
7659 }
7660 Ok(Some(result.to_boolean()))
7661 }
7662
7663 /// `[[IsExtensible]]` on a proxy.
7664 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7665 let Some((target, handler)) = self.proxy_parts(object)? else {
7666 return Ok(None);
7667 };
7668 let Some(result) = self.proxy_trap(
7669 &handler,
7670 "isExtensible",
7671 vec![Value::Object(target.clone())],
7672 )?
7673 else {
7674 return Ok(Some(self.object_is_extensible(&target)?));
7675 };
7676 // The answer is not the proxy's to invent: it must agree with the target, or a
7677 // script could learn `false` while the target keeps accepting new properties.
7678 if result.to_boolean() != self.object_is_extensible(&target)? {
7679 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7680 }
7681 Ok(Some(result.to_boolean()))
7682 }
7683
7684 /// `[[PreventExtensions]]` on a proxy.
7685 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7686 let Some((target, handler)) = self.proxy_parts(object)? else {
7687 return Ok(None);
7688 };
7689 let Some(result) = self.proxy_trap(
7690 &handler,
7691 "preventExtensions",
7692 vec![Value::Object(target.clone())],
7693 )?
7694 else {
7695 // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7696 // its answer can be `false`.
7697 return Ok(Some(self.object_prevent_extensions(&target)?));
7698 };
7699 if result.to_boolean() && self.object_is_extensible(&target)? {
7700 return Err(self.type_error(
7701 "proxy 'preventExtensions' reported success but the target is still extensible",
7702 ));
7703 }
7704 Ok(Some(result.to_boolean()))
7705 }
7706
7707 /// `[[Call]]` on a proxy, through the `apply` trap.
7708 fn proxy_apply(
7709 &mut self,
7710 object: &Gc<JsObject>,
7711 this: Value,
7712 args: Vec<Value>,
7713 ) -> JsResult<Option<Value>> {
7714 let Some((target, handler)) = self.proxy_parts(object)? else {
7715 return Ok(None);
7716 };
7717 // The trap gets the arguments as one array, which is the shape the spec passes
7718 // and the shape `apply` traps are written against (`args[0]` is the first one).
7719 let arguments = self.new_array(args.clone());
7720 let this_for_trap = this.clone();
7721 let Some(result) = self.proxy_trap(
7722 &handler,
7723 "apply",
7724 vec![
7725 Value::Object(target.clone()),
7726 this_for_trap,
7727 Value::Object(arguments),
7728 ],
7729 )?
7730 else {
7731 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7732 };
7733 Ok(Some(result))
7734 }
7735
7736 /// `[[Construct]]` on a proxy, through the `construct` trap.
7737 fn proxy_construct(
7738 &mut self,
7739 object: &Gc<JsObject>,
7740 args: Vec<Value>,
7741 new_target: &Value,
7742 ) -> JsResult<Option<Value>> {
7743 let Some((target, handler)) = self.proxy_parts(object)? else {
7744 return Ok(None);
7745 };
7746 if !target.is_callable() {
7747 return Err(self.type_error("proxy target is not a constructor"));
7748 }
7749 let arguments = self.new_array(args.clone());
7750 let Some(result) = self.proxy_trap(
7751 &handler,
7752 "construct",
7753 vec![
7754 Value::Object(target.clone()),
7755 Value::Object(arguments),
7756 new_target.clone(),
7757 ],
7758 )?
7759 else {
7760 return Ok(Some(self.construct(
7761 Value::Object(target),
7762 new_target.clone(),
7763 args,
7764 )?));
7765 };
7766 if !matches!(result, Value::Object(_)) {
7767 return Err(self.type_error("proxy 'construct' must return an object"));
7768 }
7769 Ok(Some(result))
7770 }
7771
7772 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7773 pub(crate) fn has_own_or_inherited(
7774 &mut self,
7775 object: &Gc<JsObject>,
7776 key: &PropertyKey,
7777 ) -> JsResult<bool> {
7778 // The object itself first: it may be a proxy, and then the answer is its trap's.
7779 if let Some(answer) = self.proxy_has(object, key)? {
7780 return Ok(answer);
7781 }
7782 // An integer-indexed exotic object answers a canonical numeric index from
7783 // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7784 // prototype chain. That is observable twice: a view the buffer has been resized
7785 // away from has no indices, so `2 in view` is `false` even when
7786 // `Object.getPrototypeOf(view)[2]` exists (what
7787 // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7788 // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7789 // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7790 // goes through here, which is why the same rule is repeated in `has_property_key`
7791 // rather than living only there.
7792 if object.typed_array_parts().is_some()
7793 && let Some(numeric) = canonical_numeric_index(key)
7794 {
7795 return Ok(typed_array_index_is_valid(object, numeric));
7796 }
7797 // A host class answers `in` for its own keys, which may live nowhere in a property
7798 // table — `"x" in point` is true because the class says so, not because a property
7799 // exists.
7800 if let Some(exotic) = object.exotic()
7801 && let Some(answer) = exotic.has_property(self, object, key)?
7802 {
7803 return Ok(answer);
7804 }
7805 // `has_own` rather than `own_property_key`: an array's elements and its derived
7806 // `length` are invisible to the property table, and `Array.prototype` is an array.
7807 // A host class's `get_own_property` counts too, because the reference's
7808 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7809 // lives — a class with only `get_own_property` answers `in` through it.
7810 if self.exotic_has_own(object, key)? {
7811 return Ok(true);
7812 }
7813 // A hole is *not* the end of the search: the chain may still have the key, which
7814 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7815 for ancestor in object.chain() {
7816 // A proxy further up the chain answers for itself.
7817 if let Some(answer) = self.proxy_has(&ancestor, key)? {
7818 return Ok(answer);
7819 }
7820 // Same for a host class: a prototype may be one, and `in` reaches it.
7821 if let Some(exotic) = ancestor.exotic()
7822 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7823 {
7824 return Ok(answer);
7825 }
7826 if self.exotic_has_own(&ancestor, key)? {
7827 return Ok(true);
7828 }
7829 }
7830 Ok(false)
7831 }
7832
7833 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7834 /// trap included.
7835 ///
7836 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7837 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7838 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7839 if let Some(exotic) = object.exotic()
7840 && let Some(answer) = exotic.get_own_property(self, object, key)?
7841 {
7842 return Ok(answer.is_some());
7843 }
7844 Ok(has_own(object, key))
7845 }
7846
7847 /// `CreateListFromArrayLike`, optionally restricted to property keys.
7848 ///
7849 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7850 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7851 /// `TypeError` instead of a property named `"1.5"`.
7852 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7853 let object = self.object_from(value)?;
7854 let length = self
7855 .get_property(&object, "length")?
7856 .map(|value| value.to_number())
7857 .unwrap_or(0.0);
7858 if !length.is_finite() || length < 0.0 {
7859 return Err(self.type_error("invalid array-like length"));
7860 }
7861 let length = length as usize;
7862 let mut items = Vec::with_capacity(length.min(1024));
7863 for index in 0..length {
7864 let item = self
7865 .get_property(&object, &index.to_string())?
7866 .unwrap_or(Value::Undefined);
7867 if keys_only && matches!(&item, Value::Symbol(_)) {
7868 items.push(item);
7869 continue;
7870 }
7871 if keys_only && !matches!(&item, Value::String(_)) {
7872 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7873 }
7874 items.push(item);
7875 }
7876 Ok(items)
7877 }
7878
7879 /// A `Property` from the descriptor object a trap returned.
7880 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7881 let object = self.object_from(value)?;
7882 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7883 interp.get_property(&object, name)
7884 };
7885 let getter = field(self, "get")?;
7886 let setter = field(self, "set")?;
7887 let accessor = getter.is_some() || setter.is_some();
7888 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7889 Ok(interp
7890 .get_property(&object, name)?
7891 .is_some_and(|value| value.to_boolean()))
7892 };
7893 let enumerable = boolean(self, "enumerable")?;
7894 let configurable = boolean(self, "configurable")?;
7895 if accessor {
7896 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7897 return Err(
7898 self.type_error("a descriptor cannot be both a data property and an accessor")
7899 );
7900 }
7901 Ok(Property {
7902 getter: getter.or(Some(Value::Undefined)),
7903 setter: setter.or(Some(Value::Undefined)),
7904 enumerable,
7905 configurable,
7906 writable: false,
7907 value: None,
7908 descriptor_fields: None,
7909 })
7910 } else {
7911 Ok(Property {
7912 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7913 writable: boolean(self, "writable")?,
7914 enumerable,
7915 configurable,
7916 getter: None,
7917 setter: None,
7918 descriptor_fields: None,
7919 })
7920 }
7921 }
7922
7923 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7924 fn descriptor_from_property(&mut self, property: &Property) -> Value {
7925 let object = self.new_object(None);
7926 // A partial descriptor names only some fields, and the trap must see exactly those:
7927 // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7928 // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7929 // case, where every field is present.
7930 let fields = property.descriptor_fields;
7931 let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7932 fields.is_none_or(|fields| field(&fields))
7933 };
7934 if property.is_accessor() {
7935 let getter = property.getter.clone().unwrap_or(Value::Undefined);
7936 let setter = property.setter.clone().unwrap_or(Value::Undefined);
7937 object.define_data("get", getter);
7938 object.define_data("set", setter);
7939 } else {
7940 if names(|fields| fields.value) {
7941 let value = property.value.clone().unwrap_or(Value::Undefined);
7942 object.define_data("value", value);
7943 }
7944 if names(|fields| fields.writable) {
7945 object.define_data("writable", Value::Bool(property.writable));
7946 }
7947 }
7948 if names(|fields| fields.enumerable) {
7949 object.define_data("enumerable", Value::Bool(property.enumerable));
7950 }
7951 if names(|fields| fields.configurable) {
7952 object.define_data("configurable", Value::Bool(property.configurable));
7953 }
7954 Value::Object(object)
7955 }
7956
7957 // -- calling ------------------------------------------------------------
7958
7959 /// Call `callee` with `this` and `args`.
7960 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
7961 let Value::Object(function) = &callee else {
7962 // `typeof x === "function"` is not enough to make `x()` legal: only a
7963 // callable object is. `null` and `undefined` need no special wording
7964 // here — their `ToString` already reads the way the reference's does.
7965 let what = format!("{} is not a function", callee.to_js_string());
7966 return Err(Signal::Throw(self.make_error("TypeError", &what)));
7967 };
7968 // A proxy of a function is called through its `apply` trap. It has no
7969 // `ObjectKind::Function` of its own, so this has to come before the dispatch
7970 // below, and a proxy of a non-function has nothing to forward to.
7971 if function.proxy_state().is_some() {
7972 return match self.proxy_apply(function, this, args)? {
7973 Some(result) => Ok(result),
7974 None => Err(Signal::Throw(
7975 self.make_error("TypeError", "proxy target is not callable"),
7976 )),
7977 };
7978 }
7979 let callable = function.with(|data| match &data.kind {
7980 ObjectKind::Function(callable) => match callable {
7981 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
7982 // The `Rc` is cloned out so the borrow of this object's data is released
7983 // before the closure runs: the closure may touch the same object.
7984 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
7985 Callable::Bound {
7986 target,
7987 this,
7988 args: leading,
7989 } => Some(NativeCall::Bound {
7990 target: target.clone(),
7991 this: this.clone(),
7992 leading: leading.clone(),
7993 }),
7994 Callable::Bytecode { code, env } => {
7995 Some(NativeCall::Bytecode(code.clone(), env.clone()))
7996 }
7997 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
7998 Callable::PromiseResolve(promise) => {
7999 Some(NativeCall::PromiseResolve(promise.clone()))
8000 }
8001 Callable::PromiseReject(promise) => {
8002 Some(NativeCall::PromiseReject(promise.clone()))
8003 }
8004 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
8005 state: state.clone(),
8006 }),
8007 Callable::ThenShim {
8008 handler,
8009 resolve,
8010 reject,
8011 fulfilled,
8012 } => Some(NativeCall::ThenShim {
8013 handler: handler.clone(),
8014 resolve: resolve.clone(),
8015 reject: reject.clone(),
8016 fulfilled: *fulfilled,
8017 }),
8018 Callable::AwaitResume {
8019 coroutine,
8020 promise,
8021 kind,
8022 } => Some(NativeCall::AwaitResume {
8023 coroutine: coroutine.clone(),
8024 promise: promise.clone(),
8025 kind: *kind,
8026 }),
8027 Callable::CombinatorSettle {
8028 state,
8029 index,
8030 fulfilled,
8031 } => Some(NativeCall::CombinatorSettle {
8032 state: state.clone(),
8033 index: *index,
8034 fulfilled: *fulfilled,
8035 }),
8036 Callable::FinallyShim {
8037 callback,
8038 fulfilled,
8039 constructor,
8040 } => Some(NativeCall::FinallyShim {
8041 callback: callback.clone(),
8042 fulfilled: *fulfilled,
8043 constructor: constructor.clone(),
8044 }),
8045 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
8046 Callable::CompletedReturn {
8047 generator,
8048 promise,
8049 rejected,
8050 } => Some(NativeCall::CompletedReturn {
8051 generator: generator.clone(),
8052 promise: promise.clone(),
8053 rejected: *rejected,
8054 }),
8055 Callable::YieldResult {
8056 generator,
8057 promise,
8058 done,
8059 } => Some(NativeCall::YieldResult {
8060 generator: generator.clone(),
8061 promise: promise.clone(),
8062 done: *done,
8063 }),
8064 Callable::DisposeStep {
8065 remaining,
8066 promise,
8067 error,
8068 rejected,
8069 awaited,
8070 needs_await,
8071 } => Some(NativeCall::DisposeStep {
8072 remaining: remaining.clone(),
8073 promise: promise.clone(),
8074 error: error.clone(),
8075 rejected: *rejected,
8076 awaited: *awaited,
8077 needs_await: *needs_await,
8078 }),
8079 Callable::GeneratorResume {
8080 generator,
8081 promise,
8082 kind,
8083 } => Some(NativeCall::GeneratorResume {
8084 generator: generator.clone(),
8085 promise: promise.clone(),
8086 kind: *kind,
8087 }),
8088 Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
8089 Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
8090 Callable::SettlePromise {
8091 promise,
8092 value,
8093 rejected,
8094 } => Some(NativeCall::SettlePromise {
8095 promise: promise.clone(),
8096 value: value.clone(),
8097 rejected: *rejected,
8098 }),
8099 },
8100 _ => None,
8101 });
8102 match callable {
8103 Some(NativeCall::Host(func)) => {
8104 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
8105 // function by name rather than stopping at the caller.
8106 let frame_less = function
8107 .own_property("_frame_less")
8108 .and_then(|property| property.value)
8109 .is_some_and(|value| value.to_boolean());
8110 let outer = if frame_less {
8111 None
8112 } else {
8113 self.native_frames
8114 .push((function.clone(), self.frames.len()));
8115 Some(self.current_native.replace(function.clone()))
8116 };
8117 // Same frame bookkeeping as a `Native`, plus `new.target`: a host
8118 // constructor reads it through `current_new_target` because it is handed
8119 // `undefined` for `this`. Taking the parked value here is what stops a
8120 // *plain* call made from inside a constructor body from seeing the
8121 // enclosing `new.target`.
8122 let parked = self.pending_new_target.take();
8123 let result = {
8124 let outer_new_target = std::mem::replace(
8125 &mut self.active_new_target,
8126 parked.unwrap_or(Value::Undefined),
8127 );
8128 let result = {
8129 let mut body = func.borrow_mut();
8130 body(self, this, &args)
8131 };
8132 self.active_new_target = outer_new_target;
8133 result
8134 };
8135 if !frame_less {
8136 self.native_frames.pop();
8137 self.current_native = outer.flatten();
8138 }
8139 result
8140 }
8141 Some(NativeCall::Native(func)) => {
8142 // A function marked `_frame_less` is one the reference implements
8143 // without a call frame — `eval` is the only one so far.
8144 let frame_less = function
8145 .own_property("_frame_less")
8146 .and_then(|property| property.value)
8147 .is_some_and(|value| value.to_boolean());
8148 let outer = if frame_less {
8149 None
8150 } else {
8151 self.native_frames
8152 .push((function.clone(), self.frames.len()));
8153 Some(self.current_native.replace(function.clone()))
8154 };
8155 let parked = self.pending_new_target.take();
8156 let outer_new_target = std::mem::replace(
8157 &mut self.active_new_target,
8158 parked.unwrap_or(Value::Undefined),
8159 );
8160 let result = func(self, this, &args);
8161 self.active_new_target = outer_new_target;
8162 if !frame_less {
8163 self.native_frames.pop();
8164 self.current_native = outer.flatten();
8165 }
8166 result
8167 }
8168 Some(NativeCall::Revoker(slots)) => {
8169 // Idempotent: revoking twice answers `undefined` again rather than
8170 // complaining, which is what the spec says and what a `finally` block
8171 // relies on.
8172 let mut state = slots.borrow_mut();
8173 state.target = None;
8174 state.handler = None;
8175 Ok(Value::Undefined)
8176 }
8177 Some(NativeCall::PromiseResolve(promise)) => {
8178 // §27.2.1.3.2 step 4: `[[AlreadyResolved]]` is checked **before** anything
8179 // else, so a resolve after a reject does nothing *and* a resolve after a
8180 // resolve-with-thenable does nothing — the promise is still `Pending` then,
8181 // because the adoption is a queued job.
8182 let value = args.first().cloned().unwrap_or(Value::Undefined);
8183 if !self.claim_resolution(&promise) {
8184 return Ok(Value::Undefined);
8185 }
8186 // §27.2.1.3.2 steps 7–8: a self-resolution is **rejected, not thrown** —
8187 // the resolve function performs `RejectPromise` and returns `undefined`.
8188 // (`ResolvePromise` itself throws as well, so the engine's own callers see
8189 // it; only this wrapper swallows it.)
8190 let _ = self.resolve_promise_with(&promise, value);
8191 Ok(Value::Undefined)
8192 }
8193 Some(NativeCall::PromiseReject(promise)) => {
8194 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8195 // §27.2.1.3.1 step 3: same one-shot record as `resolve`.
8196 if !self.claim_resolution(&promise) {
8197 return Ok(Value::Undefined);
8198 }
8199 self.reject_promise(&promise, reason);
8200 Ok(Value::Undefined)
8201 }
8202 Some(NativeCall::ThenShim {
8203 handler,
8204 resolve,
8205 reject,
8206 fulfilled,
8207 }) => {
8208 // `PerformPromiseThen` with a capability: run the handler, then settle
8209 // through the capability's own pair. A throw from the handler is the
8210 // rejection, and a throw from the capability's `resolve` is not caught —
8211 // exactly the spec's `?`.
8212 let value = args.first().cloned().unwrap_or(Value::Undefined);
8213 match handler {
8214 Some(handler) => {
8215 match self.call_value(handler, Value::Undefined, vec![value]) {
8216 Ok(result) => {
8217 self.call_value(resolve, Value::Undefined, vec![result])?;
8218 }
8219 Err(Signal::Throw(reason)) => {
8220 self.call_value(reject, Value::Undefined, vec![reason])?;
8221 }
8222 Err(signal) => return Err(signal),
8223 }
8224 }
8225 None => {
8226 let handler = if fulfilled { resolve } else { reject };
8227 self.call_value(handler, Value::Undefined, vec![value])?;
8228 }
8229 }
8230 Ok(Value::Undefined)
8231 }
8232 Some(NativeCall::CapabilityExecutor { state }) => {
8233 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
8234 // slot holds a value yet. The test is on the *values*, not on a call count —
8235 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
8236 // called-twice`'s first case does exactly that), while a second call after a
8237 // real pair is the `TypeError`.
8238 let defined = |name: &str| {
8239 state
8240 .own_property(name)
8241 .and_then(|property| property.value)
8242 .is_some_and(|value| !matches!(value, Value::Undefined))
8243 };
8244 if defined("resolve") || defined("reject") {
8245 return Err(self.type_error("promise capability executor called twice"));
8246 }
8247 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
8248 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
8249 state.define_data("resolve", resolve);
8250 state.define_data("reject", reject);
8251 Ok(Value::Undefined)
8252 }
8253 Some(NativeCall::CombinatorSettle {
8254 state,
8255 index,
8256 fulfilled,
8257 }) => {
8258 let value = args.first().cloned().unwrap_or(Value::Undefined);
8259 self.settle_combinator(&state, index, fulfilled, value)?;
8260 Ok(Value::Undefined)
8261 }
8262 Some(NativeCall::AwaitResume {
8263 coroutine,
8264 promise,
8265 kind,
8266 }) => {
8267 // Resume *inline*, in the reaction that delivered the value. Deferring it
8268 // by another job inserts a tick between every `await` and its
8269 // continuation, which reorders `await` against unrelated `then` chains —
8270 // `f().then(g)` then runs before `f`'s own next statement.
8271 self.drive_async(
8272 &coroutine,
8273 &promise,
8274 kind,
8275 args.first().cloned().unwrap_or(Value::Undefined),
8276 )
8277 .map(|()| Value::Undefined)
8278 }
8279 Some(NativeCall::ReturnValue(value)) => Ok(value),
8280 Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
8281 Some(NativeCall::FinallyShim {
8282 callback,
8283 fulfilled,
8284 constructor,
8285 }) => {
8286 // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
8287 // own value is discarded; what the caller sees is the *original* outcome,
8288 // delayed until `PromiseResolve(C, result)` has settled.
8289 //
8290 // Two details are observable and both have a test:
8291 //
8292 // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
8293 // `PerformPromiseThen`. A callback that returns a thenable with its own
8294 // `then` must have that `then` called
8295 // (`resolved-observable-then-calls` counts it);
8296 // * only the **fulfil** handler is supplied. A returned promise that
8297 // *rejects* rejects the whole `finally`, rather than having its failure
8298 // swallowed and the original value passed through.
8299 let original = args.first().cloned().unwrap_or(Value::Undefined);
8300 let result = match &callback {
8301 Some(callback) => {
8302 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
8303 }
8304 None => Value::Undefined,
8305 };
8306 // `PromiseResolve(C, result)`: a `result` that is already a promise of this
8307 // constructor is reused rather than rewrapped, which is what keeps
8308 // `mp1.finally(() => mp2)` from gaining a layer.
8309 let resolved = self.promise_resolve_for(&constructor, result)?;
8310 let thunk = if fulfilled {
8311 Callable::ReturnValue(original)
8312 } else {
8313 Callable::ThrowValue(original)
8314 };
8315 // `length: 0` and `name: ""`, and **not** a constructor — the three things
8316 // `resolved-observable-then-calls-argument` reads off the thunk while it has
8317 // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
8318 // function with no `length` at all.
8319 let thunk = self.builtin_function("", 0, thunk);
8320 let then = self.read_field(&resolved, "then")?;
8321 if !matches!(&then, Value::Object(object) if object.is_callable()) {
8322 return Err(self.type_error("then is not a function"));
8323 }
8324 self.call_value(then, resolved, vec![Value::Object(thunk)])
8325 }
8326 Some(NativeCall::DisposeStep {
8327 remaining,
8328 promise,
8329 error,
8330 rejected,
8331 awaited,
8332 needs_await,
8333 }) => {
8334 let error = if rejected {
8335 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8336 self.merge_dispose_error(reason, error)
8337 } else {
8338 error
8339 };
8340 self.dispose_step(&remaining, &promise, error, awaited, needs_await)?;
8341 Ok(Value::Undefined)
8342 }
8343 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
8344 Some(NativeCall::CompletedReturn {
8345 generator,
8346 promise,
8347 rejected,
8348 }) => {
8349 let value = args.first().cloned().unwrap_or(Value::Undefined);
8350 let outcome = if rejected {
8351 AsyncOutcome::Error(value)
8352 } else {
8353 AsyncOutcome::Value(self.iterator_result(value, true)?)
8354 };
8355 self.settle_async_request(&generator, &promise, outcome)?;
8356 Ok(Value::Undefined)
8357 }
8358 Some(NativeCall::YieldResult {
8359 generator,
8360 promise,
8361 done,
8362 }) => {
8363 let value = args.first().cloned().unwrap_or(Value::Undefined);
8364 let result = self.iterator_result(value, done)?;
8365 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
8366 Ok(Value::Undefined)
8367 }
8368 Some(NativeCall::GeneratorResume {
8369 generator,
8370 promise,
8371 kind,
8372 }) => {
8373 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
8374 // tick and reorders the generator against other chains.
8375 self.step_async_generator(
8376 &generator,
8377 &promise,
8378 kind,
8379 args.first().cloned().unwrap_or(Value::Undefined),
8380 )
8381 .map(|()| Value::Undefined)
8382 }
8383 Some(NativeCall::SettlePromise {
8384 promise,
8385 value,
8386 rejected,
8387 }) => {
8388 if rejected {
8389 self.reject_promise(&promise, value);
8390 } else {
8391 self.fulfill_promise(&promise, value);
8392 }
8393 Ok(Value::Undefined)
8394 }
8395 Some(NativeCall::Bound {
8396 target,
8397 this: bound_this,
8398 leading,
8399 }) => {
8400 let mut all = leading;
8401 all.extend(args);
8402 self.call_value(target, bound_this, all)
8403 }
8404 Some(NativeCall::Bytecode(code, env)) => {
8405 if code.code.kind.is_generator() {
8406 return self.new_generator(callee, this, args);
8407 }
8408 if code.code.kind.is_async() {
8409 // Same coroutine machinery as a generator; the difference is only in
8410 // what the completion does — see `new_async_function`.
8411 return self.new_async_function(callee, this, args);
8412 }
8413 self.execute(code, env, this, args, callee)
8414 }
8415 None => Err(Signal::Throw(
8416 self.make_error("TypeError", "not a function"),
8417 )),
8418 }
8419 }
8420
8421 /// Give a freshly built function its own `prototype` object.
8422 ///
8423 /// Every function that can be used with `new` carries one, and its
8424 /// `constructor` points back at the function — a reference cycle, which is
8425 /// exactly what the collector's cycle pass exists to reclaim.
8426 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
8427 self.install_function_prototype_with(function, None);
8428 }
8429
8430 /// [`Interp::install_function_prototype`] with an explicit parent for the new
8431 /// `prototype` object.
8432 ///
8433 /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
8434 /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
8435 /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
8436 /// `None` means `%Object.prototype%`.
8437 fn install_function_prototype_with(
8438 &mut self,
8439 function: &Gc<JsObject>,
8440 parent: Option<Gc<JsObject>>,
8441 ) {
8442 let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
8443 let prototype = self.new_object(Some(parent));
8444 let constructor = Value::Object(function.clone());
8445 prototype.define(
8446 "constructor",
8447 Property::with_attributes(constructor, true, false),
8448 );
8449 let value = Value::Object(prototype);
8450 function.define("prototype", Property::prototype_of(value, true));
8451 }
8452
8453 /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
8454 /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
8455 /// [`Interp::install_function_prototype`] — **no `constructor` property**.
8456 ///
8457 /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
8458 /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
8459 /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
8460 /// is `[]` there.
8461 fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
8462 let prototype = self.new_object(Some(parent));
8463 let value = Value::Object(prototype);
8464 function.define("prototype", Property::prototype_of(value, true));
8465 }
8466
8467 /// The `[[Prototype]]` a newly created generator object gets:
8468 /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
8469 ///
8470 /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
8471 /// function's `prototype` is writable, so a script can replace it with anything, and
8472 /// only an *object* is consulted.
8473 fn generator_instance_proto(
8474 &mut self,
8475 function: &Gc<JsObject>,
8476 default: Gc<JsObject>,
8477 ) -> JsResult<Gc<JsObject>> {
8478 match self.get_property(function, "prototype")? {
8479 Some(Value::Object(prototype)) => Ok(prototype),
8480 _ => Ok(default),
8481 }
8482 }
8483
8484 /// A getter or setter that reads or writes the reference cell behind a mapped
8485 /// `arguments` index.
8486 ///
8487 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
8488 /// count — which is what the collector treats as "a reference from outside the
8489 /// heap". The closure therefore keeps the cell alive for exactly as long as the
8490 /// accessor is reachable, which is the same lifetime the arguments object has.
8491 ///
8492 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8493 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8494 /// parameter value and the arguments object reaches the closure, never the other
8495 /// way round. Nothing the collector has to see is hidden.
8496 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8497 let name = if is_setter { "set" } else { "get" };
8498 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8499 if is_setter {
8500 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8501 Ok(Value::Undefined)
8502 } else {
8503 Ok(cell.get())
8504 }
8505 };
8506 self.new_host_function(name, 1, Box::new(func))
8507 }
8508
8509 /// The object `special_object` builds.
8510 ///
8511 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8512 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8513 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8514 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8515 /// write through `arguments` does not reach the parameter.
8516 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8517 match magic {
8518 0 | 1 => {
8519 let args = self.frame().passed().to_vec();
8520 let proto = self.realm.object_proto.clone();
8521 let object = self.new_object(Some(proto));
8522 // The marker `Object.prototype.toString` needs: an arguments object is an
8523 // ordinary object apart from reporting `[object Arguments]`, and that has
8524 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8525 // show up ahead of them in a key listing anyway — it is non-enumerable.
8526 self.internal_set(&object, "_class", self.string("Arguments"));
8527 // `length` is writable and configurable but neither enumerable nor a
8528 // plain data property: `Object.keys(arguments)` lists the indices only,
8529 // which is how `{...arguments}` copies them without the length.
8530 object.define(
8531 "length",
8532 Property::with_attributes(Value::Int(args.len() as i32), true, false),
8533 );
8534 // `magic == 1` is sloppy mode, where each index is *mapped* to the
8535 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8536 // change `a`, and assigning `a` has to change `arguments[0]`.
8537 //
8538 // The shared storage is the parameter's reference cell. The compiler
8539 // gives every parameter of such a function one (see
8540 // `provide_body_arguments`), and the cell outlives the frame, so this
8541 // keeps working after the arguments object escapes.
8542 //
8543 // The index becomes an accessor rather than a data property. A mapped
8544 // index reports as a plain writable/enumerable data property through
8545 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8546 // the getter/setter pair is only the plumbing underneath.
8547 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8548 let frame = self.frame();
8549 frame
8550 .code
8551 .arg_cell
8552 .iter()
8553 .map(|cell| {
8554 (*cell >= 0)
8555 .then(|| frame.cells.get(*cell as usize).cloned())
8556 .flatten()
8557 })
8558 .collect()
8559 } else {
8560 Vec::new()
8561 };
8562 // Tell the object which indices are mapped, so
8563 // `Object.getOwnPropertyDescriptor` can report them as the data
8564 // properties the spec describes instead of the accessors that
8565 // implement the aliasing.
8566 if magic == 1 {
8567 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8568 for cell in &mapped_cells {
8569 table.push(cell.clone());
8570 }
8571 object.set_mapped_arguments(table);
8572 }
8573 for (index, value) in args.into_iter().enumerate() {
8574 match mapped_cells.get(index).cloned().flatten() {
8575 Some(cell) => {
8576 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8577 let setter = self.new_mapped_arguments_accessor(cell, true);
8578 object.define(
8579 &index.to_string(),
8580 Property::accessor_with(
8581 Some(Value::Object(getter)),
8582 Some(Value::Object(setter)),
8583 true,
8584 ),
8585 );
8586 }
8587 None => object.define_data(&index.to_string(), value),
8588 }
8589 }
8590 // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8591 // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8592 // non-enumerable and non-configurable. It is not a nicety — it is the only
8593 // documented way to reach `%ThrowTypeError%`:
8594 //
8595 // Object.getOwnPropertyDescriptor(function(){"use strict";
8596 // return arguments;}(), "callee").get
8597 //
8598 // and the whole `ThrowTypeError/` directory is written against that
8599 // expression. Without it 13 cases failed with `cannot read property 'get'
8600 // of undefined`, which reads like a test harness bug rather than a missing
8601 // accessor.
8602 //
8603 // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8604 // writable data property holding the function being called, and
8605 // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8606 // `hasOwnProperty("callee")` hold there.
8607 if magic == 1 {
8608 let callee = self.frame().callee.clone();
8609 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8610 object.define("callee", Property::with_attributes(callee, true, false));
8611 } else if let Some(thrower) = self.realm.throw_type_error.clone()
8612 && object.own_property("callee").is_none()
8613 {
8614 object.define(
8615 "callee",
8616 Property {
8617 getter: Some(Value::Object(thrower.clone())),
8618 setter: Some(Value::Object(thrower)),
8619 enumerable: false,
8620 configurable: false,
8621 ..Property::default()
8622 },
8623 );
8624 }
8625 // An arguments object is iterable: `[...arguments]` and
8626 // `for (const a of arguments)` both work, through the *array* iterator
8627 // because the object is array-like. Without this the whole spread form
8628 // reported "not iterable".
8629 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8630 let values = self
8631 .realm
8632 .array_proto
8633 .own_property("values")
8634 .and_then(|property| property.value);
8635 if let Some(values) = values {
8636 object.define_key(
8637 &iterator_key,
8638 Property::with_attributes(values, true, false),
8639 );
8640 }
8641 Ok(Value::Object(object))
8642 }
8643 // `this.active_func`: the constructor `super()` resolves against.
8644 //
8645 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8646 // own, so it inherits this from the function it was written in along with `this`
8647 // — and that is a lexical relationship, not a stack one: an arrow that escaped
8648 // the constructor and is called back later (`iter.return = () => super()`) has
8649 // the constructor nowhere on the stack. The compiler therefore reads it out of
8650 // a closure variable of the enclosing function, exactly as the reference does
8651 // with its `this_active_func` local.
8652 2 => Ok(self
8653 .current_callee()
8654 .map_or(Value::Undefined, Value::Object)),
8655 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8656 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8657 // its own either, so the lookup walks out to the nearest non-arrow frame for
8658 // the same reason as `this.active_func` above — without that, `super()` inside
8659 // an arrow passed `undefined` as the new target and the parent constructor was
8660 // then rejected for being invoked without `new`.
8661 3 => Ok(self
8662 .eval_new_target
8663 .clone()
8664 .unwrap_or_else(|| self.frame().new_target.clone())),
8665 // `[[HomeObject]]` of the function being run: what `super` is relative to.
8666 // An arrow has none of its own, so the lookup walks out to the enclosing
8667 // method — which is why `super` works inside an arrow inside a method.
8668 4 => Ok(self
8669 .frames
8670 .iter()
8671 .rev()
8672 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8673 .map_or(Value::Undefined, Value::Object)),
8674 // `import.meta`: the innermost module body's meta object. Outside a module
8675 // the compiler never emits this, so an empty fallback is unreachable rather
8676 // than permissive.
8677 6 => {
8678 let name = self.module_stack.last().cloned();
8679 let meta = name
8680 .and_then(|name| self.modules.get(&name).cloned())
8681 .and_then(|module| module.with(|r| r.import_meta.clone()));
8682 Ok(meta.map_or(Value::Undefined, Value::Object))
8683 }
8684 other => Err(Signal::Throw(self.make_error(
8685 "InternalError",
8686 &format!("special_object {other} is not implemented yet"),
8687 ))),
8688 }
8689 }
8690
8691 /// `[[HomeObject]]` of the innermost function that has one, if any.
8692 ///
8693 /// An arrow has none, so the search walks out to the enclosing method — the same
8694 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8695 /// inside a method.
8696 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8697 self.frames
8698 .iter()
8699 .rev()
8700 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8701 }
8702
8703 /// The dispose method a `using` declaration should snapshot, or an error.
8704 ///
8705 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8706 /// is what makes a resource that only knows the synchronous protocol usable in both
8707 /// forms.
8708 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8709 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8710 if value.is_nullish() {
8711 return Ok(Value::Undefined);
8712 }
8713 let Some(object) = value.as_object() else {
8714 return Err(self.type_error("not an object"));
8715 };
8716 let mut method = if await_form {
8717 let found = self.get_property_key(
8718 object,
8719 &self.realm.well_known_key(WellKnown::AsyncDisposable),
8720 )?;
8721 match found {
8722 Some(found) if !found.is_nullish() => Some(found),
8723 _ => self
8724 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8725 }
8726 } else {
8727 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8728 };
8729 let Some(found) = method.take() else {
8730 return Err(self.type_error("value is not disposable"));
8731 };
8732 if found.is_nullish() {
8733 return Err(self.type_error("value is not disposable"));
8734 }
8735 let callable = found.as_object().is_some_and(|object| object.is_callable());
8736 if !callable {
8737 return Err(self.type_error("dispose method is not a function"));
8738 }
8739 Ok(found)
8740 }
8741
8742 /// Call one resource's disposer, folding a failure into `error_state`.
8743 ///
8744 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8745 /// because a captured `using` binding lives in its reference cell and the local slot is
8746 /// stale — a closure over the resource is legal and must not change what is disposed.
8747 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8748 let value = self.get_loc(slot);
8749 let method = self.get_loc(slot + 1);
8750 // A resource that was never initialised — its declaration threw — or that is
8751 // `null`/`undefined` has nothing to dispose.
8752 if value.is_nullish() || matches!(value, Value::Uninitialized) {
8753 return Ok(error_state);
8754 }
8755 if matches!(method, Value::Undefined | Value::Uninitialized) {
8756 return Ok(error_state);
8757 }
8758 match self.call_value(method, value, Vec::new()) {
8759 Ok(_) => Ok(error_state),
8760 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8761 Err(other) => Err(other),
8762 }
8763 }
8764
8765 /// Combine a disposal failure with whatever was already going wrong.
8766 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8767 if matches!(error_state, Value::Uninitialized) {
8768 return new_error;
8769 }
8770 self.new_suppressed_error(new_error, error_state)
8771 }
8772
8773 /// A `SuppressedError` instance built straight from its prototype.
8774 ///
8775 /// Not through the constructor: a script that rewrites
8776 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8777 /// error wrapping.
8778 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8779 let proto = self
8780 .realm
8781 .suppressed_error_proto
8782 .clone()
8783 .unwrap_or_else(|| self.realm.error_proto.clone());
8784 let object = self.new_object(Some(proto));
8785 object.define("error", Property::with_attributes(error, true, true));
8786 object.define(
8787 "suppressed",
8788 Property::with_attributes(suppressed, true, true),
8789 );
8790 object.define(
8791 "message",
8792 Property::with_attributes(self.string("SuppressedError"), true, true),
8793 );
8794 self.internal_set(&object, "_class", self.string("Error"));
8795 self.add_stack(&object);
8796 Value::Object(object)
8797 }
8798
8799 /// Call `callee`, or push its frame and let the main loop run it.
8800 ///
8801 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8802 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8803 /// continues, so `function f(){ return f() }` costs heap and stops at
8804 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8805 /// is entered directly, and natives do not re-enter JavaScript in this
8806 /// milestone.
8807 ///
8808 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8809 /// because the returning frame will.
8810 /// The elements of an array-like value, as a call argument list.
8811 ///
8812 /// `apply` accepts any array-like, not only a real array: the reference reads
8813 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8814 /// `ToIndex(value)`: `ToIntegerOrInfinity` and then the `2^53 - 1` bound.
8815 ///
8816 /// Used by the paths that take a *length* from script data — the typed-array
8817 /// constructor's array-like argument, `Array.from`. `ToIntegerOrInfinity` runs
8818 /// `ToNumber`, so a Symbol is a `TypeError`; a value past `2^53 - 1` is a
8819 /// `RangeError` rather than a silently clamped count.
8820 pub fn to_index(&mut self, value: &Value) -> JsResult<usize> {
8821 let number = self.to_js_number(value)?;
8822 if number.is_nan() {
8823 return Ok(0);
8824 }
8825 let number = number.trunc();
8826 if number < 0.0 || number > 9_007_199_254_740_991.0 {
8827 return Err(self.range_error("invalid length"));
8828 }
8829 Ok(number as usize)
8830 }
8831
8832 /// `CreateListFromArrayLike(value)`: the elements of an array-like, for `apply` and the
8833 /// other callers that take an argument list from script data.
8834 ///
8835 /// The length is `ToLength`, which *clamps* rather than refusing — the typed-array
8836 /// constructor and `Array.from` need `ToIndex` instead (see
8837 /// [`Interp::to_index`]), which is why they do not go through here.
8838 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8839 let Some(object) = value.as_object().cloned() else {
8840 if value.is_nullish() {
8841 // `f.apply(this, null)` passes no arguments at all.
8842 return Ok(Vec::new());
8843 }
8844 return Err(self.type_error("createListFromArrayLike called on non-object"));
8845 };
8846 let length = match self.get_property(&object, "length")? {
8847 Some(length) => length.to_number(),
8848 None => 0.0,
8849 };
8850 if !length.is_finite() || length <= 0.0 {
8851 return Ok(Vec::new());
8852 }
8853 let length = (length as usize).min(1_000_000);
8854 let mut args = Vec::with_capacity(length);
8855 for index in 0..length {
8856 let element = self.get_property(&object, &index.to_string())?;
8857 args.push(element.unwrap_or(Value::Undefined));
8858 }
8859 Ok(args)
8860 }
8861
8862 /// Turn a call to a generator function into a generator object.
8863 ///
8864 /// The frame is built exactly as an ordinary call would build it, then detached and
8865 /// stored in the generator before any body instruction runs — which is what makes
8866 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8867 /// is `initial_yield`, the first instruction of every suspending body.
8868 pub fn new_generator(
8869 &mut self,
8870 function: Value,
8871 this: Value,
8872 args: Vec<Value>,
8873 ) -> JsResult<Value> {
8874 let Some(object) = function.as_object().cloned() else {
8875 return Err(self.type_error("not a generator function"));
8876 };
8877 let Some((code, env)) = bytecode_of(&object) else {
8878 return Err(self.type_error("not a generator function"));
8879 };
8880 let is_async = code.code.kind.is_async();
8881 self.push_frame(code, env, this, args, function)?;
8882 let frame = self.frames.pop().expect("push_frame just pushed it");
8883 // A fresh generator is *suspended at start*: the body has not run, so a
8884 // `return`/`throw` on it finishes without executing anything.
8885 let mut state = GeneratorState {
8886 frame: Some(frame),
8887 phase: GeneratorPhase::SuspendedStart,
8888 parked_on_await: false,
8889 parked_on_yield_star: false,
8890 requests: std::collections::VecDeque::new(),
8891 async_busy: false,
8892 is_async,
8893 };
8894 // Run to the first suspension. For a generator that is `initial_yield`, so no
8895 // body code runs; for a malformed body it would be the first `yield`.
8896 // An `async function*` answers an async generator: same coroutine, but its
8897 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8898 let default_proto = if is_async {
8899 self.realm
8900 .async_generator_proto
8901 .clone()
8902 .unwrap_or_else(|| self.realm.generator_proto.clone())
8903 } else {
8904 self.realm.generator_proto.clone()
8905 };
8906 // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
8907 // `prototype` object when it is one, the intrinsic otherwise. Every generator having
8908 // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
8909 // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
8910 let proto = self.generator_instance_proto(&object, default_proto)?;
8911 let generator = self.new_object(Some(proto));
8912 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8913 Ok(_) => {}
8914 Err(error) => return Err(error),
8915 }
8916 generator.with_mut(|data| {
8917 data.kind = ObjectKind::Generator(Box::new(state));
8918 });
8919 Ok(Value::Object(generator))
8920 }
8921
8922 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8923 ///
8924 /// Returns the `{value, done}` object itself rather than the pair, because a
8925 /// `yield*` suspension already has one — the inner iterator's own result — and the
8926 /// protocol says to hand that straight through rather than nest it.
8927 /// Advance a generator and report *why* it parked.
8928 ///
8929 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
8930 /// "hand this value to the caller" — but an async generator does: an `await` has to
8931 /// settle before it can answer, while a `yield` is the answer.
8932 fn resume_generator_detailed(
8933 &mut self,
8934 generator: &Gc<JsObject>,
8935 kind: ResumeKind,
8936 value: Value,
8937 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8938 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
8939 ObjectKind::Generator(state) => {
8940 let is_async = state.is_async;
8941 Some(std::mem::replace(
8942 state.as_mut(),
8943 GeneratorState {
8944 frame: None,
8945 phase: GeneratorPhase::Executing,
8946 parked_on_await: false,
8947 parked_on_yield_star: false,
8948 requests: std::collections::VecDeque::new(),
8949 // **Busy while the body runs**, so a `next()` called *from inside*
8950 // the body queues instead of being served. §27.6.3.7
8951 // `AsyncGeneratorResumeNext` returns immediately for the state
8952 // "executing", and the request is served once the body suspends;
8953 // with `false` here the re-entrant call found an empty frame and
8954 // rejected (`request-queue-order-state-executing`).
8955 async_busy: is_async,
8956 is_async,
8957 },
8958 ))
8959 }
8960 _ => None,
8961 }) else {
8962 return Err(self.type_error("not a generator"));
8963 };
8964 let result = self.step_generator(&mut state, kind, value);
8965 // Requests queued *while* the body ran live on the placeholder, because the real
8966 // state is out of the object for the duration. They have to be folded back in
8967 // before the placeholder is overwritten, or the promise they carry never settles.
8968 let queued = generator.with_mut(|data| match &mut data.kind {
8969 ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
8970 _ => std::collections::VecDeque::new(),
8971 });
8972 state.requests.extend(queued);
8973 generator.with_mut(|data| {
8974 data.kind = ObjectKind::Generator(Box::new(state));
8975 });
8976 result
8977 }
8978
8979 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8980 ///
8981 /// Returns the `{value, done}` object itself rather than the pair, because a
8982 /// `yield*` suspension already has one — the inner iterator's own result — and the
8983 /// protocol says to hand that straight through rather than nest it.
8984 pub fn resume_generator(
8985 &mut self,
8986 generator: &Gc<JsObject>,
8987 kind: ResumeKind,
8988 value: Value,
8989 ) -> JsResult<Value> {
8990 let (value, done, ready, _reason) =
8991 self.resume_generator_detailed(generator, kind, value)?;
8992 if ready {
8993 return Ok(value);
8994 }
8995 self.iterator_result(value, done)
8996 }
8997
8998 /// `next`/`return`/`throw` on an async generator, which answer a promise.
8999 ///
9000 /// The body is the same coroutine a sync generator runs; what changes is that an
9001 /// `await` inside it has to settle before the method can answer, so the step is
9002 /// driven off the job queue rather than returning inline.
9003 pub fn resume_async_generator(
9004 &mut self,
9005 generator: &Gc<JsObject>,
9006 kind: ResumeKind,
9007 value: Value,
9008 ) -> JsResult<Value> {
9009 let promise = self.new_promise();
9010 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
9011 // that order, and the second value must reach the *second* `yield`.
9012 let idle = generator.with_mut(|data| match &mut data.kind {
9013 ObjectKind::Generator(state) => {
9014 state.requests.push_back(AsyncRequest {
9015 kind,
9016 value,
9017 promise: promise.clone(),
9018 });
9019 !state.async_busy
9020 }
9021 _ => false,
9022 });
9023 if idle {
9024 self.next_async_request(generator)?;
9025 }
9026 Ok(Value::Object(promise))
9027 }
9028
9029 /// Serve the front queued request, if the generator is free to run one.
9030 ///
9031 /// A finished generator answers from the queue without running anything:
9032 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
9033 /// first, and `throw(e)` rejects.
9034 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
9035 enum Front {
9036 Idle,
9037 Run(ResumeKind, Value, Gc<JsObject>),
9038 Finished(ResumeKind, Value, Gc<JsObject>),
9039 }
9040 let front = generator.with_mut(|data| match &mut data.kind {
9041 ObjectKind::Generator(state) => {
9042 let Some(request) = state.requests.front() else {
9043 return Front::Idle;
9044 };
9045 // Busy means a request is still in flight — awaiting inside the body, not
9046 // finished. Serving another now would interleave two requests.
9047 if state.async_busy && state.phase != GeneratorPhase::Completed {
9048 return Front::Idle;
9049 }
9050 let kind = request.kind;
9051 let value = request.value.clone();
9052 let promise = request.promise.clone();
9053 state.async_busy = true;
9054 if state.phase == GeneratorPhase::Completed {
9055 Front::Finished(kind, value, promise)
9056 } else {
9057 Front::Run(kind, value, promise)
9058 }
9059 }
9060 _ => Front::Idle,
9061 });
9062 match front {
9063 Front::Idle => Ok(()),
9064 Front::Run(kind, value, promise) => {
9065 self.step_async_generator(generator, &promise, kind, value)
9066 }
9067 Front::Finished(kind, value, promise) => match kind {
9068 ResumeKind::Throw => {
9069 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
9070 }
9071 ResumeKind::Next | ResumeKind::Start => {
9072 let result = self.iterator_result(Value::Undefined, true)?;
9073 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
9074 }
9075 ResumeKind::Return => {
9076 // `js_async_generator_completed_return`: the value is awaited before it
9077 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
9078 // finished generator answers `1`, not a promise.
9079 let resolved = match self.promise_resolve_intrinsic(value) {
9080 Ok(resolved) => resolved,
9081 Err(Signal::Throw(reason)) => {
9082 return self.settle_async_request(
9083 generator,
9084 &promise,
9085 AsyncOutcome::Error(reason),
9086 );
9087 }
9088 Err(other) => return Err(other),
9089 };
9090 let done = JsObject::function(
9091 self.heap,
9092 Some(self.realm.function_proto.clone()),
9093 Callable::CompletedReturn {
9094 generator: generator.clone(),
9095 promise: promise.clone(),
9096 rejected: false,
9097 },
9098 );
9099 let failed = JsObject::function(
9100 self.heap,
9101 Some(self.realm.function_proto.clone()),
9102 Callable::CompletedReturn {
9103 generator: generator.clone(),
9104 promise: promise.clone(),
9105 rejected: true,
9106 },
9107 );
9108 let Value::Object(resolved) = resolved else {
9109 return self.settle_async_request(
9110 generator,
9111 &promise,
9112 AsyncOutcome::Error(Value::Undefined),
9113 );
9114 };
9115 self.perform_then(
9116 &resolved,
9117 Some(Value::Object(done)),
9118 Some(Value::Object(failed)),
9119 )?;
9120 Ok(())
9121 }
9122 },
9123 }
9124 }
9125
9126 /// Settle the front request and start the next one.
9127 ///
9128 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
9129 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
9130 /// generator would strand every later request.
9131 fn settle_async_request(
9132 &mut self,
9133 generator: &Gc<JsObject>,
9134 promise: &Gc<JsObject>,
9135 outcome: AsyncOutcome,
9136 ) -> JsResult<()> {
9137 let settled = generator.with_mut(|data| match &mut data.kind {
9138 ObjectKind::Generator(state) => {
9139 let front = state.requests.front();
9140 debug_assert!(
9141 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
9142 "a request settled outside its turn"
9143 );
9144 state.requests.pop_front();
9145 state.async_busy = false;
9146 true
9147 }
9148 _ => false,
9149 });
9150 if settled {
9151 match outcome {
9152 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
9153 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
9154 }
9155 }
9156 self.next_async_request(generator)
9157 }
9158
9159 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
9160 ///
9161 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
9162 /// disposer runs **synchronously** — the reference starts it before returning, which
9163 /// a test can observe by logging after the call — and the rest follow once their
9164 /// predecessor settles.
9165 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
9166 let promise = self.new_promise();
9167 // §24.4.3.6 `DisposeResources` step 1: `needsAwait` is true as soon as the stack holds
9168 // any resource at all, because every `await using` resource has the async-dispose
9169 // hint — including the null/undefined ones that have nothing to call. If none of them
9170 // turned out to be awaitable, step 4 still performs one `Await(undefined)`, which is
9171 // why `stack.use(null); stack.disposeAsync()` settles one microtask later rather than
9172 // in the tick it was called from (`disposeAsync/explicit-await-for-null`).
9173 let needs_await = !resources.is_empty();
9174 let mut pairs = Vec::with_capacity(resources.len());
9175 for (value, method) in resources {
9176 let pair = self.new_array(vec![value, method]);
9177 pairs.push(Value::Object(pair));
9178 }
9179 let remaining = self.new_array(pairs);
9180 self.dispose_step(
9181 &remaining,
9182 &promise,
9183 Value::Uninitialized,
9184 false,
9185 needs_await,
9186 )?;
9187 Ok(Value::Object(promise))
9188 }
9189
9190 /// One link of the `disposeAsync` chain.
9191 ///
9192 /// Loops while the disposers finish synchronously, and parks on the first thenable it
9193 /// meets — pushing itself back in as the continuation, with the accumulated error
9194 /// carried along so a later failure can still be folded into the `SuppressedError`.
9195 fn dispose_step(
9196 &mut self,
9197 remaining: &Gc<JsObject>,
9198 promise: &Gc<JsObject>,
9199 mut error: Value,
9200 awaited: bool,
9201 needs_await: bool,
9202 ) -> JsResult<()> {
9203 loop {
9204 let length = remaining.array_length().unwrap_or(0);
9205 if length == 0 {
9206 // Step 4: `needsAwait` true and `hasAwaited` false means one `Await(undefined)`
9207 // still has to happen. Re-entering this same step past an already-fulfilled
9208 // promise is exactly one tick, and it keeps the folding of `error` in one place.
9209 if needs_await && !awaited {
9210 let finished = self.new_array(Vec::new());
9211 let thunk = JsObject::function(
9212 self.heap,
9213 Some(self.realm.function_proto.clone()),
9214 Callable::DisposeStep {
9215 remaining: finished.clone(),
9216 promise: promise.clone(),
9217 error,
9218 rejected: false,
9219 awaited: true,
9220 needs_await: false,
9221 },
9222 );
9223 let tick = self.promise_resolve_value(Value::Undefined)?;
9224 if let Value::Object(tick) = tick {
9225 self.perform_then(
9226 &tick,
9227 Some(Value::Object(thunk.clone())),
9228 Some(Value::Object(thunk)),
9229 )?;
9230 }
9231 return Ok(());
9232 }
9233 if matches!(error, Value::Uninitialized) {
9234 self.fulfill_promise(promise, Value::Undefined);
9235 } else {
9236 self.reject_promise(promise, error);
9237 }
9238 return Ok(());
9239 }
9240 let Some(Value::Object(pair)) = remaining
9241 .array_get(length - 1)
9242 .filter(|v| !matches!(v, Value::Hole))
9243 else {
9244 remaining.array_truncate(self.heap, length - 1);
9245 continue;
9246 };
9247 remaining.array_truncate(self.heap, length - 1);
9248 let value = pair.array_get(0).unwrap_or(Value::Undefined);
9249 let Some(Value::Object(method)) = pair.array_get(1) else {
9250 continue;
9251 };
9252 if !method.is_callable() {
9253 continue;
9254 }
9255 match self.call_value(Value::Object(method), value, Vec::new()) {
9256 Ok(result) => {
9257 if !self.is_thenable(&result)? {
9258 // Finished synchronously; the next disposer is the next iteration.
9259 continue;
9260 }
9261 let awaited = match self.promise_resolve_value(result) {
9262 Ok(awaited) => awaited,
9263 Err(Signal::Throw(reason)) => {
9264 self.reject_promise(promise, reason);
9265 return Ok(());
9266 }
9267 Err(other) => return Err(other),
9268 };
9269 let Value::Object(awaited) = awaited else {
9270 continue;
9271 };
9272 let ok = JsObject::function(
9273 self.heap,
9274 Some(self.realm.function_proto.clone()),
9275 Callable::DisposeStep {
9276 remaining: remaining.clone(),
9277 promise: promise.clone(),
9278 error: error.clone(),
9279 rejected: false,
9280 awaited: true,
9281 needs_await,
9282 },
9283 );
9284 let failed = JsObject::function(
9285 self.heap,
9286 Some(self.realm.function_proto.clone()),
9287 Callable::DisposeStep {
9288 remaining: remaining.clone(),
9289 promise: promise.clone(),
9290 error,
9291 rejected: true,
9292 awaited: true,
9293 needs_await,
9294 },
9295 );
9296 self.perform_then(
9297 &awaited,
9298 Some(Value::Object(ok)),
9299 Some(Value::Object(failed)),
9300 )?;
9301 return Ok(());
9302 }
9303 Err(Signal::Throw(thrown)) => {
9304 error = self.merge_dispose_error(thrown, error);
9305 }
9306 Err(other) => return Err(other),
9307 }
9308 }
9309 }
9310
9311 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
9312 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
9313 let Value::Object(object) = value else {
9314 return Ok(false);
9315 };
9316 Ok(matches!(
9317 self.get_property(object, "then")?,
9318 Some(Value::Object(then)) if then.is_callable()
9319 ))
9320 }
9321
9322 /// One step of an async generator, settling `promise` with an `{value, done}` result.
9323 fn step_async_generator(
9324 &mut self,
9325 generator: &Gc<JsObject>,
9326 promise: &Gc<JsObject>,
9327 kind: ResumeKind,
9328 value: Value,
9329 ) -> JsResult<()> {
9330 // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
9331 // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
9332 // is abrupt — a `constructor` getter that throws — the generator is resumed with a
9333 // *throw* completion instead, so the body's own `try { yield } catch` sees it:
9334 // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
9335 // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
9336 // out of the same read, one as a rejection and one as a rethrow.
9337 //
9338 // Narrow on purpose: only a value that is *already a promise* is inspected, so
9339 // nothing changes for `return 1` and the extra read is a plain data-property
9340 // lookup on the intrinsic case.
9341 if kind == ResumeKind::Return
9342 && let Value::Object(object) = &value
9343 && self.promise_state(object).is_some()
9344 && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
9345 {
9346 return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
9347 }
9348 let stepped = self.resume_generator_detailed(generator, kind, value);
9349 let (value, done, ready, reason) = match stepped {
9350 Ok(stepped) => stepped,
9351 Err(Signal::Throw(reason)) => {
9352 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
9353 }
9354 Err(other) => return Err(other),
9355 };
9356 // Only an `await` has to wait before the method can answer.
9357 if !done && reason == Some(SuspendKind::Await) {
9358 let awaited = match self.promise_resolve_value(value) {
9359 Ok(awaited) => awaited,
9360 Err(Signal::Throw(reason)) => {
9361 return self.settle_async_request(
9362 generator,
9363 promise,
9364 AsyncOutcome::Error(reason),
9365 );
9366 }
9367 Err(other) => return Err(other),
9368 };
9369 let Value::Object(awaited) = awaited else {
9370 return Ok(());
9371 };
9372 let resumed = JsObject::function(
9373 self.heap,
9374 Some(self.realm.function_proto.clone()),
9375 Callable::GeneratorResume {
9376 generator: generator.clone(),
9377 promise: promise.clone(),
9378 kind: ResumeKind::Next,
9379 },
9380 );
9381 let raised = JsObject::function(
9382 self.heap,
9383 Some(self.realm.function_proto.clone()),
9384 Callable::GeneratorResume {
9385 generator: generator.clone(),
9386 promise: promise.clone(),
9387 kind: ResumeKind::Throw,
9388 },
9389 );
9390 self.perform_then(
9391 &awaited,
9392 Some(Value::Object(resumed)),
9393 Some(Value::Object(raised)),
9394 )?;
9395 return Ok(());
9396 }
9397 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
9398 // completes it — both arrive as the settled value rather than as the promise
9399 // object. A plain value skips the round trip, which is also what keeps `yield 1`
9400 // from costing an extra tick.
9401 let awaits_value = self.is_thenable(&value)?;
9402 if awaits_value {
9403 // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
9404 // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
9405 // value that merely gets `yield`ed is awaited by the body's own `Await`, where
9406 // no `PromiseResolve` appears, so that path keeps the shortcut.
9407 let awaited = match if done {
9408 self.promise_resolve_intrinsic(value)
9409 } else {
9410 self.promise_resolve_value(value)
9411 } {
9412 Ok(awaited) => awaited,
9413 Err(Signal::Throw(reason)) => {
9414 return self.settle_async_request(
9415 generator,
9416 promise,
9417 AsyncOutcome::Error(reason),
9418 );
9419 }
9420 Err(other) => return Err(other),
9421 };
9422 let Value::Object(awaited) = awaited else {
9423 return Ok(());
9424 };
9425 // A rejected yield throws *at the yield* inside the body, so the rejection
9426 // resumes the generator rather than the method's promise.
9427 let answer = JsObject::function(
9428 self.heap,
9429 Some(self.realm.function_proto.clone()),
9430 Callable::YieldResult {
9431 generator: generator.clone(),
9432 promise: promise.clone(),
9433 done,
9434 },
9435 );
9436 let raise = JsObject::function(
9437 self.heap,
9438 Some(self.realm.function_proto.clone()),
9439 Callable::GeneratorResume {
9440 generator: generator.clone(),
9441 promise: promise.clone(),
9442 kind: ResumeKind::Throw,
9443 },
9444 );
9445 self.perform_then(
9446 &awaited,
9447 Some(Value::Object(answer)),
9448 Some(Value::Object(raise)),
9449 )?;
9450 return Ok(());
9451 }
9452 let result = if ready {
9453 // `yield*` handed back the inner iterator's own result object.
9454 value
9455 } else {
9456 self.iterator_result(value, done)?
9457 };
9458 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
9459 }
9460
9461 /// The `{value, done}` object an iterator method answers with.
9462 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
9463 let result = self.new_object(Some(self.realm.object_proto.clone()));
9464 result.define_data("value", value);
9465 result.define_data("done", Value::Bool(done));
9466 Ok(Value::Object(result))
9467 }
9468
9469 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
9470 fn step_generator(
9471 &mut self,
9472 state: &mut GeneratorState,
9473 kind: ResumeKind,
9474 value: Value,
9475 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9476 match state.phase {
9477 GeneratorPhase::Executing => {
9478 return Err(self.type_error("cannot invoke a running generator"));
9479 }
9480 GeneratorPhase::Completed => {
9481 // A finished generator answers every resumption without running.
9482 return Ok(match kind {
9483 ResumeKind::Throw => return Err(Signal::Throw(value)),
9484 ResumeKind::Return => (value, true, false, None),
9485 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
9486 });
9487 }
9488 GeneratorPhase::SuspendedStart => {
9489 if kind != ResumeKind::Next && kind != ResumeKind::Start {
9490 // The body never started, so there is nothing to unwind or return
9491 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
9492 state.frame = None;
9493 state.phase = GeneratorPhase::Completed;
9494 return Ok(match kind {
9495 ResumeKind::Throw => return Err(Signal::Throw(value)),
9496 _ => (value, true, false, None),
9497 });
9498 }
9499 }
9500 GeneratorPhase::SuspendedYield => {}
9501 }
9502
9503 let Some(mut frame) = state.frame.take() else {
9504 return Ok((Value::Undefined, true, false, None));
9505 };
9506 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
9507 // number that says which method resumed it; the emitted `if_false` branches on
9508 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
9509 let mut raised = None;
9510 match kind {
9511 ResumeKind::Next | ResumeKind::Start => {
9512 if state.phase == GeneratorPhase::SuspendedYield {
9513 frame.stack.push(value);
9514 // An `await` resumes with its value alone; only a `yield` gets the
9515 // magic number that says which of `next`/`return` resumed it.
9516 if !state.parked_on_await {
9517 frame.stack.push(Value::Int(RESUME_NEXT));
9518 }
9519 }
9520 }
9521 ResumeKind::Return => {
9522 // A `return` on a not-yet-started generator is handled above, so this is
9523 // always a real resumption.
9524 frame.stack.push(value);
9525 frame.stack.push(Value::Int(RESUME_RETURN));
9526 }
9527 ResumeKind::Throw => {
9528 // At a `yield*` the exception is *data* for the delegation: the compiled
9529 // code resumes with the value and magic `2` and calls the inner iterator's
9530 // `throw`. Everywhere else it is raised at the suspension point, so the
9531 // body's own handler sees it.
9532 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
9533 frame.stack.push(value);
9534 frame.stack.push(Value::Int(RESUME_THROW));
9535 } else {
9536 raised = Some(value);
9537 }
9538 }
9539 }
9540 state.phase = GeneratorPhase::Executing;
9541
9542 let depth = self.frames.len();
9543 self.frames.push(frame);
9544 // A `throw` unwinds from where the frame parked, exactly as if the exception had
9545 // happened at the `yield`.
9546 if let Some(mut exception) = raised {
9547 if self.catch_here(&mut exception).is_none() {
9548 self.pop_frame();
9549 state.phase = GeneratorPhase::Completed;
9550 return Err(Signal::Throw(exception));
9551 }
9552 }
9553
9554 // Only the generator's *own* frame ends the generator. The body may call ordinary
9555 // functions, and those push frames of their own: a `Step::Return` from one of them
9556 // is a nested call finishing, not the generator completing. Miscounting that is
9557 // silent — the generator reports the callee's value as its own result and marks
9558 // itself done — so the depth comparison is load-bearing, not defensive.
9559 let own_frame = depth + 1;
9560 loop {
9561 match self.step() {
9562 Ok(Step::Continue) => {}
9563 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9564 let mut frame = self.frames.pop().expect("a frame is live");
9565 // `yield` left the value on the stack; `initial_yield` left nothing.
9566 let yielded = if reason == SuspendKind::Initial {
9567 Value::Undefined
9568 } else {
9569 frame.stack.pop().unwrap_or(Value::Undefined)
9570 };
9571 state.frame = Some(frame);
9572 state.parked_on_await = reason == SuspendKind::Await;
9573 state.parked_on_yield_star =
9574 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9575 state.phase = if reason == SuspendKind::Initial {
9576 GeneratorPhase::SuspendedStart
9577 } else {
9578 GeneratorPhase::SuspendedYield
9579 };
9580 // `yield*` hands the inner iterator's own result object straight
9581 // back, so the caller sees one `{value, done}` rather than a nested
9582 // one — which is why the third field says "already a result".
9583 return Ok((
9584 yielded,
9585 false,
9586 reason == SuspendKind::YieldStar,
9587 Some(reason),
9588 ));
9589 }
9590 Ok(Step::Suspend(_)) => {
9591 // A `yield` in a frame other than the generator's would mean a
9592 // generator body entered as an ordinary call, which
9593 // `call_or_push` prevents.
9594 self.unwind_to(depth);
9595 state.phase = GeneratorPhase::Completed;
9596 return Err(Signal::Throw(self.make_error(
9597 "InternalError",
9598 "a generator body ran as an ordinary call",
9599 )));
9600 }
9601 Ok(Step::Return(value)) => {
9602 self.pop_frame();
9603 if self.frames.len() > depth {
9604 // A nested call finished: hand the value back to its caller and
9605 // keep running the generator body.
9606 self.frames
9607 .last_mut()
9608 .expect("a caller is live")
9609 .stack
9610 .push(value);
9611 continue;
9612 }
9613 state.phase = GeneratorPhase::Completed;
9614 // The reference closes the generator's closure variables here; ours
9615 // live in cells the frame owned, which the drop below releases.
9616 return Ok((value, true, false, None));
9617 }
9618 Err(Signal::Throw(exception)) => {
9619 // The frame that threw gets the first chance to catch, exactly as in
9620 // the ordinary call loop; a frame above the generator's is popped and
9621 // the exception carries on down.
9622 let mut exception = exception;
9623 loop {
9624 if self.frames.len() <= depth {
9625 // The generator's own frame is gone, so nothing here caught it.
9626 state.phase = GeneratorPhase::Completed;
9627 return Err(Signal::Throw(exception));
9628 }
9629 if self.catch_here(&mut exception).is_some() {
9630 break;
9631 }
9632 self.pop_frame();
9633 }
9634 }
9635 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9636 }
9637 }
9638 }
9639
9640 /// Pop frames until `depth` are left, keeping their buffers.
9641 fn unwind_to(&mut self, depth: usize) {
9642 while self.frames.len() > depth {
9643 self.pop_frame();
9644 }
9645 }
9646 fn call_or_push(
9647 &mut self,
9648 callee: Value,
9649 this: Value,
9650 args: Vec<Value>,
9651 ) -> JsResult<Option<Value>> {
9652 if let Value::Object(function) = &callee
9653 && let Some((code, env)) = bytecode_of(function)
9654 {
9655 // Calling a generator function does not run anything: it captures the
9656 // arguments in a frame and hands back the generator object.
9657 if code.code.kind.is_generator() {
9658 return self.new_generator(callee, this, args).map(Some);
9659 }
9660 // An async function answers a promise and runs its body as a coroutine, so it
9661 // takes the same path as a plain call into it.
9662 if code.code.kind.is_async() {
9663 return self.new_async_function(callee, this, args).map(Some);
9664 }
9665 self.push_frame(code, env, this, args, callee)?;
9666 return Ok(None);
9667 }
9668 self.call_value(callee, this, args).map(Some)
9669 }
9670
9671 /// `new callee(args)`.
9672 ///
9673 /// A constructor differs from a plain call in three ways: it gets a fresh object
9674 /// as `this` whose prototype is the constructor's `prototype` property, its
9675 /// return value is *replaced* by that object unless it returns an object itself,
9676 /// and a native constructor is expected to initialise the object it is given
9677 /// rather than build one.
9678 pub fn construct(
9679 &mut self,
9680 callee: Value,
9681 new_target: Value,
9682 args: Vec<Value>,
9683 ) -> JsResult<Value> {
9684 // `new` on a bound function constructs its *target*, prepending the arguments
9685 // the bind fixed and ignoring the bound `this` — a bound function is a
9686 // constructor only when its target is one, and `new` always makes a fresh
9687 // object of the target's prototype rather than reusing the bound receiver.
9688 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9689 // ran the body with `this === null` and threw on `this.x = a`.
9690 let mut callee = callee;
9691 let mut new_target = new_target;
9692 let mut args = args;
9693 loop {
9694 let Some(object) = callee.as_object().cloned() else {
9695 return Err(Signal::Throw(
9696 self.make_error("TypeError", "not a constructor"),
9697 ));
9698 };
9699 // A proxy of a function constructs through its `construct` trap, and the
9700 // trap's answer is the result directly — no fresh object is made here.
9701 if object.proxy_state().is_some() {
9702 return match self.proxy_construct(&object, args, &new_target)? {
9703 Some(result) => Ok(result),
9704 None => Err(Signal::Throw(
9705 self.make_error("TypeError", "proxy target is not a constructor"),
9706 )),
9707 };
9708 }
9709 // A generator function has no `[[Construct]]`, and the reference names it in
9710 // the message: `new (function* G(){})()` reports "G is not a constructor".
9711 if object.with(|data| match &data.kind {
9712 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9713 code.code.kind.is_generator()
9714 }
9715 _ => false,
9716 }) {
9717 let name = object
9718 .own_property("name")
9719 .and_then(|property| property.value)
9720 .map(|value| value.to_js_string())
9721 .unwrap_or_default();
9722 return Err(Signal::Throw(
9723 self.make_error("TypeError", &format!("{name} is not a constructor")),
9724 ));
9725 }
9726 let bound = object.with(|data| match &data.kind {
9727 ObjectKind::Function(Callable::Bound {
9728 target,
9729 args: leading,
9730 ..
9731 }) => Some((target.clone(), leading.clone())),
9732 _ => None,
9733 });
9734 let Some((target, leading)) = bound else {
9735 // Not a bound function, so this object is the callee. §7.2.4
9736 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9737 // refusals above cover only the built-ins the reference also refuses by
9738 // name. Everything else — a method, an arrow, an async function — has no
9739 // `[[Construct]]` either, and answering "yes" here made
9740 // `new (Array.prototype.map)` build an object instead of throwing.
9741 if !object.is_constructor() {
9742 let name = object
9743 .own_property("name")
9744 .and_then(|property| property.value)
9745 .map(|value| value.to_js_string())
9746 .unwrap_or_default();
9747 return Err(Signal::Throw(
9748 self.make_error("TypeError", &format!("{name} is not a constructor")),
9749 ));
9750 }
9751 break;
9752 };
9753 let mut all = leading;
9754 all.extend(args);
9755 args = all;
9756 // A bound function that is its own `new.target` stands in for its target:
9757 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9758 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9759 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9760 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9761 _ => false,
9762 };
9763 if same_wrapper {
9764 new_target = target.clone();
9765 }
9766 callee = target;
9767 }
9768 let Value::Object(function) = &callee else {
9769 unreachable!("the loop above only breaks on an object");
9770 };
9771 // The fresh object's prototype comes from `new.target`, not from the callee: a
9772 // derived constructor reaches here through `super()`, and the instance must be a
9773 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9774 // an object inheriting `D.prototype` rather than `C.prototype`.
9775 let prototype_source = match new_target.as_object() {
9776 Some(target) => target.clone(),
9777 None => function.clone(),
9778 };
9779 // A native constructor builds its own instance, through `new_ctor_instance`, once it
9780 // has validated its arguments. Pre-building one here would read
9781 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9782 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9783 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9784 let is_native = function.native_creates_own_instance();
9785 let this = if is_native {
9786 Value::Undefined
9787 } else {
9788 let prototype = self.get_property(&prototype_source, "prototype")?;
9789 let prototype = match prototype {
9790 Some(Value::Object(proto)) => Some(proto),
9791 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
9792 // object, the answer is the realm's *intrinsic* prototype for this
9793 // constructor, not `%Object.prototype%`.
9794 _ => {
9795 // `GetPrototypeFromConstructor` step 4 is `GetFunctionRealm(constructor)`,
9796 // and that is a `TypeError` for a revoked proxy. Without it, `new
9797 // revokedProxy()` quietly produced an `%Object.prototype%` instance —
9798 // `base-ctor-revoked-proxy` revokes the proxy from inside its own `get`
9799 // trap, so it is already revoked when this fallback runs.
9800 if prototype_source.proxy_state().is_some() {
9801 self.proxy_parts(&prototype_source)?;
9802 }
9803 let fallback = self.get_property(function, "prototype")?;
9804 match fallback {
9805 Some(Value::Object(proto)) => Some(proto),
9806 _ => Some(self.realm.object_proto.clone()),
9807 }
9808 }
9809 };
9810 Value::Object(self.new_object(prototype))
9811 };
9812 // `new.target` inside the body is the constructor that was written, so a bound
9813 // function's target sees itself rather than the bound wrapper.
9814 //
9815 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
9816 // `?`, so assigning `None` after the call would be skipped and the failed
9817 // `new.target` would stay visible to every later native call. The symptom was a
9818 // native constructor refusing a plain call — `var s = Symbol(); new
9819 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
9820 // "FinalizationRegistry is not a constructor".
9821 let outer_new_target = self.pending_new_target.replace(new_target);
9822 let callee = callee.clone();
9823 let result = self.call_value(callee, this.clone(), args);
9824 self.pending_new_target = outer_new_target;
9825 let result = result?;
9826 // A constructor that returns an object overrides `this`; any other return value
9827 // (including `undefined`) is ignored — **except** in a derived constructor, where
9828 // §15.7.1 step 12 makes a non-object return a `TypeError`
9829 // (`Function/internals/Construct/derived-return-val`).
9830 let derived = function.with(|data| match &data.kind {
9831 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9832 code.code.is_derived_constructor
9833 }
9834 _ => false,
9835 });
9836 Ok(match result {
9837 Value::Object(_) => result,
9838 // A bare `return;` answers `undefined`, which is **legal** even in a derived
9839 // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
9840 Value::Undefined => this,
9841 _ if derived => {
9842 return Err(Signal::Throw(self.make_error(
9843 "TypeError",
9844 "derived constructor may only return an object or undefined",
9845 )));
9846 }
9847 _ => this,
9848 })
9849 }
9850
9851 /// `new.target` for the call currently being made.
9852 ///
9853 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9854 /// it as `this`), but a *host* constructor that builds its own instance is handed
9855 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9856 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9857 /// it here.
9858 ///
9859 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9860 /// receives for a plain call.
9861 pub fn current_new_target(&self) -> Value {
9862 self.active_new_target.clone()
9863 }
9864
9865 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9866 ///
9867 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9868 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9869 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9870 let constructor = self.realm.errors.get("AggregateError").cloned();
9871 let Some(constructor) = constructor else {
9872 return self.make_error("AggregateError", message);
9873 };
9874 let list = self.new_array(errors);
9875 match self.construct(
9876 Value::Object(constructor.clone()),
9877 Value::Object(constructor),
9878 vec![Value::Object(list), self.string(message)],
9879 ) {
9880 Ok(value) => value,
9881 // A user could have replaced `AggregateError` with something that throws; the
9882 // engine still owes the caller a rejection, so it falls back rather than
9883 // turning `Promise.any`'s rejection into a throw.
9884 Err(_) => self.make_error("AggregateError", message),
9885 }
9886 }
9887
9888 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9889 ///
9890 /// The error classes themselves arrive with the builtins milestone; what
9891 /// matters here is that the thrown value stringifies the way a script printing
9892 /// the caught value expects.
9893 ///
9894 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9895 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9896 /// rely on when they print a caught value.
9897 pub fn make_error(&self, name: &str, message: &str) -> Value {
9898 let proto = self
9899 .realm
9900 .errors
9901 .get(name)
9902 .map(|constructor| self.prototype_of(constructor))
9903 .unwrap_or_else(|| self.realm.error_proto.clone());
9904 let error = self.new_object(Some(proto));
9905 // `name` and `message` are own properties of the instance, which is what
9906 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9907 // `Error`.
9908 error.define(
9909 "name",
9910 Property::with_attributes(self.string(name), true, false),
9911 );
9912 error.define(
9913 "message",
9914 Property::with_attributes(self.string(message), true, false),
9915 );
9916 // The internal class, which is what tells a printer this is an error rather than a
9917 // plain object with `name` and `message` properties. The constructor path sets it
9918 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9919 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
9920 // literally `"Error"` in both places — the *name* is read from `name`, which is why
9921 // a `RangeError` still prints as `RangeError`.
9922 self.internal_set(&error, "_class", self.string("Error"));
9923 // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
9924 // answered `false` from `Error.isError` while a constructed one answered `true`,
9925 // because only the constructor set the slot. The reference answers `true` for both
9926 // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
9927 // accessor gated on this slot the omission stopped being cosmetic: `print_error`
9928 // tests `typeof stack === "string"` to decide on a trailing newline, so every
9929 // engine-thrown error lost its blank line.
9930 self.internal_set(&error, "_error_data", Value::Bool(true));
9931 // The trace is captured where the error is *made*, which is where the reference
9932 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
9933 // way out, so a caught engine error already has its stack even if the handler
9934 // never rethrows it.
9935 self.add_stack(&error);
9936 Value::Object(error)
9937 }
9938
9939 /// Give an error object its `stack` property, from the current frame stack.
9940 ///
9941 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
9942 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
9943 /// `stack` a script set, is not rewritten.
9944 pub fn add_stack(&self, object: &Gc<JsObject>) {
9945 self.add_stack_skipping(object, 0);
9946 }
9947
9948 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
9949 ///
9950 /// An `Error` constructor passes 1: the reference builds those traces with
9951 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
9952 /// constructor itself, while a `RangeError` raised inside `toISOString` does
9953 /// report `at toISOString (native)`.
9954 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
9955 if object.has_own("stack") {
9956 return;
9957 }
9958 // The trace is *captured* here but not installed as a property: `stack` is an
9959 // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
9960 // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
9961 // is kept in a hidden slot and the getter materialises it on first read.
9962 //
9963 // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
9964 // shows it — this is the same discipline `_error_data` and `_class` follow.
9965 let trace = self.stack_trace_skipping(skip);
9966 let text = self.string(trace);
9967 self.internal_set(object, "_stack_trace", text);
9968 }
9969
9970 /// The function object currently being called, if any.
9971 ///
9972 /// A native function is a bare `fn` pointer, so it cannot capture which class
9973 /// it belongs to; it reads that from the callee instead. This is also what a
9974 /// stack trace would use.
9975 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
9976 match &self.frames.last()?.callee {
9977 Value::Object(object) => Some(object.clone()),
9978 _ => None,
9979 }
9980 }
9981
9982 /// The `prototype` property of a constructor, falling back to
9983 /// `Object.prototype` for anything that is not shaped like one.
9984 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
9985 constructor
9986 .own_property("prototype")
9987 .and_then(|property| property.value)
9988 .and_then(|value| value.as_object().cloned())
9989 .unwrap_or_else(|| self.realm.object_proto.clone())
9990 }
9991
9992 /// Throw a `TypeError` carrying `message`.
9993 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
9994 Signal::Throw(self.make_error("TypeError", message.as_ref()))
9995 }
9996
9997 /// Throw a `RangeError` carrying `message`.
9998 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
9999 Signal::Throw(self.make_error("RangeError", message.as_ref()))
10000 }
10001
10002 /// A `ReferenceError`, as the value to throw.
10003 ///
10004 /// `throw` uses it for "called on a disposed stack": `DisposableStack.prototype.defer`
10005 /// and its siblings report a `ReferenceError` there, which is what
10006 /// `adopt|defer|move/throws-if-disposed` assert.
10007 pub fn reference_error(&self, message: impl AsRef<str>) -> Signal {
10008 Signal::Throw(self.make_error("ReferenceError", message.as_ref()))
10009 }
10010
10011 /// The `ReferenceError` a read of an uninitialised binding raises.
10012 /// The name of the binding `slot` refers to, for an error message.
10013 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
10014 match kind {
10015 VarSlot::Loc => self
10016 .frame()
10017 .code
10018 .code
10019 .vars
10020 .get(slot)
10021 .map(|v| v.name.clone()),
10022 VarSlot::Closure => self
10023 .frame()
10024 .code
10025 .code
10026 .closure_vars
10027 .get(slot)
10028 .map(|c| c.name.clone()),
10029 }
10030 .unwrap_or_default()
10031 }
10032
10033 /// Whether `slot` names a `const` binding, which rejects every store after its
10034 /// initialiser.
10035 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
10036 match kind {
10037 VarSlot::Loc => self
10038 .frame()
10039 .code
10040 .code
10041 .vars
10042 .get(slot)
10043 .is_some_and(|v| v.is_const),
10044 VarSlot::Closure => self
10045 .frame()
10046 .code
10047 .code
10048 .closure_vars
10049 .get(slot)
10050 .is_some_and(|c| c.is_const),
10051 }
10052 }
10053
10054 /// The `TypeError` a store to a `const` binding raises.
10055 ///
10056 /// `const` is enforced here rather than at compile time because the binding can be
10057 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
10058 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
10059 /// both halves of what "checked store" means: the dead zone is over, and the
10060 /// binding is writable.
10061 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
10062 let name = self.binding_name(slot, kind);
10063 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
10064 }
10065
10066 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
10067 let name = match kind {
10068 VarSlot::Loc => self
10069 .frame()
10070 .code
10071 .code
10072 .vars
10073 .get(slot)
10074 .map(|v| v.name.clone()),
10075 VarSlot::Closure => self
10076 .frame()
10077 .code
10078 .code
10079 .closure_vars
10080 .get(slot)
10081 .map(|c| c.name.clone()),
10082 }
10083 .unwrap_or_default();
10084 Signal::Throw(self.make_error(
10085 "ReferenceError",
10086 &format!("cannot access '{name}' before initialization"),
10087 ))
10088 }
10089
10090 fn throw_reference(&self, name: &str) -> Signal {
10091 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
10092 }
10093
10094 // -- the instruction loop -----------------------------------------------
10095
10096 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
10097 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
10098 // measured at 16% of a tight arithmetic loop's total time.
10099 #[inline(always)]
10100 fn step(&mut self) -> JsResult<Step> {
10101 // The instruction is already decoded (see [`crate::insn`]), so this is an index
10102 // and a `Copy` read rather than a table lookup plus a width switch. Only the
10103 // borrow lives across the boundary; nothing is cloned.
10104 // **One** borrow of the frame: fetch the record, then advance in the same scope.
10105 // The obvious version borrowed it three times (`last` to read, `last_mut` to
10106 // write, and once more inside the handler), and each is a bounds check plus an
10107 // `Option` unwrap — on the one path every instruction takes.
10108 let Some((insn, next)) = ({
10109 let frame = self
10110 .frames
10111 .last_mut()
10112 .expect("step() is only called with a live frame");
10113 // Past the last instruction is a normal return: the compiler ends a function
10114 // with `return`, and a jump to the end of a block lands here.
10115 let insn = frame.insns().get(frame.pc).copied();
10116 match insn {
10117 None => None,
10118 Some(insn) => {
10119 // A fused record stands for the next few instructions, so the next
10120 // `pc` is its width ahead — the instructions it replaces are never
10121 // dispatched. `at` is the byte offset a stack trace reports; it stays
10122 // an offset because the line table is keyed by bytes.
10123 frame.at = insn.offset as usize;
10124 frame.pc += insn.width();
10125 Some((insn, frame.pc))
10126 }
10127 }
10128 }) else {
10129 return Ok(Step::Return(Value::Undefined));
10130 };
10131 self.check_memory()?;
10132 self.check_interrupt()?;
10133 if insn.fused == crate::insn::Fused::None {
10134 self.execute_instruction(insn.op, insn.a, insn.b, next)
10135 } else {
10136 self.execute_fused(insn)
10137 }
10138 }
10139
10140 /// Run a fused instruction: several bytecode instructions in one dispatch.
10141 ///
10142 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
10143 /// it cannot throw and cannot allocate — and anything else falls back to the real
10144 /// instructions, in their real order, so an exception leaves the operand stack
10145 /// exactly as it would have been.
10146 #[inline]
10147 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
10148 use crate::insn::Fused;
10149 let slot = insn.a as usize;
10150 match insn.fused {
10151 // `x = k`: `push k; put_loc x`.
10152 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
10153 // `x += k`: `get_loc x; push k; add; put_loc x`.
10154 Fused::AddImmLoc => {
10155 let delta = insn.b as i32;
10156 match self.get_loc(slot) {
10157 Value::Int(left) => {
10158 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
10159 // that built two `Value`s, called a function, and matched on them
10160 // again to reach this same `checked_add`. It is the innermost
10161 // operation of every accumulator in every program.
10162 let answer = match left.checked_add(delta) {
10163 Some(sum) => Value::Int(sum),
10164 None => Value::Float(left as f64 + delta as f64),
10165 };
10166 self.put_loc(slot, answer);
10167 }
10168 other => {
10169 self.push(other);
10170 self.push(Value::Int(delta));
10171 self.binary_add()?;
10172 let value = self.pop();
10173 self.put_loc(slot, value);
10174 }
10175 }
10176 }
10177 // `x += "literal"` and `x += y`: the two shapes that can append in place.
10178 Fused::AddAtomLoc => {
10179 let text = self.atom_wtf8(insn.b as usize);
10180 let right = self.string_wtf8(text);
10181 self.add_into_loc(slot, right)?;
10182 }
10183 Fused::AddLocLoc => {
10184 let source = (insn.a & 0xFFFF) as usize;
10185 let target = (insn.a >> 16) as usize;
10186 let right = self.get_loc(source);
10187 self.add_into_loc(target, right)?;
10188 }
10189 Fused::AddArgLoc => {
10190 let source = (insn.a & 0xFFFF) as usize;
10191 let target = (insn.a >> 16) as usize;
10192 let right = self.get_arg(source);
10193 self.add_into_loc(target, right)?;
10194 }
10195 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
10196 Fused::PostIncLoc => match self.get_loc(slot) {
10197 Value::Int(left) => {
10198 let answer = match left.checked_add(1) {
10199 Some(sum) => Value::Int(sum),
10200 None => Value::Float(left as f64 + 1.0),
10201 };
10202 self.put_loc(slot, answer);
10203 }
10204 other => {
10205 self.push(other);
10206 let raw = self.pop();
10207 let (old, updated) = self.advance_numeric(raw, true)?;
10208 self.push(old);
10209 self.push(updated);
10210 let value = self.pop();
10211 self.put_loc(slot, value);
10212 self.pop();
10213 }
10214 },
10215 // `if (!(x < arg)) goto target`: a loop header.
10216 //
10217 // The comparison is computed rather than replayed on the operand stack. That
10218 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
10219 // that throws: the effects happen in the same order, and a handler truncates
10220 // the stack down to its marker, so the intermediate values are unobservable.
10221 Fused::LtLocArgJump => {
10222 let loc = (insn.a >> 16) as usize;
10223 let arg = (insn.a & 0xFFFF) as usize;
10224 let left = self.get_loc(loc);
10225 let right = self.get_arg(arg);
10226 let taken = match (&left, &right) {
10227 (Value::Int(left), Value::Int(right)) => !(left < right),
10228 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10229 };
10230 if taken {
10231 self.frame_mut().pc = insn.b as usize;
10232 }
10233 }
10234 // `i < k` in a loop header, where `k` is an integer literal.
10235 Fused::LtLocImmJump => {
10236 let left = self.get_loc(insn.a as usize);
10237 let right = Value::Int(insn.imm as i32);
10238 let taken = match &left {
10239 Value::Int(left) => !(*left < insn.imm as i32),
10240 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10241 };
10242 if taken {
10243 self.frame_mut().pc = insn.b as usize;
10244 }
10245 }
10246 Fused::None => unreachable!("only called for a fused record"),
10247 }
10248 Ok(Step::Continue)
10249 }
10250
10251 /// Run records that cannot call script, cannot throw and cannot change frames.
10252 ///
10253 /// Returns `Some(value)` when the function ran off the end of its instructions (a
10254 /// normal return), and `None` when it stopped in front of an instruction the slow path
10255 /// has to handle — `pc` is written back either way, so `step` resumes at the right
10256 /// place.
10257 ///
10258 /// **The invariant is the whole point.** Every arm here is restricted to work that
10259 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
10260 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
10261 /// that the memory limit has to see. An opcode whose operands turn out to need any of
10262 /// that **stops the loop** instead of trying, so the slow path gets the instruction
10263 /// untouched and with its operands still on the stack. That is why the fallback is a
10264 /// `break` and not a duplicated slow arm: a second implementation of the same
10265 /// semantics is how a wrong answer gets in with no test noticing.
10266 ///
10267 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
10268 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
10269 fn run_fast(&mut self) -> JsResult<Option<Value>> {
10270 use crate::insn::Fused;
10271 // The outer loop exists only so a `Call` can come back through here: once a
10272 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
10273 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
10274 // frame. Re-entering re-reads both from whichever frame is now on top. Every
10275 // other exit from the inner loop returns, so this costs one loop per call.
10276 'outer: loop {
10277 // One reference-count bump per *slow* instruction (a call, an allocation, a
10278 // property access), never one per instruction — that distinction is worth
10279 // two orders of magnitude and was measured as such.
10280 let (code, mut pc) = {
10281 let frame = self.frame();
10282 (frame.code.clone(), frame.pc)
10283 };
10284 let insns = &code.insns;
10285 loop {
10286 let Some(insn) = insns.get(pc).copied() else {
10287 self.frame_mut().pc = pc;
10288 return Ok(Some(Value::Undefined));
10289 };
10290 match insn.fused {
10291 // `x = k`
10292 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
10293 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
10294 // object — stops the loop so `binary_add` can decide.
10295 Fused::AddImmLoc => {
10296 let slot = insn.a as usize;
10297 let delta = insn.b as i32;
10298 let Value::Int(left) = self.get_loc(slot) else {
10299 return Ok(self.stop(pc));
10300 };
10301 let sum = match left.checked_add(delta) {
10302 Some(sum) => Value::Int(sum),
10303 None => Value::Float(left as f64 + delta as f64),
10304 };
10305 self.put_loc(slot, sum);
10306 }
10307 // `x += "literal"` / `x += y`: the operand is a string, so the append
10308 // either allocates one or grows one. Both are the slow path's business;
10309 // the fusion's job is only to make the *slot* the sole owner, which is what
10310 // `execute_fused` needs and what `get_loc` alone destroys.
10311 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
10312 return Ok(self.stop(pc));
10313 }
10314 // `x++` on an integer, old value dropped.
10315 Fused::PostIncLoc => {
10316 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
10317 // value is read in place and overwritten in place, so the reference
10318 // count it held is released by the same assignment that stores the
10319 // new one. `get_loc` plus `put_loc` did two borrows, two table
10320 // lookups and a clone, and this arm is the whole body of a counting
10321 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
10322 let slot = insn.a as usize;
10323 let frame = self.frames.last_mut().expect("a frame is live");
10324 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
10325 let target = if cell < 0 {
10326 frame.locals.get_mut(slot)
10327 } else {
10328 None
10329 };
10330 let Some(target) = target else {
10331 return Ok(self.stop(pc));
10332 };
10333 let Value::Int(left) = *target else {
10334 return Ok(self.stop(pc));
10335 };
10336 *target = match left.checked_add(1) {
10337 Some(sum) => Value::Int(sum),
10338 None => Value::Float(left as f64 + 1.0),
10339 };
10340 }
10341 // A loop header, `if (!(x < arg)) goto target`, with both sides already
10342 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
10343 // bound stayed small integers.
10344 Fused::LtLocArgJump => {
10345 let loc = (insn.a >> 16) as usize;
10346 let arg = (insn.a & 0xFFFF) as usize;
10347 // One borrow for both slots: this arm *is* the whole loop of a
10348 // `for (i = 0; i < n; i++)` with an argument bound, so a second
10349 // `frames.last()` here is paid on every iteration. Measured 7.5% on
10350 // `dispatch:empty-loop`.
10351 let (left, right) = {
10352 let frame = self.frame();
10353 (frame.read_loc(loc), frame.read_arg(arg))
10354 };
10355 // Heavily measured: the bound is very often a `Float` even when the
10356 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
10357 // `JSON.parse` or a division is one — so requiring both sides to be
10358 // `Int` sent every iteration of those loops down the slow path. The
10359 // comparison below is the same one `relational` makes for two numbers.
10360 if !is_number(&left) || !is_number(&right) {
10361 return Ok(self.stop(pc));
10362 }
10363 // `if_false` branches on the comparison being false, which is **not**
10364 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
10365 // `>=` is also false and would keep it running forever. Clippy wants the
10366 // negation folded; that would be a wrong answer.
10367 let ordered = left.to_number() < right.to_number();
10368 let take_branch = !ordered;
10369 if take_branch {
10370 pc = insn.b as usize;
10371 continue;
10372 }
10373 }
10374 // The same header with a literal bound: `if (!(x < k)) goto target`.
10375 // The bound is an immediate, so only the counter needs a type test.
10376 #[allow(clippy::neg_cmp_op_on_partial_ord)]
10377 Fused::LtLocImmJump => {
10378 let left = self.get_loc(insn.a as usize);
10379 if !is_number(&left) {
10380 return Ok(self.stop(pc));
10381 }
10382 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
10383 if take_branch {
10384 pc = insn.b as usize;
10385 continue;
10386 }
10387 }
10388 Fused::None => match insn.op {
10389 // -- branches ---------------------------------------------------
10390 // A jump is an assignment now, because the target is an instruction
10391 // index. No arithmetic, no resolution table.
10392 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10393 let target = insn.a as usize;
10394 // A **back-edge** is a loop, and it is the only place an
10395 // instruction-level checkpoint can stop one: `for(;;){}` compiles
10396 // to a jump to itself and never leaves this loop, so the
10397 // per-instruction checks in `step` never run. That is exactly the
10398 // hole this arm closes — a host's `JS_SetInterruptHandler` did
10399 // nothing to a `for(;;){}` until it did, which is what
10400 // `tests/c/embed.c` is for.
10401 //
10402 // Polling here rather than on every instruction in this loop is
10403 // also the reference's choice (`OP_goto` calls
10404 // `js_poll_interrupts`), and it costs one compare per branch
10405 // instead of one decrement per instruction.
10406 if target <= pc {
10407 self.frame_mut().pc = target;
10408 self.check_memory()?;
10409 self.check_interrupt()?;
10410 }
10411 pc = target;
10412 continue;
10413 }
10414 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
10415 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
10416 let taken = self.pop().to_boolean();
10417 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
10418 if taken == want {
10419 pc = insn.a as usize;
10420 continue;
10421 }
10422 }
10423 // -- slot access -------------------------------------------------
10424 // A load's slot is already an operand (see `insn::implicit_operand`);
10425 // a captured one goes through its cell, which runs no script.
10426 Opcode::GetLoc
10427 | Opcode::GetLoc8
10428 | Opcode::GetLoc0
10429 | Opcode::GetLoc1
10430 | Opcode::GetLoc2
10431 | Opcode::GetLoc3 => {
10432 let value = self.get_loc(insn.a as usize);
10433 self.push(value);
10434 }
10435 Opcode::PutLoc
10436 | Opcode::PutLoc8
10437 | Opcode::PutLoc0
10438 | Opcode::PutLoc1
10439 | Opcode::PutLoc2
10440 | Opcode::PutLoc3 => {
10441 let value = self.pop();
10442 self.put_loc(insn.a as usize, value);
10443 }
10444 Opcode::GetArg
10445 | Opcode::GetArg0
10446 | Opcode::GetArg1
10447 | Opcode::GetArg2
10448 | Opcode::GetArg3 => {
10449 let value = self.get_arg(insn.a as usize);
10450 self.push(value);
10451 }
10452 Opcode::PutArg
10453 | Opcode::PutArg0
10454 | Opcode::PutArg1
10455 | Opcode::PutArg2
10456 | Opcode::PutArg3 => {
10457 let value = self.pop();
10458 self.put_arg(insn.a as usize, value);
10459 }
10460 // `a[i]` with an integer index on a dense array: see `fast_array_get`
10461 // for why a non-hole own element is exactly the slow path's answer.
10462 // The two operands are *peeked*, so a miss leaves the stack as the
10463 // slow path expects to find it.
10464 Opcode::GetArrayEl => {
10465 // One lookup, not two. The guard used `if …is_some()` and the arm
10466 // then called it again to get the value — two `peek`s, two
10467 // `array_get`s and two `Value` clones for one element.
10468 // `fast_array_get` was 13.1% of `array:indexed`, and the same
10469 // double call was the first version of the `get_field` fast path.
10470 let Some(value) = self.fast_array_get() else {
10471 return Ok(self.stop(pc));
10472 };
10473 // `a[i]` consumes both operands and leaves the element in their
10474 // place: one `truncate` and one write, no `pop`/`push` pair.
10475 let frame = self.frame_mut();
10476 frame.stack.truncate(frame.stack.len() - 2);
10477 frame.stack.push(value);
10478 }
10479 // `a[i] = v` on a dense array with an integer index: see
10480 // `fast_array_set` for why the whole store is one step.
10481 Opcode::PutArrayEl if self.fast_array_set() => {}
10482 // `o.x` resolved from the inline cache without leaving the loop.
10483 //
10484 // The cache is keyed by `(receiver identity, atom, site)` and a
10485 // monomorphic read re-validates the same chain every iteration, so
10486 // each one used to cost a `stop(pc)` — a write of `pc` into the
10487 // frame, a return out of this loop, a re-dispatch through `step` and
10488 // a re-entry. `property:monomorphic` spent 18% in
10489 // `read_field_cached` and 21% in `push`, both across that boundary.
10490 //
10491 // The site is `pc + width`, which is exactly the `next` the slow arm
10492 // passes — the two must agree or every fast lookup misses and
10493 // re-records the same entry forever.
10494 //
10495 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
10496 // slow arm finds the receiver where it expects it.
10497 // `name` resolved from the global-variable cache inside the loop.
10498 //
10499 // Same shape as `get_field` above and for the same reason: `get_var`
10500 // was not in the fast loop, so reading a global — which `fib` does
10501 // once per recursive call, for its own name — cost a `stop(pc)`, a
10502 // return out of the loop, a `step` re-dispatch and a re-entry, before
10503 // `get_global` even started its `scopes_are_plain` checks.
10504 //
10505 // Everything here is exactly `get_global`'s first branch: not lexical,
10506 // no `eval` scope, cache hit. Anything else leaves the stack untouched
10507 // and lets the slow arm decide.
10508 Opcode::GetVar => {
10509 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
10510 return Ok(self.stop(pc));
10511 };
10512 self.push(value);
10513 }
10514 Opcode::GetField | Opcode::GetField2 => {
10515 let Some(value) =
10516 self.fast_field_get(insn.a as usize, pc + insn.width())
10517 else {
10518 return Ok(self.stop(pc));
10519 };
10520 if insn.op == Opcode::GetField2 {
10521 // `get_field2` keeps the receiver for the `call_method` that
10522 // follows.
10523 self.push(value);
10524 } else {
10525 // `get_field` replaces the receiver, so this is one store over
10526 // the top slot rather than a `pop` and a `push`: the length
10527 // never changes, so neither `Vec` arm has a capacity check or a
10528 // drop to run beyond the one the overwrite itself does.
10529 let frame = self.frame_mut();
10530 match frame.stack.last_mut() {
10531 Some(slot) => *slot = value,
10532 None => return Ok(self.stop(pc)),
10533 }
10534 }
10535 }
10536 // -- constants ---------------------------------------------------
10537 Opcode::PushMinus1
10538 | Opcode::Push0
10539 | Opcode::Push1
10540 | Opcode::Push2
10541 | Opcode::Push3
10542 | Opcode::Push4
10543 | Opcode::Push5
10544 | Opcode::Push6
10545 | Opcode::Push7
10546 | Opcode::PushI8
10547 | Opcode::PushI16
10548 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
10549 // -- stack shuffling ---------------------------------------------
10550 Opcode::Drop => {
10551 self.pop();
10552 }
10553 // -- arithmetic on two integers ----------------------------------
10554 //
10555 // The operands are *looked at* before they are popped, so a non-integer
10556 // pair leaves the stack exactly as the slow path expects to find it.
10557 Opcode::Add if self.numeric_pair() => {
10558 let right = self.pop();
10559 let left = self.pop();
10560 // Exactly [`add_numbers`], which is what the slow arm reaches.
10561 let answer = match (&left, &right) {
10562 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10563 Some(sum) => Value::Int(sum),
10564 None => Value::Float(*a as f64 + *b as f64),
10565 },
10566 _ => Value::Float(left.to_number() + right.to_number()),
10567 };
10568 self.push(answer);
10569 }
10570 Opcode::Sub
10571 | Opcode::And
10572 | Opcode::Or
10573 | Opcode::Xor
10574 | Opcode::Shl
10575 | Opcode::Sar
10576 | Opcode::Shr
10577 if self.numeric_pair() =>
10578 {
10579 let right = self.pop();
10580 let left = self.pop();
10581 let answer =
10582 arithmetic(insn.op, left, right).expect("numbers cannot throw");
10583 self.push(answer);
10584 }
10585 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10586 if self.numeric_pair() =>
10587 {
10588 let right = self.pop();
10589 let left = self.pop();
10590 let answer = self
10591 .relational(insn.op, left, right)
10592 .expect("numbers cannot throw");
10593 self.push(answer);
10594 }
10595 // -- calls -------------------------------------------------------
10596 //
10597 // A plain call: `callee(arg0, …, argN) -> result`.
10598 //
10599 // This arm exists because of one measurement. `call:recursion` had
10600 // **20.4% of its profile in `execute_instruction`** — the *slow*
10601 // executor — and `fib`'s recursive call is the only thing in that
10602 // function which is not a fast arm. Every call therefore left this
10603 // loop via `stop()`, went through `step()`'s dispatch and
10604 // `execute_instruction`'s match over every opcode, and came back here
10605 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
10606 //
10607 // Two things make it safe to do here rather than only in the slow path:
10608 //
10609 // * the caller's `pc` is stored *before* the call, which is what
10610 // `step` does too — so when the callee returns, the caller resumes
10611 // after the call and not at it;
10612 // * `check_memory` runs, because `step` calls it once per instruction
10613 // and a call allocates a frame, its locals and its cells. Skipping
10614 // the checkpoint here would let a `--memory-limit` script overshoot
10615 // by one call per instruction.
10616 Opcode::Call
10617 | Opcode::Call0
10618 | Opcode::Call1
10619 | Opcode::Call2
10620 | Opcode::Call3 => {
10621 let argc = self.argc_operand(insn.op, insn.a);
10622 let next = pc + insn.width();
10623 {
10624 let frame = self
10625 .frames
10626 .last_mut()
10627 .expect("run_fast() is only called with a live frame");
10628 // `at` is what a stack trace reports for this frame, so a throw
10629 // inside the callee has to see the call site and not whatever
10630 // the last `stop()` left there.
10631 frame.at = insn.offset as usize;
10632 frame.pc = next;
10633 }
10634 self.check_memory()?;
10635 self.check_interrupt()?;
10636 let args = self.pop_n(argc);
10637 let callee = self.pop();
10638 // A plain call has no receiver; the callee decides what to do with
10639 // `undefined` (a sloppy function substitutes the global object).
10640 if let Some(result) =
10641 self.call_or_push(callee, Value::Undefined, args)?
10642 {
10643 // Native, host, generator, async, bound — no frame was pushed,
10644 // so this loop is still describing the right function. `pc`
10645 // is advanced by the loop tail like every other arm; only the
10646 // frame's copy had to be written here, and it already was.
10647 self.push(result);
10648 } else {
10649 // A bytecode callee: its frame is on top now, and `insns` and
10650 // `pc` both belong to the caller. Start over on the new frame.
10651 continue 'outer;
10652 }
10653 }
10654 // -- return ------------------------------------------------------
10655 Opcode::Return => {
10656 let value = self.pop();
10657 self.frame_mut().pc = pc + insn.width();
10658 return Ok(Some(value));
10659 }
10660 Opcode::ReturnUndef => {
10661 self.frame_mut().pc = pc + insn.width();
10662 return Ok(Some(Value::Undefined));
10663 }
10664 // Everything else needs the slow path.
10665 _ => return Ok(self.stop(pc)),
10666 },
10667 }
10668 pc += insn.width();
10669 }
10670 }
10671 }
10672
10673 /// Whether the top two operand-stack values are both numbers.
10674 ///
10675 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
10676 /// cannot run script, so the arm may not throw and may not change frames.
10677 fn numeric_pair(&self) -> bool {
10678 is_number(&self.peek(0)) && is_number(&self.peek(1))
10679 }
10680
10681 /// `a[i]` for a dense array and an integer index, without the string round trip.
10682 ///
10683 /// The slow path answers this by turning `i` into a string (`propkey` →
10684 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
10685 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
10686 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
10687 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
10688 /// without even the cheap `Int` formatting.
10689 ///
10690 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
10691 /// unambiguously the one the slow path would give:
10692 ///
10693 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
10694 /// `2^32-1` is the length, not an index),
10695 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
10696 /// typed array or an ordinary object, all of which have their own rules),
10697 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
10698 /// starts walking the prototype chain, and `a[i]` on a hole must find
10699 /// `Array.prototype[i]` if it exists rather than `undefined`.
10700 ///
10701 /// The last condition is the one that makes this safe rather than merely fast: an own
10702 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
10703 /// `get_var` answered from the global-variable cache, or `None`.
10704 ///
10705 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10706 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10707 /// records nothing — the slow arm is about to walk the chain and record it.
10708 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10709 let frame = self.frame();
10710 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10711 // "Lexical" is presence in the realm's table, not the closure var's flag: a
10712 // `GlobalRef` forwarded through a nested function has its flags cleared.
10713 if self.realm.globals.contains_key(name) {
10714 return None;
10715 }
10716 if !self.scopes_are_plain() {
10717 return None;
10718 }
10719 let object = &self.realm.global;
10720 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10721 let cached = self.global_cache[site].as_ref()?;
10722 if !object.upgrades_to(&cached.object) {
10723 return None;
10724 }
10725 object.data_property_at(cached.index, name)
10726 }
10727
10728 /// `o.x` answered entirely from the inline cache, or `None`.
10729 ///
10730 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
10731 /// about to do exactly that and recording it twice would rebuild the chain for every
10732 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
10733 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
10734 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
10735 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
10736 // an object receiver is a reference-count bump that the answer never needs.
10737 let frame = self.frame();
10738 let object = frame.stack.last()?;
10739 let Value::Object(target) = object else {
10740 return None;
10741 };
10742 // A proxy traps the lookup, so no cache entry ever describes it.
10743 if target.proxy_state().is_some() {
10744 return None;
10745 }
10746 let key = frame.code.atom_keys.get(atom)?;
10747 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
10748 if cached.key != *key {
10749 return None;
10750 }
10751 Self::cached_hit(target, cached)
10752 }
10753
10754 fn fast_array_get(&self) -> Option<Value> {
10755 let Value::Int(index) = self.peek(0) else {
10756 return None;
10757 };
10758 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
10759 // set for an `i32`.
10760 if index < 0 {
10761 return None;
10762 }
10763 let Value::Object(object) = self.peek(1) else {
10764 return None;
10765 };
10766 match object.array_get(index as usize) {
10767 Some(value) if !matches!(value, Value::Hole) => Some(value),
10768 _ => None,
10769 }
10770 }
10771
10772 /// `a[i] = v` on a dense array with an integer index, as one store.
10773 ///
10774 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
10775 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
10776 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
10777 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
10778 /// reference at the time it was measured (14.7x).
10779 ///
10780 /// Every condition here is one the slow path would also have to satisfy before
10781 /// storing into the element vector:
10782 ///
10783 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
10784 /// accepts as an index;
10785 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
10786 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
10787 /// one inside a recorded descriptor, reports `false` and the caller stops.
10788 ///
10789 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
10790 /// writes the own element too once `array_set` says it did.
10791 fn fast_array_set(&mut self) -> bool {
10792 // Every test runs *before* anything is popped: a refusal has to leave the stack
10793 // exactly as the slow path expects to find it. Popping first and reporting the
10794 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
10795 // then ran the slow path with nothing to write.
10796 let Value::Int(index) = self.peek(1) else {
10797 return false;
10798 };
10799 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
10800 if index < 0 {
10801 return false;
10802 }
10803 // Only a real array: a typed array's elements live in its buffer, a string-like
10804 // object has no element vector, and `array_set` on either does nothing.
10805 let Value::Object(object) = self.peek(2) else {
10806 return false;
10807 };
10808 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
10809 return false;
10810 }
10811 // A non-extensible array reports `false` here, but the *slow* path has to decide
10812 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
10813 // that with the key and the stack still intact.
10814 if !object.is_extensible() {
10815 return false;
10816 }
10817 // Inside the logical length, so the store cannot change `length`. Combined with
10818 // extensibility above, the only growth left for `array_set` is filling a hole in
10819 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
10820 // shape this fast path exists for. A store past the length would grow the array,
10821 // and whether that is allowed is the slow path's question.
10822 if index as usize >= object.array_length().unwrap_or(0) {
10823 return false;
10824 }
10825 // Only an *own element* can take the inline store. A hole is not an own property,
10826 // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
10827 // trap or a setter decides, and where `new Array(1)` with a proxy above it must
10828 // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
10829 // the one case this path used to swallow.
10830 //
10831 // The cost is small: `array:indexed` only reads after a 64-element fill, and
10832 // `array:push` appends past the length, which this path already refused.
10833 if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
10834 {
10835 return false;
10836 }
10837 // The bound `array_set` refuses past. Checking it here keeps that arm from having
10838 // to report a failure after the operands are gone.
10839 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
10840 return false;
10841 }
10842 let value = self.pop();
10843 self.pop();
10844 self.pop();
10845 object.array_store(self.heap, index as usize, value)
10846 }
10847
10848 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
10849 fn stop(&mut self, pc: usize) -> Option<Value> {
10850 self.frame_mut().pc = pc;
10851 None
10852 }
10853
10854 fn push(&mut self, value: Value) {
10855 self.frame_mut().stack.push(value);
10856 }
10857
10858 fn pop(&mut self) -> Value {
10859 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10860 }
10861
10862 fn pop_n(&mut self, count: usize) -> Vec<Value> {
10863 let frame = self.frame_mut();
10864 let start = frame.stack.len().saturating_sub(count);
10865 frame.stack.split_off(start)
10866 }
10867
10868 fn peek(&self, back: usize) -> Value {
10869 let frame = self.frame();
10870 frame
10871 .stack
10872 .get(frame.stack.len().wrapping_sub(1 + back))
10873 .cloned()
10874 .unwrap_or(Value::Undefined)
10875 }
10876
10877 #[allow(clippy::too_many_lines)]
10878 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10879 use Opcode::*;
10880 match op {
10881 // -- constants and stack shuffling -----------------------------
10882 Nop => {}
10883 PushMinus1 => self.push(Value::Int(-1)),
10884 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10885 let value = match op {
10886 Push0 => 0,
10887 Push1 => 1,
10888 Push2 => 2,
10889 Push3 => 3,
10890 Push4 => 4,
10891 Push5 => 5,
10892 Push6 => 6,
10893 _ => 7,
10894 };
10895 self.push(Value::Int(value));
10896 }
10897 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
10898 PushBigintI32 => {
10899 // The immediate form of a `BigInt` literal; the reference has the same
10900 // split between this and a constant-pool entry.
10901 let value = crate::bigint::BigInt::from_i64(a as i64);
10902 self.push(self.bigint(value));
10903 }
10904 PushTrue => self.push(Value::Bool(true)),
10905 PushFalse => self.push(Value::Bool(false)),
10906 PushEmptyString => self.push(self.string("")),
10907 Undefined => self.push(Value::Undefined),
10908 Null => self.push(Value::Null),
10909 Object => {
10910 let proto = self.realm.object_proto.clone();
10911 self.push(Value::Object(self.new_object(Some(proto))));
10912 }
10913 PushThis => {
10914 let this = self.frame().this.clone();
10915 self.push(this);
10916 }
10917 PushConst | PushConst8 => {
10918 let value = self.constant(a as usize)?;
10919 self.push(value);
10920 }
10921 PushAtomValue => {
10922 let text = self.atom_wtf8(a as usize);
10923 self.push(self.string_wtf8(text));
10924 }
10925 Dup => {
10926 let value = self.peek(0);
10927 self.push(value);
10928 }
10929 Dup2 => {
10930 // `a b -> a b a b`
10931 let b = self.peek(0);
10932 let a = self.peek(1);
10933 self.push(a);
10934 self.push(b);
10935 }
10936 Dup3 => {
10937 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
10938 // prototype and key while reading the current value through them.
10939 let c = self.peek(0);
10940 let b = self.peek(1);
10941 let a = self.peek(2);
10942 self.push(a);
10943 self.push(b);
10944 self.push(c);
10945 }
10946 Swap => {
10947 // `a b -> b a`
10948 let bottom = self.pop();
10949 let top = self.pop();
10950 self.push(bottom);
10951 self.push(top);
10952 }
10953 Perm3 => {
10954 // `a b c -> b a c`, the reference's reordering for a spread method
10955 // call: `obj func array` becomes the `func this array` that `apply`
10956 // takes.
10957 let c = self.pop();
10958 let b = self.pop();
10959 let a = self.pop();
10960 self.push(b);
10961 self.push(a);
10962 self.push(c);
10963 }
10964 Dup1 => {
10965 let value = self.peek(1);
10966 self.push(value);
10967 }
10968 Drop => {
10969 self.pop();
10970 }
10971 Nip => {
10972 // `a b -> b`
10973 let top = self.pop();
10974 self.pop();
10975 self.push(top);
10976 }
10977 Perm4 => {
10978 // `obj prop a b -> a obj prop b`, the reference's reordering for a
10979 // postfix update of a computed element: it puts the *old* value
10980 // underneath the receiver and key so `put_array_el` can consume them
10981 // and leave the old value as the expression's result.
10982 let d = self.pop();
10983 let c = self.pop();
10984 let b = self.pop();
10985 let a = self.pop();
10986 self.push(c);
10987 self.push(a);
10988 self.push(b);
10989 self.push(d);
10990 }
10991 Insert2 => {
10992 // `obj a -> a obj a`
10993 let value = self.pop();
10994 let object = self.pop();
10995 self.push(value.clone());
10996 self.push(object);
10997 self.push(value);
10998 }
10999 Insert3 => {
11000 // `obj prop a -> a obj prop a`
11001 let value = self.pop();
11002 let key = self.pop();
11003 let object = self.pop();
11004 self.push(value.clone());
11005 self.push(object);
11006 self.push(key);
11007 self.push(value);
11008 }
11009 Insert4 => {
11010 // `this obj prop a -> a this obj prop a`
11011 //
11012 // `put_super_value` consumes all four and yields nothing, so the copy
11013 // underneath is what leaves the assignment an expression value.
11014 let value = self.pop();
11015 let key = self.pop();
11016 let object = self.pop();
11017 let receiver = self.pop();
11018 self.push(value.clone());
11019 self.push(receiver);
11020 self.push(object);
11021 self.push(key);
11022 self.push(value);
11023 }
11024 Swap2 => {
11025 // `a b c d -> c d a b`
11026 let d = self.pop();
11027 let c = self.pop();
11028 let b = self.pop();
11029 let a = self.pop();
11030 self.push(c);
11031 self.push(d);
11032 self.push(a);
11033 self.push(b);
11034 }
11035 Rot3l => {
11036 // `x a b -> a b x`
11037 let b = self.pop();
11038 let a = self.pop();
11039 let x = self.pop();
11040 self.push(a);
11041 self.push(b);
11042 self.push(x);
11043 }
11044 Rot3r => {
11045 // `a b c -> c a b`
11046 let c = self.pop();
11047 let b = self.pop();
11048 let a_value = self.pop();
11049 self.push(c);
11050 self.push(a_value);
11051 self.push(b);
11052 }
11053
11054 Rest => {
11055 // `...rest` in a parameter list: the arguments from index `a` on, as a
11056 // real array. It takes nothing off the stack — the arguments are in the
11057 // frame, not on it.
11058 let frame = self.frame();
11059 let from = a as usize;
11060 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
11061 let array = self.new_array(collected);
11062 self.push(Value::Object(array));
11063 }
11064
11065 // -- slots ------------------------------------------------------
11066 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
11067 let slot = self.slot_operand(op, a);
11068 let value = self.get_loc(slot);
11069 self.push(value);
11070 }
11071 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
11072 let slot = self.slot_operand(op, a);
11073 let value = self.pop();
11074 self.put_loc(slot, value);
11075 }
11076 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
11077 let slot = self.slot_operand(op, a);
11078 let value = self.pop();
11079 self.put_loc(slot, value.clone());
11080 self.push(value);
11081 }
11082 // The `_check` forms are the temporal dead zone: they throw when the
11083 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
11084 // *reads*, so only the two writes may pop — mishandling that quietly
11085 // consumes the value the caller pushed just before.
11086 GetLocCheck => {
11087 let slot = self.slot_operand(op, a);
11088 let value = self.get_loc(slot);
11089 if matches!(value, Value::Uninitialized) {
11090 return Err(self.dead_zone(slot, VarSlot::Loc));
11091 }
11092 self.push(value);
11093 }
11094 PutLocCheck | SetLocCheck => {
11095 let slot = self.slot_operand(op, a);
11096 let value = self.pop();
11097 // The dead zone is a property of the **slot**, not of the value being
11098 // stored: `x = 1; let x` is a `ReferenceError` because `x` has not been
11099 // initialised yet. Testing the value instead — which is never
11100 // `Uninitialized` in practice — let every such store through, so the check
11101 // only ever fired for an explicit `x = undefined`-shaped accident. Reads
11102 // (`get_loc_check`) were already asking the slot, which is why
11103 // `print(x); let x` threw while `x = 1; let x` did not.
11104 if matches!(self.get_loc(slot), Value::Uninitialized) {
11105 return Err(self.dead_zone(slot, VarSlot::Loc));
11106 }
11107 // The initialiser goes through `put_loc`, not this, so any store that
11108 // reaches here is a later assignment — which a `const` refuses.
11109 if self.is_read_only(slot, VarSlot::Loc) {
11110 return Err(self.read_only(slot, VarSlot::Loc));
11111 }
11112 if op == SetLocCheck {
11113 self.put_loc(slot, value.clone());
11114 self.push(value);
11115 } else {
11116 self.put_loc(slot, value);
11117 }
11118 }
11119 PutLocCheckInit => {
11120 // The one store that *initialises* a lexical slot: `this` in a derived
11121 // constructor, which only exists after `super()` has run. A second
11122 // initialisation is the error the reference reports as
11123 // "'this' can be initialized only once".
11124 let slot = self.slot_operand(op, a);
11125 let value = self.pop();
11126 if !matches!(self.get_loc(slot), Value::Uninitialized) {
11127 return Err(Signal::Throw(self.make_error(
11128 "ReferenceError",
11129 "'this' can be initialized only once",
11130 )));
11131 }
11132 self.put_loc(slot, value);
11133 }
11134 CheckCtor => {
11135 // A class constructor may only run under `new`, which is what makes
11136 // `class A {}; A()` a TypeError.
11137 if matches!(self.frame().new_target, Value::Undefined) {
11138 return Err(Signal::Throw(self.make_error(
11139 "TypeError",
11140 "class constructors must be invoked with 'new'",
11141 )));
11142 }
11143 }
11144 InitCtor => {
11145 // The body a derived class gets when it declares no constructor:
11146 // forward every argument to the parent constructor, keeping `new.target`.
11147 if matches!(self.frame().new_target, Value::Undefined) {
11148 return Err(Signal::Throw(self.make_error(
11149 "TypeError",
11150 "class constructors must be invoked with 'new'",
11151 )));
11152 }
11153 let Some(callee) = self.current_callee() else {
11154 return Err(Signal::Throw(
11155 self.make_error("TypeError", "no constructor to inherit from"),
11156 ));
11157 };
11158 let parent = callee.proto().map_or(Value::Null, Value::Object);
11159 let new_target = self.frame().new_target.clone();
11160 let args = self.frame().passed().to_vec();
11161 let result = self.construct(parent, new_target, args)?;
11162 self.push(result);
11163 }
11164 SetLocUninitialized => {
11165 let slot = self.slot_operand(op, a);
11166 self.put_loc(slot, Value::Uninitialized);
11167 }
11168 CloseLoc => {
11169 // "Close" a binding: give it a *fresh* cell holding the current
11170 // value. Closures created before this point keep the old cell and the
11171 // ones created after see the new one, which is what makes every
11172 // iteration of `for (let i ...)` capture its own `i`, and what freezes
11173 // a block-scoped binding when the block ends.
11174 //
11175 // Clearing the slot instead (which this used to do) broke both: a
11176 // closure over a captured block variable read `undefined`, and a loop
11177 // terminated after one iteration.
11178 let slot = self.slot_operand(op, a);
11179 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
11180 if index >= 0 {
11181 let current = self.frame().cells[index as usize].get();
11182 let fresh = self.new_cell(current);
11183 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
11184 *cell = fresh;
11185 }
11186 }
11187 }
11188 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
11189 let slot = self.slot_operand(op, a);
11190 let value = self.get_arg(slot);
11191 self.push(value);
11192 }
11193 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
11194 let slot = self.slot_operand(op, a);
11195 let value = self.pop();
11196 self.put_arg(slot, value);
11197 }
11198 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
11199 let slot = self.slot_operand(op, a);
11200 let value = self.pop();
11201 self.put_arg(slot, value.clone());
11202 self.push(value);
11203 }
11204
11205 // -- closure variables ------------------------------------------
11206 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
11207 let slot = self.slot_operand(op, a);
11208 // A name a direct `eval` created shadows the binding the compiler chose.
11209 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
11210 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
11211 // and only a runtime lookup can know that.
11212 if let Some(cell) = self.eval_created_local(slot) {
11213 self.push(cell.get());
11214 return self.step();
11215 }
11216 let value = self.cell_value(slot)?;
11217 self.push(value);
11218 }
11219 GetVarRefCheck => {
11220 let slot = self.slot_operand(op, a);
11221 let value = self.cell_value(slot)?;
11222 if matches!(value, Value::Uninitialized) {
11223 return Err(self.dead_zone(slot, VarSlot::Closure));
11224 }
11225 self.push(value);
11226 }
11227 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
11228 let slot = self.slot_operand(op, a);
11229 let value = self.pop();
11230 if let Some(cell) = self.eval_created_local(slot) {
11231 cell.set(value);
11232 return self.step();
11233 }
11234 // Same two rules as `PutLocCheck`: a checked store to a captured binding
11235 // asks the cell about the dead zone, then refuses a `const` whose
11236 // initialiser has already run.
11237 if op == PutVarRefCheck {
11238 let current = self.cell_value(slot)?;
11239 if matches!(current, Value::Uninitialized) {
11240 return Err(self.dead_zone(slot, VarSlot::Closure));
11241 }
11242 if self.is_read_only(slot, VarSlot::Closure) {
11243 return Err(self.read_only(slot, VarSlot::Closure));
11244 }
11245 }
11246 self.set_cell(slot, value)?;
11247 }
11248 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
11249 let slot = self.slot_operand(op, a);
11250 let value = self.pop();
11251 if let Some(cell) = self.eval_created_local(slot) {
11252 cell.set(value.clone());
11253 self.push(value);
11254 return self.step();
11255 }
11256 self.set_cell(slot, value.clone())?;
11257 self.push(value);
11258 }
11259
11260 // -- globals ----------------------------------------------------
11261 GetVar => {
11262 let value = self.get_global(a as usize)?;
11263 self.push(value);
11264 }
11265 GetVarUndef => {
11266 let slot = a as usize;
11267 // `typeof undeclared` answers `"undefined"`; `typeof x` where `x` is in its
11268 // **dead zone** still throws (§13.5.3 evaluates the operand as a Reference
11269 // and `GetValue`s it, and only the unresolvable case is forgiven).
11270 //
11271 // The distinction is made by asking whether a binding exists at all: a name
11272 // in the realm's lexical table is declared, so a `ReferenceError` from
11273 // reading it is the dead zone talking. Swallowing every error made
11274 // `eval("typeof x; let x;")` print `"undefined"`.
11275 let declared = self.realm.globals.contains_key(&self.global_name(slot));
11276 let value = if declared {
11277 self.get_global(slot)?
11278 } else {
11279 match self.get_global(slot) {
11280 Ok(value) => value,
11281 Err(Signal::Throw(_)) => Value::Undefined,
11282 Err(other) => return Err(other),
11283 }
11284 };
11285 self.push(value);
11286 }
11287 DeleteVar => {
11288 // `delete name` for a name that is not a declared binding. A lexical
11289 // global lives in the reference table and cannot be deleted; anything
11290 // reachable only as a property of the global object is *implicit* —
11291 // `x = 1` with no declaration — and goes away if it is configurable,
11292 // which is what `delete` on an implicit global answers.
11293 let name = self.atom_text(a as usize);
11294 let global = self.realm.global.clone();
11295 let deleted = if self.realm.globals.contains_key(&name) {
11296 false
11297 } else if global.own_property(&name).is_some() {
11298 self.delete_property(&global, &name)?
11299 } else {
11300 true
11301 };
11302 self.push(Value::Bool(deleted));
11303 }
11304 PutVar => {
11305 let value = self.pop();
11306 self.put_global(a as usize, value)?;
11307 }
11308 PutVarInit => {
11309 let slot = a as usize;
11310 let value = self.pop();
11311 self.init_global(slot, value)?;
11312 }
11313
11314 // -- arithmetic -------------------------------------------------
11315 Add => self.binary_add()?,
11316 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
11317 let raw_right = self.pop();
11318 let raw_left = self.pop();
11319 // BigInt arithmetic is a separate path, and not only for the type of the
11320 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
11321 // rather than a silent conversion.
11322 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
11323 let left = self.primitive_of(raw_left)?;
11324 let right = self.primitive_of(raw_right)?;
11325 let value = self.bigint_arithmetic(op, left, right)?;
11326 self.push(value);
11327 } else {
11328 let right = self.numeric(raw_right)?;
11329 let left = self.numeric(raw_left)?;
11330 self.push(arithmetic(op, left, right)?);
11331 }
11332 }
11333 Neg => {
11334 let raw = self.pop();
11335 match raw {
11336 // A bigint negates exactly, however wide it is.
11337 Value::BigInt(big) => {
11338 let negated = big.negate();
11339 self.push(self.bigint(negated));
11340 }
11341 other => {
11342 let value = self.numeric(other)?;
11343 self.push(negate(value));
11344 }
11345 }
11346 }
11347 Plus => {
11348 let value = self.pop();
11349 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
11350 // unary plus is defined to produce a *number*, which a bigint cannot
11351 // become without loss. It used to fall through to `NaN`.
11352 if matches!(value, Value::BigInt(_)) {
11353 return Err(self.type_error("cannot convert bigint to number"));
11354 }
11355 let numeric = self.numeric_of(value)?;
11356 self.push(numeric);
11357 }
11358 Inc => {
11359 let raw = self.pop();
11360 let (_, updated) = self.advance_numeric(raw, true)?;
11361 self.push(updated);
11362 }
11363 Dec => {
11364 let raw = self.pop();
11365 let (_, updated) = self.advance_numeric(raw, false)?;
11366 self.push(updated);
11367 }
11368 PostInc | PostDec => {
11369 // `x -> x x+1`: the *new* value ends up on top, so the store the
11370 // compiler emits right after (`put_var`) writes the incremented
11371 // one, while the old value stays underneath for the expression's
11372 // own result. Getting this backwards makes `i++` a no-op, which
11373 // turns `while (i < 3)` into an infinite loop.
11374 let raw = self.pop();
11375 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
11376 self.push(old);
11377 self.push(updated);
11378 }
11379 Not => {
11380 let raw = self.pop();
11381 match raw {
11382 // `~x` on a bigint is `-x - 1`, exact at any width.
11383 Value::BigInt(big) => {
11384 let inverted = big.bitnot();
11385 self.push(self.bigint(inverted));
11386 }
11387 other => {
11388 let value = self.numeric(other)?;
11389 self.push(Value::Int(!value.to_int32()));
11390 }
11391 }
11392 }
11393 Lnot => {
11394 let value = self.pop();
11395 self.push(Value::Bool(!value.to_boolean()));
11396 }
11397
11398 // -- comparison -------------------------------------------------
11399 Lt | Lte | Gt | Gte => {
11400 let right = self.pop();
11401 let left = self.pop();
11402 let answer = self.relational(op, left, right)?;
11403 self.push(answer);
11404 }
11405 Eq | Neq => {
11406 let right = self.pop();
11407 let left = self.pop();
11408 let equal = self.abstract_equals(left, right)?;
11409 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
11410 }
11411 StrictEq => {
11412 let right = self.pop();
11413 let left = self.pop();
11414 self.push(Value::Bool(left.strict_equals(&right)));
11415 }
11416 StrictNeq => {
11417 let right = self.pop();
11418 let left = self.pop();
11419 self.push(Value::Bool(!left.strict_equals(&right)));
11420 }
11421 IsUndefined => {
11422 // `=== undefined`, which is what a destructuring default tests. It is
11423 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
11424 let value = self.pop();
11425 self.push(Value::Bool(matches!(value, Value::Undefined)));
11426 }
11427 IsUndefinedOrNull => {
11428 let value = self.pop();
11429 self.push(Value::Bool(value.is_nullish()));
11430 }
11431 Typeof => {
11432 let value = self.pop();
11433 self.push(self.string(value.type_of()));
11434 }
11435 ToObject => {
11436 // A destructuring *object* pattern starts here, which is why
11437 // `var {} = null` throws. Only `undefined` and `null` are refused; a
11438 // primitive is boxed.
11439 let value = self.pop();
11440 let object = self.object_from(&value)?;
11441 self.push(Value::Object(object));
11442 }
11443 Instanceof => {
11444 let constructor = self.pop();
11445 let object = self.pop();
11446 let answer = self.instance_of(&object, &constructor)?;
11447 self.push(Value::Bool(answer));
11448 }
11449 In => {
11450 let object = self.pop();
11451 let key = self.pop();
11452 let answer = self.has_property(&key, &object)?;
11453 self.push(Value::Bool(answer));
11454 }
11455
11456 // -- control flow -----------------------------------------------
11457 Goto | Goto8 | Goto16 => {
11458 self.frame_mut().pc = a as usize;
11459 }
11460 IfTrue | IfTrue8 => {
11461 let value = self.pop();
11462 if value.to_boolean() {
11463 self.frame_mut().pc = a as usize;
11464 }
11465 }
11466 IfFalse | IfFalse8 => {
11467 let value = self.pop();
11468 if !value.to_boolean() {
11469 self.frame_mut().pc = a as usize;
11470 }
11471 }
11472 Catch => {
11473 // Pushes the handler target onto the value stack; `unwind` finds it.
11474 self.push(Value::CatchOffset(a));
11475 }
11476 Gosub => {
11477 self.push(Value::ReturnAddress(next as u32));
11478 self.frame_mut().pc = a as usize;
11479 }
11480 Ret => {
11481 let value = self.pop();
11482 match value {
11483 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
11484 _ => {
11485 return Err(Signal::Throw(
11486 self.make_error("InternalError", "invalid return address"),
11487 ));
11488 }
11489 }
11490 }
11491 NipCatch => {
11492 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
11493 // including the marker, keeping the top value.
11494 let top = self.pop();
11495 loop {
11496 match self.pop() {
11497 Value::CatchOffset(_) | Value::Undefined => break,
11498 _ => {}
11499 }
11500 if self.frame().stack.is_empty() {
11501 break;
11502 }
11503 }
11504 self.push(top);
11505 }
11506 Throw => {
11507 let value = self.pop();
11508 return Err(Signal::Throw(value));
11509 }
11510 ThrowError => {
11511 let name = self.atom_text(a as usize);
11512 let (class, message) = match b {
11513 0 => ("TypeError", format!("'{name}' is read-only")),
11514 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
11515 2 => ("ReferenceError", format!("'{name}' is not initialized")),
11516 // `delete super.x` is a syntax-level mistake the reference reports
11517 // with this wording, not a property-access failure.
11518 3 => (
11519 "ReferenceError",
11520 "unsupported reference to 'super'".to_string(),
11521 ),
11522 4 => (
11523 "TypeError",
11524 "iterator does not have a throw method".to_string(),
11525 ),
11526 5 => (
11527 "ReferenceError",
11528 "invalid assignment left-hand side".to_string(),
11529 ),
11530 _ => ("TypeError", format!("invalid operation on '{name}'")),
11531 };
11532 return Err(Signal::Throw(self.make_error(class, &message)));
11533 }
11534 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
11535 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
11536 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
11537 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
11538 Await => return Ok(Step::Suspend(SuspendKind::Await)),
11539 ReturnAsync => {
11540 // The reference's `return_async` returns `undefined` and lets the resume
11541 // machinery pick the real value off `sp[-1]`, which is how it tells a
11542 // completion from a suspension. Carrying the value explicitly says the
11543 // same thing without the implicit stack slot.
11544 let value = self.pop();
11545 return Ok(Step::Return(value));
11546 }
11547 Return => {
11548 let value = self.pop();
11549 return Ok(Step::Return(value));
11550 }
11551 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
11552
11553 // -- calls ------------------------------------------------------
11554 Call | Call0 | Call1 | Call2 | Call3 => {
11555 let argc = self.argc_operand(op, a);
11556 let args = self.pop_n(argc);
11557 let callee = self.pop();
11558 // A plain call has no receiver; the callee decides what to do with
11559 // `undefined` (a sloppy function substitutes the global object).
11560 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
11561 self.push(result);
11562 }
11563 }
11564 CallConstructor => {
11565 // `constructor this_obj args… -> object`. The duplicated
11566 // constructor is `new.target`; this milestone does not expose it,
11567 // so the extra copy is simply consumed here.
11568 let argc = a as usize;
11569 let args = self.pop_n(argc);
11570 let new_target = self.pop();
11571 let callee = self.pop();
11572 let result = self.construct(callee, new_target, args)?;
11573 self.push(result);
11574 }
11575 CallMethod => {
11576 let argc = a as usize;
11577 let args = self.pop_n(argc);
11578 let callee = self.pop();
11579 let this = self.pop();
11580 if let Some(result) = self.call_or_push(callee, this, args)? {
11581 self.push(result);
11582 }
11583 }
11584 Apply => {
11585 // `func this array -> result`, the spread-call form: the compiler
11586 // builds one array of arguments, and all that is left here is to
11587 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
11588 let array = self.pop();
11589 let this = self.pop();
11590 let callee = self.pop();
11591 let args = self.array_like_to_args(&array)?;
11592 if a & 1 != 0 {
11593 let result = self.construct(callee, this, args)?;
11594 self.push(result);
11595 } else if let Some(result) = self.call_or_push(callee, this, args)? {
11596 self.push(result);
11597 }
11598 }
11599 TailCall | TailCallMethod => {
11600 // `tail_call` is `call` whose result is returned immediately — the
11601 // reference jumps straight to `done` instead of storing the value and
11602 // running on. The callee still gets its own frame, so deep tail
11603 // recursion hits the stack limit exactly like plain recursion does;
11604 // marking this frame lets the return path unwind without needing
11605 // instructions after the call.
11606 let argc = if op == TailCallMethod {
11607 a as usize
11608 } else {
11609 self.argc_operand(op, a)
11610 };
11611 let args = self.pop_n(argc);
11612 let callee = self.pop();
11613 let this = if op == TailCallMethod {
11614 self.pop()
11615 } else {
11616 Value::Undefined
11617 };
11618 if let Value::Object(function) = &callee
11619 && let Some((code, env)) = bytecode_of(function)
11620 {
11621 // A generator or async body is not run here at all: calling it only
11622 // *creates* the generator/coroutine, so it must not inherit this
11623 // frame. Doing so made `function f(){ return g() }` push `g`'s body
11624 // onto `f`'s frame, and the first `yield`/`await` then reported
11625 // "a generator body ran as an ordinary call".
11626 if code.code.kind.is_generator() || code.code.kind.is_async() {
11627 let value = self.call_value(callee, this, args)?;
11628 return Ok(Step::Return(value));
11629 }
11630 self.frame_mut().tail = true;
11631 self.push_frame(code, env, this, args, callee)?;
11632 return Ok(Step::Continue);
11633 }
11634 // A native callee has no frame to reuse, so its value is simply
11635 // returned.
11636 let value = self.call_value(callee, this, args)?;
11637 return Ok(Step::Return(value));
11638 }
11639
11640 // -- objects ----------------------------------------------------
11641 SpecialObject => {
11642 let value = self.special_object(a)?;
11643 self.push(value);
11644 }
11645 PrivateSymbol => {
11646 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
11647 // symbol each time it is evaluated, which is why the compiler evaluates it
11648 // once (at class definition) and stores it in a class-scope binding.
11649 let name = self.atom_text(a as usize);
11650 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
11651 self.push(Value::Symbol(symbol));
11652 }
11653 GetPrivateField => {
11654 // `obj symbol -> value`. A missing private field is a TypeError, which is what
11655 // makes `#x` inaccessible on any object not built by this class.
11656 let symbol = self.pop();
11657 let object = self.pop();
11658 let value = self.read_private_field(&object, &symbol)?;
11659 self.push(value);
11660 }
11661 PutPrivateField => {
11662 // `obj value symbol ->`, and the store is a plain assignment to a property the
11663 // class already created, so there is no setter to consult.
11664 let symbol = self.pop();
11665 let value = self.pop();
11666 let object = self.pop();
11667 self.write_private_field(&object, &symbol, value)?;
11668 }
11669 DefinePrivateField => {
11670 // `obj symbol value -> obj`: a field initialiser creates the property, and
11671 // redefining one is a TypeError ("already exists").
11672 let value = self.pop();
11673 let symbol = self.pop();
11674 let object = self.pop();
11675 self.define_private_field(&object, &symbol, value)?;
11676 self.push(object);
11677 }
11678 PrivateIn => {
11679 // `obj key -> bool`: `#x in o`. The second operand decides which question is
11680 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
11681 // is a field, so this is an own-property test; a *function* is a method or
11682 // accessor, so this is a brand check.
11683 let key = self.pop();
11684 let object = self.pop();
11685 let Some(target) = object.as_object() else {
11686 return Err(Signal::Throw(
11687 self.make_error("TypeError", "invalid 'in' operand"),
11688 ));
11689 };
11690 let present = match &key {
11691 Value::Object(_) => self.check_brand(target, &key)?,
11692 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
11693 };
11694 self.push(Value::Bool(present));
11695 }
11696 AddBrand => {
11697 // `obj home ->`: create the class brand on `home` if it has none, then give
11698 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
11699 // class definition: only the prototype's copy of the symbol is wanted.
11700 let home = self.pop();
11701 let object = self.pop();
11702 self.add_brand(&object, &home)?;
11703 }
11704 CheckBrand => {
11705 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
11706 // Both stay, because the caller needs them — `nip` halves a read into its
11707 // value and `call_method` uses the pair as receiver and callee.
11708 let function = self.peek(0);
11709 let object = self.peek(1);
11710 let Some(target) = object.as_object() else {
11711 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11712 };
11713 if !self.check_brand(target, &function)? {
11714 return Err(Signal::Throw(
11715 self.make_error("TypeError", "invalid brand on object"),
11716 ));
11717 }
11718 }
11719 GetLength => {
11720 // `get_length` is the `.length` read; an array and a string answer
11721 // from their own length, anything else from the property.
11722 let target = self.pop();
11723 let value = match &target {
11724 Value::Object(object) => match object.array_length() {
11725 Some(length) => crate::object::length_value(length),
11726 None => self.read_field(&target, "length")?,
11727 },
11728 Value::String(text) => Value::Int(text.utf16_len() as i32),
11729 _ => self.read_field(&target, "length")?,
11730 };
11731 self.push(value);
11732 }
11733 GetField | GetField2 => {
11734 let object = self.pop();
11735 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
11736 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
11737 // just below is what lets the borrow outlive the `&mut self` the lookup
11738 // needs — one refcount bump instead of a key clone plus its drop, on the
11739 // hottest property path there is: every `o.x` and every `o.m()` receiver.
11740 let code = self.frame().code.clone();
11741 let key = &code.atom_keys[a as usize];
11742 let value = self.read_field_cached(&object, key, next)?;
11743 if op == GetField2 {
11744 self.push(object);
11745 }
11746 self.push(value);
11747 }
11748 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
11749 let key = self.pop();
11750 let object = self.pop();
11751 let key = self.propkey(&key)?;
11752 let value = self.read_field_key(&object, &key)?;
11753 if matches!(op, GetArrayEl2 | GetArrayEl3) {
11754 self.push(object);
11755 }
11756 if op == GetArrayEl3 {
11757 // The key goes back in its *value* form, which the compiler stores
11758 // into the target of a destructuring assignment.
11759 self.push(match &key {
11760 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11761 PropertyKey::String(text) => self.string_wtf8(text.clone()),
11762 });
11763 }
11764 self.push(value);
11765 }
11766 PutField => {
11767 let value = self.pop();
11768 let object = self.pop();
11769 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
11770 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
11771 // only reads. `this.value = …` is the write half of the hottest loop in
11772 // `property:method-call`, and `own_property_key` was 4.8% of the case.
11773 let code = self.frame().code.clone();
11774 let key = &code.atom_keys[a as usize];
11775 self.write_field_key(&object, key, value)?;
11776 }
11777 PutArrayEl => {
11778 let value = self.pop();
11779 let key = self.pop();
11780 let object = self.pop();
11781 let key = self.propkey(&key)?;
11782 self.write_field_key(&object, &key, value)?;
11783 }
11784 DefineField => {
11785 let value = self.pop();
11786 let object = self.pop();
11787 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
11788 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
11789 // three U+FFFD — a property under a different name from the one
11790 // `o["\uD800"]` reads.
11791 let code = self.frame().code.clone();
11792 let key = code.atom_keys[a as usize].clone();
11793 // No naming here. `{m: function(){}}` is named by the *compiler*, which
11794 // emits `set_name` — and only where `NamedEvaluation` applies, so
11795 // `{m: (0, function(){})}` stays anonymous. Naming every function that
11796 // reaches a property definition got that case wrong, and the compiler is
11797 // the only place that can tell the two apart.
11798 if let Some(target) = object.as_object() {
11799 // Only an *array* stores into the element vector. A numeric key
11800 // on an ordinary object is an ordinary property, which is what
11801 // makes `{1: 'a'}` iterate as a key rather than disappear.
11802 let stored = target.is_array()
11803 && key.as_str().and_then(array_index).is_some_and(|index| {
11804 target.array_set(self.heap, index as usize, value.clone())
11805 });
11806 if !stored {
11807 target.define_data_key(&key, value);
11808 }
11809 }
11810 self.push(object);
11811 }
11812 DefineArrayEl => {
11813 // `obj key value -> obj key`. The *value* form of the key is what goes
11814 // back on the stack — the compiler stores it into the pattern's binding —
11815 // so the symbol is not stringified on the way through.
11816 let value = self.pop();
11817 let key_value = self.pop();
11818 let object = self.peek(0);
11819 let key = self.propkey(&key_value)?;
11820 self.write_field_key(&object, &key, value)?;
11821 self.push(key_value);
11822 }
11823 SetHomeObject => {
11824 // `obj func -> obj func`: records the object a method was defined on so
11825 // `super` inside it resolves against that object's prototype.
11826 let function = self.peek(0);
11827 let home = self.peek(1);
11828 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
11829 function.set_home_object(Some(home.clone()));
11830 }
11831 }
11832 Regexp => {
11833 // `pattern flags -> regexp`. A literal compiles here rather than through the
11834 // constructor, which is both what the reference's dedicated opcode is for
11835 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
11836 let flags = self.pop();
11837 let pattern = self.pop();
11838 let pattern = self.to_js_string(&pattern)?;
11839 let flags = self.to_js_string(&flags)?;
11840 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
11841 self.push(Value::Object(object));
11842 }
11843 UsingDisposeInit => {
11844 // The error state a disposal accumulates into. Uninitialised means "no
11845 // failure yet"; anything else is the exception being propagated.
11846 self.push(Value::Uninitialized);
11847 }
11848 UsingCheck => {
11849 // `value -> value, method`: validate and snapshot the disposer now, so a
11850 // later change to `Symbol.dispose` cannot change what gets called, and so a
11851 // value that is not disposable fails before the body runs.
11852 let value = self.pop();
11853 let method = self.using_method_for(&value, a as u8 == 1)?;
11854 self.push(value);
11855 self.push(method);
11856 }
11857 UsingDispose => {
11858 // `error_state -> error_state'`: dispose the variable at `slot` — its value
11859 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
11860 // the pending error.
11861 let slot = self.slot_operand(op, a);
11862 let error_state = self.pop();
11863 let merged = self.using_dispose_once(slot, error_state)?;
11864 self.push(merged);
11865 }
11866 UsingDisposeMerge => {
11867 let new_error = self.pop();
11868 let error_state = self.pop();
11869 let merged = self.merge_dispose_error(new_error, error_state);
11870 self.push(merged);
11871 }
11872 UsingDisposeEnd => {
11873 // A disposal that failed replaces the block's normal completion, so the
11874 // error state becomes a real throw here rather than at the call site.
11875 let error_state = self.pop();
11876 if !matches!(error_state, Value::Uninitialized) {
11877 return Err(Signal::Throw(error_state));
11878 }
11879 }
11880 UsingDisposeAsync => {
11881 // `await using` needs a promise to await and this runtime has no
11882 // `Promise` builtin, so the disposer is called synchronously and its result
11883 // discarded. That is correct for a disposer that returns nothing and is
11884 // reported as a gap rather than silently skipped.
11885 let slot = self.slot_operand(op, a);
11886 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
11887 self.push(error_state);
11888 }
11889 GetSuper => {
11890 // `obj -> obj's prototype`: the starting point of a `super` lookup.
11891 let object = self.pop();
11892 let proto = match &object {
11893 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
11894 _ => Value::Null,
11895 };
11896 self.push(proto);
11897 }
11898 GetSuperValue => {
11899 // `receiver proto key -> value`, searching from `proto` but reporting to
11900 // `receiver`, which is what `super.g` must do for a getter to see `this`.
11901 //
11902 // Three values in, one out: the receiver is *consumed*, not left under the
11903 // result. Leaving it there was invisible for `super.x` in `return` or
11904 // statement position (the result is what gets popped) and corrupted the
11905 // frame everywhere else — `print(super.x)` left the class where the call
11906 // opcode looks for the receiver and called the class itself.
11907 let key = self.pop();
11908 let proto = self.pop();
11909 let receiver = self.pop();
11910 let value = self.super_read(&receiver, &proto, &key)?;
11911 self.push(value);
11912 }
11913 PutSuperValue => {
11914 // `receiver proto key value ->`: a store that starts at `proto` but
11915 // assigns to `receiver`.
11916 let value = self.pop();
11917 let key = self.pop();
11918 let proto = self.pop();
11919 let receiver = self.pop();
11920 self.super_write(&receiver, &proto, &key, value)?;
11921 }
11922 DefineClass => {
11923 // `parent ctor -> ctor proto`: the constructor becomes the class and a
11924 // fresh prototype object lands on top for the methods to go on.
11925 let name = self.atom_text(a as usize);
11926 let (ctor, proto) = self.define_class(&name, b)?;
11927 self.push(ctor);
11928 self.push(Value::Object(proto));
11929 }
11930 DefineClassComputed => {
11931 // `parent ctor key -> ctor proto key`: the computed name stays put so
11932 // `define_field`-style consumers can still read it.
11933 let key = self.pop();
11934 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11935 let (ctor, proto) = self.define_class(&name, b)?;
11936 self.push(ctor);
11937 self.push(Value::Object(proto));
11938 self.push(key);
11939 }
11940 DefineMethod => {
11941 let function = self.pop();
11942 let object = self.pop();
11943 // The exact key, like `define_field`: a quoted method key may hold an
11944 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
11945 // that `o["\uD800"]` finds.
11946 let code = self.frame().code.clone();
11947 let key = code.atom_keys[a as usize].clone();
11948 // A method's `[[HomeObject]]` is the object it was defined on, which is
11949 // what `super` inside it resolves against.
11950 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11951 function.set_home_object(Some(object.clone()));
11952 }
11953 if let Some(text) = key.as_wtf8() {
11954 self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
11955 } else {
11956 self.set_function_name(
11957 &function,
11958 &key_with_accessor_prefix(&key.to_string(), b),
11959 );
11960 }
11961 if let Some(array) = object.as_object() {
11962 define_function_property(array, &key, function, b);
11963 }
11964 self.push(object);
11965 }
11966 DefineMethodComputed => {
11967 let function = self.pop();
11968 let key = self.pop();
11969 let object = self.pop();
11970 let key = self.propkey(&key)?;
11971 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
11972 // the name: `super` inside a computed method resolves through it. Without
11973 // this, `class B extends A { [k]() { return super.m() } }` read the
11974 // home object as null and threw.
11975 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11976 function.set_home_object(Some(object.clone()));
11977 }
11978 match key.as_wtf8() {
11979 Some(text) => {
11980 let name = accessor_prefixed(text, a);
11981 self.set_function_name_wtf8(&function, &name);
11982 }
11983 None => self.set_function_name(
11984 &function,
11985 &key_with_accessor_prefix(&key.to_string(), a),
11986 ),
11987 }
11988 if let Some(array) = object.as_object() {
11989 define_function_property(array, &key, function, a);
11990 }
11991 self.push(object);
11992 }
11993 SetProto => {
11994 let proto = self.pop();
11995 let object = self.pop();
11996 if let Some(target) = object.as_object() {
11997 target.set_proto(proto.as_object().cloned());
11998 }
11999 self.push(object);
12000 }
12001 CopyDataProperties => {
12002 let exclusion = self.pop();
12003 let source = self.pop();
12004 let target = self.peek(0);
12005 self.copy_properties(&target, &source, &exclusion)?;
12006 self.push(source);
12007 self.push(exclusion);
12008 }
12009 ToPropkey => {
12010 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
12011 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
12012 // ordinary `"Symbol(b)"` property.
12013 let value = self.pop();
12014 let key = match self.propkey(&value)? {
12015 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
12016 PropertyKey::String(text) => self.string_wtf8(text),
12017 };
12018 self.push(key);
12019 }
12020 SetName => {
12021 let function = self.peek(0);
12022 let name = self.atom_wtf8(a as usize);
12023 self.set_function_name_wtf8(&function, &name);
12024 }
12025 SetNameComputed => {
12026 let key = self.peek(1);
12027 let function = self.peek(0);
12028 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
12029 self.set_function_name(&function, &name);
12030 }
12031
12032 // -- arrays -----------------------------------------------------
12033 ArrayFrom => {
12034 let count = a as usize;
12035 let elements = self.pop_n(count);
12036 let array = self.new_array(elements);
12037 self.push(Value::Object(array));
12038 }
12039 Append => {
12040 // `array index iterable -> array new_index`
12041 let iterable = self.pop();
12042 self.pop();
12043 let array = self.peek(0);
12044 let added = self.append_enumerate(&array, &iterable)?;
12045 self.push(Value::Int(added));
12046 }
12047
12048 // -- iteration --------------------------------------------------
12049 ForInStart => {
12050 let value = self.pop();
12051 let record = self.for_in_record(&value)?;
12052 self.push(Value::Object(record));
12053 }
12054 ForInNext => {
12055 // `record -> record key done`. The flag is *done*, not "found":
12056 // the compiler tests it with `if_false` to jump back into the body,
12057 // so reporting `true` while keys remain would end the loop at once.
12058 let record = self.peek(0);
12059 match self.for_in_advance(&record)? {
12060 Some(key) => {
12061 let text = self.string(key);
12062 self.push(text);
12063 self.push(Value::Bool(false));
12064 }
12065 None => {
12066 self.push(Value::Undefined);
12067 self.push(Value::Bool(true));
12068 }
12069 }
12070 }
12071 ForOfStart => {
12072 let value = self.pop();
12073 let iterator = self.get_iterator(&value)?;
12074 self.push(iterator.object);
12075 self.push(iterator.next);
12076 self.push(Value::CatchOffset(0));
12077 }
12078 ForOfNext => {
12079 // `iter next catch_offset -> iter next catch_offset value done`.
12080 //
12081 // The operand is how many values sit *above* the iterator triple: a
12082 // destructuring rest element keeps its target array and running index
12083 // there while draining the iterator, so the triple is not at the top.
12084 let extra = a as usize;
12085 let iterator_slot = 2 + extra;
12086 // An exhausted iterator is replaced by `undefined` (see below), so a
12087 // second step must not call `next` again — `Array.from` and a
12088 // destructuring pattern both keep stepping past the end.
12089 let stepped = if matches!(self.peek(iterator_slot), Value::Undefined) {
12090 Ok((Value::Undefined, true))
12091 } else {
12092 let iterator = Iterator {
12093 object: self.peek(iterator_slot),
12094 next: self.peek(1 + extra),
12095 };
12096 self.iterator_step(&iterator)
12097 };
12098 let (value, done) = match stepped {
12099 Ok(stepped) => stepped,
12100 Err(signal) => {
12101 // An exception from `next()` is not an abrupt completion of the
12102 // *body*, so §7.4.6 does not apply and the iterator must not be
12103 // closed: `[ , ] = iterable` with a throwing `next` expects
12104 // `returnCount === 0`. Clearing the slot is how the reference says
12105 // so (`js_for_of_next`: `sp[offset] = JS_UNDEFINED` before it
12106 // returns -1), and it is also what makes the destructor below — the
12107 // exception path's `catch_offset 0` close — a no-op here.
12108 self.clear_iterator_slot(iterator_slot);
12109 return Err(signal);
12110 }
12111 };
12112 if done {
12113 // The result's `value` is meaningless once the iterator is done:
12114 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
12115 // rather than binding the generator's return value.
12116 let top = self.frame().stack.len() - 1 - iterator_slot;
12117 self.frame_mut().stack[top] = Value::Undefined;
12118 self.push(Value::Undefined);
12119 self.push(Value::Bool(true));
12120 } else {
12121 self.push(value);
12122 self.push(Value::Bool(false));
12123 }
12124 }
12125 IteratorNext => {
12126 // `iter next catch val -> iter next catch val'`: replace the argument with
12127 // the result of `next(val)`. The triple below stays put, which is why the
12128 // three instructions of the `yield*` loop all address the stack the same way.
12129 let value = self.pop();
12130 let object = self.peek(2);
12131 let next = self.peek(1);
12132 let result = self.call_value(next, object, vec![value])?;
12133 self.push(result);
12134 }
12135 IteratorCall => {
12136 // `iter next catch val -> iter next catch val' flag`.
12137 //
12138 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
12139 // The flag is `true` when the method was missing, which is how the
12140 // caller learns that the inner iterator cannot take part in the
12141 // unwinding.
12142 let value = self.pop();
12143 let object = self.peek(2);
12144 let key = if a & 1 != 0 { "throw" } else { "return" };
12145 let method = self.read_field(&object, key)?;
12146 if matches!(method, Value::Undefined | Value::Null) {
12147 self.push(value);
12148 self.push(Value::Bool(true));
12149 } else {
12150 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
12151 let result = self.call_value(method, object, argument)?;
12152 self.push(result);
12153 self.push(Value::Bool(false));
12154 }
12155 }
12156 IteratorCheckObject => {
12157 if !matches!(self.peek(0), Value::Object(_)) {
12158 return Err(Signal::Throw(
12159 self.make_error("TypeError", "iterator must return an object"),
12160 ));
12161 }
12162 }
12163 IteratorClose => {
12164 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
12165 // calling the iterator's `return` so it can release whatever it holds.
12166 //
12167 // The catch offset goes first, so an exception from `return` is not caught
12168 // by the loop being abandoned. This used to pop the three operands and call
12169 // nothing at all, which made `break` out of a `for of` invisible to an
12170 // iterator with a `return` method.
12171 self.pop();
12172 self.pop();
12173 let iterator = self.pop();
12174 if !matches!(iterator, Value::Undefined) {
12175 let method = self.read_field(&iterator, "return")?;
12176 if !matches!(method, Value::Undefined | Value::Null) {
12177 let result = self.call_value(method, iterator.clone(), Vec::new())?;
12178 // §7.4.6: a `return` that answers a non-object is a TypeError.
12179 if !matches!(result, Value::Object(_)) {
12180 return Err(Signal::Throw(
12181 self.make_error("TypeError", "iterator must return an object"),
12182 ));
12183 }
12184 }
12185 }
12186 }
12187 Import => {
12188 // `import(specifier, options)`: the options slot is on top. Both are
12189 // `GetValue`-ed by the compiler, which is why this pops values rather than
12190 // references — and why the validation of `options` (§13.3.10.1 step 10)
12191 // happens inside `dynamic_import`, where its failures can be turned into a
12192 // rejection instead of a throw.
12193 let options = self.pop();
12194 let specifier = self.pop();
12195 let promise = self.dynamic_import(specifier, options)?;
12196 self.push(promise);
12197 }
12198 ForAwaitOfStart => {
12199 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
12200 // `Symbol.iterator` fallback.
12201 let value = self.pop();
12202 let iterator = self.get_async_iterator(&value)?;
12203 self.push(iterator.object);
12204 self.push(iterator.next);
12205 self.push(Value::CatchOffset(0));
12206 }
12207 ForAwaitOfNext => {
12208 // `for await` steps the iterator and leaves the *result* wrapped in a
12209 // promise, so the `await` the compiler emits right after this can suspend
12210 // on it. Unwrapping happens in `iterator_get_value_done`.
12211 let extra = a as usize;
12212 let iterator_slot = 2 + extra;
12213 // The enumerator marker is **disabled for the step**, and
12214 // `iterator_get_value_done` puts it back once the result has survived the
12215 // awaiting. Both halves are load-bearing for the async case:
12216 //
12217 // * a rejection is not "the body threw", so the loop must not close the
12218 // iterator *again* — the wrapper already did;
12219 // * but until the result arrives the record is live, so a later failure
12220 // still has to close it.
12221 //
12222 // The reference says the same in one line each
12223 // (`js_for_await_of_next`: `sp[-1] = JS_UNDEFINED; /* disable the catch
12224 // offset so that exceptions do not close the iterator */`).
12225 self.clear_iterator_slot(extra);
12226 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
12227 Value::Undefined
12228 } else {
12229 let iterator = Iterator {
12230 object: self.peek(iterator_slot),
12231 next: self.peek(1 + extra),
12232 };
12233 let next = iterator.next.clone();
12234 self.call_value(next, iterator.object, Vec::new())?
12235 };
12236 let promise = self.promise_resolve_value(result)?;
12237 self.push(promise);
12238 }
12239 IteratorGetValueDone => {
12240 // `result -> value done`. A missing result object means the iterator was
12241 // already exhausted, which the loop treats as `done`.
12242 let result = self.pop();
12243 // Re-arm the marker `for_await_of_next` disabled; the step got this far, so
12244 // from here on the record is closeable again.
12245 {
12246 let depth = self.frame().stack.len();
12247 if depth >= 2 {
12248 self.frame_mut().stack[depth - 1] = Value::CatchOffset(0);
12249 }
12250 }
12251 let done = match &result {
12252 Value::Object(object) => self
12253 .get_property(object, "done")?
12254 .is_some_and(|value| value.to_boolean()),
12255 _ => true,
12256 };
12257 if done {
12258 // Clear the iterator object so the `iterator_close` the loop emits on
12259 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
12260 // on normal completion, and this is where a normal completion is
12261 // recognised — the same trick `for_of_next` uses, which also replaces
12262 // the slot with `undefined`.
12263 //
12264 // The layout is fixed because only `for await` emits this opcode:
12265 // `iter next catch [result]`, so the iterator is three below the top.
12266 let depth = self.frame().stack.len();
12267 if depth >= 3 {
12268 self.frame_mut().stack[depth - 3] = Value::Undefined;
12269 }
12270 self.push(Value::Undefined);
12271 self.push(Value::Bool(true));
12272 } else {
12273 let Value::Object(object) = &result else {
12274 self.push(Value::Undefined);
12275 self.push(Value::Bool(true));
12276 return Ok(Step::Continue);
12277 };
12278 let value = self
12279 .get_property(object, "value")?
12280 .unwrap_or(Value::Undefined);
12281 self.push(value);
12282 self.push(Value::Bool(false));
12283 }
12284 }
12285
12286 Delete => {
12287 // `delete obj[key]`, where the key was just pushed. Deleting an array
12288 // index leaves a *hole* rather than closing the gap, and a
12289 // non-configurable property answers `false` and stays.
12290 let key = self.pop();
12291 let target = self.pop();
12292 let key = self.propkey(&key)?;
12293 let text_label = key.as_str().unwrap_or("").to_string();
12294 let deleted = match &target {
12295 Value::Object(object) => {
12296 let object = object.clone();
12297 self.delete_property_key(&object, &key)?
12298 }
12299 // A string's `length` and its index properties are
12300 // non-configurable, so deleting one answers `false`.
12301 Value::String(text) => {
12302 !(text_label == "length"
12303 || array_index(&text_label)
12304 .is_some_and(|index| (index as usize) < text.utf16_len()))
12305 }
12306 // "delete null.a" is a TypeError, not a no-op: the operator needs an
12307 // object to delete from, and only a *boxable* primitive has one.
12308 Value::Undefined | Value::Null => {
12309 return Err(Signal::Throw(
12310 self.make_error("TypeError", "cannot convert to object"),
12311 ));
12312 }
12313 // Any other primitive has no own properties; deleting nothing
12314 // succeeds.
12315 _ => true,
12316 };
12317 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
12318 // `TypeError` rather than a `false` result. Sloppy mode silently reports
12319 // the refusal, which is why the same statement throws here but not there.
12320 if !deleted && self.current_strict() {
12321 return Err(Signal::Throw(
12322 self.make_error("TypeError", "cannot delete property"),
12323 ));
12324 }
12325 self.push(Value::Bool(deleted));
12326 }
12327
12328 // -- exceptions and bookkeeping ---------------------------------
12329 Fclosure | Fclosure8 => {
12330 let value = self.closure(a as usize)?;
12331 self.push(value);
12332 }
12333
12334 other => {
12335 let name = other.info().name;
12336 return Err(Signal::Throw(self.make_error(
12337 "InternalError",
12338 &format!("{name} is not implemented yet"),
12339 )));
12340 }
12341 }
12342 Ok(Step::Continue)
12343 }
12344
12345 // -- operand helpers ----------------------------------------------------
12346
12347 /// The slot index an operand names, taking short forms into account.
12348 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
12349 use Opcode::*;
12350 match op {
12351 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
12352 | SetVarRef0 => 0,
12353 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
12354 | SetVarRef1 => 1,
12355 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
12356 | SetVarRef2 => 2,
12357 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
12358 | SetVarRef3 => 3,
12359 _ => a as usize,
12360 }
12361 }
12362
12363 /// The argument count of a call, taking `call0`…`call3` into account.
12364 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
12365 use Opcode::*;
12366 match op {
12367 Call0 => 0,
12368 Call1 => 1,
12369 Call2 => 2,
12370 Call3 => 3,
12371 _ => a as usize,
12372 }
12373 }
12374
12375 /// The atom's name as a property key.
12376 ///
12377 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
12378 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
12379 /// `String::clone` was a heap allocation and a copy — per property access.
12380 /// The atom at `index`, as a property key.
12381 ///
12382 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
12383 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
12384 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
12385 /// 5.3% of `property:monomorphic`.
12386 /// The atom's text, exactly — including an unpaired surrogate.
12387 ///
12388 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
12389 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
12390 /// `atom_text` below is for the other kind of use, where the atom is a key in the
12391 /// engine's own tables.
12392 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
12393 self.frame()
12394 .code
12395 .code
12396 .atoms
12397 .get(index)
12398 .map(|atom| match atom {
12399 Atom::Str(text) => text.clone(),
12400 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
12401 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
12402 Atom::Null => crate::value::Wtf8::new(String::new()),
12403 })
12404 .unwrap_or_default()
12405 }
12406
12407 fn atom_text(&self, index: usize) -> String {
12408 self.frame()
12409 .code
12410 .code
12411 .atoms
12412 .get(index)
12413 .map(|atom| match atom {
12414 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
12415 // compare it to an identifier, and a surrogate-bearing name is reachable
12416 // through `atom_wtf8` where it matters.
12417 Atom::Str(text) => text.to_string_lossy().into_owned(),
12418 Atom::Index(value) => value.to_string(),
12419 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
12420 // `throw_error`, `delete super.x`) never read it.
12421 Atom::Null => String::new(),
12422 })
12423 .unwrap_or_default()
12424 }
12425
12426 fn constant(&mut self, index: usize) -> JsResult<Value> {
12427 let constant = self.frame().code.code.cpool.get(index).cloned();
12428 Ok(match &constant {
12429 Some(Constant::Number(number)) => Value::Float(*number),
12430 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
12431 Some(Constant::BigInt { digits, radix }) => {
12432 match crate::bigint::BigInt::from_radix(digits, *radix) {
12433 Some(big) => self.bigint(big),
12434 // A literal the parser accepted is always parseable; a failure here
12435 // would be a compiler bug, so it reads as an `InternalError`.
12436 None => {
12437 return Err(Signal::Throw(
12438 self.make_error("InternalError", "unparseable bigint literal"),
12439 ));
12440 }
12441 }
12442 }
12443 Some(Constant::Function(_)) => {
12444 return Err(Signal::Throw(
12445 self.make_error("InternalError", "a bare function constant"),
12446 ));
12447 }
12448 // A tagged template's call site: a frozen array of the cooked chunks with a
12449 // frozen `raw` array beside it, which is what `String.raw` reads back.
12450 Some(Constant::Template { cooked, raw }) => {
12451 let cooked_values: Vec<Value> = cooked
12452 .iter()
12453 .map(|chunk| match chunk {
12454 Some(text) => self.string_wtf8(text.clone()),
12455 None => Value::Undefined,
12456 })
12457 .collect();
12458 let raw_values: Vec<Value> =
12459 raw.iter().map(|text| self.string(text.clone())).collect();
12460 let raw_array = self.new_array(raw_values);
12461 raw_array.set_extensible(false);
12462 let template = self.new_array(cooked_values);
12463 template.define(
12464 "raw",
12465 Property::with_attributes(Value::Object(raw_array), false, false),
12466 );
12467 template.set_extensible(false);
12468 Value::Object(template)
12469 }
12470 _ => Value::Undefined,
12471 })
12472 }
12473
12474 /// The reference cell a closure-variable slot names.
12475 ///
12476 /// Two kinds of binding share this addressing: a genuine closure variable
12477 /// (captured from an enclosing function) lives in this frame's environment,
12478 /// while a *declared global* lives in the realm so that a script, a function
12479 /// declaration and their uses all see one binding. A plain `Global` — an
12480 /// undeclared name that may be satisfied by the global object — has no cell at
12481 /// all, which is how `typeof x` still works for a name that does not exist.
12482 /// The reference cell a closure-variable slot names.
12483 ///
12484 /// The environment is resolved once, when the closure is built, and this is
12485 /// just the lookup afterwards. A *declared global* is in there too, pointing at
12486 /// the realm's cell, so a script, a hoisted function declaration and their uses
12487 /// all share one binding. A plain `Global` — a name the script never declared —
12488 /// is read and written through `get_var`/`put_var` by name instead, which is
12489 /// what lets the global object satisfy it.
12490 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
12491 self.frame().env.cells.get(slot).cloned()
12492 }
12493
12494 /// Whether `slot` refers to a global binding through the reference table.
12495 ///
12496 /// A global's cell in the closure environment only exists so the slot has
12497 /// something to point at; the binding itself lives on the global object (a `var`)
12498 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
12499 /// be routed, not performed on the placeholder.
12500 fn is_global_slot(&self, slot: usize) -> bool {
12501 self.frame()
12502 .code
12503 .code
12504 .closure_vars
12505 .get(slot)
12506 .is_some_and(|c| {
12507 // A module's declarations and imports are *not* globals: their cells are
12508 // the module environment's, filled by the host, so the placeholder routing
12509 // must not apply to them.
12510 matches!(
12511 c.closure_type,
12512 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
12513 )
12514 })
12515 }
12516
12517 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
12518 if self.is_global_slot(slot) {
12519 return self.get_global(slot);
12520 }
12521 Ok(self
12522 .var_ref_cell(slot)
12523 .map(|cell| cell.get())
12524 .unwrap_or(Value::Undefined))
12525 }
12526
12527 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
12528 // A function declaration is hoisted by storing into a global reference before
12529 // the body runs, so this path is also what puts it on the global object.
12530 if self.is_global_slot(slot) {
12531 return self.put_global(slot, value);
12532 }
12533 if let Some(cell) = self.var_ref_cell(slot) {
12534 cell.set(value);
12535 }
12536 Ok(())
12537 }
12538
12539 // -- closures -----------------------------------------------------------
12540
12541 /// Build the closure for the function constant `index`.
12542 ///
12543 /// Every entry in the child's closure table names where its binding lives in
12544 /// *this* frame: a local or argument slot that was marked captured, or a cell
12545 /// this frame is itself holding. That is how a variable three functions deep
12546 /// stays one binding.
12547 fn closure(&mut self, index: usize) -> JsResult<Value> {
12548 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
12549 else {
12550 return Err(Signal::Throw(
12551 self.make_error("InternalError", "fclosure of a non-function"),
12552 ));
12553 };
12554 let mut cells = Vec::with_capacity(function.closure_vars.len());
12555 for closure_var in &function.closure_vars {
12556 let cell = match closure_var.closure_type {
12557 ClosureType::Arg => {
12558 let slot = closure_var.var_idx as usize;
12559 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
12560 }
12561 ClosureType::Local => {
12562 let slot = closure_var.var_idx as usize;
12563 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
12564 }
12565 ClosureType::Ref | ClosureType::GlobalRef => {
12566 // A `Ref` names a cell in this frame's own closure table; a
12567 // `GlobalRef` also starts there, then resolves by name below.
12568 let slot = closure_var.var_idx as usize;
12569 if let Some(cell) = self.frame().env.cells.get(slot) {
12570 cells.push(cell.clone());
12571 continue;
12572 }
12573 -1
12574 }
12575 _ => -1,
12576 };
12577 if cell >= 0 {
12578 let cell = self.frame().cells[cell as usize].clone();
12579 cells.push(cell);
12580 continue;
12581 }
12582 // A global: the cell is created on demand and shared through the realm,
12583 // so every function sees one binding.
12584 let name = closure_var.name.clone();
12585 let cell = match self.realm.globals.get(&name) {
12586 Some(cell) => cell.clone(),
12587 None => {
12588 let cell = self.new_cell(Value::Undefined);
12589 self.realm.globals.insert(name.clone(), cell.clone());
12590 cell
12591 }
12592 };
12593 cells.push(cell);
12594 }
12595 let name = function.name.clone();
12596 // `.length` is the arity before any default or rest parameter, not the number
12597 // of slots a pattern parameter needs.
12598 let length = function.defined_args;
12599 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
12600 // function and an arrow function do not. A *method* also does not, but that is not
12601 // known here — the method is marked when the `[[HomeObject]]` is attached (see
12602 // `set_home_object`), which is the moment it becomes a method.
12603 let function_kind = function.kind;
12604 let constructible =
12605 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
12606 let code = Gc::new(self.heap, CompiledCode::new(*function));
12607 // A closure built inside an `eval` inherits the eval's view of the enclosing
12608 // bindings, so it can still read them once the eval has returned.
12609 let eval_scope = self
12610 .active_eval_scope
12611 .clone()
12612 .or_else(|| self.frame().env.eval_scope.clone());
12613 // A closure sees the variables a direct `eval` declared in the frame it was
12614 // created in — the ones declared before *and after* it, so the same object is
12615 // shared; only the phase bounds which of them are visible.
12616 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
12617 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
12618 let env = Gc::new(
12619 self.heap,
12620 ClosureEnv {
12621 cells,
12622 eval_scope,
12623 local_vars,
12624 local_phase,
12625 },
12626 );
12627 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
12628 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
12629 // the only thing that carries `Symbol.toStringTag`, so without it
12630 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
12631 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
12632 let proto = match function_kind {
12633 js_compile::bytecode::FunctionKind::AsyncGenerator => self
12634 .realm
12635 .async_generator_function_proto
12636 .clone()
12637 .or_else(|| self.realm.function_proto.clone().into()),
12638 js_compile::bytecode::FunctionKind::Generator => self
12639 .realm
12640 .generator_function_proto
12641 .clone()
12642 .or_else(|| self.realm.function_proto.clone().into()),
12643 js_compile::bytecode::FunctionKind::Async => self
12644 .realm
12645 .async_function_proto
12646 .clone()
12647 .or_else(|| self.realm.function_proto.clone().into()),
12648 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
12649 };
12650 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
12651 object.set_constructible(constructible);
12652 object.define(
12653 "length",
12654 Property::name_or_length(Value::Int(length as i32)),
12655 );
12656 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
12657 // that checks the own-property descriptor fails if the property is missing.
12658 object.define("name", Property::name_or_length(self.string(name)));
12659 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
12660 // when `[[Construct]]` is created, so an async function and an arrow function have
12661 // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
12662 // function) an own `prototype` property, which `builtin.js` checks for absence.
12663 //
12664 // A **generator** function is the exception that is not constructible: it still
12665 // gets a `prototype` field, because that object is what a generator *instance*
12666 // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
12667 // made `function* g(){}; g.prototype` `undefined` and every generator share
12668 // `%GeneratorPrototype%` as its direct prototype.
12669 if constructible {
12670 self.install_function_prototype(&object);
12671 } else if matches!(
12672 function_kind,
12673 js_compile::bytecode::FunctionKind::Generator
12674 | js_compile::bytecode::FunctionKind::AsyncGenerator
12675 ) {
12676 let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
12677 self.realm.generator_proto.clone()
12678 } else {
12679 self.realm
12680 .async_generator_proto
12681 .clone()
12682 .unwrap_or_else(|| self.realm.generator_proto.clone())
12683 };
12684 self.install_generator_prototype(&object, parent);
12685 }
12686 Ok(Value::Object(object))
12687 }
12688
12689 // -- conversions used by the operators ----------------------------------
12690
12691 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
12692 // `+x` is `ToNumber`, which for a string parses it and for an object runs
12693 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
12694 // string, which then behaves differently in every later comparison.
12695 match value {
12696 Value::Int(_) | Value::Float(_) => Ok(value),
12697 other => Ok(Value::Float(self.to_js_number(&other)?)),
12698 }
12699 }
12700
12701 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
12702 ///
12703 /// Returns the *converted* old value and the new one, because the two callers need
12704 /// different halves: `++x` yields the new value, while `x++` yields the old one and
12705 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
12706 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
12707 /// boolean.
12708 ///
12709 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
12710 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
12711 /// a bigint algorithm then ran exactly once.
12712 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
12713 if let Value::BigInt(big) = &value {
12714 let one = crate::bigint::BigInt::from_i64(1);
12715 let next = if up { big.add(&one) } else { big.sub(&one) };
12716 return Ok((value, self.bigint(next)));
12717 }
12718 let old = self.numeric(value)?;
12719 let new = if up {
12720 increment(old.clone())
12721 } else {
12722 decrement(old.clone())
12723 };
12724 Ok((old, new))
12725 }
12726
12727 fn numeric(&mut self, value: Value) -> JsResult<Value> {
12728 // `ToNumber` on an object runs `ToPrimitive` first, which is how
12729 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
12730 // heard at all. Reading the object's own tag instead (`other.to_number()`)
12731 // turned the whole operand into `NaN` and swallowed the exception.
12732 match value {
12733 Value::Int(_) | Value::Float(_) => Ok(value),
12734 other => Ok(Value::Float(self.to_js_number(&other)?)),
12735 }
12736 }
12737
12738 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
12739 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
12740 match value {
12741 Value::BigInt(big) => Ok((**big).clone()),
12742 // The reference words this the same way for every operator, so a failing
12743 // script reads identically; the operator itself adds nothing a caller can use.
12744 _ => Err(Signal::Throw(
12745 self.make_error("TypeError", "cannot convert bigint to number"),
12746 )),
12747 }
12748 }
12749
12750 /// Arithmetic where at least one operand is a `BigInt`.
12751 ///
12752 /// The two numeric types never mix, so a bigint paired with anything else is an error
12753 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
12754 /// that the relational operators handle it separately.
12755 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12756 use Opcode::*;
12757 let a = self.bigint_operand(&left)?;
12758 let b = self.bigint_operand(&right)?;
12759 let result = match op {
12760 Add => a.add(&b),
12761 Sub => a.sub(&b),
12762 Mul => a.mul(&b),
12763 Div | Mod => {
12764 let Some((quotient, remainder)) = a.div_rem(&b) else {
12765 return Err(Signal::Throw(
12766 self.make_error("RangeError", "division by zero"),
12767 ));
12768 };
12769 if op == Div { quotient } else { remainder }
12770 }
12771 Pow => {
12772 let Some(value) = a.pow(&b) else {
12773 return Err(Signal::Throw(self.make_error(
12774 "RangeError",
12775 "BigInt exponent must be non-negative and not absurdly large",
12776 )));
12777 };
12778 value
12779 }
12780 And => a.bitand(&b),
12781 Or => a.bitor(&b),
12782 Xor => a.bitxor(&b),
12783 Shl | Sar => {
12784 // A shift count is a `BigInt` here, and both directions are exact; a
12785 // negative count would be the other direction, which the spec forbids.
12786 let Some(count) = b.to_i64() else {
12787 return Err(Signal::Throw(
12788 self.make_error("RangeError", "BigInt shift count is too large"),
12789 ));
12790 };
12791 if count < 0 {
12792 return Err(Signal::Throw(self.make_error(
12793 "RangeError",
12794 "BigInt shift count must be non-negative",
12795 )));
12796 }
12797 if op == Shl {
12798 a.shl(count as u64)
12799 } else {
12800 a.shr(count as u64)
12801 }
12802 }
12803 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
12804 _ => {
12805 return Err(Signal::Throw(self.make_error(
12806 "TypeError",
12807 "BigInts have no unsigned right shift, use >> instead",
12808 )));
12809 }
12810 };
12811 Ok(self.bigint(result))
12812 }
12813
12814 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
12815 ///
12816 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
12817 /// is on the mathematical values, and nothing is rounded first.
12818 /// `<`, `<=`, `>`, `>=`.
12819 ///
12820 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
12821 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
12822 /// It is a `?`-returning function for exactly that reason: an object operand can run
12823 /// script, and script can throw. The old version compared `to_number` of the raw
12824 /// values, which answered `false` for every object instead of calling `valueOf` —
12825 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
12826 /// never ran.
12827 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12828 // The hot arm first: `i < n` with both sides already integers. No conversion, no
12829 // call, nothing that can throw.
12830 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12831 let ordering = Some(left.cmp(right));
12832 return Ok(ordering_answer(op, ordering));
12833 }
12834 // Anything that can run script has to be converted first, in this order.
12835 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
12836 {
12837 (
12838 self.to_primitive(left, Hint::Number)?,
12839 self.to_primitive(right, Hint::Number)?,
12840 )
12841 } else {
12842 (left, right)
12843 };
12844 let ordering = match (&left, &right) {
12845 // The loop condition `i < n` is integer against integer, and it runs once
12846 // per iteration of every loop in every program. Without this arm it took the
12847 // `to_number` path twice, which is a `match` plus a conversion each.
12848 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
12849 (Value::String(a), Value::String(b)) => {
12850 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
12851 }
12852 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
12853 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
12854 // is true even though `2.5` has no bigint form.
12855 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
12856 let b = other.to_number();
12857 if b.is_nan() {
12858 None
12859 } else {
12860 compare_bigint_and_f64(a, b)
12861 }
12862 }
12863 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
12864 let a = other.to_number();
12865 if a.is_nan() {
12866 None
12867 } else {
12868 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
12869 }
12870 }
12871 // `ToNumeric` on the pair, which refuses a Symbol rather than answering `NaN`:
12872 // `Object(Symbol()) <= ""` is a `TypeError`, and the total `to_number` made it
12873 // `false` (`Symbol/prototype/Symbol.toPrimitive/…-ordinary-toprimitive`).
12874 _ => self
12875 .to_js_number(&left)?
12876 .partial_cmp(&self.to_js_number(&right)?),
12877 };
12878 Ok(ordering_answer(op, ordering))
12879 }
12880
12881 fn binary_add(&mut self) -> JsResult<()> {
12882 let right = self.pop();
12883 let left = self.pop();
12884 // Two integers add without any of the machinery below: no `ToPrimitive` (an
12885 // `Int` is already primitive), no string check, no bigint check, no allocation.
12886 // `x += 1` in a loop is the single most common instruction sequence in real
12887 // script, and it used to walk every one of those checks before reaching the
12888 // same `checked_add`.
12889 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12890 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
12891 return Ok(());
12892 }
12893 let left = self.primitive_of(left)?;
12894 let right = self.primitive_of(right)?;
12895 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
12896 // that check comes before the bigint one: `"" + 1n` is a string, not a
12897 // mixed-type error.
12898 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
12899 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
12900 // `TypeError`, the one place a symbol and a string do not mix.
12901 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
12902 // between a copy and a rope from their lengths, and a rope is what turns
12903 // `text += "abc"` in a loop from quadratic into linear.
12904 if let (Value::String(left), Value::String(right)) = (&left, &right) {
12905 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
12906 // reports as `InternalError: string too long`.
12907 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
12908 return Err(Signal::Throw(
12909 self.make_error("InternalError", "string too long"),
12910 ));
12911 };
12912 self.push(Value::String(Gc::new(self.heap, joined)));
12913 return Ok(());
12914 }
12915 // At least one operand was not a string, so `ToString` it. This rejects a
12916 // symbol, which is the one place a symbol and a string do not mix.
12917 let left = self.checked_to_wtf8(&left)?;
12918 let right = self.checked_to_wtf8(&right)?;
12919 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
12920 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
12921 let text = left.concat(&right);
12922 self.push(self.string_wtf8(text));
12923 return Ok(());
12924 }
12925 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
12926 // not a conversion.
12927 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
12928 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
12929 self.push(value);
12930 return Ok(());
12931 }
12932 let left = self.numeric(left)?;
12933 let right = self.numeric(right)?;
12934 self.push(add_numbers(left, right));
12935 Ok(())
12936 }
12937
12938 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
12939 self.to_primitive(value, Hint::Default)
12940 }
12941
12942 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
12943 ///
12944 /// The order depends on the hint: the "number" order tries `valueOf` first and
12945 /// `toString` second, the "string" order the other way round, and the default
12946 /// hint uses the number order. A result that is still an object is a `TypeError`,
12947 /// because no built-in `valueOf`/`toString` returns one.
12948 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
12949 let Value::Object(object) = &value else {
12950 return Ok(value);
12951 };
12952 // A Date overrides the default hint to mean "string", which is what
12953 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
12954 // this, `"" + new Date()` would print the milliseconds, not the date.
12955 let hint = if hint == Hint::Default && is_date_object(self, object) {
12956 Hint::String
12957 } else {
12958 hint
12959 };
12960 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
12961 // handed the hint as a string. This is the hook a Date uses for its default hint
12962 // and a script uses to take over conversion entirely.
12963 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
12964 // `GetMethod`, not "is it a callable object": the property has to be read and then
12965 // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
12966 // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
12967 // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
12968 // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
12969 // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
12970 // callable.
12971 match self.get_property_key(object, &key)? {
12972 None | Some(Value::Undefined) | Some(Value::Null) => {}
12973 Some(Value::Object(function)) if function.is_callable() => {
12974 let hint = match hint {
12975 Hint::String => "string",
12976 Hint::Number => "number",
12977 Hint::Default => "default",
12978 };
12979 let hint = self.string(hint);
12980 let result = self.call_value(
12981 Value::Object(function),
12982 Value::Object(object.clone()),
12983 vec![hint],
12984 )?;
12985 if !matches!(result, Value::Object(_)) {
12986 return Ok(result);
12987 }
12988 return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
12989 }
12990 Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
12991 }
12992 let order: [&str; 2] = match hint {
12993 Hint::String => ["toString", "valueOf"],
12994 Hint::Number | Hint::Default => ["valueOf", "toString"],
12995 };
12996 let receiver = object.clone();
12997 for method in order {
12998 if let Some(function) = self.get_property(&receiver, method)?
12999 && matches!(&function, Value::Object(object) if object.is_callable())
13000 {
13001 let result =
13002 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
13003 if !matches!(result, Value::Object(_)) {
13004 return Ok(result);
13005 }
13006 }
13007 }
13008 Err(self.type_error("cannot convert object to primitive value"))
13009 }
13010
13011 /// `ToString` with the object case going through `ToPrimitive`.
13012 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
13013 if matches!(value, Value::Object(_)) {
13014 let primitive = self.to_primitive(value.clone(), Hint::String)?;
13015 return Ok(primitive.to_js_string());
13016 }
13017 // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
13018 // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
13019 // callers that want that strictness call [`Interp::to_string_strict`] — putting the
13020 // check here broke `String(Symbol())` and 45 cases that print a symbol.
13021 Ok(value.to_js_string())
13022 }
13023
13024 /// `ToString(value)`, with §7.1.19's symbol refusal.
13025 ///
13026 /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
13027 /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
13028 /// operations and conflating them cost 45 cases in one direction and 6 in the other.
13029 pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
13030 if matches!(value, Value::Symbol(_)) {
13031 return Err(self.type_error("cannot convert a Symbol to a string"));
13032 }
13033 if matches!(value, Value::Object(_)) {
13034 let primitive = self.to_primitive(value.clone(), Hint::String)?;
13035 if matches!(primitive, Value::Symbol(_)) {
13036 return Err(self.type_error("cannot convert a Symbol to a string"));
13037 }
13038 return Ok(primitive.to_js_string());
13039 }
13040 Ok(value.to_js_string())
13041 }
13042
13043 /// `ToString` that keeps the string's code units instead of flattening them.
13044 ///
13045 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
13046 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
13047 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13048 if matches!(value, Value::Symbol(_)) {
13049 return Err(Signal::Throw(
13050 self.make_error("TypeError", "cannot convert symbol to string"),
13051 ));
13052 }
13053 // An object runs `ToPrimitive` first, which may itself produce a symbol.
13054 let value = self.to_primitive(value.clone(), Hint::String)?;
13055 match value {
13056 Value::Symbol(_) => Err(Signal::Throw(
13057 self.make_error("TypeError", "cannot convert symbol to string"),
13058 )),
13059 Value::String(text) => Ok(text.wtf8().clone()),
13060 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
13061 }
13062 }
13063
13064 /// `ToNumber` with the object case going through `ToPrimitive`.
13065 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
13066 let value = if matches!(value, Value::Object(_)) {
13067 self.to_primitive(value.clone(), Hint::Number)?
13068 } else {
13069 value.clone()
13070 };
13071 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
13072 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
13073 // `NaN` to stay total, and the operators check for the bigint themselves — but
13074 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
13075 // refuse, and answering `NaN` made them silently wrong instead.
13076 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
13077 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
13078 match value {
13079 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
13080 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
13081 other => Ok(other.to_number()),
13082 }
13083 }
13084
13085 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
13086 /// [`ElementType::write`].
13087 ///
13088 /// This is separated from the write because both conversions are observable script —
13089 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
13090 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
13091 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
13092 /// setters, and a plain `a[i] = v`.
13093 pub(crate) fn element_value(
13094 &mut self,
13095 element: crate::builtins::typedarray::ElementType,
13096 value: Value,
13097 ) -> JsResult<Value> {
13098 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
13099 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
13100 let primitive = match &value {
13101 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
13102 _ => value,
13103 };
13104 if element.is_bigint() {
13105 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
13106 Ok(Value::BigInt(Gc::new(self.heap, big)))
13107 } else {
13108 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
13109 Ok(Value::Float(self.to_js_number(&primitive)?))
13110 }
13111 }
13112
13113 /// `ToPropertyKey`: what a computed member access uses as its key.
13114 ///
13115 /// A symbol is returned as itself, never stringified — that is what keeps
13116 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
13117 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
13118 match value {
13119 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
13120 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
13121 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
13122 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
13123 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13124 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
13125 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
13126 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
13127 other.to_js_string(),
13128 ))),
13129 },
13130 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
13131 }
13132 }
13133
13134 /// `ToPropertyKey` for the callers that can only use a string key.
13135 ///
13136 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
13137 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
13138 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
13139 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
13140 /// program continues with a value nobody asked for.
13141 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13142 use crate::value::Wtf8;
13143 Ok(match value {
13144 // A string key keeps its code units. Going through a lossy `String` would make
13145 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
13146 Value::String(text) => text.wtf8().clone(),
13147 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
13148 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
13149 // falling back to its `ToString` would print `[object Object]`.
13150 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13151 Value::String(text) => text.wtf8().clone(),
13152 other => Wtf8::new(other.to_js_string()),
13153 },
13154 other => Wtf8::new(other.to_js_string()),
13155 })
13156 }
13157
13158 // -- object operations used by instructions -----------------------------
13159
13160 /// Read `object[key]`, returning `undefined` when the property is missing.
13161 ///
13162 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
13163 /// primitive (looking through its prototype) as well as an object — which is what
13164 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
13165 /// argument needs too.
13166 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
13167 self.read_field_key(object, &PropertyKey::from(key))
13168 }
13169
13170 /// [`Interp::read_field`] with a key that may be a symbol.
13171 ///
13172 /// A symbol key never reaches the string shortcuts: a string's `length` and its
13173 /// indices are string properties, and a symbol named `length` is a different
13174 /// property that a string primitive cannot have.
13175 /// [`Interp::read_field_key`], with an inline cache in front of it.
13176 ///
13177 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
13178 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
13179 /// without this the engine walked the chain and compared ~40 property names on each
13180 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
13181 ///
13182 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
13183 /// missing property. Those answers depend on running code or on state the guard below
13184 /// does not cover, and a wrong answer here is far more expensive than a lookup.
13185 ///
13186 /// A hit is re-validated against the *whole* walked chain, not just the level that
13187 /// answered: the receiver and every prototype down to that level must still be the same
13188 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
13189 /// property-table *lengths* — which is what catches a property appearing on an
13190 /// intermediate prototype and shadowing the cached one.
13191 pub fn read_field_cached(
13192 &mut self,
13193 object: &Value,
13194 key: &PropertyKey,
13195 slot: usize,
13196 ) -> JsResult<Value> {
13197 let index = Self::field_cache_slot(object, key, slot);
13198 let Value::Object(target) = object else {
13199 return self.read_field_key(object, key);
13200 };
13201 if target.proxy_state().is_some() {
13202 return self.read_field_key(object, key);
13203 }
13204 if let Some(cached) = &self.field_cache[index]
13205 && cached.key == *key
13206 && let Some(value) = Self::cached_hit(target, cached)
13207 {
13208 return Ok(value);
13209 }
13210 let value = self.read_field_key(object, key)?;
13211 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
13212 Ok(value)
13213 }
13214
13215 /// Whether a cache entry still describes this lookup, and if so the value.
13216 ///
13217 /// The guard is the whole point of the entry: identity plus property-table length for
13218 /// every level walked. Re-checked per level rather than once at the receiving end,
13219 /// because a shadowing property can appear anywhere along the chain.
13220 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
13221 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
13222 // starts with: a clone is a reference-count bump and a drop, and for
13223 // `property:monomorphic` every single hit takes only this arm.
13224 let (weak, len) = cached.chain[0].as_ref()?;
13225 if !target.upgrades_to(weak) {
13226 return None;
13227 }
13228 if cached.level == 0 {
13229 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
13230 return target.cached_property_at(cached.index, &cached.key, *len);
13231 }
13232 if target.props_len() != *len {
13233 return None;
13234 }
13235 let mut level = 1;
13236 let mut current = target.proto()?;
13237 loop {
13238 let (weak, len) = cached.chain[level].as_ref()?;
13239 if !current.upgrades_to(weak) || current.props_len() != *len {
13240 return None;
13241 }
13242 if level == cached.level as usize {
13243 // The level that answered: the value is only reusable while the key is
13244 // still there and still a plain data property.
13245 return current.cached_data_property(cached.index, &cached.key);
13246 }
13247 current = current.proto()?;
13248 level += 1;
13249 }
13250 }
13251
13252 /// Build a cache entry for a lookup that just went through the slow path.
13253 ///
13254 /// Records the chain only when the answer came from a plain data property at a level
13255 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
13256 /// costs the next lookup the walk it would have cost anyway.
13257 fn record_field_lookup(
13258 target: &Gc<JsObject>,
13259 key: &PropertyKey,
13260 _value: Value,
13261 ) -> Option<FieldCache> {
13262 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
13263 [None, None, None];
13264 let mut current = target.clone();
13265 for level in 0..MAX_CACHED_CHAIN {
13266 chain[level] = Some((current.downgrade(), current.props_len()));
13267 if let Some((found, _)) = current.own_property_index(key) {
13268 // `own_property_index` declines an accessor and a hole, which is exactly
13269 // the set that must not be cached.
13270 return Some(FieldCache {
13271 key: key.clone(),
13272 index: found,
13273 level: level as u8,
13274 chain,
13275 });
13276 }
13277 current = current.proto()?;
13278 }
13279 None
13280 }
13281
13282 /// Which cache slot a lookup uses.
13283 ///
13284 /// Mixes the object's address, the name and the site, so that two properties of one
13285 /// object, and one property of two objects, land in different slots — which is what lets
13286 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
13287 /// other iteration.
13288 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
13289 let mut hash = match object {
13290 Value::Object(object) => object.address(),
13291 _ => 0,
13292 };
13293 hash = hash
13294 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
13295 .rotate_left(17)
13296 .wrapping_add(key.hash_code());
13297 hash = hash.wrapping_add(site.wrapping_mul(31));
13298 // The table is a power of two, so the low bits are the slot.
13299 hash & (FIELD_CACHE_SLOTS - 1)
13300 }
13301
13302 /// Read `key` from `object`, without the inline cache.
13303 ///
13304 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
13305 /// prototype chain, while the cached form answers an own data property from memory.
13306 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
13307 let text = key.as_str().unwrap_or("");
13308 let Value::Object(object) = object else {
13309 // Reading a property of `undefined`/`null` is the classic TypeError.
13310 if object.is_nullish() {
13311 return Err(Signal::Throw(self.make_error(
13312 "TypeError",
13313 &format!("cannot read property '{key}' of {}", object.to_js_string()),
13314 )));
13315 }
13316 // A string has `length` and index access without being boxed.
13317 if let Value::String(value) = object {
13318 if text == "length" {
13319 return Ok(Value::Int(value.utf16_len() as i32));
13320 }
13321 if let Some(index) = array_index(text) {
13322 return Ok(match value.wtf8().unit_at(index as usize) {
13323 Some(unit) => self.string_wtf8(unit),
13324 None => Value::Undefined,
13325 });
13326 }
13327 }
13328 // A property of a primitive is looked up on its prototype: this is what
13329 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
13330 let prototype = match object {
13331 Value::String(_) => self.realm.string_proto.clone(),
13332 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13333 Value::Bool(_) => self.realm.boolean_proto.clone(),
13334 // A symbol's methods live on `Symbol.prototype`, reached the same way —
13335 // `sym.description` reads through the prototype, not off the symbol.
13336 Value::Symbol(_) => self.realm.symbol_proto.clone(),
13337 // …and a bigint's on `BigInt.prototype`, which is how
13338 // `(255n).toString(16)` reaches its method.
13339 Value::BigInt(_) => self.realm.bigint_proto.clone(),
13340 _ => None,
13341 };
13342 if let Some(prototype) = prototype
13343 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
13344 {
13345 return Ok(value);
13346 }
13347 return Ok(Value::Undefined);
13348 };
13349 Ok(self
13350 .get_property_key(object, key)?
13351 .unwrap_or(Value::Undefined))
13352 }
13353
13354 /// The `#name` a private symbol stands for, for error messages.
13355 ///
13356 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
13357 /// was made from.
13358 fn private_name(symbol: &Value) -> Option<String> {
13359 match symbol {
13360 Value::Symbol(symbol) if symbol.is_private() => Some(
13361 symbol
13362 .description()
13363 .map(|text| text.to_string())
13364 .unwrap_or_default(),
13365 ),
13366 _ => None,
13367 }
13368 }
13369
13370 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
13371 ///
13372 /// Every private-field opcode takes the symbol the class stored in its own scope; a
13373 /// non-symbol here would be a compiler bug, and the reference guards it with
13374 /// `JS_ThrowTypeErrorNotASymbol`.
13375 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
13376 match symbol {
13377 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
13378 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
13379 }
13380 }
13381
13382 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
13383 ///
13384 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
13385 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
13386 /// would hit if the parser did not reject it first.
13387 fn define_private_field(
13388 &mut self,
13389 object: &Value,
13390 symbol: &Value,
13391 value: Value,
13392 ) -> JsResult<()> {
13393 let key = self.private_key(symbol)?;
13394 let Some(target) = object.as_object() else {
13395 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13396 };
13397 if !target.is_extensible() {
13398 return Err(Signal::Throw(
13399 self.make_error("TypeError", "object is not extensible"),
13400 ));
13401 }
13402 if target.own_property_key(&key).is_some() {
13403 let name = Self::private_name(symbol).unwrap_or_default();
13404 return Err(Signal::Throw(self.make_error(
13405 "TypeError",
13406 &format!("private class field '{name}' already exists"),
13407 )));
13408 }
13409 target.define_data_key(&key, value);
13410 Ok(())
13411 }
13412
13413 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
13414 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
13415 let key = self.private_key(symbol)?;
13416 let Some(target) = object.as_object() else {
13417 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13418 };
13419 match target.own_property_key(&key) {
13420 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
13421 None => {
13422 let name = Self::private_name(symbol).unwrap_or_default();
13423 Err(Signal::Throw(self.make_error(
13424 "TypeError",
13425 &format!("private class field '{name}' does not exist"),
13426 )))
13427 }
13428 }
13429 }
13430
13431 /// `JS_SetPrivateField`: the store half of the same rule.
13432 fn write_private_field(
13433 &mut self,
13434 object: &Value,
13435 symbol: &Value,
13436 value: Value,
13437 ) -> JsResult<()> {
13438 let key = self.private_key(symbol)?;
13439 let Some(target) = object.as_object() else {
13440 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13441 };
13442 if target.write_value_key(&key, value) {
13443 return Ok(());
13444 }
13445 let name = Self::private_name(symbol).unwrap_or_default();
13446 Err(Signal::Throw(self.make_error(
13447 "TypeError",
13448 &format!("private class field '{name}' does not exist"),
13449 )))
13450 }
13451
13452 /// The `in` half: does `object` have this private field?
13453 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
13454 ///
13455 /// The symbol is created once per class — the first `add_brand` on a given home object
13456 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
13457 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
13458 /// emit for the *instance* brand passes null because all it wants is the symbol.
13459 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
13460 let Some(home_object) = home.as_object() else {
13461 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13462 };
13463 let symbol = match home_object.private_brand() {
13464 Some(symbol) => symbol,
13465 None => {
13466 let symbol = Gc::new(
13467 self.heap,
13468 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
13469 );
13470 home_object.set_private_brand(symbol.clone());
13471 symbol
13472 }
13473 };
13474 let Some(target) = object.as_object() else {
13475 // Not an object: nothing to brand. The reference does the same, and `undefined`
13476 // here would otherwise turn a field initialiser into a TypeError.
13477 return Ok(());
13478 };
13479 if !target.is_extensible() {
13480 return Err(Signal::Throw(
13481 self.make_error("TypeError", "object is not extensible"),
13482 ));
13483 }
13484 if target.carries_brand(&symbol) {
13485 return Err(Signal::Throw(
13486 self.make_error("TypeError", "private method is already present"),
13487 ));
13488 }
13489 target.add_brand(symbol);
13490 Ok(())
13491 }
13492
13493 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
13494 ///
13495 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
13496 /// decides whether to throw.
13497 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
13498 let Some(function) = function.as_object() else {
13499 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13500 };
13501 let Some(home) = function.home_object() else {
13502 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13503 };
13504 let Some(brand) = home.private_brand() else {
13505 return Err(Signal::Throw(
13506 self.make_error("TypeError", "expecting <brand> private field"),
13507 ));
13508 };
13509 Ok(object.carries_brand(&brand))
13510 }
13511
13512 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
13513 let Value::Object(object) = object else {
13514 // `PutValue` on a property of a primitive is a silent no-op in sloppy mode and a
13515 // `TypeError` in strict mode: `sym.a = 1` on a Symbol must leave `sym.a`
13516 // `undefined` rather than throwing (`Symbol/auto-boxing-non-strict`). `null` and
13517 // `undefined` still throw, with their own message.
13518 if !self.current_strict() && !matches!(object, Value::Null | Value::Undefined) {
13519 return Ok(());
13520 }
13521 return Err(Signal::Throw(self.make_error(
13522 "TypeError",
13523 &format!("cannot set property '{key}' of {}", object.to_js_string()),
13524 )));
13525 };
13526 // The write half of the property inline cache, in effect: an own, writable,
13527 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
13528 // decide — no prototype walk (an own property shadows the chain before a setter
13529 // there could matter), no extensibility check (the object already has the key),
13530 // and no `[[DefineOwnProperty]]`.
13531 //
13532 // `this.value = …` inside a method is the whole write side of
13533 // `property:method-call`, and it was reaching `set_property_with_key` with its
13534 // proxy test, its typed-array test, its array-index test and finally a linear
13535 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
13536 //
13537 // Every disqualifier is checked here: a proxy traps the set, an array index and
13538 // `length` live outside the property table, and a typed array's element is stored
13539 // through its view's element type.
13540 if object.proxy_state().is_none()
13541 && !object.is_array()
13542 && object.typed_array_element_type().is_none()
13543 && object.write_value_key(key, value.clone())
13544 {
13545 return Ok(());
13546 }
13547 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
13548 let on_failure = if self.frame().code.code.strict {
13549 DeleteFailure::Throw
13550 } else {
13551 DeleteFailure::Ignore
13552 };
13553 self.set_property_with_key(object, key, value, on_failure)
13554 }
13555
13556 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
13557 ///
13558 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
13559 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
13560 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
13561 /// `Number.parseInt(sym)` — so those callers use this instead.
13562 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
13563 if matches!(value, Value::Symbol(_)) {
13564 return Err(Signal::Throw(
13565 self.make_error("TypeError", "cannot convert symbol to string"),
13566 ));
13567 }
13568 // An object runs `ToPrimitive` first, which may itself produce a symbol —
13569 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
13570 let value = self.to_primitive(value.clone(), Hint::String)?;
13571 if matches!(value, Value::Symbol(_)) {
13572 return Err(Signal::Throw(
13573 self.make_error("TypeError", "cannot convert symbol to string"),
13574 ));
13575 }
13576 Ok(value.to_js_string())
13577 }
13578
13579 /// `ToPropertyKey` for a builtin that takes a key argument.
13580 ///
13581 /// Fallible: a key whose `toString` throws has to propagate that error, both for
13582 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
13583 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
13584 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
13585 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
13586 self.propkey(value)
13587 }
13588
13589 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
13590 ///
13591 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
13592 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
13593 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
13594 /// `RangeError` — and why this cannot be a plain `ToNumber`.
13595 /// `ToNumber(value)` for `ArraySetLength`, which the spec performs **twice**.
13596 ///
13597 /// §10.4.2.4 steps 3–5 are `ToUint32(Desc.[[Value]])`, then `ToNumber(Desc.[[Value]])`,
13598 /// then a `RangeError` when they disagree. Two conversions rather than one is
13599 /// observable: a `valueOf` that runs the first time can make `length` non-writable
13600 /// before the second, which turns the store into a refused write
13601 /// (`length/define-own-prop-length-coercion-order`, `…-set`).
13602 pub fn coerce_array_length_twice(&mut self, value: &Value) -> JsResult<u32> {
13603 let first = self.array_length_of(value)?;
13604 let second = self.array_length_of(value)?;
13605 debug_assert_eq!(first, second);
13606 Ok(first)
13607 }
13608
13609 /// `ArraySetLength`'s `ToNumber(value)`, then the `ToUint32` round-trip check.
13610 ///
13611 /// Separate from [`Interp::coerce_array_length_twice`] so the callers that need one
13612 /// conversion can say so; a caller that needs the spec's two uses that instead.
13613 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
13614 let number = match value {
13615 Value::Int(number) => *number as f64,
13616 Value::Float(number) => *number,
13617 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
13618 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
13619 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
13620 // reference answers 0.
13621 Value::Null | Value::Bool(_) | Value::Undefined => value.to_number(),
13622 // A string goes through the full numeric-literal grammar: `"0x00B"` is 11 and
13623 // `" 5 "` is 5, which is exactly what `string_to_number` implements.
13624 Value::String(text) => crate::value::string_to_number(&text.to_string_lossy()),
13625 _ => {
13626 // The primitive comes back through this same conversion, so a wrapper of a
13627 // boolean (`new Boolean(false)`) is `0` rather than the `NaN` that
13628 // `ToNumber("false")` would give — `S15.4.5.1_A1.3_T1` walks every wrapper.
13629 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
13630 return self.array_length_of(&primitive);
13631 }
13632 };
13633 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
13634 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
13635 // is a `RangeError`, not `0`.
13636 if !number.is_finite()
13637 || number.fract() != 0.0
13638 || !(0.0..=u32::MAX as f64).contains(&number)
13639 {
13640 return Err(self.range_error("invalid array length"));
13641 }
13642 Ok(number as u32)
13643 }
13644
13645 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
13646 /// `Object.getOwnPropertySymbols` put in their result array.
13647 pub fn key_value(&self, key: &PropertyKey) -> Value {
13648 match key {
13649 PropertyKey::String(text) => self.string_wtf8(text.clone()),
13650 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
13651 }
13652 }
13653
13654 /// Fill in a String exotic object: `_value`, `length` and the index properties.
13655 ///
13656 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
13657 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
13658 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
13659 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
13660 /// the two paths had drifted; this is the one both now use.
13661 ///
13662 /// The indices are *code units*, so an astral character occupies two of them — the
13663 /// same rule `s.length` and `s[i]` follow.
13664 /// Give an already-created object the internal slot that makes it a wrapper of
13665 /// `value`, so the primitive's prototype methods work on it.
13666 ///
13667 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
13668 /// which are wrappers of their own type holding the empty value.
13669 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
13670 self.internal_set(object, "_value", value);
13671 }
13672
13673 pub(crate) fn init_string_wrapper(
13674 &mut self,
13675 object: &Gc<JsObject>,
13676 text: &Gc<crate::value::JsString>,
13677 ) {
13678 object.define(
13679 "length",
13680 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
13681 );
13682 for index in 0..text.utf16_len() {
13683 if let Some(unit) = text.wtf8().unit_at(index) {
13684 object.define(
13685 &index.to_string(),
13686 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
13687 Property::with_attributes(self.string_wtf8(unit), false, true),
13688 );
13689 }
13690 }
13691 object.define_key(
13692 &self.internal_slot("_value"),
13693 Property::with_attributes(Value::String(text.clone()), false, false),
13694 );
13695 }
13696
13697 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
13698 ///
13699 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
13700 /// throws. The wrapper carries its primitive in `_value` — the same slot
13701 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
13702 /// on a boxed value no constructor ever built.
13703 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13704 let (prototype, primitive) = match value {
13705 Value::Object(object) => return Ok(object.clone()),
13706 Value::String(text) => {
13707 let object = self.new_object(self.realm.string_proto.clone());
13708 self.init_string_wrapper(&object, text);
13709 return Ok(object);
13710 }
13711 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
13712 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
13713 // A symbol and a bigint box into wrappers whose methods live on
13714 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
13715 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
13716 // branch below instead produced an object with *no* prototype, so those
13717 // methods were unreachable on a box.
13718 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
13719 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
13720 Value::Undefined | Value::Null => {
13721 return Err(Signal::Throw(self.make_error(
13722 "TypeError",
13723 &format!("cannot convert {} to object", value.to_js_string()),
13724 )));
13725 }
13726 _ => (None, value.clone()),
13727 };
13728 let object = self.new_object(prototype);
13729 self.internal_set(&object, "_value", primitive);
13730 Ok(object)
13731 }
13732
13733 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
13734 ///
13735 /// Split out for a reader that has to create the object *before* it knows what it wraps:
13736 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
13737 /// written before its primitive, so the placeholder has to exist first and be filled in
13738 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
13739 /// than a second in the deserialiser.
13740 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
13741 let prototype = match value {
13742 Value::String(_) => self.realm.string_proto.clone(),
13743 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13744 Value::Bool(_) => self.realm.boolean_proto.clone(),
13745 Value::Symbol(_) => self.realm.symbol_proto.clone(),
13746 Value::BigInt(_) => self.realm.bigint_proto.clone(),
13747 _ => {
13748 return Err(Signal::Throw(self.make_error(
13749 "TypeError",
13750 &format!("cannot box {}", value.to_js_string()),
13751 )));
13752 }
13753 };
13754 object.set_proto(prototype);
13755 if let Value::String(text) = value {
13756 self.init_string_wrapper(object, text);
13757 return Ok(());
13758 }
13759 self.internal_set(object, "_value", value.clone());
13760 Ok(())
13761 }
13762
13763 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
13764 ///
13765 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
13766 /// through the `Symbol` function object, so the registry is reachable as a method rather
13767 /// than only from `builtins::symbol`.
13768 pub fn symbol_for(&mut self, key: &str) -> Value {
13769 if let Some(existing) = self.realm.symbol_registry.get(key) {
13770 return existing.clone();
13771 }
13772 let symbol = crate::builtins::symbol::symbol_value(
13773 self,
13774 crate::value::JsSymbol::registered(key.to_string()),
13775 );
13776 self.realm
13777 .symbol_registry
13778 .insert(key.to_string(), symbol.clone());
13779 symbol
13780 }
13781
13782 /// `a == b`, the coercing comparison.
13783 ///
13784 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
13785 /// which is what makes `[] == ""` true: `[]` becomes `""` via
13786 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
13787 /// because the conversion is allowed to call script code, so the two primitive
13788 /// operands are handed back to it.
13789 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
13790 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
13791 return Ok(left.loose_equals(&right));
13792 }
13793 // `null == undefined` holds even though neither is an object.
13794 if matches!(left, Value::Undefined | Value::Null)
13795 && matches!(right, Value::Undefined | Value::Null)
13796 {
13797 return Ok(true);
13798 }
13799 if matches!(left, Value::Undefined | Value::Null)
13800 || matches!(right, Value::Undefined | Value::Null)
13801 {
13802 return Ok(false);
13803 }
13804 // Two objects compare by identity. Only an object *against a primitive* is
13805 // converted, which is why `{} == {}` is false while `[] == ""` is true.
13806 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
13807 return Ok(a.ptr_eq(b));
13808 }
13809 let left = self.to_primitive(left, Hint::Default)?;
13810 let right = self.to_primitive(right, Hint::Default)?;
13811 Ok(left.loose_equals(&right))
13812 }
13813
13814 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
13815 let Value::Object(object) = object else {
13816 return Err(Signal::Throw(
13817 self.make_error("TypeError", "cannot use 'in' on a non-object"),
13818 ));
13819 };
13820 let key = self.propkey(key)?;
13821 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
13822 // trap. One implementation, so an array's derived `length` and its inherited holes
13823 // cannot be right in one caller and wrong in another.
13824 self.has_own_or_inherited(object, &key)
13825 }
13826
13827 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
13828 ///
13829 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
13830 /// whole reason the operator is a hook rather than a prototype walk.
13831 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13832 if let Value::Object(function) = constructor {
13833 let key = self.realm.well_known_key(WellKnown::HasInstance);
13834 let method = self.get_property_key(function, &key)?;
13835 if let Some(method) = method
13836 && !matches!(method, Value::Undefined)
13837 {
13838 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
13839 return Ok(answer.to_boolean());
13840 }
13841 }
13842 self.instance_of(object, constructor)
13843 }
13844
13845 /// `OrdinaryHasInstance`: the prototype walk on its own.
13846 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13847 self.instance_of(object, constructor)
13848 }
13849
13850 /// `IsArray`: an array, or a proxy whose target is one.
13851 ///
13852 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
13853 /// makes `Array.isArray(new Proxy([], {}))` true.
13854 pub fn is_array_value(&self, value: &Value) -> bool {
13855 match value {
13856 Value::Object(object) => {
13857 if let Some(state) = object.proxy_state() {
13858 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
13859 }
13860 object.is_array()
13861 }
13862 _ => false,
13863 }
13864 }
13865
13866 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
13867 ///
13868 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
13869 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
13870 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
13871 /// see [`Interp::enqueue_job_function`].
13872 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
13873 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
13874 // the handler is reported rather than lost — the same reason a `then` reaction needs a
13875 // promise to settle.
13876 let promise = self.new_promise();
13877 self.fulfill_promise(&promise, Value::Undefined);
13878 self.jobs.push_back(Job::Reaction {
13879 handler: Some(function),
13880 argument: Value::Undefined,
13881 rejected: false,
13882 promise,
13883 });
13884 Ok(())
13885 }
13886
13887 /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
13888 ///
13889 /// Four of its steps were missing or wrong, and each one is a test262 case in
13890 /// `Function/prototype/Symbol.hasInstance/`:
13891 ///
13892 /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
13893 /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
13894 /// `[[BoundThis]]` standing in for the object when that is an object), which is why
13895 /// `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
13896 /// `prototype` of its own, so without this step the walk below gives `false`;
13897 /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
13898 /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
13899 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13900 let Value::Object(function) = constructor else {
13901 return Ok(false);
13902 };
13903 if !function.is_callable() {
13904 return Ok(false);
13905 }
13906 // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
13907 // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
13908 // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
13909 if let Some((target, this)) = function.bound_target_and_this() {
13910 let object = if this.as_object().is_some() {
13911 this
13912 } else {
13913 object.clone()
13914 };
13915 return self.instance_of(&object, &target);
13916 }
13917 let Value::Object(target) = object else {
13918 return Ok(false);
13919 };
13920 let prototype = self.get_property(function, "prototype")?;
13921 let Some(Value::Object(prototype)) = prototype else {
13922 return Err(Signal::Throw(self.make_error(
13923 "TypeError",
13924 "function has non-object prototype in instanceof check",
13925 )));
13926 };
13927 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
13928 // which is also what makes `proxyOfInstance instanceof C` work.
13929 let mut current = Some(target.clone());
13930 while let Some(object) = current {
13931 if object.ptr_eq(&prototype) {
13932 return Ok(true);
13933 }
13934 current = self.object_prototype_of(&object)?;
13935 }
13936 Ok(false)
13937 }
13938
13939 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
13940 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
13941 if let Some(proto) = self.proxy_get_prototype_of(object)? {
13942 return Ok(proto);
13943 }
13944 if let Some(exotic) = object.exotic()
13945 && let Some(proto) = exotic.get_prototype(self, object)?
13946 {
13947 return Ok(proto);
13948 }
13949 Ok(object.proto())
13950 }
13951
13952 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
13953 pub fn object_set_prototype_of(
13954 &mut self,
13955 object: &Gc<JsObject>,
13956 proto: Option<Gc<JsObject>>,
13957 ) -> JsResult<bool> {
13958 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
13959 return Ok(answer);
13960 }
13961 if let Some(exotic) = object.exotic()
13962 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
13963 {
13964 return Ok(answer);
13965 }
13966 // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
13967 // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
13968 // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
13969 // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
13970 if self
13971 .internal_get(object, "_immutable_proto")
13972 .is_some_and(|flag| flag.to_boolean())
13973 && !same_proto(object.proto().as_ref(), proto.as_ref())
13974 {
13975 return Ok(false);
13976 }
13977 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
13978 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
13979 // inheriting from itself, which every later prototype walk then had to defend
13980 // against — and `Reflect.setPrototypeOf` reported success for an operation the
13981 // language says is impossible.
13982 if let Some(proto) = &proto {
13983 let mut current = Some(proto.clone());
13984 let mut guard = 0;
13985 while let Some(node) = current {
13986 if node.ptr_eq(object) {
13987 // §10.1.2.1 step 5.a: a cycle is `return false`, not a throw —
13988 // `Object.setPrototypeOf` turns that `false` into the `TypeError`,
13989 // while `Reflect.setPrototypeOf` reports it
13990 // (`setPrototypeOf/return-false-if-target-is-prototype-of-proto`).
13991 return Ok(false);
13992 }
13993 guard += 1;
13994 if guard > 1000 {
13995 break;
13996 }
13997 current = node.proto();
13998 }
13999 }
14000 // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
14001 // re-setting it to the *same* one is a no-op `true`. Missing this made
14002 // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
14003 // actually reparent the object — and it is what
14004 // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
14005 // forwarding path has nothing else left to refuse it.
14006 if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
14007 return Ok(false);
14008 }
14009 object.set_proto(proto);
14010 Ok(true)
14011 }
14012
14013 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
14014 ///
14015 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
14016 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
14017 /// already one.
14018 /// `HasProperty(O, P)`.
14019 ///
14020 /// One implementation, shared with the `in` operator. It used to be a second copy that
14021 /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
14022 /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
14023 /// proxy ran the wrong hook and could even disagree with `in`. The
14024 /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
14025 /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
14026 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
14027 self.has_own_or_inherited(object, key)
14028 }
14029
14030 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
14031 ///
14032 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
14033 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
14034 /// boolean as well, and it needs the receiver to be the one the caller named.
14035 pub fn set_property_with_key_receiver(
14036 &mut self,
14037 object: &Gc<JsObject>,
14038 key: &PropertyKey,
14039 value: Value,
14040 receiver: Option<&Value>,
14041 on_failure: DeleteFailure,
14042 ) -> JsResult<bool> {
14043 let receiver = receiver
14044 .cloned()
14045 .unwrap_or_else(|| Value::Object(object.clone()));
14046 if object.proxy_state().is_some() {
14047 return match self.proxy_set(object, key, value, &receiver)? {
14048 Some(accepted) => Ok(accepted),
14049 None => Ok(true),
14050 };
14051 }
14052 // §10.4.6.7: a module namespace's `[[Set]]` always answers false, whatever the
14053 // receiver. This has to be answered here as well as in the storing path below,
14054 // because `Reflect.set` reports the refusal as a `bool` instead of raising.
14055 if object.module_namespace_marker() {
14056 return Ok(false);
14057 }
14058 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
14059 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
14060 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
14061 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
14062 //
14063 // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
14064 //
14065 // * `SameValue(O, Receiver)` stores into the buffer, converting first;
14066 // * an *invalid* index with a different receiver answers `true` and does nothing,
14067 // not even converting `V` (`valueOfCalls` stays 0);
14068 // * a valid index with a different receiver falls through to
14069 // `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
14070 // value lands on the **receiver**, unconverted, and can be refused by a
14071 // non-extensible receiver, an accessor, or a read-only index there.
14072 //
14073 // The last one used to write into the view itself, which left `target[0]` changed
14074 // and `receiver[0]` untouched — backwards.
14075 if object.typed_array_element_type().is_some()
14076 && let Some(numeric) = canonical_numeric_index(key)
14077 {
14078 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14079 if same {
14080 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14081 return Ok(true);
14082 }
14083 if !typed_array_index_is_valid(object, numeric) {
14084 return Ok(true);
14085 }
14086 let Some(receiver) = receiver.as_object().cloned() else {
14087 return Ok(false);
14088 };
14089 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
14090 if existing.is_accessor() || !existing.writable {
14091 return Ok(false);
14092 }
14093 let property = Property {
14094 value: Some(value),
14095 ..existing
14096 };
14097 return self.object_define_own_property(&receiver, key, property);
14098 }
14099 return self.object_define_own_property(&receiver, key, Property::data(value));
14100 }
14101 // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
14102 // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
14103 // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
14104 // `Reflect.set` to *report* the refusal instead of raising.
14105 //
14106 // A receiver that is not the object turns the whole operation into
14107 // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
14108 // `[[Set]]` rather than a lookup — that is what makes
14109 // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
14110 // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
14111 // writes to `object`, so it cannot express that and is only used when the two are
14112 // the same.
14113 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14114 if !same {
14115 return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
14116 }
14117 // Same receiver: the plain path below writes into `object`, which is right, but it
14118 // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
14119 // boolean, so the two step-1 refusals have to be read off the own descriptor here.
14120 if let Some(existing) = self.object_get_own_property(object, key)? {
14121 if existing.is_accessor() {
14122 return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
14123 Some(setter) => {
14124 self.call_value(setter, receiver, vec![value])?;
14125 Ok(true)
14126 }
14127 None => Ok(false),
14128 };
14129 }
14130 if !existing.writable {
14131 return Ok(false);
14132 }
14133 }
14134 // Otherwise it is an ordinary create-or-write into `object` itself.
14135 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14136 Ok(true)
14137 }
14138
14139 /// `[[IsExtensible]]`, with the proxy trap when there is one.
14140 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14141 if let Some(answer) = self.proxy_is_extensible(object)? {
14142 return Ok(answer);
14143 }
14144 if let Some(exotic) = object.exotic()
14145 && let Some(answer) = exotic.is_extensible(self, object)?
14146 {
14147 return Ok(answer);
14148 }
14149 Ok(object.is_extensible())
14150 }
14151
14152 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
14153 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14154 if let Some(answer) = self.proxy_prevent_extensions(object)? {
14155 return Ok(answer);
14156 }
14157 // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
14158 //
14159 // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
14160 //
14161 // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
14162 // created with an explicit length, because the buffer can still move it. That is
14163 // what makes `Object.freeze` refuse every such view, including a zero-length one
14164 // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
14165 // plain buffer is allowed.
14166 if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
14167 && buffer
14168 .array_buffer_storage()
14169 .is_some_and(|storage| storage.borrow().is_resizable())
14170 {
14171 return Err(
14172 self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
14173 );
14174 }
14175 if let Some(exotic) = object.exotic()
14176 && let Some(answer) = exotic.prevent_extensions(self, object)?
14177 {
14178 return Ok(answer);
14179 }
14180 object.set_extensible(false);
14181 Ok(true)
14182 }
14183
14184 fn copy_properties(
14185 &mut self,
14186 target: &Value,
14187 source: &Value,
14188 exclusion: &Value,
14189 ) -> JsResult<()> {
14190 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
14191 // does contribute: its index properties are own, enumerable and writable, which
14192 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
14193 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
14194 // is a no-op.
14195 let Some(target) = target.as_object() else {
14196 return Ok(());
14197 };
14198 let source_object = match source {
14199 Value::Object(object) => object.clone(),
14200 Value::String(text) => {
14201 // Untaken keys are the string's indices, which are code units.
14202 for index in 0..text.utf16_len() {
14203 if let Some(unit) = text.wtf8().unit_at(index) {
14204 target.define_data(&index.to_string(), self.string_wtf8(unit));
14205 }
14206 }
14207 return Ok(());
14208 }
14209 _ => return Ok(()),
14210 };
14211 // An object *rest* element passes the keys already taken by the literal part as
14212 // an array of **key values**; a spread passes `null`, which excludes nothing. The
14213 // array is read by its elements rather than by its own property names, and the
14214 // values stay `PropertyKey`s: a computed key can be a symbol, and
14215 // `{[sym]: a, ...rest}` has to leave `sym` out of `rest`
14216 // (`object-rest-proxy-gopd-not-called-on-excluded-keys`). Flattening them to
14217 // strings made a symbol exclusion a no-op.
14218 let mut excluded: Vec<PropertyKey> = Vec::new();
14219 if let Value::Object(list) = exclusion
14220 && let Some(length) = list.array_length()
14221 {
14222 for index in 0..length {
14223 if let Some(value) = list.array_get(index) {
14224 excluded.push(self.propkey(&value)?);
14225 }
14226 }
14227 }
14228 let source = &source_object;
14229 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
14230 // Reading the property table directly made every spread of a proxy empty.
14231 let keys = self.object_own_property_keys(source)?;
14232 for as_key in keys {
14233 // §7.3.25 step 4 walks `[[OwnPropertyKeys]]`, so **symbol**-keyed properties
14234 // are copied as well — `{...{[Symbol("s")]: 1}}` has one own symbol key.
14235 // Skipping them silently lost every symbol on every spread and every object
14236 // rest element (`obj-rest-order`).
14237 //
14238 if excluded.contains(&as_key) {
14239 continue;
14240 }
14241 let enumerable = self
14242 .object_get_own_property(source, &as_key)?
14243 .is_some_and(|property| property.enumerable);
14244 if !enumerable {
14245 continue;
14246 }
14247 let value = self
14248 .get_property_key(source, &as_key)?
14249 .unwrap_or(Value::Undefined);
14250 target.define_data_key(&as_key, value);
14251 }
14252 Ok(())
14253 }
14254
14255 // -- iteration ---------------------------------------------------------
14256
14257 /// One object's own keys in enumeration order: array indices ascending, then the
14258 /// rest in insertion order.
14259 ///
14260 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
14261 /// whether the key is enumerable, which the caller resolves per key because an
14262 /// array's elements are not in the same store as its named properties.
14263 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
14264 // An index can arrive twice, once from the array's element store and once from
14265 // its property map, so the numeric keys go through a map that keeps the
14266 // enumerable answer if either source gave one.
14267 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
14268 for (key, enumerable) in &own {
14269 if let Some(index) = key.as_str().and_then(array_index) {
14270 let entry = numeric.entry(index).or_insert(false);
14271 *entry = *entry || *enumerable;
14272 }
14273 }
14274 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
14275 .into_iter()
14276 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
14277 .collect();
14278 ordered.extend(
14279 own.into_iter()
14280 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
14281 );
14282 ordered
14283 }
14284
14285 /// Build the key list a `for-in` loop walks.
14286 ///
14287 /// The order is the specification's: own properties before inherited ones, and
14288 /// within one object the integer-like keys in ascending numeric order ahead of the
14289 /// string keys in insertion order. A shadowed key only appears once, and a key that
14290 /// is a non-enumerable own property anywhere nearer is skipped entirely.
14291 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
14292 let record = self.new_object(None);
14293 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
14294 // A proxy supplies its own key list, and — the reason this is not just another
14295 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
14296 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
14297 // descriptor there.
14298 if let Value::Object(object) = value
14299 && object.proxy_state().is_some()
14300 {
14301 let own = self
14302 .proxy_own_keys(object)?
14303 .unwrap_or_else(|| object.own_property_keys());
14304 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
14305 let mut numeric: Vec<u32> = Vec::new();
14306 let mut rest: Vec<PropertyKey> = Vec::new();
14307 for key in own {
14308 match key.as_str().and_then(array_index) {
14309 Some(index) => numeric.push(index),
14310 None => rest.push(key),
14311 }
14312 }
14313 numeric.sort_unstable();
14314 ordered.extend(
14315 numeric
14316 .into_iter()
14317 .map(|index| PropertyKey::from(index.to_string())),
14318 );
14319 ordered.extend(rest);
14320 for (index, key) in ordered.into_iter().enumerate() {
14321 record.define_data(&index.to_string(), self.key_value(&key));
14322 }
14323 record.define_data("__index", Value::Int(0));
14324 // The mark that makes `for_in_advance` re-ask the proxy per key.
14325 record.define_data("__proxy", Value::Object(object.clone()));
14326 return Ok(record);
14327 }
14328 if let Value::Object(object) = value {
14329 let mut chain = vec![object.clone()];
14330 chain.extend(object.chain());
14331 // Every own string key the walk has seen, enumerable or not. A
14332 // non-enumerable own property still hides a same-named enumerable one
14333 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
14334 // keeps `x` out of the loop even when the prototype has one.
14335 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
14336 for object in chain {
14337 let mut own: Vec<(crate::value::Wtf8, bool)> = object
14338 .own_property_keys()
14339 .iter()
14340 .filter_map(|key| key.as_wtf8().cloned())
14341 .map(|key| {
14342 let enumerable = object
14343 .own_property(&key.to_string_lossy())
14344 .map(|property| property.enumerable)
14345 .unwrap_or(false);
14346 (key, enumerable)
14347 })
14348 .collect();
14349 if let Some(length) = object.array_length() {
14350 own.retain(|(key, _)| key.as_str() != Some("length"));
14351 for index in 0..length {
14352 // A dense element is enumerable; a **hole** is not there at all —
14353 // and a hole is also what an index with a recorded descriptor
14354 // leaves behind, in which case the table entry above already
14355 // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
14356 // defines index 0 non-enumerable and `for…in` must skip it).
14357 if let Some(value) = object.array_get(index)
14358 && !matches!(value, Value::Hole)
14359 {
14360 own.push((crate::value::Wtf8::new(index.to_string()), true));
14361 }
14362 }
14363 }
14364 // Integer-like keys come first in ascending order, then the rest in
14365 // insertion order — and the ordering is *per object*, not for the chain
14366 // as a whole: one pass over every collected key lifted a prototype's
14367 // `"4"` above the target's own `x`/`y`, which is not the order
14368 // `for…in` reports.
14369 for (key, enumerable) in Self::order_own_keys(own) {
14370 if visited.contains(&key) {
14371 continue;
14372 }
14373 visited.push(key.clone());
14374 if enumerable {
14375 keys.push(key);
14376 }
14377 }
14378 }
14379 }
14380 for (index, key) in keys.into_iter().enumerate() {
14381 record.define_data(&index.to_string(), self.string_wtf8(key));
14382 }
14383 record.define_data("__index", Value::Int(0));
14384 Ok(record)
14385 }
14386
14387 /// The next key of a `for…in` record, `None` when the loop is done.
14388 ///
14389 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
14390 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
14391 /// the loop reaches it, so a handler that stops reporting a key partway through drops
14392 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
14393 /// key the handler had already withdrawn.
14394 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
14395 let Value::Object(record) = record else {
14396 return Ok(None);
14397 };
14398 let proxy = record
14399 .own_property("__proxy")
14400 .and_then(|property| property.value);
14401 loop {
14402 let index = record
14403 .own_property("__index")
14404 .and_then(|property| property.value)
14405 .map(|value| value.to_int32())
14406 .unwrap_or(0);
14407 let Some(candidate) = record
14408 .own_property(&index.to_string())
14409 .and_then(|property| property.value)
14410 else {
14411 return Ok(None);
14412 };
14413 record.define_data("__index", Value::Int(index + 1));
14414 let text = candidate.to_js_string();
14415 let Some(Value::Object(proxy)) = &proxy else {
14416 return Ok(Some(text));
14417 };
14418 // The candidate is already a key string here, so the lookup does not need a
14419 // second `ToPropertyKey` conversion.
14420 let key = PropertyKey::from(text.as_str());
14421 let live = match self.proxy_get_own_property(proxy, &key)? {
14422 Some(descriptor) => descriptor,
14423 // Not a proxy after all, or it lost its state: fall back to the target.
14424 None => proxy.own_property_key(&key),
14425 };
14426 if live.is_some_and(|property| property.enumerable) {
14427 return Ok(Some(text));
14428 }
14429 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
14430 // next one.
14431 }
14432 }
14433
14434 /// The iterator for `for-of`: the object and its `next` method.
14435 ///
14436 /// An object that already carries a `next` method is used as it is — that is what
14437 /// `arr.values()` returns — and only arrays and strings get the built-in
14438 /// sequence iterator.
14439 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
14440 ///
14441 /// Callers that must choose between the iterable and the array-like protocol — the
14442 /// typed-array constructor is the main one — need to ask *before* committing to one.
14443 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
14444 let key = self.realm.well_known_key(WellKnown::Iterator);
14445 let method = self.read_field_key(value, &key)?;
14446 if matches!(method, Value::Undefined | Value::Null) {
14447 return Ok(false);
14448 }
14449 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14450 return Err(Signal::Throw(
14451 self.make_error("TypeError", "Symbol.iterator is not callable"),
14452 ));
14453 }
14454 Ok(true)
14455 }
14456
14457 /// Collect everything an iterable yields.
14458 ///
14459 /// The cap is a guard against a generator that never ends: an unbounded collect would
14460 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
14461 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
14462 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
14463 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
14464 const MAX_ITEMS: usize = 1 << 24;
14465 let iterator = self.get_iterator(value)?;
14466 let mut out = Vec::new();
14467 loop {
14468 let (element, done) = self.iterator_step(&iterator)?;
14469 if done {
14470 return Ok(out);
14471 }
14472 out.push(element);
14473 if out.len() > MAX_ITEMS {
14474 // Close before refusing: the walk is being abandoned, so the iterator's
14475 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
14476 // unrun and a locked resource unreleased.
14477 self.close_iterator_after_throw(&iterator)?;
14478 return Err(self.range_error("iterable is too long to collect"));
14479 }
14480 }
14481 }
14482
14483 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
14484 ///
14485 /// A native constructor calls this once it has validated its arguments, which is the
14486 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
14487 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
14488 /// never reached. The prototype comes from `new.target` when it is an object, and from
14489 /// `default_proto` otherwise.
14490 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14491 let proto = self.ctor_prototype(default_proto)?;
14492 Ok(self.new_object(Some(proto)))
14493 }
14494
14495 /// An **array** whose prototype comes from `new.target`.
14496 ///
14497 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
14498 /// instance from `new.target.prototype`, and building a plain array instead made every
14499 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
14500 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
14501 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
14502 Ok(JsObject::array(self.heap, Some(proto), 0))
14503 }
14504
14505 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
14506 ///
14507 /// The `Option` form is for the constructors that build their instance in a helper which
14508 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
14509 /// from `await`'s internal promise, and only the first has a `new.target`.
14510 fn ctor_prototype_opt(
14511 &mut self,
14512 default_proto: Option<Gc<JsObject>>,
14513 ) -> JsResult<Option<Gc<JsObject>>> {
14514 // `active_new_target`: by the time a native constructor runs, `call_value` has
14515 // already consumed the parked value.
14516 let Some(target) = self
14517 .active_new_target
14518 .as_object()
14519 .cloned()
14520 .map(Value::Object)
14521 else {
14522 return Ok(default_proto);
14523 };
14524 let Some(target) = target.as_object().cloned() else {
14525 return Ok(default_proto);
14526 };
14527 match self.get_property(&target, "prototype")? {
14528 Some(Value::Object(proto)) => Ok(Some(proto)),
14529 _ => Ok(default_proto),
14530 }
14531 }
14532
14533 /// `new.target.prototype`, or `default_proto` when this is a plain call.
14534 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14535 let Some(target) = self.active_new_target.as_object().cloned() else {
14536 return Ok(default_proto);
14537 };
14538 match self.get_property(&target, "prototype")? {
14539 Some(Value::Object(proto)) => Ok(proto),
14540 _ => Ok(default_proto),
14541 }
14542 }
14543
14544 /// `CreateDataPropertyOrThrow(O, key, value)`.
14545 ///
14546 /// A *definition*, not an assignment. The difference is visible the moment the target
14547 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
14548 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
14549 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
14550 /// refused (`configurable: false`).
14551 ///
14552 /// The fast path exists because this is called once per element by `map`, `filter`,
14553 /// `slice` and friends: a plain array with no custom element descriptors and a writable
14554 /// `length` can store straight into its element vector.
14555 pub fn create_data_property_or_throw(
14556 &mut self,
14557 object: &Gc<JsObject>,
14558 index: usize,
14559 value: Value,
14560 ) -> JsResult<()> {
14561 // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
14562 // an array (that is what `Array.isArray` must say), so the element fast path would
14563 // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
14564 // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
14565 // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
14566 // records the exact trap sequence.
14567 if object.proxy_state().is_none()
14568 && object.is_array()
14569 && object.elements_writable()
14570 && !object.has_element_descriptors()
14571 && object.is_extensible()
14572 && object.array_set(self.heap, index, value.clone())
14573 {
14574 return Ok(());
14575 }
14576 let key = PropertyKey::from(index.to_string());
14577 let property = Property {
14578 value: Some(value),
14579 writable: true,
14580 enumerable: true,
14581 configurable: true,
14582 ..Property::default()
14583 };
14584 // `CreateDataProperty` always asks for the default attributes, so it can only ever
14585 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
14586 // the rest. Checking here rather than inside `object_define_own_property` is
14587 // deliberate: that function receives a fully-populated `Property` and cannot tell
14588 // an omitted attribute from an explicit `false`, so the generic check it would need
14589 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
14590 // writable property (that cost eight `Object/defineProperty` tests).
14591 if object.proxy_state().is_none()
14592 && let Some(existing) = self.object_get_own_property(object, &key)?
14593 && !existing.configurable
14594 {
14595 return Err(self.type_error("cannot create the property"));
14596 }
14597 if self.object_define_own_property(object, &key, property)? {
14598 return Ok(());
14599 }
14600 Err(self.type_error("cannot create the property"))
14601 }
14602
14603 /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
14604 ///
14605 /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
14606 /// its callers have; this is the same operation for the named properties a built-in
14607 /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
14608 /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
14609 /// `Array.prototype` cannot see it — while `Set` would run that accessor.
14610 pub fn create_named_data_property_or_throw(
14611 &mut self,
14612 object: &Gc<JsObject>,
14613 key: &str,
14614 value: Value,
14615 ) -> JsResult<()> {
14616 let key = PropertyKey::from(key);
14617 let property = Property {
14618 value: Some(value),
14619 writable: true,
14620 enumerable: true,
14621 configurable: true,
14622 ..Property::default()
14623 };
14624 if object.proxy_state().is_none()
14625 && let Some(existing) = self.object_get_own_property(object, &key)?
14626 && !existing.configurable
14627 {
14628 return Err(self.type_error("cannot create the property"));
14629 }
14630 if self.object_define_own_property(object, &key, property)? {
14631 return Ok(());
14632 }
14633 Err(self.type_error("cannot create the property"))
14634 }
14635
14636 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
14637 ///
14638 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
14639 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
14640 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
14641 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
14642 /// run user code and both can throw.
14643 pub fn species_constructor(
14644 &mut self,
14645 object: &Gc<JsObject>,
14646 default: Value,
14647 ) -> JsResult<Value> {
14648 let Some(constructor) = self.get_property(object, "constructor")? else {
14649 return Ok(default);
14650 };
14651 let constructor = match constructor {
14652 Value::Undefined => return Ok(default),
14653 Value::Object(constructor) => constructor,
14654 _ => return Err(self.type_error("constructor is not an object")),
14655 };
14656 let key = self.realm.well_known_key(WellKnown::Species);
14657 let species = self.get_property_key(&constructor, &key)?;
14658 match species {
14659 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
14660 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
14661 Some(_) => Err(self.type_error("species is not a constructor")),
14662 }
14663 }
14664
14665 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
14666 ///
14667 /// The result is an array of `length` holes whose prototype comes from
14668 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
14669 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
14670 /// is why the `IsArray` check is the first step and not an optimisation.
14671 pub fn array_species_create(
14672 &mut self,
14673 original: &Value,
14674 length: usize,
14675 ) -> JsResult<Gc<JsObject>> {
14676 // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
14677 // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
14678 // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
14679 // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
14680 // `new_array_of_length` (`slice/create-non-array-invalid-len`).
14681 // `ArrayCreate(length)` is only reached when the result is a **plain array of this
14682 // realm** — the species may be a user function that ignores the length entirely, and
14683 // then `2**53 - 1` is not its problem
14684 // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
14685 // a short proxy and expects the copy loop to run).
14686 let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
14687 if length > ARRAY_CREATE_LIMIT {
14688 return Err(interp.range_error("invalid array length"));
14689 }
14690 Ok(interp.new_array_of_length(length))
14691 };
14692 let Some(object) = original.as_object().cloned() else {
14693 return default(self);
14694 };
14695 if !object.is_array() {
14696 return default(self);
14697 }
14698 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
14699 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
14700 let Some(constructor) = self.get_property(&object, "constructor")? else {
14701 return default(self);
14702 };
14703 let species = match constructor {
14704 Value::Undefined => return Ok(self.new_array_of_length(length)),
14705 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
14706 return default(self);
14707 }
14708 Value::Object(constructor) => {
14709 let key = self.realm.well_known_key(WellKnown::Species);
14710 match self.get_property_key(&constructor, &key)? {
14711 None | Some(Value::Undefined) | Some(Value::Null) => {
14712 return default(self);
14713 }
14714 Some(species) => species,
14715 }
14716 }
14717 // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
14718 // is a `TypeError`, not "the default". Treating it as the default made
14719 // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
14720 // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
14721 // `concat/create-ctor-non-object` are the same rule three times.
14722 _ => return Err(self.type_error("constructor is not an object")),
14723 };
14724 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
14725 // that is merely callable is the `create-species-non-ctor` case.
14726 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
14727 return Err(self.type_error("species is not a constructor"));
14728 }
14729 // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
14730 // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
14731 // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
14732 let created = self.construct(
14733 species.clone(),
14734 species,
14735 vec![crate::object::length_value(length)],
14736 )?;
14737 let Some(created) = created.as_object().cloned() else {
14738 return Err(self.type_error("species constructor did not answer an object"));
14739 };
14740 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
14741 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
14742 // object, and `create-species-with-non-writable-property` asserts exactly that.
14743 // The length is set for the array case; the generic case is the caller's
14744 // `Set(A, "length", …)`.
14745 if created.is_array() {
14746 created.array_set_length(self.heap, length);
14747 }
14748 Ok(created)
14749 }
14750
14751 /// Whether `object` is this realm's `%Array%`.
14752 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
14753 self.realm
14754 .array_constructor
14755 .as_ref()
14756 .is_some_and(|array| array.ptr_eq(object))
14757 }
14758
14759 /// A fresh `length`-hole array with the intrinsic prototype.
14760 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
14761 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
14762 array.array_set_length(self.heap, length);
14763 array
14764 }
14765
14766 /// Whether this call is a construction, i.e. `new.target` is defined.
14767 ///
14768 /// A native constructor receives `this = undefined` (it builds its own instance), so it
14769 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
14770 /// The native function currently executing, if any.
14771 pub fn current_native(&self) -> Option<Gc<JsObject>> {
14772 self.current_native.clone()
14773 }
14774
14775 /// Whether this call is a construction, i.e. `new.target` is defined.
14776 pub fn is_constructing(&self) -> bool {
14777 // `active_new_target`, not `pending_new_target`: the parked value is consumed by
14778 // `call_value` before a native runs, so by the time a constructor body asks, the
14779 // answer is only in the active slot.
14780 matches!(self.active_new_target, Value::Object(_))
14781 }
14782
14783 /// The `TypeError` a constructor too primitive to have a wrapper raises.
14784 ///
14785 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
14786 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
14787 /// happens inside the native function, which is why the trace carries an
14788 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
14789 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
14790 /// constructor`, and an unnamed one reports the leading space of `" is not a
14791 /// constructor"` because the reference formats the empty name as it is.
14792 ///
14793 /// It is also the answer for a `new.target` that cannot be named at all — not a
14794 /// function, or a throwing `name` getter — where the reference falls back to the bare
14795 /// `not a constructor`.
14796 pub fn not_a_constructor_error(&mut self) -> Signal {
14797 let target = self.active_new_target.clone();
14798 self.not_a_constructor_error_for(target)
14799 }
14800
14801 /// The same `TypeError` for an explicit target, for the callers that check
14802 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
14803 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
14804 let target = match target {
14805 Value::Object(target) if target.is_callable() => target,
14806 _ => return self.type_error("not a constructor"),
14807 };
14808 let name = match self.get_property(&target, "name") {
14809 Ok(Some(value)) => value.to_js_string(),
14810 _ => return self.type_error("not a constructor"),
14811 };
14812 self.type_error(format!("{name} is not a constructor"))
14813 }
14814
14815 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
14816 ///
14817 /// True whenever `new.target` is not the callee itself, or when it has no usable
14818 /// `prototype` — the cases where reading the property is observable at all.
14819 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
14820 match &self.active_new_target {
14821 Value::Object(target) => !target.ptr_eq(callee),
14822 Value::Undefined => false,
14823 _ => true,
14824 }
14825 }
14826
14827 /// The symbol key for one of the engine's own hidden slots.
14828 ///
14829 /// Cached on the realm, so every object of a kind shares one key and a slot can be
14830 /// read back by name.
14831 /// Whether any object on `object`'s **prototype chain** owns an array index.
14832 ///
14833 /// The one question the array methods' dense fast paths have to ask before touching the
14834 /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
14835 /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
14836 /// vector an unreliable answer. Walking the chain once per call is cheap because a
14837 /// prototype almost never holds an index.
14838 pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
14839 let mut current = object.proto();
14840 // Bounded, like every other prototype walk here: a proxy can answer a cycle.
14841 for _ in 0..10_000 {
14842 let Some(proto) = current else {
14843 return false;
14844 };
14845 if proto.has_indexed_own_property() {
14846 return true;
14847 }
14848 current = proto.proto();
14849 }
14850 false
14851 }
14852
14853 /// The hidden symbol a named internal slot is keyed by, created on first use.
14854 ///
14855 /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
14856 /// either keeping a table of its own.
14857 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
14858 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
14859 return PropertyKey::Symbol(symbol.clone());
14860 }
14861 let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
14862 self.realm
14863 .internal_slots
14864 .borrow_mut()
14865 .insert(name, Value::Symbol(symbol.clone()));
14866 PropertyKey::Symbol(symbol)
14867 }
14868
14869 /// Read a hidden slot, or `None` when the object has none of that name.
14870 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
14871 let slots = self.realm.internal_slots.borrow();
14872 let Value::Symbol(symbol) = slots.get(name)? else {
14873 return None;
14874 };
14875 object
14876 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
14877 .and_then(|property| property.value)
14878 }
14879
14880 /// Define a hidden slot.
14881 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
14882 let key = self.internal_slot(name);
14883 object.define_key(&key, Property::with_attributes(value, false, false));
14884 }
14885
14886 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
14887 ///
14888 /// The method is looked up on the value (through its prototype), called with no
14889 /// arguments, and its result becomes the iterator. A generator gets here through
14890 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
14891 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
14892 ///
14893 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
14894 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
14895 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
14896 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
14897 /// does, and a user-defined iterable works without a special case.
14898 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
14899 /// `Symbol.iterator`.
14900 ///
14901 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
14902 /// iterable is legal there, and each value it produces is simply already settled by
14903 /// the time the `await` around it runs.
14904 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14905 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
14906 let method = self.read_field_key(value, &async_key)?;
14907 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
14908 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
14909 // is *present but not callable* is a TypeError — it does not mean "try the other
14910 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
14911 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
14912 // guard is there to catch.
14913 let absent = matches!(method, Value::Undefined | Value::Null);
14914 if !absent {
14915 let Value::Object(object) = &method else {
14916 return Err(Signal::Throw(
14917 self.make_error("TypeError", "value is not iterable"),
14918 ));
14919 };
14920 if !object.is_callable() {
14921 return Err(Signal::Throw(
14922 self.make_error("TypeError", "value is not iterable"),
14923 ));
14924 }
14925 }
14926 if absent {
14927 // §7.4.2 step 5: the synchronous iterator is **wrapped**. `for await` and an async
14928 // generator's `yield*` both reach here, and the wrapper is what puts
14929 // `PromiseResolve(%Promise%, value)` between the sync iterator's `value` and the
14930 // caller — a poisoned `constructor` on that value rejects instead of being
14931 // yielded, and a rejection closes the synchronous iterator first.
14932 let sync = self.get_iterator(value)?;
14933 return self.async_from_sync_iterator(sync);
14934 }
14935 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14936 if !matches!(iterator, Value::Object(_)) {
14937 return Err(Signal::Throw(
14938 self.make_error("TypeError", "iterator is not an object"),
14939 ));
14940 }
14941 let next = self.read_field(&iterator, "next")?;
14942 Ok(Iterator {
14943 object: iterator,
14944 next,
14945 })
14946 }
14947
14948 /// `CreateAsyncFromSyncIterator(syncIteratorRecord)` (§27.1.4.1).
14949 ///
14950 /// The wrapper itself is script (see [`crate::builtins::async_from_sync`]); this only
14951 /// hands it the record and reads back its `next`. Both are properties of the wrapper, so
14952 /// the returned [`Iterator`] steps through `%AsyncFromSyncIteratorPrototype%.next`.
14953 fn async_from_sync_iterator(&mut self, sync: Iterator) -> JsResult<Iterator> {
14954 let Some(factory) = self.realm.async_from_sync.clone() else {
14955 // No wrapper installed (a realm whose heap refused to hold it): fall back to the
14956 // raw synchronous iterator rather than refusing to iterate at all.
14957 return Ok(sync);
14958 };
14959 let wrapper = self.call_value(factory, Value::Undefined, vec![sync.object, sync.next])?;
14960 let next = self.read_field(&wrapper, "next")?;
14961 Ok(Iterator {
14962 object: wrapper,
14963 next,
14964 })
14965 }
14966
14967 /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
14968 /// read — `@@iterator` is **not** consulted.
14969 ///
14970 /// The distinction is observable and test262 exercises it: a set-like object's `keys`
14971 /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
14972 /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
14973 /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
14974 /// refused it with "[object Object] is not iterable".
14975 pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
14976 if !matches!(value, Value::Object(_)) {
14977 return Err(self.type_error("iterator is not an object"));
14978 }
14979 let next = self.read_field(&value, "next")?;
14980 Ok(Iterator {
14981 object: value,
14982 next,
14983 })
14984 }
14985
14986 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14987 let key = self.realm.well_known_key(WellKnown::Iterator);
14988 let method = self.read_field_key(value, &key)?;
14989 let Value::Object(function) = &method else {
14990 return Err(Signal::Throw(self.make_error(
14991 "TypeError",
14992 &format!("{} is not iterable", value.to_js_string()),
14993 )));
14994 };
14995 if !function.is_callable() {
14996 return Err(Signal::Throw(self.make_error(
14997 "TypeError",
14998 &format!("{} is not iterable", value.to_js_string()),
14999 )));
15000 }
15001 let iterator = self.call_value(method, value.clone(), Vec::new())?;
15002 // The spec requires an object here; a primitive iterator has no `next` to call
15003 // and would fail one step later with a confusing message.
15004 if !matches!(iterator, Value::Object(_)) {
15005 return Err(Signal::Throw(
15006 self.make_error("TypeError", "iterator is not an object"),
15007 ));
15008 }
15009 let next = self.read_field(&iterator, "next")?;
15010 Ok(Iterator {
15011 object: iterator,
15012 next,
15013 })
15014 }
15015
15016 /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
15017 /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
15018 /// exception from `return` propagates normally instead of being swallowed. That is the
15019 /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
15020 /// because confusing them is exactly the bug both exist to avoid.
15021 pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
15022 let method = self.read_field(&iterator.object, "return")?;
15023 if matches!(method, Value::Undefined | Value::Null) {
15024 return Ok(());
15025 }
15026 if !matches!(&method, Value::Object(object) if object.is_callable()) {
15027 return Err(self.type_error("iterator return is not a function"));
15028 }
15029 self.call_value(method, iterator.object.clone(), Vec::new())?;
15030 Ok(())
15031 }
15032
15033 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
15034 /// cannot replace it.
15035 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
15036 let method = self.read_field(&iterator.object, "return")?;
15037 if matches!(method, Value::Undefined | Value::Null) {
15038 return Ok(());
15039 }
15040 if !matches!(&method, Value::Object(object) if object.is_callable()) {
15041 return Err(self.type_error("iterator return is not a function"));
15042 }
15043 self.call_value(method, iterator.object.clone(), Vec::new())?;
15044 Ok(())
15045 }
15046
15047 /// One step of an internal iterator: the value and whether it is exhausted.
15048 /// Replace the iterator slot of an iteration record with `undefined`.
15049 ///
15050 /// `slot` counts values above it, the same convention `for_of_next`'s operand uses. An
15051 /// `undefined` record is what every close path already treats as "nothing to close", so
15052 /// one store both records "this iterator must not be closed" and keeps
15053 /// [`Interp::catch_here`] from calling `return` on an iterator whose `next` threw.
15054 fn clear_iterator_slot(&mut self, slot: usize) {
15055 let frame = self.frame_mut();
15056 let depth = frame.stack.len();
15057 if depth > slot {
15058 frame.stack[depth - 1 - slot] = Value::Undefined;
15059 }
15060 }
15061
15062 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
15063 // §7.4.4 `IteratorNext`: `Call(iteratorRecord.[[NextMethod]], …)` is where a
15064 // non-callable `next` is rejected — **not** `GetIteratorDirect`, which only reads
15065 // the property. The difference is observable: `[ …{}[yield] ] = it` suspends
15066 // before the first step, so an iterator with no `next` still gets its `return`
15067 // called by `it.return()` instead of failing up front
15068 // (`array-rest-iter-rtrn-close-err`).
15069 if let Value::Object(object) = &iterator.next
15070 && object.is_callable()
15071 {
15072 let result =
15073 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
15074 let Some(result) = result.as_object().cloned() else {
15075 return Err(self.type_error("iterator result is not an object"));
15076 };
15077 let done = self
15078 .get_property(&result, "done")?
15079 .is_some_and(|value| value.to_boolean());
15080 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
15081 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
15082 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
15083 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
15084 // made an unrelated `value` getter observable after the loop was over.
15085 if done {
15086 return Ok((Value::Undefined, true));
15087 }
15088 let value = self
15089 .get_property(&result, "value")?
15090 .unwrap_or(Value::Undefined);
15091 return Ok((value, false));
15092 }
15093 // §7.4.4: `next` was read by `GetIteratorDirect` but its callability is only
15094 // tested at the call. Treating a non-callable `next` as "exhausted" instead made
15095 // `Object.fromEntries({[Symbol.iterator]: () => ({next: null})})` succeed with an
15096 // empty object, where §21.1.2.2's `? IteratorStepValue` must throw a `TypeError`.
15097 Err(Signal::Throw(self.make_error(
15098 "TypeError",
15099 "iterator's next method is not callable",
15100 )))
15101 }
15102
15103 /// `[...iterable]`: append everything the iterator yields, and answer the next
15104 /// index.
15105 ///
15106 /// This goes through the same iterator machinery `for-of` uses rather than copying
15107 /// an array's elements, because a spread source is any iterable: a string spreads
15108 /// into its characters and an array iterator spreads into its results. Handling
15109 /// only arrays made `[..."ab"]` come out empty with no error at all.
15110 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
15111 let Some(target) = array.as_object().cloned() else {
15112 return Ok(0);
15113 };
15114 let start = target.array_length().unwrap_or(0);
15115 let mut added = 0;
15116 let iterator = self.get_iterator(iterable)?;
15117 loop {
15118 let (value, done) = self.iterator_step(&iterator)?;
15119 if done {
15120 break;
15121 }
15122 target.array_set(self.heap, start + added, value);
15123 added += 1;
15124 }
15125 Ok((start + added) as i32)
15126 }
15127
15128 /// How an uncaught exception is reported.
15129 ///
15130 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
15131 /// with `ToString` — `js_std_dump_error` is three lines that end in
15132 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
15133 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
15134 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
15135 ///
15136 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
15137 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
15138 /// `toString`"; it does call it, but only for objects of a class it does not know how
15139 /// to walk, and never for errors, arrays or plain objects.
15140 ///
15141 /// A printer that fails must not take the reporter down with it, so that case falls
15142 /// back to the `ToString` rendering.
15143 pub fn describe_exception(&mut self, value: &Value) -> String {
15144 match crate::print::sprint(self, value) {
15145 Ok(text) => text,
15146 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
15147 }
15148 }
15149
15150 /// The file name of whatever is running, innermost frame first.
15151 ///
15152 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
15153 /// innermost frame's file name, without distinguishing a module body from a plain
15154 /// script. `import()` uses it as the base for a relative specifier, which is why
15155 /// `import('./x.js')` inside a script resolves next to the script and not next to the
15156 /// process's working directory.
15157 pub fn script_or_module_name(&self) -> Option<String> {
15158 self.script_or_module_name_at(0)
15159 }
15160
15161 /// [`Interp::script_or_module_name`] `level` frames further out.
15162 ///
15163 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
15164 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
15165 /// frame without a file name is skipped rather than counted, because a native call
15166 /// pushes no frame of its own and so cannot be a level.
15167 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
15168 self.frames
15169 .iter()
15170 .rev()
15171 .filter_map(|frame| frame.code.code.filename.clone())
15172 .nth(level)
15173 }
15174
15175 /// The innermost frame name that could be a *file*, skipping `<eval>`-style pseudo-names.
15176 ///
15177 /// `eval` and `std.evalScript` compile their bodies under `<input>` / `<evalScript>`
15178 /// because that is what a stack trace should print, but §19.2.1.1's
15179 /// `GetActiveScriptOrModule` makes an eval'd body belong to the script that called it —
15180 /// never to something called `<input>`. Resolving `import('./x.js')` against a pseudo-name
15181 /// produced the bare specifier `x.js`, which the loader then looked for in the working
15182 /// directory instead of beside the file that called `eval`.
15183 pub fn script_or_module_file_name(&self) -> Option<String> {
15184 self.frames.iter().rev().find_map(|frame| {
15185 let name = frame.code.code.filename.as_deref()?;
15186 (!name.starts_with('<')).then(|| name.to_string())
15187 })
15188 }
15189
15190 /// The current call stack, formatted the way `qjs` prints `error.stack`.
15191 ///
15192 /// One ` at name (file:line:col)` line per active frame, innermost first. The
15193 /// position is the one recorded for the instruction each frame is stopped on, which
15194 /// is why the compiler builds a pc-to-position table per function: without it a
15195 /// trace could only name the function, not the line inside it.
15196 ///
15197 /// A frame whose code has no positions prints just `(file)`, matching the
15198 /// reference's output for stripped bytecode.
15199 pub fn stack_trace(&self) -> String {
15200 self.stack_trace_skipping(0)
15201 }
15202
15203 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
15204 fn stack_trace_skipping(&self, skip: usize) -> String {
15205 // One ordered list, innermost first, so `skip` counts the same thing whether the
15206 // frames it leaves out are native or bytecode. Indices rather than references: a
15207 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
15208 let depth = self.frames.len();
15209 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
15210 // A native entered while `at` bytecode frames were live was called *from* the
15211 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
15212 // entered at the current depth are therefore innermost of all.
15213 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
15214 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
15215 if *at == wanted {
15216 order.push((true, index));
15217 }
15218 }
15219 };
15220 push_natives(&mut order, depth);
15221 for index in (0..depth).rev() {
15222 order.push((false, index));
15223 push_natives(&mut order, index);
15224 }
15225 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
15226 // barrier. Natives entered at exactly the barrier depth are the eval entry point
15227 // itself (`evalScript (native)`), and the reference leaves those out too.
15228 if let Some(barrier) = self.trace_barriers.last().copied() {
15229 order.retain(|(is_native, index)| match is_native {
15230 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
15231 false => *index >= barrier,
15232 });
15233 }
15234
15235 let mut out = String::new();
15236 for (is_native, index) in order.into_iter().skip(skip) {
15237 match is_native {
15238 true => {
15239 out.push_str(" at ");
15240 let (native, _) = &self.native_frames[index];
15241 let name = native
15242 .own_property("name")
15243 .and_then(|property| property.value)
15244 .map(|value| value.to_js_string())
15245 .unwrap_or_default();
15246 out.push_str(&name);
15247 out.push_str(" (native)\n");
15248 }
15249 false => {
15250 let frame = &self.frames[index];
15251 let code = &frame.code.code;
15252 let file = code.filename.as_deref().unwrap_or("<input>");
15253 // The name comes from the function *object*, not from the compiled code:
15254 // an anonymous function expression is named by the property it is stored
15255 // in (`{valueOf: function(){}}`), which only the object knows.
15256 let bound_name = match &frame.callee {
15257 Value::Object(object) => {
15258 object
15259 .own_property("name")
15260 .and_then(|property| match property.value {
15261 Some(Value::String(text)) if !text.wtf8().is_empty() => {
15262 Some(text.to_string_lossy().into_owned())
15263 }
15264 _ => None,
15265 })
15266 }
15267 _ => None,
15268 };
15269 // No callee object means the body was entered by the host, so the
15270 // name has to come from the compiled code. Two cases differ:
15271 //
15272 // * an *unnamed* function of any kind — the reference reads the
15273 // `name` property, finds it empty, and prints `<anonymous>`;
15274 // * a *module* body, which has no `name` property at all: the
15275 // reference builds that function object with `js_closure2` and
15276 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
15277 // so a trace reaching it also prints `<anonymous>` — while a
15278 // *script* body prints `<eval>`, its `name`.
15279 let unnamed = code.name.is_empty() || code.module.is_some();
15280 out.push_str(" at ");
15281 match bound_name.as_deref() {
15282 Some(name) => out.push_str(name),
15283 None if unnamed => out.push_str("<anonymous>"),
15284 None => out.push_str(&code.name),
15285 }
15286 match code.position_at(frame.at as u32) {
15287 Some((line, column)) => {
15288 out.push_str(&format!(" ({file}:{line}:{column})\n"));
15289 }
15290 None => out.push_str(&format!(" ({file})\n")),
15291 }
15292 }
15293 }
15294 }
15295 out
15296 }
15297
15298 /// Give an anonymous function the name of the property it is stored in.
15299 ///
15300 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
15301 /// enumerable and not configurable, and a function that already has a real name
15302 /// keeps it.
15303 ///
15304 /// "Already named" means a *non-empty* name: every function object is created with
15305 /// a `name` of `""` so the property exists on all of them, and treating that empty
15306 /// string as a name left every anonymous function nameless — which is how a stack
15307 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
15308 /// `SetFunctionName`, for a name that came from source text.
15309 fn set_function_name(&mut self, function: &Value, name: &str) {
15310 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
15311 }
15312
15313 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
15314 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
15315 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
15316 let Value::Object(object) = function else {
15317 return;
15318 };
15319 // `SetFunctionName` applies to *functions* and classes only, and only when they are
15320 // anonymous. Without the callability guard, `{value: someObject}` renamed
15321 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
15322 // on the right-hand side of a property. That is how a `zipKeyed` result object
15323 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
15324 // has no `NamedEvaluation` at all.
15325 if !object.is_callable() {
15326 return;
15327 }
15328 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
15329 && !existing.wtf8().is_empty()
15330 {
15331 return;
15332 }
15333 let text = self.string_wtf8(name.clone());
15334 object.define("name", Property::name_or_length(text));
15335 }
15336
15337 // -- global declarations -----------------------------------------------
15338
15339 /// Declare a global binding, creating its reference cell.
15340 /// Declare a `var` or function global, whose home is the global object.
15341 ///
15342 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
15343 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
15344 /// such as `print`, or a redeclaration — is left alone.
15345 pub fn declare_var_global(&mut self, name: &str) {
15346 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
15347 // global object is exactly the leak `typeof my_var === "undefined"` after
15348 // `eval("var my_var=2")` rules out.
15349 if let Some(scope) = self.eval_scope.as_mut() {
15350 scope.entry(name.to_string()).or_insert(Value::Undefined);
15351 return;
15352 }
15353 // A sloppy direct eval declares into its *caller's* variable environment. Doing
15354 // this on the global object instead made `eval("var c = 1")` inside a parameter
15355 // list overwrite a global `c`, and made two calls to the same function share one
15356 // binding.
15357 if let Some(cell) = self.declare_eval_local(name) {
15358 cell.set(Value::Undefined);
15359 return;
15360 }
15361 let global = self.realm.global.clone();
15362 if global.own_property(name).is_some() {
15363 return;
15364 }
15365 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
15366 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
15367 // whole point of that trick and what lets `Object.defineProperty` reshape it
15368 // afterwards. `eval_scope` is `Some` while an eval is running.
15369 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
15370 global.define(
15371 name,
15372 Property {
15373 value: Some(Value::Undefined),
15374 writable: true,
15375 enumerable: true,
15376 configurable: from_eval,
15377 ..Property::default()
15378 },
15379 );
15380 }
15381
15382 /// Declare a *lexical* global binding, which starts in its dead zone.
15383 ///
15384 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
15385 /// global object and is created when its initialiser runs.
15386 pub fn declare_global(&mut self, name: &str, is_const: bool) {
15387 if is_const {
15388 self.realm.lexical_consts.insert(name.to_string());
15389 }
15390 if !self.realm.globals.contains_key(name) {
15391 // `Uninitialized` rather than `Undefined`: the binding exists but is not
15392 // readable until its initialiser runs, and that is what `let x` before
15393 // `x = 1` has to observe.
15394 let cell = self.new_cell(Value::Uninitialized);
15395 self.realm.globals.insert(name.to_string(), cell);
15396 self.realm.declared.push(name.to_string());
15397 }
15398 }
15399}
15400
15401/// The bytecode and environment of a function object, if it is a bytecode function.
15402///
15403/// Extracted before a call so no borrow of the object is held across it.
15404fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
15405 function.with(|data| match &data.kind {
15406 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
15407 _ => None,
15408 })
15409}
15410
15411/// A native call target, extracted before the call so no borrow is held.
15412enum NativeCall {
15413 Native(NativeFn),
15414 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
15415 /// not hold that object's `RefCell` borrow.
15416 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
15417 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
15418 Bound {
15419 target: Value,
15420 this: Value,
15421 leading: Vec<Value>,
15422 },
15423 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
15424 Revoker(crate::object::ProxyRef),
15425 /// A promise's `resolve`.
15426 PromiseResolve(Gc<JsObject>),
15427 /// A promise's `reject`.
15428 PromiseReject(Gc<JsObject>),
15429 /// The executor `NewPromiseCapability(C)` hands a user constructor.
15430 CapabilityExecutor {
15431 state: Gc<JsObject>,
15432 },
15433 /// One leg of a `then` that settles through a user capability.
15434 ThenShim {
15435 handler: Option<Value>,
15436 resolve: Value,
15437 reject: Value,
15438 fulfilled: bool,
15439 },
15440 /// One continuation of an `await`.
15441 AwaitResume {
15442 coroutine: Gc<JsObject>,
15443 promise: Gc<JsObject>,
15444 kind: ResumeKind,
15445 },
15446 /// One element of a `Promise` combinator settling.
15447 CombinatorSettle {
15448 state: Gc<JsObject>,
15449 index: usize,
15450 fulfilled: bool,
15451 },
15452 /// One of `Promise.prototype.finally`'s two shims.
15453 FinallyShim {
15454 callback: Option<Value>,
15455 fulfilled: bool,
15456 constructor: Value,
15457 },
15458 /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
15459 ReturnValue(Value),
15460 /// A thunk that throws a fixed value, for `finally`'s `thrower`.
15461 ThrowValue(Value),
15462 /// Settle a promise with a fixed outcome.
15463 SettlePromise {
15464 promise: Gc<JsObject>,
15465 value: Value,
15466 rejected: bool,
15467 },
15468 /// Continue an async generator after its `await` settled.
15469 GeneratorResume {
15470 generator: Gc<JsObject>,
15471 promise: Gc<JsObject>,
15472 kind: ResumeKind,
15473 },
15474 /// Read a module namespace's binding out of its cell.
15475 ModuleBinding(Gc<Cell>),
15476 /// Finish a completed async generator's `return(v)` once `v` has settled.
15477 CompletedReturn {
15478 generator: Gc<JsObject>,
15479 promise: Gc<JsObject>,
15480 rejected: bool,
15481 },
15482 /// Answer a pending async-generator method with `{value, done}`.
15483 YieldResult {
15484 generator: Gc<JsObject>,
15485 promise: Gc<JsObject>,
15486 done: bool,
15487 },
15488 /// One step of `AsyncDisposableStack.disposeAsync`.
15489 DisposeStep {
15490 remaining: Gc<JsObject>,
15491 promise: Gc<JsObject>,
15492 error: Value,
15493 rejected: bool,
15494 awaited: bool,
15495 needs_await: bool,
15496 },
15497}
15498
15499/// What a store does when the object refuses the write.
15500#[derive(Clone, Copy, PartialEq, Eq)]
15501pub enum DeleteFailure {
15502 /// Raise a `TypeError`, which is what strict mode and every built-in does.
15503 Throw,
15504 /// Ignore the write, which is what a sloppy-mode assignment does.
15505 Ignore,
15506}
15507
15508/// Whether `object` is a `Date` instance, by the class tag it carries.
15509///
15510/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
15511/// builtins module depending on the interpreter's conversion order.
15512fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
15513 interp
15514 .internal_get(object, "_class")
15515 .is_some_and(|value| value.to_js_string() == "Date")
15516}
15517
15518/// Which type `ToPrimitive` prefers when it converts an object.
15519#[derive(Clone, Copy, PartialEq, Eq)]
15520pub enum Hint {
15521 /// The default hint, which behaves like [`Hint::Number`].
15522 Default,
15523 /// `Number(obj)` and the arithmetic operators.
15524 Number,
15525 /// `String(obj)` and `ToPropertyKey`.
15526 String,
15527}
15528
15529/// Which table a binding slot indexes, for the messages that name it.
15530#[derive(Clone, Copy)]
15531enum VarSlot {
15532 Loc,
15533 Closure,
15534}
15535
15536/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
15537fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
15538 Ok(this)
15539}
15540
15541/// An internal iterator: the sequence plus a cursor.
15542pub(crate) struct Iterator {
15543 pub(crate) object: Value,
15544 pub(crate) next: Value,
15545}
15546
15547/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
15548/// and plain `a` for a method.
15549///
15550/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
15551/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
15552/// reads `at get a (file:1:2)`.
15553/// The same prefixing, for a name that may hold an unpaired surrogate.
15554fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
15555 let prefix = match flags & 3 {
15556 1 => "get ",
15557 2 => "set ",
15558 _ => return key.clone(),
15559 };
15560 let mut units: Vec<u16> = prefix.encode_utf16().collect();
15561 units.extend_from_slice(&key.to_units());
15562 crate::value::Wtf8::from_units(&units)
15563}
15564
15565fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
15566 match flags & 3 {
15567 1 => format!("get {key}"),
15568 2 => format!("set {key}"),
15569 _ => key.to_string(),
15570 }
15571}
15572
15573/// Define a method or accessor property, per the `define_method` flag byte.
15574///
15575/// The low two bits pick value/getter/setter and bit 2 marks the property
15576/// enumerable.
15577///
15578/// A getter and a setter arrive as two separate `define_method` instructions, and the
15579/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
15580/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
15581/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
15582/// `JS_DefineProperty`, which leaves the other half alone.
15583fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
15584 let enumerable = flags & 4 != 0;
15585 let kind = flags & 3;
15586 let existing = object.own_property_key(key);
15587 let property = match kind {
15588 1 => Property {
15589 getter: Some(function),
15590 // The setter half, if this literal already defined one.
15591 setter: existing
15592 .filter(Property::is_accessor)
15593 .and_then(|p| p.setter),
15594 enumerable,
15595 configurable: true,
15596 ..Property::default()
15597 },
15598 2 => Property {
15599 getter: existing
15600 .filter(Property::is_accessor)
15601 .and_then(|p| p.getter),
15602 setter: Some(function),
15603 enumerable,
15604 configurable: true,
15605 ..Property::default()
15606 },
15607 _ => Property {
15608 value: Some(function),
15609 writable: true,
15610 enumerable,
15611 configurable: true,
15612 ..Property::default()
15613 },
15614 };
15615 object.define_key(key, property);
15616}
15617
15618// ---------------------------------------------------------------------------
15619// Operand decoding
15620// ---------------------------------------------------------------------------
15621
15622/// How `print` renders a value: the reference's `JS_PrintValue`.
15623///
15624/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
15625/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
15626/// The format is reproduced closely because the test suite compares output text:
15627///
15628/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
15629/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
15630/// * a cycle prints `[circular N]` with `N` the stack index of the object;
15631/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
15632/// end print as `<N empty item(s)>`;
15633/// * a string is quoted inside a container but raw at the top level, which is why
15634/// `print("x")` and `print(["x"])` differ.
15635pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
15636 // A string argument is printed raw: `js_print` converts it with `ToString`
15637 // instead of dumping it, and the quoting only appears inside a container.
15638 if let Value::String(text) = value {
15639 return text.to_string_lossy().into_owned();
15640 }
15641 let mut printer = Printer {
15642 interp,
15643 out: String::new(),
15644 stack: Vec::new(),
15645 };
15646 printer.value(value, 0);
15647 printer.out
15648}
15649
15650/// The internal class name an object carries, when it has one.
15651fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
15652 interp
15653 .internal_get(object, "_class")
15654 .map(|value| value.to_js_string())
15655}
15656
15657/// A string property, looked up the way `GetProperty` does: own first, then the
15658/// prototype chain. Needed because the print formatter holds the interpreter
15659/// immutably and so cannot run getters.
15660fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
15661 let mut current = Some(object.clone());
15662 // Bounded, because a prototype cycle would otherwise loop forever.
15663 for _ in 0..100 {
15664 let node = current?;
15665 if let Some(property) = node.own_property(name)
15666 && let Some(value) = property.value
15667 {
15668 return Some(value.to_js_string());
15669 }
15670 current = node.with(|data| data.proto.clone());
15671 }
15672 None
15673}
15674
15675/// The `JS_PrintValue` state: output, and the objects currently being printed.
15676struct Printer<'a, 'rt> {
15677 /// Kept for the class-name lookups that typed arrays and `Date` will need.
15678 #[allow(dead_code)]
15679 interp: &'a Interp<'rt>,
15680 out: String,
15681 stack: Vec<Gc<JsObject>>,
15682}
15683
15684impl Printer<'_, '_> {
15685 /// Depth past which a container is summarised by its class name.
15686 const MAX_DEPTH: usize = 2;
15687
15688 fn value(&mut self, value: &Value, level: usize) {
15689 match value {
15690 Value::Undefined
15691 | Value::Uninitialized
15692 | Value::Hole
15693 | Value::CatchOffset(_)
15694 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
15695 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
15696 // The printer writes a bigint the way the language spells one, so a dump is
15697 // unambiguous about which kind of number it is showing.
15698 Value::BigInt(big) => {
15699 self.out.push_str(&big.to_decimal_string());
15700 self.out.push('n');
15701 }
15702 Value::Null => self.out.push_str("null"),
15703 Value::Bool(true) => self.out.push_str("true"),
15704 Value::Bool(false) => self.out.push_str("false"),
15705 Value::Int(number) => self.out.push_str(&number.to_string()),
15706 Value::Float(number) => {
15707 self.out
15708 .push_str(&crate::value::number_to_string_for_print(*number));
15709 }
15710 Value::String(text) => self.print_string(&text.to_string_lossy()),
15711 Value::Object(object) => self.object(object, level),
15712 }
15713 }
15714
15715 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
15716 // A cycle is reported rather than followed; the index is where the object
15717 // already sits in the print stack, which is what the reference shows.
15718 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
15719 self.out.push_str(&format!("[circular {index}]"));
15720 return;
15721 }
15722 if object.is_callable() {
15723 let name = object
15724 .own_property("name")
15725 .and_then(|property| property.value)
15726 .map(|value| value.to_js_string())
15727 .unwrap_or_default();
15728 if name.is_empty() {
15729 self.out.push_str("[Function (anonymous)]");
15730 } else {
15731 self.out.push_str(&format!("[Function {name}]"));
15732 }
15733 return;
15734 }
15735 if level >= Self::MAX_DEPTH {
15736 let class = if object.is_array() { "Array" } else { "Object" };
15737 self.out.push_str(&format!("[{class}]"));
15738 return;
15739 }
15740 // `Date` and `Error` print as themselves rather than as bags of properties:
15741 // the ISO string, and `Name: message` followed by the trace.
15742 if let Some(class) = class_of(self.interp, object) {
15743 if class == "Date" {
15744 self.date(object);
15745 return;
15746 }
15747 if class == "Error" {
15748 self.error(object);
15749 return;
15750 }
15751 }
15752 self.stack.push(object.clone());
15753 if object.is_array() {
15754 self.array(object, level);
15755 } else {
15756 self.plain_object(object, level);
15757 }
15758 self.stack.pop();
15759 }
15760
15761 /// A Date prints as its ISO string; an invalid one falls through to the plain
15762 /// object form, the way the reference falls back when `toISOString` throws.
15763 fn date(&mut self, object: &Gc<JsObject>) {
15764 let value = self
15765 .interp
15766 .internal_get(object, "_date_value")
15767 .map(|value| value.to_number());
15768 match value.and_then(crate::builtins::date::iso_string) {
15769 Some(text) => self.out.push_str(&text),
15770 None => self.plain_object(object, 0),
15771 }
15772 }
15773
15774 /// `Name: message`, then the trace with its trailing newline removed.
15775 fn error(&mut self, object: &Gc<JsObject>) {
15776 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
15777 self.out.push_str(&name);
15778 if let Some(message) = inherited(object, "message")
15779 && !message.is_empty()
15780 {
15781 self.out.push_str(": ");
15782 self.out.push_str(&message);
15783 }
15784 if let Some(stack) = inherited(object, "stack") {
15785 self.out.push('\n');
15786 self.out.push_str(stack.trim_end_matches('\n'));
15787 }
15788 }
15789
15790 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
15791 let elements = object.array_elements().unwrap_or_default();
15792 self.out.push_str("[ ");
15793 // An interior hole means the array is "sparse": the reference prints those
15794 // as `index: value` pairs and says nothing about the holes themselves, while
15795 // a hole run at the end becomes a single `<N empty items>` note.
15796 let last_present = elements
15797 .iter()
15798 .rposition(|value| !matches!(value, Value::Hole));
15799 let has_interior_hole = match last_present {
15800 Some(last) => elements[..last]
15801 .iter()
15802 .any(|value| matches!(value, Value::Hole)),
15803 None => false,
15804 };
15805 let mut first = true;
15806 if has_interior_hole {
15807 let mut index = 0;
15808 while index < elements.len() {
15809 let value = &elements[index];
15810 if matches!(value, Value::Hole) {
15811 index += 1;
15812 continue;
15813 }
15814 if !first {
15815 self.out.push_str(", ");
15816 }
15817 first = false;
15818 self.out.push_str(&format!("{index}: "));
15819 self.value(value, level + 1);
15820 index += 1;
15821 }
15822 } else {
15823 for (index, value) in elements.iter().enumerate() {
15824 if matches!(value, Value::Hole) {
15825 continue;
15826 }
15827 if !first {
15828 self.out.push_str(", ");
15829 }
15830 first = false;
15831 let _ = index;
15832 self.value(value, level + 1);
15833 }
15834 if let Some(last) = last_present {
15835 let trailing = elements.len() - last - 1;
15836 if trailing > 0 {
15837 if !first {
15838 self.out.push_str(", ");
15839 }
15840 self.out.push_str(&format!(
15841 "<{trailing} empty item{}>",
15842 if trailing > 1 { "s" } else { "" }
15843 ));
15844 }
15845 } else if !elements.is_empty() {
15846 let count = elements.len();
15847 self.out.push_str(&format!(
15848 "<{count} empty item{}>",
15849 if count > 1 { "s" } else { "" }
15850 ));
15851 }
15852 }
15853 self.out.push_str(" ]");
15854 }
15855
15856 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
15857 self.out.push_str("{ ");
15858 let mut first = true;
15859 for key in object.own_keys() {
15860 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
15861 continue;
15862 };
15863 if !property.enumerable {
15864 continue;
15865 }
15866 if !first {
15867 self.out.push_str(", ");
15868 }
15869 first = false;
15870 self.out
15871 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
15872 &key.to_string_lossy(),
15873 )));
15874 self.out.push_str(": ");
15875 // An accessor has no value to dump; the reference names the half that
15876 // exists instead of calling it.
15877 if property.is_accessor() {
15878 let text = match (property.getter.is_some(), property.setter.is_some()) {
15879 (true, true) => "[Getter/Setter]",
15880 (false, true) => "[Setter]",
15881 _ => "[Getter]",
15882 };
15883 self.out.push_str(text);
15884 } else {
15885 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
15886 }
15887 }
15888 self.out.push_str(" }");
15889 }
15890
15891 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
15892 fn print_string(&mut self, text: &str) {
15893 self.out.push('"');
15894 for character in text.chars() {
15895 match character {
15896 '"' => self.out.push_str("\\\""),
15897 '\\' => self.out.push_str("\\\\"),
15898 '\n' => self.out.push_str("\\n"),
15899 '\r' => self.out.push_str("\\r"),
15900 '\t' => self.out.push_str("\\t"),
15901 c if (c as u32) < 0x20 => {
15902 self.out.push_str(&format!("\\u{:04x}", c as u32));
15903 }
15904 c => self.out.push(c),
15905 }
15906 }
15907 self.out.push('"');
15908 }
15909}
15910
15911/// How `print` renders a value.
15912///
15913/// `ToString`, except that negative zero keeps its sign — the reference's host
15914/// printer does that while `String(-0)` is `"0"`.
15915pub fn display(value: &Value) -> String {
15916 match value {
15917 Value::Float(number) => crate::value::number_to_string_for_print(*number),
15918 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
15919 "undefined".to_string()
15920 }
15921 other => other.to_js_string(),
15922 }
15923}
15924
15925// ---------------------------------------------------------------------------
15926// Numeric operators
15927// ---------------------------------------------------------------------------
15928
15929/// `a + b` keeping the `Int` representation when it fits.
15930fn add_numbers(left: Value, right: Value) -> Value {
15931 match (&left, &right) {
15932 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
15933 Some(sum) => Value::Int(sum),
15934 None => Value::Float(*a as f64 + *b as f64),
15935 },
15936 _ => Value::Float(left.to_number() + right.to_number()),
15937 }
15938}
15939
15940/// The arithmetic operators other than `+`, which needs string concatenation.
15941fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15942 use Opcode::*;
15943 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
15944 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
15945 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
15946 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
15947 return Ok(match op {
15948 And => Value::Int(x & y),
15949 Or => Value::Int(x | y),
15950 Xor => Value::Int(x ^ y),
15951 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
15952 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
15953 Shr => match (*x as u32) >> ((*y as u32) & 31) {
15954 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
15955 shifted => Value::Float(shifted as f64),
15956 },
15957 Sub => match x.checked_sub(*y) {
15958 Some(value) => Value::Int(value),
15959 None => Value::Float(*x as f64 - *y as f64),
15960 },
15961 _ => return arithmetic_slow(op, left, right),
15962 });
15963 }
15964 arithmetic_slow(op, left, right)
15965}
15966
15967/// [`arithmetic`] for everything the integer fast path above does not take.
15968fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15969 use Opcode::*;
15970 let (a, b) = (left.to_number(), right.to_number());
15971 Ok(match op {
15972 Sub => match (&left, &right) {
15973 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
15974 Some(value) => Value::Int(value),
15975 None => Value::Float(a - b),
15976 },
15977 _ => Value::Float(a - b),
15978 },
15979 Mul => Value::Float(a * b),
15980 Div => Value::Float(a / b),
15981 Mod => Value::Float(js_mod(a, b)),
15982 Pow => Value::Float(a.powf(b)),
15983 And => Value::Int(left.to_int32() & right.to_int32()),
15984 Or => Value::Int(left.to_int32() | right.to_int32()),
15985 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
15986 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
15987 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
15988 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
15989 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
15990 // fits the small-integer representation stays an `Int`; the rest become a
15991 // float, which is how the reference keeps `n >>> 0` non-negative.
15992 Shr => {
15993 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
15994 match i32::try_from(shifted) {
15995 Ok(value) => Value::Int(value),
15996 Err(_) => Value::Float(shifted as f64),
15997 }
15998 }
15999 _ => Value::Float(a),
16000 })
16001}
16002
16003/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
16004///
16005/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
16006/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
16007/// slow path where the rules live.
16008fn is_number(value: &Value) -> bool {
16009 matches!(value, Value::Int(_) | Value::Float(_))
16010}
16011
16012/// The `Value::Bool` a comparison operator answers for `ordering`.
16013///
16014/// `None` is the unordered case — a `NaN` on either side — and every operator answers
16015/// false for it, including `<=` and `>=`.
16016fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
16017 use Opcode::*;
16018 let answer = match (op, ordering) {
16019 (_, None) => false,
16020 (Lt, Some(ordering)) => ordering.is_lt(),
16021 (Lte, Some(ordering)) => ordering.is_le(),
16022 (Gt, Some(ordering)) => ordering.is_gt(),
16023 (Gte, Some(ordering)) => ordering.is_ge(),
16024 _ => false,
16025 };
16026 Value::Bool(answer)
16027}
16028
16029/// `%`, which follows the sign of the dividend rather than Rust's.
16030fn js_mod(left: f64, right: f64) -> f64 {
16031 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
16032 return f64::NAN;
16033 }
16034 if right.is_infinite() {
16035 return left;
16036 }
16037 let remainder = left % right;
16038 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
16039 // the spec makes the sign match the dividend.
16040 if remainder == 0.0 {
16041 0.0f64.copysign(left)
16042 } else {
16043 remainder
16044 }
16045}
16046
16047fn negate(value: Value) -> Value {
16048 match value {
16049 Value::Int(0) => Value::Float(-0.0),
16050 Value::Int(i) => Value::Int(-i),
16051 other => Value::Float(-other.to_number()),
16052 }
16053}
16054
16055fn increment(value: Value) -> Value {
16056 match value {
16057 Value::Int(i) => match i.checked_add(1) {
16058 Some(next) => Value::Int(next),
16059 None => Value::Float(i as f64 + 1.0),
16060 },
16061 other => Value::Float(other.to_number() + 1.0),
16062 }
16063}
16064
16065fn decrement(value: Value) -> Value {
16066 match value {
16067 Value::Int(i) => match i.checked_sub(1) {
16068 Some(next) => Value::Int(next),
16069 None => Value::Float(i as f64 - 1.0),
16070 },
16071 other => Value::Float(other.to_number() - 1.0),
16072 }
16073}
16074
16075/// Compare a `BigInt` with an `f64` on their mathematical values.
16076///
16077/// Neither side is rounded to the other's precision: the number is split into its integer
16078/// part (compared as an exact bigint) and its fraction, which is what decides the answer
16079/// when the integer parts are equal. An infinite value is larger than every bigint.
16080fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
16081 use std::cmp::Ordering;
16082 if number.is_nan() {
16083 return None;
16084 }
16085 if number.is_infinite() {
16086 return Some(if number > 0.0 {
16087 Ordering::Less
16088 } else {
16089 Ordering::Greater
16090 });
16091 }
16092 let truncated = number.trunc();
16093 // A number wider than `i128` still has an exact integer part, but no bigint form we can
16094 // build cheaply; the sign of the difference is all that is needed, so compare against
16095 // the bigint's own magnitude instead.
16096 if truncated.abs() >= 1.7e38 {
16097 let big_as_f64 = big.to_f64();
16098 return big_as_f64.partial_cmp(&number);
16099 }
16100 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
16101 match big.cmp(&integer) {
16102 Ordering::Equal => {
16103 // Same integer part: the fraction decides, and a negative number's fraction is
16104 // below the integer (`-1.5` truncates to `-1`).
16105 if number > truncated {
16106 Some(Ordering::Less)
16107 } else if number < truncated {
16108 Some(Ordering::Greater)
16109 } else {
16110 Some(Ordering::Equal)
16111 }
16112 }
16113 other => Some(other),
16114 }
16115}
16116
16117/// `CanonicalNumericIndexString(argument)` (§7.1.21).
16118///
16119/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
16120/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
16121/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
16122/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
16123/// rather than treating it as `0`.
16124fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
16125 let PropertyKey::String(text) = key else {
16126 // A symbol is never an index.
16127 return None;
16128 };
16129 let text = text.to_string_lossy();
16130 if text == "-0" {
16131 return Some(-0.0);
16132 }
16133 let number: f64 = text.parse().ok()?;
16134 // The round-trip test *is* the definition: only the canonical spelling qualifies.
16135 // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
16136 // `"0.10"` does not.
16137 let rendered = Value::Float(number).to_js_string();
16138 (rendered == text).then_some(number)
16139}
16140
16141/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
16142///
16143/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
16144/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
16145/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
16146/// numeric and invalid, which is why they stop the prototype chain instead of falling
16147/// through it.
16148///
16149/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
16150/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
16151/// `in`, `delete` and `defineProperty` separately to make sure it does not.
16152fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
16153 numeric.is_finite()
16154 && numeric.fract() == 0.0
16155 && !(numeric == 0.0 && numeric.is_sign_negative())
16156 && numeric >= 0.0
16157 && object
16158 .typed_array_length()
16159 .is_some_and(|length| (numeric as usize) < length)
16160}
16161
16162/// `ArrayCreate`'s length bound, `2**32 - 1`.
16163///
16164/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
16165/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
16166/// through — can enforce it without depending on a builtin module.
16167const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;