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 let context = js_parse::EvalContext {
4082 in_method: self.enclosing_home_object().is_some(),
4083 // `super()` belongs to a derived constructor, and an eval'd body is not a
4084 // constructor at all: the caller frame's `this` is already built.
4085 in_derived_constructor: false,
4086 };
4087 // A *global* eval is not a function body: `new.target` and `super` are out of
4088 // reach there. Its `{async: true}` form differs in the other direction — the body
4089 // may `await` — so the two flags are independent and the reference sets both from
4090 // the eval type rather than from the caller.
4091 let parsed = if async_body {
4092 js_parse::parse_suspensible_global_eval(source, strict)
4093 } else {
4094 js_parse::parse_eval_script_in(source, strict, context)
4095 };
4096 let program = match parsed {
4097 Ok(program) => program,
4098 Err(error) => {
4099 // The message is bare: the position lives in `fileName`,
4100 // `lineNumber`, `columnNumber` and the stack frame above, which is where
4101 // the reference puts it. An `invalid source: L:C: ` prefix made
4102 // `e.message` differ from the reference while the stack already agreed.
4103 return Err(Signal::Throw(self.syntax_error_at(
4104 file,
4105 error.span.start.line,
4106 error.span.start.column,
4107 &error.message,
4108 )));
4109 }
4110 };
4111 let mut compiled = match if async_body {
4112 js_compile::compile_script_suspensible(&program)
4113 } else {
4114 js_compile::compile_script(&program)
4115 } {
4116 Ok(compiled) => compiled,
4117 // A construct the compiler does not handle yet is reported the same way a
4118 // parse error is: it happens before anything runs, so the trace is the
4119 // position in the source followed by the caller.
4120 Err(error) => {
4121 return Err(Signal::Throw(self.syntax_error_at(
4122 file,
4123 error.span.start.line,
4124 error.span.start.column,
4125 &error.message,
4126 )));
4127 }
4128 };
4129 compiled.set_filename(file);
4130 Ok(compiled)
4131 }
4132
4133 /// Run an `eval`'d script in the caller's scope.
4134 ///
4135 /// Three things have to come from the calling frame, because the eval'd code is a
4136 /// script and would otherwise see only the global object:
4137 ///
4138 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
4139 /// * `arguments`, exposed as a binding of the eval's own scope, so
4140 /// `f("arguments.length", 1)` sees the caller's arguments;
4141 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
4142 /// `eval("var v = 1")` into the global object.
4143 ///
4144 /// Locals of the calling function are *not* reachable: that needs the compiler to
4145 /// hand its variable environment over, which this milestone does not do.
4146 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
4147 // `this` and `arguments` come from the innermost frame only — those are not
4148 // lexical — while the name bindings come from the whole chain of frames, part
4149 // of it being ordinary scope resolution.
4150 // An arrow has no `this` of its own, so an `eval` inside one inherits the
4151 // enclosing function's receiver — the lexical `this` the arrow was compiled to
4152 // read from its closure.
4153 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
4154 // variable environment is the innermost frame of all: an arrow's own body is where
4155 // `var`s declared by an `eval` inside it belong.
4156 let caller_index = self
4157 .frames
4158 .iter()
4159 .rposition(|frame| !frame.code.code.is_arrow)
4160 .or_else(|| self.frames.len().checked_sub(1));
4161 let env_index = self.frames.len().checked_sub(1);
4162 let caller = caller_index.and_then(|index| self.frames.get(index));
4163 let (this, passed) = match caller {
4164 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
4165 // No frame at all: the eval is running at the top level, so there is
4166 // nothing to inherit and the global receiver is right.
4167 None => (Value::Object(self.realm.global.clone()), Vec::new()),
4168 };
4169 // Innermost frame first, so the first binding found for a name is the one that
4170 // shadows the rest. A script frame (`<eval>`) contributes nothing.
4171 let mut bindings: Vec<EvalBinding> = Vec::new();
4172 // The calling function's own bindings, resolved by the compiler at the call
4173 // site. That table is the only reliable answer when a name is declared twice in
4174 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
4175 // body means, and guessing by declaration order picks the wrong one as soon as
4176 // two loops in a row use the same name.
4177 // Only a *direct* eval sees the caller's scope. The compiler records a site for
4178 // every direct call — a bare `eval(...)` callee — so finding one at the current
4179 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
4180 // callee to a value first and leave no site behind.
4181 let mut direct = false;
4182 let mut resolved_here = false;
4183 if let Some(frame) = self.frames.last() {
4184 let (line, column) = frame
4185 .code
4186 .code
4187 .position_at(frame.at as u32)
4188 .unwrap_or_default();
4189 // The nearest site at or before the current position, not an exact match:
4190 // the recorded position of the `call` instruction is the callee's, which
4191 // sits a few columns inside the call expression the compiler recorded. A
4192 // site is unique per call, so "the closest one behind us" identifies it.
4193 if let Some(site) = frame
4194 .code
4195 .code
4196 .eval_sites
4197 .iter()
4198 .filter(|site| (site.line, site.column) <= (line, column))
4199 .max_by_key(|site| (site.line, site.column))
4200 {
4201 direct = true;
4202 resolved_here = true;
4203 for binding in &site.bindings {
4204 // An enclosing function's frame sits `owner` levels below the one
4205 // running the call.
4206 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
4207 else {
4208 continue;
4209 };
4210 bindings.push(EvalBinding {
4211 name: binding.name.clone(),
4212 frame,
4213 slot: if binding.is_arg {
4214 EvalSlot::Arg
4215 } else {
4216 EvalSlot::Local
4217 },
4218 index: binding.index as usize,
4219 });
4220 }
4221 }
4222 }
4223 for frame_index in (0..self.frames.len()).rev() {
4224 // Skip the innermost frame's flat scan when the compiler already answered
4225 // for it; an enclosing frame still needs one, because the eval resolves
4226 // those names dynamically.
4227 if resolved_here && frame_index == self.frames.len() - 1 {
4228 continue;
4229 }
4230 let frame = &self.frames[frame_index];
4231 for (index, arg) in frame.code.code.args.iter().enumerate() {
4232 bindings.push(EvalBinding {
4233 name: arg.name.clone(),
4234 frame: frame_index,
4235 slot: EvalSlot::Arg,
4236 index,
4237 });
4238 }
4239 for (index, local) in frame.code.code.vars.iter().enumerate() {
4240 bindings.push(EvalBinding {
4241 name: local.name.clone(),
4242 frame: frame_index,
4243 slot: EvalSlot::Local,
4244 index,
4245 });
4246 }
4247 }
4248 let mut seen = BTreeSet::new();
4249 bindings.retain(|binding| seen.insert(binding.name.clone()));
4250
4251 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4252 // elements is all the spec's ordinary uses need.
4253 //
4254 // Known divergence: this is bound for a *global* eval too, where there is no
4255 // caller and the reference throws `'arguments' is not defined`. Deciding properly
4256 // needs "does the calling frame have an `arguments` of its own", which is not
4257 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4258 // script or eval body does not, and `eval(b)` passes the callee as a value so even
4259 // the call-site detection does not answer it. Modelled as a binding in the caller's
4260 // variable environment, this would fall out; that is a larger change than the one
4261 // this comment is attached to.
4262 let arguments = Value::Object(self.new_array(passed));
4263
4264 // Only a *strict* eval gets a variable environment of its own. A sloppy one
4265 // declares its `var`s in the caller's — which for a top-level eval is the global
4266 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4267 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4268 // vanish into a scope nobody reads back from.
4269 let previous_scope = if code_strict {
4270 self.eval_scope.replace(BTreeMap::new())
4271 } else {
4272 None
4273 };
4274 let previous_arguments = self.eval_arguments.replace(arguments);
4275 let previous_with = self.eval_with.replace(self.with_objects());
4276 let inherited_new_target = self
4277 .frames
4278 .iter()
4279 .rev()
4280 .find(|frame| !frame.code.code.is_arrow)
4281 .map(|frame| frame.new_target.clone());
4282 let previous_new_target = self
4283 .eval_new_target
4284 .replace(inherited_new_target.unwrap_or(Value::Undefined));
4285 let eval_cells = self.eval_cells_for(&bindings);
4286 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4287 // A sloppy direct eval declares its `var`s in the caller's variable environment;
4288 // `declare_eval_local` needs to know which frame that is.
4289 // An indirect eval gets the global environment, so nothing of the caller's is
4290 // recorded as the place its `var`s belong.
4291 let previous_caller = self
4292 .eval_caller
4293 .replace(if direct { env_index } else { None });
4294 // The cell-based view of the same bindings, which is what a closure created
4295 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4296 // whose compiler did not put a binding in a cell simply does not appear here —
4297 // reads and writes still work through `eval_bindings`, they just cannot outlive
4298 // the eval.
4299 let previous_eval_scope = self
4300 .active_eval_scope
4301 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4302 let compiled = Gc::new(self.heap, CompiledCode::new(code));
4303 let closure_vars = compiled.code.closure_vars.clone();
4304 // Declaration instantiation is where this belongs: the check needs the caller frame
4305 // (recorded just above) and the eval's own var names, and it raises before any of
4306 // the eval's code runs.
4307 self.check_eval_var_named_arguments(&closure_vars, code_strict)?;
4308 let env = self.global_env(&closure_vars);
4309 let callee = Value::Undefined;
4310 // An async body does not run here: it becomes a coroutine and answers a promise,
4311 // which is what makes `await` legal in it. `this` still has to be the caller's
4312 // (for a global eval, the global object), because `this` is not part of `await`.
4313 let result = if compiled.code.kind.is_async() {
4314 self.run_async_body(compiled, env, this)
4315 } else {
4316 self.execute(compiled, env, this, Vec::new(), callee)
4317 };
4318 self.eval_scope = previous_scope;
4319 self.eval_arguments = previous_arguments;
4320 self.eval_with = previous_with;
4321 self.eval_new_target = previous_new_target;
4322 self.eval_bindings = previous_bindings;
4323 self.eval_caller = previous_caller;
4324 self.active_eval_scope = previous_eval_scope;
4325 result
4326 }
4327
4328 /// The declarations an eval cannot instantiate: they are `SyntaxError`/`TypeError`
4329 /// rather than bindings.
4330 ///
4331 /// Two rules, both from `EvalDeclarationInstantiation` (§19.2.1.3) and both about a
4332 /// declaration that cannot exist:
4333 ///
4334 /// * **`var arguments` in a function's parameter scope.** §10.2.1.3 gives a function with
4335 /// parameter expressions a separate parameter environment, and `arguments` is bound
4336 /// implicitly there, so a `var` of that name collides. An arrow that binds no
4337 /// `arguments` of its own has nothing to collide with and is allowed — see the table in
4338 /// [`Interp::check_eval_var_named_arguments`].
4339 /// * **A global `var` on a non-extensible global object**, where `CanDeclareGlobalVar` is
4340 /// false; the operation is a `TypeError`, and `eval("var x")` with
4341 /// `Object.preventExtensions(this)` must raise rather than quietly do nothing
4342 /// (`non-definable-global-var` and its four siblings).
4343 fn check_eval_var_named_arguments(
4344 &self,
4345 closure_vars: &[js_compile::bytecode::ClosureVar],
4346 strict: bool,
4347 ) -> JsResult<()> {
4348 if strict {
4349 return Ok(());
4350 }
4351 // A `var` this eval would declare on the global object, where there is no room for it.
4352 let global = &self.realm.global;
4353 if !global.is_extensible() {
4354 for var in closure_vars {
4355 if var.is_lexical || var.name == "*default*" {
4356 continue;
4357 }
4358 let declare = matches!(
4359 var.closure_type,
4360 js_compile::bytecode::ClosureType::GlobalDecl
4361 );
4362 if declare && global.own_property(&var.name).is_none() {
4363 return Err(Signal::Throw(self.make_error(
4364 "TypeError",
4365 "cannot declare a global in a non-extensible global object",
4366 )));
4367 }
4368 }
4369 }
4370 // Only a *direct* eval declares into a caller's environment; an indirect one gets the
4371 // global environment, where `var arguments` is an ordinary global.
4372 let Some(caller) = self.eval_caller.flatten() else {
4373 return Ok(());
4374 };
4375 if !closure_vars
4376 .iter()
4377 .any(|var| var.name == "arguments" && !var.is_lexical)
4378 {
4379 return Ok(());
4380 }
4381 // The body of a function is a different environment from its parameter list, and only
4382 // the parameter list is separate from `arguments`.
4383 if !self.in_parameter_list_at(caller) {
4384 return Ok(());
4385 }
4386 let caller_is_arrow = self
4387 .frames
4388 .get(caller)
4389 .is_some_and(|frame| frame.code.code.is_arrow);
4390 // A *parameter* named `arguments`, not merely a binding of that name: a body
4391 // `let arguments` is in the body's environment, which is the one that is separate and
4392 // therefore cannot collide. The slot tells them apart — an argument lives in
4393 // `EvalSlot::Arg`, a lexical in `EvalSlot::Local`.
4394 let parameter_scope_binds_arguments = self.eval_bindings.iter().any(|binding| {
4395 binding.frame == caller
4396 && binding.name == "arguments"
4397 && matches!(binding.slot, EvalSlot::Arg)
4398 });
4399 if caller_is_arrow && !parameter_scope_binds_arguments {
4400 return Ok(());
4401 }
4402 Err(Signal::Throw(self.make_error(
4403 "SyntaxError",
4404 "eval declares 'arguments' in a function's parameter scope",
4405 )))
4406 }
4407
4408 /// The cell-backed subset of `bindings`, in the same priority order.
4409 ///
4410 /// Both lookup routes have to agree — the eval's own reads go through
4411 /// [`Interp::eval_binding_value`] and the closures it builds go through
4412 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4413 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4414 /// is not in a cell simply does not appear: reads and writes still work, they just
4415 /// cannot be handed to a closure that outlives the eval.
4416 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4417 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4418 for binding in bindings {
4419 let Some(frame) = self.frames.get(binding.frame) else {
4420 continue;
4421 };
4422 let cell = match binding.slot {
4423 EvalSlot::Arg => frame
4424 .code
4425 .arg_cell
4426 .get(binding.index)
4427 .copied()
4428 .unwrap_or(-1),
4429 EvalSlot::Local => frame
4430 .code
4431 .loc_cell
4432 .get(binding.index)
4433 .copied()
4434 .unwrap_or(-1),
4435 };
4436 if cell < 0 {
4437 continue;
4438 }
4439 if let Some(cell) = frame.cells.get(cell as usize) {
4440 names.push((binding.name.clone(), cell.clone()));
4441 }
4442 }
4443 names
4444 }
4445
4446 /// A `SyntaxError` that reports where in the source it happened.
4447 ///
4448 /// Compile-time failures never run, so they have no frame of their own; the
4449 /// reference still puts the position first in the trace, with no function name and
4450 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4451 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4452 /// reference borrows), which is how a script reads the position without parsing
4453 /// the trace.
4454 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4455 ///
4456 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4457 /// `columnNumber`, which is how the reference prints one. A positionless error
4458 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4459 /// the reference raises it from `js_resolve_module`, where there is no position.
4460 pub(crate) fn syntax_error_plain(
4461 &mut self,
4462 error: &js_parse::SyntaxError,
4463 file: &str,
4464 ) -> Value {
4465 if error.positionless {
4466 return self.make_error("SyntaxError", &error.message);
4467 }
4468 self.syntax_error_at(
4469 file,
4470 error.span.start.line,
4471 error.span.start.column,
4472 &error.message,
4473 )
4474 }
4475
4476 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4477 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
4478 let value = self.make_error("SyntaxError", message);
4479 if let Value::Object(object) = &value {
4480 let text = self.string(blamed);
4481 // `stack` is an own data property, and the reference keeps it
4482 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4483 object.define("stack", Property::with_attributes(text, true, false));
4484 let name = self.string(file);
4485 object.define("fileName", Property::with_attributes(name, true, true));
4486 object.define(
4487 "lineNumber",
4488 Property::with_attributes(Value::Int(line as i32), true, true),
4489 );
4490 object.define(
4491 "columnNumber",
4492 Property::with_attributes(Value::Int(column as i32), true, true),
4493 );
4494 }
4495 value
4496 }
4497
4498 /// Run a compiled script whose completion value is a function, returning it.
4499 ///
4500 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4501 /// get the closure out, which keeps the constant-pool plumbing in one place.
4502 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4503 self.run_script(code)
4504 }
4505
4506 /// The environment of a script or of any function compiled at global scope:
4507 /// every entry is a global binding, so each one resolves to the realm's cell.
4508 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4509 let mut cells = Vec::with_capacity(closure_vars.len());
4510 for closure_var in closure_vars {
4511 let cell = match closure_var.closure_type {
4512 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4513 if closure_var.is_lexical =>
4514 {
4515 // A lexical declaration: the cell is created here holding the
4516 // dead-zone marker, which is what makes the binding exist and
4517 // unreadable before its initialiser runs.
4518 self.declare_global(&closure_var.name, closure_var.is_const);
4519 self.realm.globals[&closure_var.name].clone()
4520 }
4521 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4522 // A `var` or function declaration becomes a property of the global
4523 // object, and it exists from here on — which is why
4524 // `print(v); var v = 1` prints `undefined` instead of raising.
4525 // Declaring it at instantiation time (rather than at the
4526 // initialiser) is also what makes it non-configurable: the store
4527 // then lands on an existing property instead of creating one.
4528 self.declare_var_global(&closure_var.name);
4529 // The cell is a placeholder that nothing indexes; it cannot be
4530 // omitted because the slot has to hold something.
4531 self.new_cell(Value::Undefined)
4532 }
4533 _ => {
4534 // An undeclared global is read by name; the cell is a
4535 // placeholder that nothing indexes.
4536 self.new_cell(Value::Undefined)
4537 }
4538 };
4539 cells.push(cell);
4540 }
4541 Gc::new(
4542 self.heap,
4543 ClosureEnv {
4544 cells,
4545 eval_scope: None,
4546 local_vars: None,
4547 local_phase: 1,
4548 },
4549 )
4550 }
4551
4552 /// Push a frame and run until it returns.
4553 pub(crate) fn execute(
4554 &mut self,
4555 code: Gc<CompiledCode>,
4556 env: Gc<ClosureEnv>,
4557 this: Value,
4558 args: Vec<Value>,
4559 callee: Value,
4560 ) -> JsResult<Value> {
4561 let depth = self.frames.len();
4562 if depth == 0 {
4563 // A throw that reached the host ends the *active* mode: the next one is catchable
4564 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4565 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4566 // for the throw that evaluation will raise.
4567 self.uncatchable = false;
4568 }
4569 self.push_frame(code, env, this, args, callee)?;
4570 loop {
4571 // The fast loop first: it runs whole runs of records with `pc` in a register.
4572 //
4573 // `step`'s `pc` lives in the frame, so every instruction writes it back and
4574 // reads it again — a store, a load and two bounds checks that a loop body does
4575 // not need, because nothing outside the loop can run in between. This is the
4576 // classic split: advance a register, and only spill it when leaving.
4577 //
4578 // `Some(value)` means the function ended by running off the end of its
4579 // instruction array, which is a normal return.
4580 let step = match self.run_fast() {
4581 Ok(Some(value)) => Ok(Step::Return(value)),
4582 Ok(None) => self.step(),
4583 Err(signal) => Err(signal),
4584 };
4585 match step {
4586 Ok(Step::Continue) => {}
4587 Ok(Step::Return(value)) => {
4588 self.pop_frame();
4589 // A frame that ended in a `tail_call` hands its value straight to
4590 // its caller: nothing after the call can run, so every frame above
4591 // the callee unwinds with the same value. See [`Frame::tail`] —
4592 // the reference does not reuse frames either, so recursion depth
4593 // and the stack-overflow limit behave the same way.
4594 while self.frames.len() > depth && self.frame().tail {
4595 self.pop_frame();
4596 }
4597 if self.frames.len() == depth {
4598 return Ok(value);
4599 }
4600 // The caller resumes with the value on its stack.
4601 self.frames
4602 .last_mut()
4603 .expect("a caller is live")
4604 .stack
4605 .push(value);
4606 }
4607 Err(Signal::Throw(value)) => {
4608 // The host's standing request becomes the active mode for this unwind,
4609 // and is consumed here so it does not leak into the next throw.
4610 if self.uncatchable_next {
4611 self.uncatchable_next = false;
4612 self.uncatchable = true;
4613 }
4614 // An uncatchable throw walks past every `catch` on the way out. The
4615 // frames are still popped, because the values they hold have to be
4616 // dropped — only the search for a handler is skipped.
4617 if self.uncatchable {
4618 while self.frames.len() > depth {
4619 self.frames.pop();
4620 }
4621 return Err(Signal::Throw(value));
4622 }
4623 // A handler lives on the stack of the frame that is throwing —
4624 // `catch` pushed it there — so this frame gets the first chance
4625 // to catch before it is popped.
4626 let value = value;
4627 loop {
4628 if self.frames.len() <= depth {
4629 return Err(Signal::Throw(value));
4630 }
4631 if self.catch_here(value.clone()).is_some() {
4632 break;
4633 }
4634 self.frames.pop();
4635 }
4636 }
4637 // A `yield` in a frame that `execute` is running directly means a
4638 // generator body was entered as an ordinary call, which only happens if
4639 // the generator check in `call_or_push` was bypassed.
4640 Ok(Step::Suspend(_)) => {
4641 return Err(Signal::Throw(self.make_error(
4642 "InternalError",
4643 "a generator body ran as an ordinary call",
4644 )));
4645 }
4646 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4647 }
4648 }
4649 }
4650
4651 /// Install a handler for `value` if this frame has one, resuming at it.
4652 ///
4653 /// The scan is the reference's: walk the frame's stack downwards looking for the
4654 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
4655 /// `0` is an enumerator marker rather than a handler — it exists so that a
4656 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
4657 /// here and the unwinding continues.
4658 fn catch_here(&mut self, value: Value) -> Option<()> {
4659 let frame = self.frames.last_mut()?;
4660 while let Some(top) = frame.stack.pop() {
4661 if let Value::CatchOffset(offset) = top {
4662 if offset == 0 {
4663 continue;
4664 }
4665 frame.stack.push(value);
4666 frame.pc = offset as usize;
4667 return Some(());
4668 }
4669 }
4670 None
4671 }
4672
4673 fn push_frame(
4674 &mut self,
4675 code: Gc<CompiledCode>,
4676 env: Gc<ClosureEnv>,
4677 this: Value,
4678 mut args: Vec<Value>,
4679 callee: Value,
4680 ) -> JsResult<()> {
4681 // Two bounds, and the byte budget is the one that decides in practice. The
4682 // reference's message is `stack overflow` on an `InternalError`, not V8's
4683 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4684 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4685 let frame_cost = Self::frame_cost(&code);
4686 let stack_base = self.stack_used();
4687 if self.frames.len() >= self.max_frames
4688 || stack_base.saturating_add(frame_cost) > self.stack_limit
4689 {
4690 return Err(Signal::Throw(
4691 self.make_error("InternalError", "stack overflow"),
4692 ));
4693 }
4694 let arg_count = code.code.args.len();
4695 // How many were actually passed, which `arguments.length` reports and
4696 // `assert(x)` depends on: a call with one argument must not look like a call
4697 // with one argument and an explicit `undefined`.
4698 let passed = args.len();
4699 // Missing arguments are `undefined` in their slots; extra ones are dropped
4700 // from the slots but still reachable through `arguments`.
4701 //
4702 // A call that passes no more than the declared parameters needs **no** copy:
4703 // after the resize below, `args[..passed]` *is* the passed values. Only the
4704 // extra ones — which `truncate` is about to drop — have to be kept, and they are
4705 // the rare case. This used to copy every call: one `Value` clone per argument
4706 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4707 let passed_overflow = (passed > arg_count).then(|| {
4708 let mut values = self.take_values(passed, Value::Undefined);
4709 values[..passed].clone_from_slice(&args[..passed]);
4710 values
4711 });
4712 // Only when the counts differ, which for the overwhelmingly common call — as many
4713 // arguments as parameters — is never. `resize` followed by `truncate` on equal
4714 // lengths is two length compares and nothing else, but this is the hottest few
4715 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4716 if passed != arg_count {
4717 args.resize(arg_count, Value::Undefined);
4718 args.truncate(arg_count);
4719 }
4720 let cell_count = code.code.var_ref_count as usize;
4721 let mut cells = Vec::with_capacity(cell_count);
4722 for _ in 0..cell_count {
4723 cells.push(self.new_cell(Value::Undefined));
4724 }
4725 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4726 // A captured argument lives in its cell, not in the argument slot, so the
4727 // incoming value has to be moved there before the body runs.
4728 for (slot, cell) in code.arg_cell.iter().enumerate() {
4729 if *cell >= 0
4730 && let Some(value) = args.get(slot).cloned()
4731 {
4732 cells[*cell as usize].set(value);
4733 }
4734 }
4735 // Sloppy mode substitutes the global object for a missing receiver and boxes a
4736 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4737 // reports `object`. Strict mode passes the value through untouched.
4738 let this = if code.code.strict {
4739 this
4740 } else if this.is_nullish() {
4741 Value::Object(self.realm.global.clone())
4742 } else if matches!(this, Value::Object(_)) {
4743 this
4744 } else {
4745 match crate::builtins::this_object(self, &this) {
4746 Ok(boxed) => Value::Object(boxed),
4747 Err(_) => this,
4748 }
4749 };
4750 let stack_depth = code.code.stack_size as usize + 1;
4751 // Taken before the `push` borrows `self.frames`, because the operand stack comes
4752 // out of the same recycle pool the locals did.
4753 let stack = self.take_values(stack_depth, Value::Undefined);
4754 self.frames.push(Frame {
4755 code,
4756 env,
4757 this,
4758 args,
4759 passed_count: passed,
4760 passed_overflow: passed_overflow.map(Box::new),
4761 locals,
4762 cells,
4763 local_vars: None,
4764 // Exactly the depth the compiler computed, so the operand stack never
4765 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4766 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4767 // the buffer between calls, so "exactly" costs nothing after the first one.
4768 stack,
4769 pc: 0,
4770 at: 0,
4771 callee,
4772 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4773 cost: frame_cost,
4774 stack_base,
4775 tail: false,
4776 });
4777 Ok(())
4778 }
4779
4780 /// A value buffer of `len` slots, from the recycle pool when there is one.
4781 ///
4782 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4783 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4784 // A frame with no locals asks for nothing, and that is most frames: taking a
4785 // buffer out of the pool, clearing it and resizing it to zero is four operations
4786 // and a pool pop for an empty `Vec`, which is free to construct.
4787 if len == 0 {
4788 return Vec::new();
4789 }
4790 let mut buffer = self.free_values.pop().unwrap_or_default();
4791 buffer.clear();
4792 buffer.resize(len, fill);
4793 buffer
4794 }
4795
4796 /// Return a finished frame's value buffers for the next call to reuse.
4797 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4798 for mut buffer in [
4799 std::mem::take(&mut frame.locals),
4800 frame
4801 .passed_overflow
4802 .take()
4803 .map(|buffer| *buffer)
4804 .unwrap_or_default(),
4805 std::mem::take(&mut frame.stack),
4806 ] {
4807 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4808 // GC root: it kept every value the frame held reachable, which is invisible
4809 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4810 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4811 // exactly that within one run — the target `{}` of a finished IIFE was still
4812 // in its operand stack, in the pool.
4813 buffer.clear();
4814 // A buffer with no capacity is what `Vec::new` is; putting it back would just
4815 // fill the pool with nothing to offer.
4816 if free_values.len() < RECYCLE_SLOTS
4817 && buffer.capacity() > 0
4818 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4819 {
4820 free_values.push(buffer);
4821 }
4822 }
4823 }
4824
4825 /// Pop a finished frame and keep its buffers.
4826 ///
4827 /// Every place that drops a frame goes through here: a recycled buffer is also where
4828 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4829 /// nothing but the reuse.
4830 fn pop_frame(&mut self) -> Option<()> {
4831 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4832 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4833 let last = self.frames.len().checked_sub(1)?;
4834 Self::recycle(&mut self.free_values, &mut self.frames[last]);
4835 self.frames.truncate(last);
4836 Some(())
4837 }
4838
4839 /// Poll the host's interrupt handler, if one is installed.
4840 ///
4841 /// The counter is what keeps this off the hot path when nobody asked: the early return is
4842 /// one `Option` test, and with no handler installed the whole function is that test —
4843 /// `check_memory` next door already costs more, so this cannot be what shows up in a
4844 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4845 #[inline]
4846 fn check_interrupt(&mut self) -> JsResult<()> {
4847 if self.interrupt.is_none() {
4848 return Ok(());
4849 }
4850 if self.interrupt_counter > 0 {
4851 self.interrupt_counter -= 1;
4852 return Ok(());
4853 }
4854 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4855 // The closure is taken out for the duration so that a handler which re-enters the
4856 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4857 let mut handler = self.interrupt.take().expect("checked above");
4858 let abort = handler();
4859 self.interrupt = Some(handler);
4860 if abort {
4861 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4862 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4863 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4864 // documentation says.
4865 self.uncatchable = true;
4866 return Err(Signal::Throw(
4867 self.make_error("InternalError", "interrupted"),
4868 ));
4869 }
4870 Ok(())
4871 }
4872
4873 /// A memory checkpoint: does the heap still fit under its limit?
4874 ///
4875 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4876 /// a `Cell` read and a predictable branch, and the point of asking that often is that
4877 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4878 /// only at calls would let it run until the machine died, which is the exact failure
4879 /// `--memory-limit` exists to prevent.
4880 ///
4881 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4882 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4883 /// script that catches it, drops the reference and carries on is legitimate: measured
4884 /// on `qjs --memory-limit 1M`, the engine recovers.
4885 fn check_memory(&mut self) -> JsResult<()> {
4886 // One `Cell` read and a predictable branch when no limit is set, and an integer
4887 // compare when one is. Containers report their own growth as it happens
4888 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4889 // walking it here was the first version and it was O(live) per 256 instructions,
4890 // which turned a 100k-element push loop into a five-minute one.
4891 let Some(limit) = self.heap.memory_limit() else {
4892 return Ok(());
4893 };
4894 let used = self.heap.used_bytes();
4895 if used <= limit {
4896 // Back under the limit — a collection or a dropped reference did it. The next
4897 // time it goes over is a new failure, not a repeat of this one.
4898 self.oom_reported_at = 0;
4899 return Ok(());
4900 }
4901 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4902 // block runs normally after `out of memory` — it allocates nothing, so nothing
4903 // fails. A check that re-fired on every instruction made the handler itself throw,
4904 // which is a dead end: the error became unobservable from script.
4905 //
4906 // Comparing against the total at the last report gives the same behaviour: the
4907 // handler runs while the total is unchanged, and the very next allocation over the
4908 // limit fails.
4909 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4910 {
4911 return Ok(());
4912 }
4913 self.oom_reported_at = used;
4914 Err(Signal::Throw(
4915 self.make_error("InternalError", "out of memory"),
4916 ))
4917 }
4918
4919 /// Fail before allocating `payload` bytes, if they would not fit.
4920 ///
4921 /// For the allocations whose size comes from script data — `new Array(n)`,
4922 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4923 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4924 /// answering NULL for the one big request.
4925 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4926 if self.heap.fits(payload) {
4927 return Ok(());
4928 }
4929 Err(Signal::Throw(
4930 self.make_error("InternalError", "out of memory"),
4931 ))
4932 }
4933
4934 /// Bytes of frame state the live call chain accounts for.
4935 pub fn stack_used(&self) -> usize {
4936 match self.frames.last() {
4937 Some(frame) => frame.stack_base + frame.cost,
4938 None => 0,
4939 }
4940 }
4941
4942 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4943 ///
4944 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4945 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4946 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4947 /// instead. That is the whole difference between the two models: it rations C stack, we
4948 /// ration frame state, and both quantities are dominated by the value slots — which is
4949 /// why the two depths come out comparable rather than merely proportional.
4950 fn frame_cost(code: &CompiledCode) -> usize {
4951 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4952 std::mem::size_of::<Frame>()
4953 + std::mem::size_of::<Value>() * slots
4954 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4955 }
4956
4957 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4958 ///
4959 /// Only names the eval created are here: a name the frame already declared statically
4960 /// is written through to its own slot instead, so this cannot shadow a real local.
4961 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4962 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4963 let (local_vars, phase) = self.visible_local_vars()?;
4964 if !local_vars.contains(name) {
4965 return None;
4966 }
4967 local_vars.get(name, phase)
4968 }
4969
4970 /// The variables a direct `eval` declared, as the code currently running sees them.
4971 ///
4972 /// Inside an eval that is the *caller's* set — the eval's own variable environment
4973 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4974 /// else it is the current frame's, falling back to the frame the closure was created
4975 /// in.
4976 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4977 ///
4978 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4979 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4980 /// refcount operations (the clone out of the frame, the drop at the end of the match)
4981 /// just to be asked `is_none`.
4982 fn has_visible_local_vars(&self) -> bool {
4983 let index = match self.eval_caller.flatten() {
4984 Some(caller) => caller,
4985 None => match self.frames.len().checked_sub(1) {
4986 Some(top) => top,
4987 None => return false,
4988 },
4989 };
4990 match self.frames.get(index) {
4991 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4992 None => false,
4993 }
4994 }
4995
4996 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4997 // While an `eval` runs, its own frame is on top but its variable environment is
4998 // the *caller's* — so the caller is what the lookup has to start from.
4999 let (index, phase) = match self.eval_caller.flatten() {
5000 Some(caller) => (
5001 caller,
5002 if self.in_parameter_list_at(caller) {
5003 0
5004 } else {
5005 1
5006 },
5007 ),
5008 None => (
5009 self.frames.len().checked_sub(1)?,
5010 if self.in_parameter_list() { 0 } else { 1 },
5011 ),
5012 };
5013 let frame = self.frames.get(index)?;
5014 // The frame's own variables, or — for an arrow, which has no variable environment
5015 // of its own — the one it was created in, which `ClosureEnv` carries.
5016 if let Some(local_vars) = frame.local_vars.clone() {
5017 return Some((local_vars, phase));
5018 }
5019 frame
5020 .env
5021 .local_vars
5022 .clone()
5023 .map(|local_vars| (local_vars, frame.env.local_phase))
5024 }
5025
5026 /// Whether the innermost frame is still evaluating its parameter list.
5027 ///
5028 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
5029 /// and a closure created there may only see that much of [`LocalVars`].
5030 fn in_parameter_list(&self) -> bool {
5031 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
5032 }
5033
5034 /// [`Interp::in_parameter_list`] for a specific frame.
5035 fn in_parameter_list_at(&self, frame: usize) -> bool {
5036 let Some(frame) = self.frames.get(frame) else {
5037 return false;
5038 };
5039 let code = &frame.code.code;
5040 if !code.has_parameter_expressions {
5041 return false;
5042 }
5043 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
5044 // function as its body and let a direct `eval` act accordingly.
5045 if code.body_start == (0, 0) {
5046 return false;
5047 }
5048 match code.position_at(frame.at as u32) {
5049 Some(position) => position < code.body_start,
5050 None => false,
5051 }
5052 }
5053
5054 fn frame(&self) -> &Frame {
5055 self.frames.last().expect("a frame is live")
5056 }
5057
5058 fn frame_mut(&mut self) -> &mut Frame {
5059 self.frames.last_mut().expect("a frame is live")
5060 }
5061
5062 // -- slot access --------------------------------------------------------
5063
5064 /// Move a local's value out, leaving `undefined` in the slot.
5065 ///
5066 /// `None` for a captured slot: its value lives in a cell shared with every closure
5067 /// that closed over it, so it can never be exclusively ours and must not be taken.
5068 ///
5069 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
5070 /// for every read and fatal for this one — a clone is exactly the second handle that
5071 /// rules out growing the string in place.
5072 fn take_loc(&mut self, slot: usize) -> Option<Value> {
5073 let frame = self.frames.last_mut()?;
5074 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
5075 return None;
5076 }
5077 frame
5078 .locals
5079 .get_mut(slot)
5080 .map(|value| std::mem::replace(value, Value::Undefined))
5081 }
5082
5083 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
5084 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
5085 ///
5086 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
5087 /// it** — the value is put back before the general path runs — so a `valueOf` that
5088 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
5089 /// error as it would have without the fusion. This is why the in-place attempt is a
5090 /// `take` and not a `get`: an optimisation that changes what an exception observes is
5091 /// a wrong answer with a good excuse.
5092 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
5093 // The take is `matches!`-guarded on the *right* operand only, and the taken value
5094 // is put back on every path that does not append. An earlier version wrote the two
5095 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
5096 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
5097 // through with its value already taken and dropped: the general path below then
5098 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
5099 // A wrong answer, from an optimisation, with every test green.
5100 if matches!(right, Value::String(_))
5101 && let Some(taken) = self.take_loc(slot)
5102 {
5103 if let Value::String(mut left) = taken {
5104 let appended = match left.get_mut() {
5105 Some(string) => string.append_in_place(
5106 // The pattern is the one `matches!` just checked.
5107 match &right {
5108 Value::String(text) => text,
5109 _ => unreachable!("guarded above"),
5110 },
5111 ),
5112 None => None,
5113 };
5114 self.put_loc(slot, Value::String(left));
5115 if let Some(added) = appended {
5116 // The buffer grew where it stood, so the heap's running total has to
5117 // be told: `measure_used` would report the new length, and the two must
5118 // agree or the subtraction at free time leaves the counter wrong.
5119 self.heap.adjust_payload(added as isize);
5120 return Ok(());
5121 }
5122 } else {
5123 self.put_loc(slot, taken);
5124 }
5125 }
5126 // The two-number case, without an operand stack round trip. Everything below
5127 // this point is the *general* path: push both, call `binary_add`, pop the answer,
5128 // store it — five operations and two `Value` clones for what is one integer add.
5129 // `AddImmLoc` already answers this shape that way; the fusion above it was written
5130 // for string append and never got the numeric half, so `t += i` — a counting loop
5131 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
5132 let left = self.get_loc(slot);
5133 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
5134 self.put_loc(
5135 slot,
5136 match a.checked_add(*b) {
5137 Some(sum) => Value::Int(sum),
5138 None => Value::Float(*a as f64 + *b as f64),
5139 },
5140 );
5141 return Ok(());
5142 }
5143 self.push(left);
5144 self.push(right);
5145 self.binary_add()?;
5146 let value = self.pop();
5147 self.put_loc(slot, value);
5148 Ok(())
5149 }
5150
5151 fn get_arg(&self, slot: usize) -> Value {
5152 self.frame().read_arg(slot)
5153 }
5154
5155 fn put_arg(&mut self, slot: usize, value: Value) {
5156 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
5157 if cell == -1 {
5158 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
5159 *slot = value;
5160 }
5161 } else {
5162 self.frame().cells[cell as usize].set(value);
5163 }
5164 }
5165
5166 fn get_loc(&self, slot: usize) -> Value {
5167 // The cell mapping is `-1` for every slot that was not captured — which is all of
5168 // them in a function that creates no closure. `Frame::read_loc` tests that first,
5169 // so the common case is one array read and a clone: 20% of every loop iteration
5170 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
5171 // sample of `dispatch:arith`).
5172 self.frame().read_loc(slot)
5173 }
5174
5175 fn put_loc(&mut self, slot: usize, value: Value) {
5176 // One borrow instead of three, and the cell check on the frame we already hold.
5177 let frame = self.frames.last_mut().expect("a frame is live");
5178 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
5179 if cell < 0 {
5180 if let Some(slot) = frame.locals.get_mut(slot) {
5181 *slot = value;
5182 }
5183 } else if let Some(cell) = frame.cells.get(cell as usize) {
5184 cell.set(value);
5185 }
5186 }
5187
5188 // -- globals ------------------------------------------------------------
5189
5190 /// The name a global-slot operand refers to.
5191 fn global_name(&self, slot: usize) -> String {
5192 self.frame()
5193 .code
5194 .code
5195 .closure_vars
5196 .get(slot)
5197 .map(|c| c.name.clone())
5198 .unwrap_or_default()
5199 }
5200
5201 /// The facts about a global binding that decide where it lives.
5202 ///
5203 /// A script's globals split in two, and the split is observable: `var` and
5204 /// function declarations become properties of the global object (`globalThis.v`
5205 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
5206 /// declarations live in the global *lexical* environment and are invisible there
5207 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
5208 /// `is_lexical` flag means the answer is already in the bytecode.
5209 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
5210 let name = self.global_name(slot);
5211 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
5212 // while forwarding a reference through a nested function is built with the
5213 // flags cleared, so `const c` would look like an ordinary `var` from inside a
5214 // closure. Presence in the realm's lexical table is the same fact, recorded
5215 // once, and every slot sees it.
5216 let lexical = self.realm.globals.contains_key(&name);
5217 let is_const = self.realm.lexical_consts.contains(&name);
5218 (name, lexical, is_const)
5219 }
5220
5221 /// The value of `name` in the innermost active `with` object, if any.
5222 ///
5223 /// The active objects are the [`VarKind::With`] locals of every frame still running,
5224 /// innermost frame first and innermost block first within one. Walking frames rather
5225 /// than keeping a separate stack is what makes a closure called from inside a `with`
5226 /// see it, and what keeps the object alive only as long as the block is.
5227 /// The innermost active `with` object that has `name`, if any.
5228 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
5229 let objects = self.eval_with.clone().unwrap_or_default();
5230 for object in objects {
5231 let key = self.string(name.to_string());
5232 if self
5233 .has_property(&key, &Value::Object(object.clone()))
5234 .ok()?
5235 {
5236 return Some(object);
5237 }
5238 }
5239 None
5240 }
5241
5242 /// Every active `with` object, innermost first.
5243 fn with_objects(&self) -> Vec<Gc<JsObject>> {
5244 let mut objects = Vec::new();
5245 for frame in self.frames.iter().rev() {
5246 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
5247 if var.kind != js_compile::VarKind::With {
5248 continue;
5249 }
5250 // A captured binding lives in its cell and not in the slot list, so the
5251 // cell is consulted first — a closure created inside the block is exactly
5252 // what makes the object captured. Before the store runs the slot still
5253 // holds `undefined`, and a `with` object is always boxed, so a non-object
5254 // entry is simply not in scope yet.
5255 let value = frame
5256 .code
5257 .loc_cell
5258 .get(index)
5259 .copied()
5260 .filter(|cell| *cell >= 0)
5261 .and_then(|cell| frame.cells.get(cell as usize))
5262 .map(|cell| cell.get())
5263 .or_else(|| frame.locals.get(index).cloned());
5264 if let Some(Value::Object(object)) = value {
5265 objects.push(object);
5266 }
5267 }
5268 }
5269 objects
5270 }
5271
5272 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
5273 for object in self.eval_with.clone().unwrap_or_default() {
5274 let key = self.string(name.to_string());
5275 if self.has_property(&key, &Value::Object(object.clone()))? {
5276 return Ok(Some(self.read_field(&Value::Object(object), name)?));
5277 }
5278 }
5279 Ok(None)
5280 }
5281
5282 /// Whether every scope between here and the global object is an ordinary one.
5283 ///
5284 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
5285 /// bytecode resolved; when any is live the general path has to run in full order. When
5286 /// none is — every ordinary program — a global read is a property read and nothing
5287 /// else, and that is worth caching.
5288 fn scopes_are_plain(&self) -> bool {
5289 self.eval_caller.is_none()
5290 && self.eval_with.is_none()
5291 && self.eval_arguments.is_none()
5292 && self.eval_bindings.is_empty()
5293 && self.eval_scope.is_none()
5294 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
5295 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
5296 // its `ClosureEnv`, so the test has to be the same one the general path makes.
5297 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
5298 // upstream corpus caught and no unit test did.
5299 && !self.has_visible_local_vars()
5300 && self.frame().env.eval_scope.is_none()
5301 }
5302
5303 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
5304 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
5305 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
5306 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
5307 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
5308 // borrow outlive the `&mut self` the lookup needs.
5309 //
5310 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
5311 // forwarded through a nested function has its flags cleared, so the flag cannot
5312 // be believed.
5313 let code = self.frame().code.clone();
5314 let name = code
5315 .code
5316 .closure_vars
5317 .get(slot)
5318 .map(|c| c.name.as_str())
5319 .unwrap_or_default();
5320 let lexical = self.realm.globals.contains_key(name);
5321 // The common case, first: an ordinary global `var`, with a cache in front of the
5322 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
5323 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
5324 // cache hit and return without touching any of it.
5325 if !lexical && self.scopes_are_plain() {
5326 return self.get_plain_global(name, slot);
5327 }
5328 if name == "arguments"
5329 && let Some(arguments) = &self.eval_arguments
5330 {
5331 return Ok(arguments.clone());
5332 }
5333 // A `with` block around the *call site* is part of the scope an `eval` sees, so
5334 // the objects live when the eval started are consulted before anything else. The
5335 // snapshot is taken at entry rather than scanning the frames on every read: a
5336 // block that has already finished still leaves its object in the slot, and a
5337 // bytecode read outside the block must not see it.
5338 if let Some(value) = self.with_lookup(name)? {
5339 return Ok(value);
5340 }
5341 // A variable a direct `eval` declared shadows everything the compiler resolved,
5342 // including an enclosing function's binding: the eval put it in the caller's own
5343 // variable environment, which is nearer than any captured scope.
5344 if let Some((local_vars, phase)) = self.visible_local_vars()
5345 && let Some(cell) = local_vars.get(name, phase)
5346 {
5347 return Ok(cell.get());
5348 }
5349 // The frame that called `eval` is the innermost scope the eval'd code sees, so
5350 // its local `a` wins over a global `a`.
5351 if let Some(value) = self.eval_binding_value(name) {
5352 return Ok(value);
5353 }
5354 // A closure created by an `eval` resolves its free names against the bindings
5355 // that eval saw, even after the eval (and its frames) are gone.
5356 if let Some(cell) = self
5357 .frame()
5358 .env
5359 .eval_scope
5360 .as_ref()
5361 .and_then(|scope| scope.get(name))
5362 {
5363 let value = cell.get();
5364 if matches!(value, Value::Uninitialized) {
5365 return Err(self.throw_reference(name));
5366 }
5367 return Ok(value);
5368 }
5369 // A binding declared by the strict `eval` currently running shadows anything
5370 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5371 if let Some(scope) = &self.eval_scope
5372 && let Some(value) = scope.get(name)
5373 {
5374 return Ok(value.clone());
5375 }
5376 if lexical {
5377 // A lexical global is a binding in a side table, so the dead zone is
5378 // visible and it is nowhere on the global object.
5379 if let Some(cell) = self.realm.globals.get(name) {
5380 let value = cell.get();
5381 if matches!(value, Value::Uninitialized) {
5382 return Err(self.throw_reference(name));
5383 }
5384 return Ok(value);
5385 }
5386 return Err(self.throw_reference(name));
5387 }
5388 // A `var` global is an ordinary property, so the prototype chain and the
5389 // global object's own builtins are all reachable through it.
5390 match self.get_property(&self.realm.global.clone(), name)? {
5391 Some(value) => Ok(value),
5392 None => Err(self.throw_reference(name)),
5393 }
5394 }
5395
5396 /// Read a plain global `var`: a cached own data property, or the full lookup.
5397 ///
5398 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5399 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5400 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5401 let object = self.realm.global.clone();
5402 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5403 if let Some(cached) = &self.global_cache[site]
5404 && object.upgrades_to(&cached.object)
5405 && let Some(value) = object.data_property_at(cached.index, name)
5406 {
5407 return Ok(value);
5408 }
5409 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5410 // chain exactly as before, then remember the answer if it is worth remembering.
5411 let Some(value) = self.get_property(&object, name)? else {
5412 return Err(self.throw_reference(name));
5413 };
5414 if let Some(index) = object.own_data_index(name) {
5415 self.global_cache[site] = Some(GlobalCache {
5416 object: object.downgrade(),
5417 index,
5418 });
5419 }
5420 Ok(value)
5421 }
5422
5423 /// Store to a global binding.
5424 ///
5425 /// Returns a signal when the store is refused: a `const` global may only be
5426 /// written by its initialiser, and a non-configurable `var` global may not be
5427 /// deleted but is always writable.
5428 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5429 let (name, lexical, is_const) = self.global_binding(slot);
5430
5431 // An assignment inside a `with` writes through to the object that supplies the
5432 // name, which for an `eval` means consulting the same chain `get_global` does.
5433 if let Some(owner) = self.with_owner(&name) {
5434 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5435 return Ok(());
5436 }
5437 // A variable the running eval *declared* takes the write before any caller
5438 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5439 // environment even when an enclosing function has a `var c` of its own.
5440 if self.eval_caller.flatten().is_some()
5441 && let Some((local_vars, phase)) = self.visible_local_vars()
5442 && local_vars.contains(&name)
5443 && let Some(cell) = local_vars.get(&name, phase)
5444 {
5445 cell.set(value);
5446 return Ok(());
5447 }
5448 // A binding of the frame that called `eval` takes the write, which is what
5449 // makes `f("a = 3")` change the caller's `a`.
5450 if self.set_eval_binding(&name, &value)? {
5451 return Ok(());
5452 }
5453 // A closure that outlived its `eval` writes through to the same cell it reads.
5454 if let Some(cell) = self
5455 .frame()
5456 .env
5457 .eval_scope
5458 .as_ref()
5459 .and_then(|scope| scope.get(&name))
5460 .cloned()
5461 {
5462 cell.set(value);
5463 return Ok(());
5464 }
5465 // Inside a strict `eval`, a name it declared itself is stored there. An
5466 // *assignment* to a name nobody declared is not a declaration, so it falls
5467 // through: strict mode raises `ReferenceError` for it, which is what
5468 // `eval("1 + (@not_def = 1)")` has to do.
5469 if let Some(scope) = self.eval_scope.as_mut()
5470 && scope.contains_key(&name)
5471 {
5472 scope.insert(name, value);
5473 return Ok(());
5474 }
5475 if lexical {
5476 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5477 if is_const && !matches!(cell.get(), Value::Uninitialized) {
5478 return Err(self.read_only_global(&name));
5479 }
5480 cell.set(value);
5481 return Ok(());
5482 }
5483 // Writing an undeclared lexical global is a `ReferenceError` in strict
5484 // mode and a silent global creation otherwise; creating the cell here
5485 // keeps both paths from losing the value.
5486 let cell = self.new_cell(value);
5487 self.realm.globals.insert(name, cell);
5488 return Ok(());
5489 }
5490 // A variable a direct `eval` declared in this call shadows the global object, even
5491 // when the global already has a property of that name — `var c = "global"` at the
5492 // top level must not capture `eval("var c = 1")` inside a function.
5493 if let Some((local_vars, phase)) = self.visible_local_vars()
5494 && local_vars.contains(&name)
5495 && let Some(cell) = local_vars.get(&name, phase)
5496 {
5497 cell.set(value);
5498 return Ok(());
5499 }
5500 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5501 // remembered a global's slot index since M12b, but the *store* side never did: it
5502 // converted the name to a `PropertyKey` (two allocations) and then scanned the
5503 // global object's whole table — which holds every builtin — on every assignment to
5504 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5505 // full global lookup per iteration; measured with a counter, `s` as a global made
5506 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5507 //
5508 // Re-validated exactly like the read: same object, same index, still the name, and
5509 // — the one extra check a store needs — still writable. A global that is an
5510 // accessor, non-writable, or inherited fails here and falls through to the full
5511 // path below, which reports the failure the way it always did.
5512 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5513 let global = self.realm.global.clone();
5514 if let Some(cached) = &self.global_cache[site]
5515 && global.upgrades_to(&cached.object)
5516 && global.write_data_at(cached.index, &name, value.clone())
5517 {
5518 return Ok(());
5519 }
5520 match global.own_property(&name) {
5521 // A `var` global is writable, so the store goes straight through — but
5522 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5523 // store (a non-writable or accessor-without-setter global) is a silent
5524 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5525 // split every other assignment has.
5526 Some(_) => {
5527 let on_failure = if self.current_strict() {
5528 DeleteFailure::Throw
5529 } else {
5530 DeleteFailure::Ignore
5531 };
5532 let result = self.set_property_with(&global, &name, value, on_failure);
5533 // Teach the cache the slot for a plain writable own data property, which is
5534 // what a declared `var` is. Without this the fast path above could never
5535 // fire for a global that is only ever *written* — its entry would have to
5536 // be put there by a read of the same slot, and a write-only loop has none.
5537 if result.is_ok()
5538 && let Some(index) = global.own_data_index(&name)
5539 {
5540 self.global_cache[site] = Some(GlobalCache {
5541 object: global.downgrade(),
5542 index,
5543 });
5544 }
5545 result
5546 }
5547 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5548 // declaration creates a *configurable* property, which is what makes it
5549 // deletable and is the one way a global differs from a declared `var`.
5550 // In strict mode the same store is a `ReferenceError` instead: that is the
5551 // whole point of strict mode, and creating the global silently meant
5552 // `"use strict"; x = 1` looked like it worked.
5553 None => {
5554 if self.current_strict() {
5555 return Err(self.throw_reference(&name));
5556 }
5557 // A direct eval declares here rather than on the global object: its
5558 // `var`s belong to the caller's variable environment. `declare_eval_local`
5559 // also covers a plain assignment to a variable an earlier eval made.
5560 if let Some(cell) = self.declare_eval_local(&name) {
5561 cell.set(value);
5562 return Ok(());
5563 }
5564 global.define_data(&name, value);
5565 Ok(())
5566 }
5567 }
5568 }
5569
5570 /// The value of a binding of the frame that called `eval`, if there is one.
5571 fn eval_binding_value(&self, name: &str) -> Option<Value> {
5572 let binding = self
5573 .eval_bindings
5574 .iter()
5575 .find(|binding| binding.name == name)?;
5576 let owner = self.frames.get(binding.frame)?;
5577 let (slot, index) = (binding.slot, binding.index);
5578 Some(match slot {
5579 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5580 cell if cell >= 0 => owner
5581 .cells
5582 .get(cell as usize)
5583 .map(|cell| cell.get())
5584 .unwrap_or(Value::Undefined),
5585 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5586 },
5587 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5588 cell if cell >= 0 => owner
5589 .cells
5590 .get(cell as usize)
5591 .map(|cell| cell.get())
5592 .unwrap_or(Value::Undefined),
5593 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5594 },
5595 })
5596 }
5597
5598 /// Write to a binding of the frame that called `eval`.
5599 ///
5600 /// `Ok(false)` means no binding matched and the caller should keep looking. A
5601 /// matched binding can still refuse the store, which is why this is fallible: a
5602 /// `const` is read-only everywhere, and a named function expression's own name is
5603 /// read-only in strict mode.
5604 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5605 let Some(binding) = self
5606 .eval_bindings
5607 .iter()
5608 .find(|binding| binding.name == name)
5609 else {
5610 return Ok(false);
5611 };
5612 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5613 let strict = self.current_strict();
5614 let Some(owner) = self.frames.get_mut(frame) else {
5615 return Ok(false);
5616 };
5617 match slot {
5618 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5619 cell if cell >= 0 => {
5620 if let Some(cell) = owner.cells.get(cell as usize) {
5621 cell.set(value.clone());
5622 }
5623 }
5624 _ => {
5625 if let Some(slot) = owner.args.get_mut(index) {
5626 *slot = value.clone();
5627 }
5628 }
5629 },
5630 EvalSlot::Local => {
5631 let declared = owner.code.code.vars.get(index);
5632 // A `const` is read-only even through `eval`. The realm records this for
5633 // globals (see `lexical_consts`), but a local's `const`-ness is only in
5634 // the bytecode, so this is where it has to be enforced.
5635 if declared.is_some_and(|var| var.is_const) {
5636 return Err(self.read_only_local(name));
5637 }
5638 // The name of a named function expression is read-only too, but only
5639 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5640 // such a name is ignored, the same as a direct store would be.
5641 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5642 return if strict {
5643 Err(self.read_only_local(name))
5644 } else {
5645 Ok(true)
5646 };
5647 }
5648 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5649 cell if cell >= 0 => {
5650 if let Some(cell) = owner.cells.get(cell as usize) {
5651 cell.set(value.clone());
5652 }
5653 }
5654 _ => {
5655 if let Some(slot) = owner.locals.get_mut(index) {
5656 *slot = value.clone();
5657 }
5658 }
5659 }
5660 }
5661 }
5662 Ok(true)
5663 }
5664
5665 /// The `TypeError` an assignment to a read-only binding raises.
5666 fn read_only_local(&self, name: &str) -> Signal {
5667 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5668 }
5669
5670 /// Declare `name` as a variable of the frame that called the running `eval`.
5671 ///
5672 /// `None` when there is no direct eval in progress, or it was called from the top
5673 /// level — then the caller's variable environment *is* the global one and the
5674 /// existing path is right.
5675 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5676 let caller = self.eval_caller.flatten()?;
5677 // The bottom frame is the top-level script, whose variable environment *is* the
5678 // global one — so `eval("var x = 1")` at the top level still creates a global.
5679 if caller == 0 {
5680 return None;
5681 }
5682 // A name the eval's *own* variable environment already binds is not a new
5683 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5684 // `arguments`, and creating a second binding would leave the first — the one
5685 // closures read — untouched. A binding of an *outer* frame does not count: a
5686 // declaration shadows it rather than writing through.
5687 if self
5688 .eval_bindings
5689 .iter()
5690 .any(|binding| binding.name == name && binding.frame == caller)
5691 {
5692 return None;
5693 }
5694 let phase = if self.in_parameter_list_at(caller) {
5695 0
5696 } else {
5697 1
5698 };
5699 self.frame_local_vars(caller)?;
5700 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5701 if let Some(cell) = local_vars.get(name, 1) {
5702 return Some(cell);
5703 }
5704 let cell = self.new_cell(Value::Undefined);
5705 Some(local_vars.declare(name, phase, cell))
5706 }
5707
5708 /// Make sure `frame` has a `LocalVars`, creating it on demand.
5709 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5710 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5711 return Some(local_vars.clone());
5712 }
5713 let local_vars = Gc::new(self.heap, LocalVars::new());
5714 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5715 Some(local_vars)
5716 }
5717
5718 /// Whether the realm already has a binding for `name`, lexically or as an *own*
5719 /// property of the global object. Used to decide whether a store inside an
5720 /// `eval` writes through to the realm or declares a binding of its own.
5721 ///
5722 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5723 /// write to `Object.prototype.toString`, and must not shadow it either.
5724 fn global_knows(&mut self, name: &str) -> bool {
5725 if self.realm.globals.contains_key(name) {
5726 return true;
5727 }
5728 self.realm.global.own_property(name).is_some()
5729 }
5730
5731 /// Whether the code currently running is strict.
5732 ///
5733 /// Read off the frame's function, which is where the parser's answer ended up; a
5734 /// native function never runs strict-only checks, and there is no frame at all
5735 /// before the first script.
5736 pub fn current_strict(&self) -> bool {
5737 self.frames
5738 .last()
5739 .is_some_and(|frame| frame.code.code.strict)
5740 }
5741
5742 /// Initialise a declared global, which is what ends its dead zone.
5743 ///
5744 /// A `var` global becomes a property of the global object: writable, so a later
5745 /// assignment goes through, and non-configurable, so `delete` refuses.
5746 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5747 let (name, lexical, _) = self.global_binding(slot);
5748 // A `var` declared by the strict `eval` currently running belongs to the
5749 // eval's scope, not to the global object: `eval("var v = 1")` must not make
5750 // `typeof v` answer `"number"` afterwards. A name the realm already has is
5751 // initialised in place, which is what a re-declaration inside eval does.
5752 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5753 self.eval_scope
5754 .as_mut()
5755 .expect("checked above")
5756 .insert(name, value);
5757 return Ok(());
5758 }
5759 if let Some(scope) = self.eval_scope.as_mut()
5760 && scope.contains_key(&name)
5761 {
5762 scope.insert(name, value);
5763 return Ok(());
5764 }
5765 if lexical {
5766 // The cell exists (created at declaration time) holding the dead-zone
5767 // marker; storing the value is what makes the binding readable.
5768 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5769 cell.set(value);
5770 return Ok(());
5771 }
5772 let cell = self.new_cell(value);
5773 self.realm.globals.insert(name, cell);
5774 return Ok(());
5775 }
5776 let global = self.realm.global.clone();
5777 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5778 // to answer `false` and leave the binding in place. `with_attributes` ties
5779 // `configurable` to `writable`, so the property is built field by field.
5780 global.define(
5781 &name,
5782 Property {
5783 value: Some(value),
5784 writable: true,
5785 enumerable: true,
5786 configurable: false,
5787 ..Property::default()
5788 },
5789 );
5790 Ok(())
5791 }
5792
5793 /// The `TypeError` a store to a `const` global raises.
5794 fn read_only_global(&self, name: &str) -> Signal {
5795 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5796 }
5797
5798 // -- properties ---------------------------------------------------------
5799
5800 /// Read `object[key]`, following the prototype chain.
5801 ///
5802 /// An inherited accessor runs with the *receiver* as `this`, which is why the
5803 /// lookup returns the owner rather than just the value.
5804 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5805 self.get_property_key(object, &PropertyKey::from(key))
5806 }
5807
5808 /// [`Interp::get_property`] with a key that may be a symbol.
5809 pub fn get_property_key(
5810 &mut self,
5811 object: &Gc<JsObject>,
5812 key: &PropertyKey,
5813 ) -> JsResult<Option<Value>> {
5814 self.get_property_key_for(object, None, key)
5815 }
5816
5817 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5818 ///
5819 /// The receiver matters when the property is found on a *prototype*: a getter has to
5820 /// see the object the read started from. For a primitive that is the primitive
5821 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5822 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5823 /// the owner.
5824 pub fn get_property_key_for(
5825 &mut self,
5826 object: &Gc<JsObject>,
5827 receiver: Option<&Value>,
5828 key: &PropertyKey,
5829 ) -> JsResult<Option<Value>> {
5830 // A proxy answers for itself, before any of the shortcuts below: `new
5831 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5832 // have.
5833 if object.proxy_state().is_some() {
5834 let receiver = receiver
5835 .cloned()
5836 .unwrap_or_else(|| Value::Object(object.clone()));
5837 return self.proxy_get(object, &receiver, key);
5838 }
5839 // A host class's `get_property` trap replaces the whole read, prototype walk
5840 // included — that is what makes a native accessor free rather than a JavaScript
5841 // getter call.
5842 if let Some(exotic) = object.exotic() {
5843 let receiver_value = receiver
5844 .cloned()
5845 .unwrap_or_else(|| Value::Object(object.clone()));
5846 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5847 return Ok(Some(value));
5848 }
5849 // With no `get_property` trap, a `get_own_property` trap still answers for the
5850 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5851 // and the hook lives exactly there. A key the trap reports as absent is still
5852 // looked for on the prototype, which is why the search resumes *above*.
5853 if let Some(property) = exotic.get_own_property(self, object, key)? {
5854 return match property {
5855 Some(property) => self.read_property(property, object, receiver),
5856 None => match lookup_key_above(object, key) {
5857 Some((_, property)) => self.read_property(property, object, receiver),
5858 None => Ok(None),
5859 },
5860 };
5861 }
5862 }
5863 // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
5864 // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
5865 // The `[[Get]]` short-circuit therefore belongs to this one arm.
5866 //
5867 // Constructibility is exactly the split the reference makes: `function f(){}` and
5868 // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
5869 // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
5870 // function" — it *is* the predicate, which is why no extra marker is needed.
5871 if let Some(text) = key.as_str()
5872 && (text == "caller" || text == "arguments")
5873 && object.is_constructor()
5874 && object.is_callable()
5875 && !object.is_bound_function()
5876 // …and only when the body is **sloppy**. A strict body reaches the
5877 // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
5878 // whole `Function/15.3.5.4_2-*gs` family is written against
5879 // (`onlyStrict`, so every function in them is strict).
5880 && !object.function_is_strict()
5881 && object.own_property(text).is_none()
5882 {
5883 return Ok(Some(Value::Undefined));
5884 }
5885 // The element-vector and `length` shortcuts are string-only: an array index
5886 // has no symbol spelling.
5887 if let Some(text) = key.as_str() {
5888 if let Some(value) = self.own_element(object, text) {
5889 return Ok(Some(value));
5890 }
5891 // `length` is not stored as a property: an array's length is its element
5892 // count, and keeping one copy of it is what makes `push`/`pop` and
5893 // `a.length = n` agree.
5894 if let Some(length) = object.array_length()
5895 && text == "length"
5896 {
5897 // Not `Value::Int(length as i32)`: see [`length_value`].
5898 return Ok(Some(crate::object::length_value(length)));
5899 }
5900 }
5901 // A proxy or a hooked exotic object anywhere above `object` makes the static
5902 // table walk below wrong: a proxy's own table is *empty by design* (the properties
5903 // live on its target), so the walk skipped that link entirely and everything behind
5904 // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
5905 // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
5906 // -target-is-proxy.js` are the four.
5907 if Self::chain_needs_dispatch(object) {
5908 return self.walk_get(object, receiver, key);
5909 }
5910 match lookup_key(object, key) {
5911 Some((_, property)) => self.read_property(property, object, receiver),
5912 None => Ok(None),
5913 }
5914 }
5915
5916 /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
5917 /// answer for itself.
5918 ///
5919 /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
5920 /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
5921 /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
5922 /// an inherited getter the object the read started from.
5923 fn walk_get(
5924 &mut self,
5925 start: &Gc<JsObject>,
5926 receiver: Option<&Value>,
5927 key: &PropertyKey,
5928 ) -> JsResult<Option<Value>> {
5929 let receiver = receiver
5930 .cloned()
5931 .unwrap_or_else(|| Value::Object(start.clone()));
5932 let mut current = Some(start.clone());
5933 while let Some(holder) = current {
5934 // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
5935 // has to ask it, not read its (empty) own-property table. `Object.create(new
5936 // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
5937 // instead found nothing.
5938 if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
5939 return Ok(Some(value));
5940 }
5941 // A host class's `get_property` trap replaces the whole read for that holder,
5942 // prototype walk included — the same rule `get_property_key_for` applies to the
5943 // first object.
5944 if let Some(exotic) = holder.exotic()
5945 && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
5946 {
5947 return Ok(Some(value));
5948 }
5949 if let Some(property) = self.object_get_own_property(&holder, key)? {
5950 return self.read_property(property, &holder, Some(&receiver));
5951 }
5952 current = self.object_prototype_of(&holder)?;
5953 }
5954 Ok(None)
5955 }
5956
5957 /// Whether `object` or anything above it has properties that cannot be read out of a
5958 /// property table — a proxy, or an exotic object with a `get_own_property` hook.
5959 ///
5960 /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
5961 /// is the hot path for every property read; this is the check that decides whether it
5962 /// is safe to take it.
5963 fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
5964 object
5965 .chain()
5966 .iter()
5967 .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
5968 }
5969
5970 /// The value a property read answers.
5971 ///
5972 /// One place rather than three, because an accessor has to run with the *receiver* as
5973 /// `this` whether the descriptor came from the property table, an exotic
5974 /// `get_own_property` trap, or a prototype above one.
5975 fn read_property(
5976 &mut self,
5977 property: Property,
5978 object: &Gc<JsObject>,
5979 receiver: Option<&Value>,
5980 ) -> JsResult<Option<Value>> {
5981 if property.is_accessor() {
5982 match &property.getter {
5983 Some(getter) if !matches!(getter, Value::Undefined) => {
5984 let receiver = receiver
5985 .cloned()
5986 .unwrap_or_else(|| Value::Object(object.clone()));
5987 self.call_value(getter.clone(), receiver, Vec::new())
5988 .map(Some)
5989 }
5990 // An accessor with no getter reads as `undefined`.
5991 _ => Ok(Some(Value::Undefined)),
5992 }
5993 } else {
5994 Ok(property.value)
5995 }
5996 }
5997
5998 /// `super.key` — start the search at `proto`, but report to `receiver`.
5999 ///
6000 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
6001 /// found on the prototype of a class has to see the *instance* as `this`, and a
6002 /// plain property read off `proto` would lose that.
6003 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
6004 let start = self.require_object(proto)?;
6005 let key = self.propkey(key)?;
6006 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
6007 if matches!(proto, Value::Null) {
6008 return Ok(Value::Undefined);
6009 }
6010 match lookup_key(&start, &key) {
6011 Some((_, property)) if property.is_accessor() => match &property.getter {
6012 Some(getter) if !matches!(getter, Value::Undefined) => {
6013 self.call_value(getter.clone(), receiver.clone(), Vec::new())
6014 }
6015 _ => Ok(Value::Undefined),
6016 },
6017 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
6018 None => Ok(Value::Undefined),
6019 }
6020 }
6021
6022 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
6023 ///
6024 /// A setter found on the prototype runs with `receiver` as `this`; a data property
6025 /// is shadowed by a new own property on the receiver, the same rule an ordinary
6026 /// assignment follows.
6027 fn super_write(
6028 &mut self,
6029 receiver: &Value,
6030 proto: &Value,
6031 key: &Value,
6032 value: Value,
6033 ) -> JsResult<()> {
6034 let target = self.require_object(receiver)?;
6035 let key = self.propkey(key)?;
6036 if !matches!(proto, Value::Null)
6037 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
6038 {
6039 if property.is_accessor() {
6040 if let Some(setter) = &property.setter
6041 && !matches!(setter, Value::Undefined)
6042 {
6043 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
6044 }
6045 return Ok(());
6046 }
6047 // A data property on the prototype is writable or not; reading `owner` at
6048 // all is only for the attribute check.
6049 if !property.writable {
6050 return Err(self.type_error(format!("'{key}' is read-only")));
6051 }
6052 let _ = owner;
6053 }
6054 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
6055 }
6056
6057 /// The object a `super` operation needs, or the `TypeError` the spec raises.
6058 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
6059 match value.as_object() {
6060 Some(object) => Ok(object.clone()),
6061 None => Err(Signal::Throw(
6062 self.make_error("TypeError", "value is not an object"),
6063 )),
6064 }
6065 }
6066
6067 /// Build the class object `define_class` produces.
6068 ///
6069 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
6070 /// whose prototype property is a fresh object inheriting from the parent's
6071 /// prototype, and whose own prototype is the parent constructor — which is what makes
6072 /// a static method inherited too.
6073 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
6074 let ctor = self.pop();
6075 let parent = self.pop();
6076 let Value::Object(function) = &ctor else {
6077 return Err(Signal::Throw(
6078 self.make_error("TypeError", "class constructor must be a function"),
6079 ));
6080 };
6081 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
6082 // but gives the instances no prototype at all.
6083 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
6084 match &parent {
6085 Value::Null => (Some(self.realm.function_proto.clone()), None),
6086 Value::Object(parent_class) => {
6087 if !parent_class.is_callable() {
6088 return Err(Signal::Throw(
6089 self.make_error("TypeError", "parent class must be constructor"),
6090 ));
6091 }
6092 let proto = self.get_property(parent_class, "prototype")?;
6093 match proto {
6094 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
6095 Some(Value::Null) => (Some(parent_class.clone()), None),
6096 _ => {
6097 return Err(Signal::Throw(self.make_error(
6098 "TypeError",
6099 "parent prototype must be an object or null",
6100 )));
6101 }
6102 }
6103 }
6104 _ => {
6105 return Err(Signal::Throw(
6106 self.make_error("TypeError", "parent class must be constructor"),
6107 ));
6108 }
6109 }
6110 } else {
6111 (
6112 Some(self.realm.function_proto.clone()),
6113 Some(self.realm.object_proto.clone()),
6114 )
6115 };
6116 let proto = self.new_object(parent_proto);
6117 function.set_proto(parent_ctor);
6118 // A class is not callable without `new`, and its `prototype` is not writable —
6119 // both follow from being a class and are what `class A {}; A()` throws on.
6120 function.set_class_constructor(true);
6121 function.set_home_object(None);
6122 self.set_function_name(&ctor, name);
6123 self.define_class_properties(function, &ctor, &proto)?;
6124 Ok((ctor, proto))
6125 }
6126
6127 /// Give the constructor its `prototype` and `length`, and the prototype its
6128 /// `constructor` back-pointer.
6129 fn define_class_properties(
6130 &mut self,
6131 function: &Gc<JsObject>,
6132 ctor: &Value,
6133 proto: &Gc<JsObject>,
6134 ) -> JsResult<()> {
6135 proto.define(
6136 "constructor",
6137 Property::with_attributes(ctor.clone(), true, false),
6138 );
6139 function.define(
6140 "prototype",
6141 Property::prototype_of(Value::Object(proto.clone()), false),
6142 );
6143 if let Some((code, _)) = bytecode_of(function) {
6144 let length = code.code.defined_args;
6145 function.define(
6146 "length",
6147 Property::name_or_length(Value::Int(length as i32)),
6148 );
6149 }
6150 Ok(())
6151 }
6152
6153 /// The own array element `key` names, if this object has one.
6154 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
6155 // A typed array's elements live in its buffer, not in a property list: reading one
6156 // goes through the view's element type so a bounds check and a detached buffer are
6157 // both handled there.
6158 //
6159 // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
6160 // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
6161 // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
6162 // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
6163 // consulted. Testing with `array_index` rejected all three, which let a throwing
6164 // getter installed on `TypedArray.prototype["-1"]` run.
6165 if object.typed_array_parts().is_some() {
6166 let property_key = PropertyKey::from(key);
6167 let numeric = canonical_numeric_index(&property_key)?;
6168 if typed_array_index_is_valid(object, numeric) {
6169 return object.typed_array_element(numeric as usize);
6170 }
6171 // Canonical, but not a valid index: `undefined`, and *final*.
6172 return Some(Value::Undefined);
6173 }
6174 let index = array_index(key)?;
6175 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
6176 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
6177 // search early, which is why `Array.prototype[1] = 9` could not be seen through
6178 // `[1,,3][1]`.
6179 match object.array_get(index as usize) {
6180 Some(Value::Hole) | None => None,
6181 other => other,
6182 }
6183 }
6184
6185 /// Store `object[key] = value`, honouring setters and inherited properties.
6186 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
6187 self.set_property_with(object, key, value, DeleteFailure::Throw)
6188 }
6189
6190 /// Store a property, choosing what to do when the object refuses.
6191 ///
6192 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
6193 /// mode, which is the one place assignment differs by mode. Native code (the array
6194 /// methods, `JSON`) always asks for the throw.
6195 pub fn set_property_with(
6196 &mut self,
6197 object: &Gc<JsObject>,
6198 key: &str,
6199 value: Value,
6200 on_failure: DeleteFailure,
6201 ) -> JsResult<()> {
6202 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
6203 }
6204
6205 /// [`Interp::set_property_with`] with a key that may be a symbol.
6206 pub fn set_property_with_key(
6207 &mut self,
6208 object: &Gc<JsObject>,
6209 key: &PropertyKey,
6210 value: Value,
6211 on_failure: DeleteFailure,
6212 ) -> JsResult<()> {
6213 self.set_property_with_key_receiver_aware(object, key, value, on_failure)
6214 }
6215
6216 /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
6217 ///
6218 /// The receiver split lives one level up, in
6219 /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
6220 /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
6221 /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
6222 /// stores into `object` itself, which is why the element branch below converts `V`
6223 /// before asking whether the index is valid: `V` may put it back in bounds
6224 /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
6225 fn set_property_with_key_receiver_aware(
6226 &mut self,
6227 object: &Gc<JsObject>,
6228 key: &PropertyKey,
6229 value: Value,
6230 on_failure: DeleteFailure,
6231 ) -> JsResult<()> {
6232 // §10.4.6.7: a module namespace's `[[Set]]` **always** returns false — for an
6233 // exported name, for a name that is not exported, and for `@@toStringTag` alike.
6234 // Nothing about the receiver or the value changes that, so the whole operation is
6235 // one answer.
6236 //
6237 // Not implementing it explicitly left the ordinary algorithm in charge, and that
6238 // says "true" for names the namespace does not own as soon as the value matches or
6239 // the key is writable, so `Reflect.set(ns, 'local1', …)` answered `true` and strict
6240 // assignment stopped throwing (`await-ns-set-strict`).
6241 if object.module_namespace_marker() {
6242 return match on_failure {
6243 DeleteFailure::Ignore => Ok(()),
6244 DeleteFailure::Throw => Err(self.type_error(format!(
6245 "cannot assign to property '{key}' of a module namespace object"
6246 ))),
6247 };
6248 }
6249 // A proxy's `set` trap decides, and its `false` means the same thing an
6250 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
6251 if object.proxy_state().is_some() {
6252 let receiver = Value::Object(object.clone());
6253 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
6254 return match (accepted, on_failure) {
6255 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6256 (false, DeleteFailure::Throw) => {
6257 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
6258 }
6259 };
6260 }
6261 }
6262 // A host class's `set_property` trap decides for itself. `Some(false)` is a
6263 // refusal and means exactly what a proxy's `false` means.
6264 if let Some(exotic) = object.exotic() {
6265 let receiver = Value::Object(object.clone());
6266 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
6267 return match (accepted, on_failure) {
6268 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6269 (false, DeleteFailure::Throw) => {
6270 Err(self.type_error(format!("property '{key}' is read-only")))
6271 }
6272 };
6273 }
6274 }
6275 // The element and `length` shortcuts only exist for string keys: an array
6276 // index has no symbol spelling, and a symbol named `length` is an ordinary
6277 // property.
6278 let text = key.as_str();
6279 // A typed array's elements are a window onto its buffer: the store has to go
6280 // through the view's element type so the value is wrapped (or clamped) and so an
6281 // out-of-range or detached write is a silent no-op, as the spec says.
6282 //
6283 // The key test is `CanonicalNumericIndexString`, like every other index operation
6284 // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
6285 // does not exist, so they do nothing and leave no own property behind
6286 // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
6287 // path, which created a property named `"-0"`.
6288 //
6289 // The conversion comes **first**, before the index is checked at all, and that
6290 // order is observable twice over:
6291 //
6292 // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
6293 // has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
6294 // then store the converted value;
6295 // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
6296 // `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
6297 // run and its exception to escape.
6298 //
6299 // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
6300 // validity check, not a validity check that skips the conversion. The store itself
6301 // is a no-op when the index is invalid by then, which is why no extra guard is
6302 // needed around `typed_array_set`.
6303 if let Some(element) = object.typed_array_element_type()
6304 && let Some(numeric) = canonical_numeric_index(key)
6305 {
6306 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
6307 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
6308 // in `Interp`, because it is script-observable and the storage borrow inside
6309 // `typed_array_set` must not be held across it.
6310 let stored = self.element_value(element, value)?;
6311 if typed_array_index_is_valid(object, numeric)
6312 && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
6313 {
6314 return Err(self.type_error(reason));
6315 }
6316 return Ok(());
6317 }
6318 if let Some(text) = text
6319 && let Some(index) = array_index(text)
6320 && object.is_array()
6321 {
6322 // An accessor defined on an index lives in the property table while the
6323 // element slot is a hole, so the store has to go through the property first.
6324 // Writing the vector directly skipped the setter entirely.
6325 if let Some(existing) = object.own_property_key(key) {
6326 if existing.is_accessor() {
6327 return match existing.setter.clone() {
6328 Some(setter) if !matches!(setter, Value::Undefined) => {
6329 let receiver = Value::Object(object.clone());
6330 self.call_value(setter, receiver, vec![value]).map(|_| ())
6331 }
6332 _ => match on_failure {
6333 DeleteFailure::Throw => Err(self.type_error(format!(
6334 "cannot set property '{text}', it has only a getter"
6335 ))),
6336 DeleteFailure::Ignore => Ok(()),
6337 },
6338 };
6339 }
6340 if !existing.writable {
6341 return match on_failure {
6342 DeleteFailure::Throw => {
6343 Err(self.type_error(format!("'{text}' is read-only")))
6344 }
6345 DeleteFailure::Ignore => Ok(()),
6346 };
6347 }
6348 }
6349 {
6350 // Growing the array needs a writable `length`.
6351 if (index as usize) >= object.array_length().unwrap_or(0)
6352 && !object.length_writable()
6353 {
6354 return match on_failure {
6355 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6356 DeleteFailure::Ignore => Ok(()),
6357 };
6358 }
6359 // Adding an index past the end makes the array longer, which a
6360 // non-extensible array refuses.
6361 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6362 return match on_failure {
6363 DeleteFailure::Throw => Err(self.type_error(format!(
6364 "cannot add property '{key}', object is not extensible"
6365 ))),
6366 DeleteFailure::Ignore => Ok(()),
6367 };
6368 }
6369 if object.element_is_locked(index) {
6370 return match on_failure {
6371 DeleteFailure::Throw => {
6372 Err(self.type_error(format!("'{key}' is read-only")))
6373 }
6374 DeleteFailure::Ignore => Ok(()),
6375 };
6376 }
6377 // The element vector is only half of `[[Set]]` for an index: the
6378 // prototype chain is consulted first, and a setter there answers instead
6379 // of the element store. This branch used to write the element directly, so
6380 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6381 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6382 // the reference calls the setter and the array keeps no own index.
6383 //
6384 // An *exotic* prototype has no entry to find, because its indices live
6385 // outside the property table — `Object.setPrototypeOf([], typedArray)`
6386 // then looked like "nothing on the chain" and the store created the
6387 // element, where the view's `[[Set]]` answers `true` and does nothing for
6388 // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6389 // checks the array's `length` stays 0). So the dispatch comes first.
6390 if !object.has_own_key(key)
6391 && let Some(proto) = object.proto()
6392 && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6393 {
6394 let receiver = Value::Object(object.clone());
6395 let accepted =
6396 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6397 return if accepted {
6398 Ok(())
6399 } else {
6400 match on_failure {
6401 DeleteFailure::Throw => {
6402 Err(self.type_error(format!("'{key}' is read-only")))
6403 }
6404 DeleteFailure::Ignore => Ok(()),
6405 }
6406 };
6407 }
6408 if let Some((owner, property)) = lookup_key(object, key)
6409 && !owner.ptr_eq(object)
6410 {
6411 match &property {
6412 property if property.is_accessor() => {
6413 match &property.setter {
6414 Some(setter) if !matches!(setter, Value::Undefined) => {
6415 let receiver = Value::Object(object.clone());
6416 self.call_value(setter.clone(), receiver, vec![value])?;
6417 }
6418 _ => {
6419 return match on_failure {
6420 DeleteFailure::Throw => Err(self.type_error(format!(
6421 "cannot set property '{text}', it has only a getter"
6422 ))),
6423 DeleteFailure::Ignore => Ok(()),
6424 };
6425 }
6426 }
6427 return Ok(());
6428 }
6429 property if !property.writable => {
6430 return match on_failure {
6431 DeleteFailure::Throw => {
6432 Err(self.type_error(format!("'{text}' is read-only")))
6433 }
6434 DeleteFailure::Ignore => Ok(()),
6435 };
6436 }
6437 _ => {}
6438 }
6439 }
6440 if object.array_set(self.heap, index as usize, value.clone()) {
6441 return Ok(());
6442 }
6443 // Past the dense limit the slot is too far out to be worth one `Value`
6444 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6445 // constant time by keeping the index as an ordinary property. The store
6446 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6447 // to a legal program.
6448 object.define_key(key, Property::with_attributes(value, true, true));
6449 // Extend, never shorten: the index may be *inside* the current length (a
6450 // huge `length` with a sparse store), and shortening would delete the
6451 // sparse properties above it — including the one just stored.
6452 if index as usize + 1 > object.array_length().unwrap_or(0) {
6453 object.array_set_length(self.heap, index as usize + 1);
6454 }
6455 return Ok(());
6456 }
6457 }
6458 if text == Some("length") && object.is_array() {
6459 // §10.4.2.4 steps 3–5: **two** `ToNumber` conversions, then the writability
6460 // test. A `valueOf` that locks `length` on its second call therefore turns the
6461 // store into a refused write rather than a silent success
6462 // (`length/define-own-prop-length-coercion-order-set`).
6463 let rounded = self.coerce_array_length_twice(&value)?;
6464 if !object.length_writable() {
6465 return match on_failure {
6466 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6467 DeleteFailure::Ignore => Ok(()),
6468 };
6469 }
6470 // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6471 // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6472 // answered `NaN`, which left the assignment silently ignored
6473 // (`S15.4.5.2_A3_T2`).
6474 let _ = rounded;
6475 let length = self.to_js_number(&value)?;
6476 // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6477 // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6478 // `RangeError`s; the old code only tested "finite and non-negative" and then
6479 // truncated, so `[].length = 4294967297` quietly produced a length no array can
6480 // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6481 let valid = length.is_finite()
6482 && length >= 0.0
6483 && length.fract() == 0.0
6484 && length <= u32::MAX as f64;
6485 if !valid {
6486 return Err(self.range_error("invalid array length"));
6487 }
6488 {
6489 let length = length as usize;
6490 // `a.length = n` with `n` below a non-configurable element cannot
6491 // drop that element, so the whole assignment fails. The spec makes
6492 // this a `TypeError` rather than a silent no-op, in any mode.
6493 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6494 // Sloppy mode stops the truncation at the blocking element
6495 // instead of failing; strict mode raises.
6496 // Both modes stop at the blocking element; they differ in
6497 // whether that is reported. The reference truncates *then*
6498 // throws, so the array is left in the shortened state.
6499 object.array_truncate(self.heap, blocked + 1);
6500 return match on_failure {
6501 DeleteFailure::Throw => {
6502 Err(self.type_error(format!("cannot delete property '{blocked}'")))
6503 }
6504 DeleteFailure::Ignore => Ok(()),
6505 };
6506 }
6507 object.array_set_length(self.heap, length);
6508 return Ok(());
6509 }
6510 }
6511 // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6512 // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6513 // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6514 //
6515 // The prototype step is a dispatch, not a lookup. Walking the chain here and
6516 // applying whatever came back is the same thing for an ordinary prototype and
6517 // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6518 // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6519 // answers "not mine, the receiver is not me" without touching the buffer. This
6520 // code used to find nothing owned by `o`, find no property on the view either,
6521 // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6522 // object and never converted (`key-is-valid-index-prototype-chain-set`,
6523 // `key-is-canonical-invalid-index-prototype-chain-set`).
6524 //
6525 // The read-only and accessor rules of step 1 are what make
6526 // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6527 // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6528 let own = match self.lookup_for_write(object, key)? {
6529 Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6530 _ => None,
6531 };
6532 if let Some(property) = own {
6533 if property.is_accessor() {
6534 return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6535 Some(setter) => {
6536 let receiver = Value::Object(object.clone());
6537 self.call_value(setter, receiver, vec![value])?;
6538 Ok(())
6539 }
6540 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6541 // Sloppy code swallows that refusal, strict code raises — the same
6542 // rule the read-only *data* property below follows, and skipping it
6543 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6544 // return silently. The reference answers `TypeError: 'x' is
6545 // read-only`.
6546 None => match on_failure {
6547 DeleteFailure::Throw => {
6548 Err(self.type_error(format!("'{key}' is read-only")))
6549 }
6550 DeleteFailure::Ignore => Ok(()),
6551 },
6552 };
6553 }
6554 // An own non-writable data property stops here: nothing may change it.
6555 if !property.writable {
6556 return match on_failure {
6557 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6558 DeleteFailure::Ignore => Ok(()),
6559 };
6560 }
6561 // An existing writable own property keeps its attributes: only the value
6562 // moves. Redefining instead would reset them, which is how a
6563 // non-configurable global `var` used to become deletable.
6564 if object.write_value_key(key, value.clone()) {
6565 return Ok(());
6566 }
6567 }
6568 // Step 2: hand the store to the prototype, with `object` as the receiver.
6569 if let Some(proto) = object.proto() {
6570 let receiver = Value::Object(object.clone());
6571 let accepted =
6572 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6573 return if accepted {
6574 Ok(())
6575 } else {
6576 match on_failure {
6577 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6578 DeleteFailure::Ignore => Ok(()),
6579 }
6580 };
6581 }
6582 // Step 3: create one, and a non-extensible object cannot.
6583 if !object.is_extensible() {
6584 return match on_failure {
6585 DeleteFailure::Throw => Err(self.type_error(format!(
6586 "cannot add property {key}, object is not extensible"
6587 ))),
6588 DeleteFailure::Ignore => Ok(()),
6589 };
6590 }
6591 object.define_data_key(key, value);
6592 Ok(())
6593 }
6594
6595 /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6596 ///
6597 /// The distinction the fast path above does not need: it is called with the store's
6598 /// receiver already being the object it writes to. Here `object` is the one whose
6599 /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6600 /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6601 /// and not a write to `object`.
6602 ///
6603 /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6604 /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6605 /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6606 /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6607 /// descriptor on the prototype refuses instead, which is the same rule that keeps
6608 /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6609 ///
6610 /// Answers `false` where the spec says `false`; the caller turns that into the
6611 /// strict-mode `TypeError` or the sloppy-mode silence.
6612 fn ordinary_set_with_receiver(
6613 &mut self,
6614 object: &Gc<JsObject>,
6615 receiver: &Value,
6616 key: &PropertyKey,
6617 value: Value,
6618 on_failure: DeleteFailure,
6619 ) -> JsResult<bool> {
6620 // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6621 if object.proxy_state().is_some() {
6622 return Ok(self
6623 .proxy_set(object, key, value, receiver)?
6624 .unwrap_or(true));
6625 }
6626 // A host class decides for itself, with the receiver the caller named.
6627 if let Some(exotic) = object.exotic()
6628 && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6629 {
6630 return Ok(accepted);
6631 }
6632 // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6633 // rather than the receiver, but the receiver may still *be* the view:
6634 // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6635 // itself as receiver, and then the first half applies — convert `V` once, store
6636 // if the index is valid, answer `true` either way. The conversion is the observable
6637 // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6638 //
6639 // Only the second half, a view that is *not* the receiver, skips the conversion
6640 // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6641 // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6642 // below with the value still unconverted.
6643 if object.typed_array_element_type().is_some()
6644 && let Some(numeric) = canonical_numeric_index(key)
6645 {
6646 if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6647 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6648 return Ok(true);
6649 }
6650 if !typed_array_index_is_valid(object, numeric) {
6651 return Ok(true);
6652 }
6653 }
6654 let own = self.object_get_own_property(object, key)?;
6655 if let Some(own) = own {
6656 if own.is_accessor() {
6657 return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6658 Some(setter) => {
6659 self.call_value(setter, receiver.clone(), vec![value])?;
6660 Ok(true)
6661 }
6662 None => Ok(false),
6663 };
6664 }
6665 // A non-writable data descriptor refuses, own or inherited. Either way the
6666 // receiver must not gain a shadowing property.
6667 if !own.writable {
6668 return Ok(false);
6669 }
6670 // Step 1.d: the *receiver's* own descriptor decides whether it can be
6671 // created or written, and it is created as an ordinary data property.
6672 let Some(receiver_object) = receiver.as_object().cloned() else {
6673 return Ok(false);
6674 };
6675 return match self.object_get_own_property(&receiver_object, key)? {
6676 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6677 Some(existing) => self.object_define_own_property(
6678 &receiver_object,
6679 key,
6680 Property {
6681 value: Some(value),
6682 ..existing
6683 },
6684 ),
6685 None => {
6686 self.object_define_own_property(&receiver_object, key, Property::data(value))
6687 }
6688 };
6689 }
6690 // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6691 if let Some(proto) = object.proto() {
6692 return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6693 }
6694 // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6695 // *default* data descriptor here, so control falls into step 2 exactly as if the
6696 // target had owned a writable property — which means the **receiver's** own
6697 // descriptor is asked for before the write. Skipping that question went straight to
6698 // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6699 // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6700 // exactly those calls).
6701 let Some(receiver_object) = receiver.as_object().cloned() else {
6702 return Ok(false);
6703 };
6704 match self.object_get_own_property(&receiver_object, key)? {
6705 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6706 Some(existing) => self.object_define_own_property(
6707 &receiver_object,
6708 key,
6709 Property {
6710 value: Some(value),
6711 ..existing
6712 },
6713 ),
6714 None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6715 }
6716 }
6717
6718 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6719 ///
6720 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6721 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6722 /// a virtual accessor gets its setter run without implementing `set_property` at all.
6723 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6724 /// the prototype, so the walk resumes above the object.
6725 fn lookup_for_write(
6726 &mut self,
6727 object: &Gc<JsObject>,
6728 key: &PropertyKey,
6729 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6730 let Some(exotic) = object.exotic() else {
6731 return Ok(lookup_key(object, key));
6732 };
6733 Ok(match exotic.get_own_property(self, object, key)? {
6734 Some(Some(property)) => Some((object.clone(), property)),
6735 Some(None) => lookup_key_above(object, key),
6736 None => lookup_key(object, key),
6737 })
6738 }
6739
6740 /// Delete `object[key]`.
6741 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6742 self.delete_property_key(object, &PropertyKey::from(key))
6743 }
6744
6745 /// [`Interp::delete_property`] with a key that may be a symbol.
6746 pub fn delete_property_key(
6747 &mut self,
6748 object: &Gc<JsObject>,
6749 key: &PropertyKey,
6750 ) -> JsResult<bool> {
6751 // A proxy decides for itself, and may even throw; the invariant checks live in
6752 // `proxy_delete`.
6753 if let Some(answer) = self.proxy_delete(object, key)? {
6754 return Ok(answer);
6755 }
6756 // A host class's `delete_property` trap decides; `false` is a refusal, which the
6757 // caller reports as a failed delete.
6758 if let Some(exotic) = object.exotic()
6759 && let Some(answer) = exotic.delete_property(self, object, key)?
6760 {
6761 return Ok(answer);
6762 }
6763 // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6764 // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6765 // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6766 // one answers `false` because the elements are non-configurable. The prototype
6767 // chain is not consulted either, which is what makes a throwing getter on
6768 // `TypedArray.prototype["-1"]` stay unrun.
6769 if object.typed_array_parts().is_some()
6770 && object.proxy_state().is_none()
6771 && let Some(numeric) = canonical_numeric_index(key)
6772 {
6773 return Ok(!typed_array_index_is_valid(object, numeric));
6774 }
6775 let mapped_index = key.as_str().and_then(array_index);
6776 if let Some(index) = mapped_index
6777 && let Some(length) = object.array_length()
6778 && (index as usize) < length
6779 {
6780 // An accessor defined on an index lives in the property table rather than the
6781 // element vector, so both have to be cleared: `delete` after
6782 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6783 object.delete_key(key);
6784 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6785 // index stops answering `in`.
6786 if object.element_is_undeletable(index) {
6787 return Ok(false);
6788 }
6789 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6790 // so a later `defineProperty(arguments, "0", {value})` writes to the object
6791 // and no longer through to the parameter. A refused delete leaves the
6792 // mapping alone.
6793 object.drop_mapped_argument(index as usize);
6794 object.array_set(self.heap, index as usize, Value::Hole);
6795 return Ok(true);
6796 }
6797 // An array's `length` is a non-configurable own property that lives outside the
6798 // property table, so `delete_key` finds nothing and reports success — `Reflect
6799 // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6800 // §10.4.4.1 step 3 refuses it.
6801 if key.as_str() == Some("length") && object.array_length().is_some() {
6802 return Ok(false);
6803 }
6804 // The same for an object that is not an array: only a delete that actually
6805 // removed the property ends the alias.
6806 let deleted = object.delete_key(key);
6807 if deleted && let Some(index) = mapped_index {
6808 object.drop_mapped_argument(index as usize);
6809 }
6810 Ok(deleted)
6811 }
6812
6813 // -- proxy traps --------------------------------------------------------
6814 //
6815 // A proxy's internal methods all look the same: ask the handler for the trap, call it
6816 // with the target and the operation's own arguments, then check the answer against
6817 // the target. The checks are not decoration — they are what stops a proxy from
6818 // reporting a `non-configurable` property as missing, which would let a frozen object
6819 // be rewritten by standing in front of it.
6820
6821 /// The target and handler of `object`, or `None` when it is not a proxy.
6822 ///
6823 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6824 /// one has to fail: the slots the traps would have been read from are gone.
6825 pub(crate) fn proxy_parts(
6826 &mut self,
6827 object: &Gc<JsObject>,
6828 ) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6829 let Some(state) = object.proxy_state() else {
6830 return Ok(None);
6831 };
6832 let state = state.borrow();
6833 match (&state.target, &state.handler) {
6834 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
6835 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
6836 }
6837 }
6838
6839 /// Call `handler[name]`, or answer `None` when the trap is absent.
6840 ///
6841 /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
6842 /// and only a value that is neither is `IsCallable`-checked and refused. Treating
6843 /// `null` as "present but not callable" made every `{ get: null }` proxy throw
6844 /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
6845 /// one per trap plus the `target-is-proxy` variants.
6846 ///
6847 /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
6848 /// this cannot simply be "any non-callable means no trap".
6849 fn proxy_trap(
6850 &mut self,
6851 handler: &Value,
6852 name: &str,
6853 args: Vec<Value>,
6854 ) -> JsResult<Option<Value>> {
6855 let Value::Object(table) = handler else {
6856 return Err(self.type_error("proxy handler is not an object"));
6857 };
6858 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
6859 match trap {
6860 Value::Undefined | Value::Null => Ok(None),
6861 Value::Object(function) if function.is_callable() => {
6862 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
6863 Ok(Some(answer))
6864 }
6865 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
6866 }
6867 }
6868
6869 /// Whether the target's own property `key` is one it refuses to lose.
6870 ///
6871 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
6872 /// its value behind the target's back.
6873 ///
6874 /// A **method**, not a free function, because §10.5.1's invariants say
6875 /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
6876 /// property table directly finds nothing (a proxy's table is empty by design), so every
6877 /// invariant check silently passed for a proxy target. That is what
6878 /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
6879 /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
6880 /// where an array's elements and its `length` — both fixed, both outside the table —
6881 /// are covered.
6882 fn fixed_property(
6883 &mut self,
6884 target: &Gc<JsObject>,
6885 key: &PropertyKey,
6886 ) -> JsResult<Option<Property>> {
6887 Ok(self
6888 .object_get_own_property(target, key)?
6889 .filter(|property| !property.configurable))
6890 }
6891
6892 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
6893 fn proxy_get(
6894 &mut self,
6895 object: &Gc<JsObject>,
6896 receiver: &Value,
6897 key: &PropertyKey,
6898 ) -> JsResult<Option<Value>> {
6899 let Some((target, handler)) = self.proxy_parts(object)? else {
6900 return Ok(None);
6901 };
6902 let key_value = self.key_value(key);
6903 let Some(result) = self.proxy_trap(
6904 &handler,
6905 "get",
6906 vec![Value::Object(target.clone()), key_value, receiver.clone()],
6907 )?
6908 else {
6909 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
6910 // inherited getter still sees the proxy.
6911 return Ok(Some(
6912 self.get_property_key_for(&target, Some(receiver), key)?
6913 .unwrap_or(Value::Undefined),
6914 ));
6915 };
6916 if let Some(fixed) = self.fixed_property(&target, key)? {
6917 if fixed.is_accessor() {
6918 // A fixed accessor with no getter must read as `undefined`.
6919 let has_getter = fixed
6920 .getter
6921 .as_ref()
6922 .is_some_and(|getter| !matches!(getter, Value::Undefined));
6923 if !has_getter && !matches!(result, Value::Undefined) {
6924 return Err(self.type_error(format!(
6925 "proxy 'get' must report undefined for the non-configurable property '{key}'"
6926 )));
6927 }
6928 } else if !fixed.writable {
6929 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6930 if !fixed_value.same_value(&result) {
6931 return Err(self.type_error(format!(
6932 "proxy 'get' disagrees with the non-configurable property '{key}'"
6933 )));
6934 }
6935 }
6936 }
6937 Ok(Some(result))
6938 }
6939
6940 /// `[[Set]]` on a proxy.
6941 ///
6942 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
6943 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
6944 /// read-only store has.
6945 fn proxy_set(
6946 &mut self,
6947 object: &Gc<JsObject>,
6948 key: &PropertyKey,
6949 value: Value,
6950 receiver: &Value,
6951 ) -> JsResult<Option<bool>> {
6952 let Some((target, handler)) = self.proxy_parts(object)? else {
6953 return Ok(None);
6954 };
6955 let key_value = self.key_value(key);
6956 let Some(result) = self.proxy_trap(
6957 &handler,
6958 "set",
6959 vec![
6960 Value::Object(target.clone()),
6961 key_value,
6962 value.clone(),
6963 receiver.clone(),
6964 ],
6965 )?
6966 else {
6967 // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
6968 // given — not the target. `OrdinarySet` step 3 is
6969 // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
6970 // object whose prototype is a typed array has to reach the proxy's own
6971 // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
6972 // calls and expects exactly one. Storing on the target instead put the value
6973 // in the target and never consulted the trap.
6974 let accepted = self.ordinary_set_with_receiver(
6975 &target,
6976 receiver,
6977 key,
6978 value,
6979 DeleteFailure::Ignore,
6980 )?;
6981 return Ok(Some(accepted));
6982 };
6983 if !result.to_boolean() {
6984 return Ok(Some(false));
6985 }
6986 if let Some(fixed) = self.fixed_property(&target, key)? {
6987 if fixed.is_accessor() {
6988 let has_setter = fixed
6989 .setter
6990 .as_ref()
6991 .is_some_and(|setter| !matches!(setter, Value::Undefined));
6992 if !has_setter {
6993 return Err(self.type_error(format!(
6994 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
6995 )));
6996 }
6997 } else if !fixed.writable {
6998 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6999 if !fixed_value.same_value(&value) {
7000 return Err(self.type_error(format!(
7001 "proxy 'set' changed the non-configurable property '{key}'"
7002 )));
7003 }
7004 }
7005 }
7006 // A new property cannot appear on a target that refuses new properties.
7007 if self.object_get_own_property(&target, key)?.is_none()
7008 && !self.object_is_extensible(&target)?
7009 {
7010 return Err(self.type_error(format!(
7011 "proxy 'set' added '{key}' to a non-extensible target"
7012 )));
7013 }
7014 Ok(Some(true))
7015 }
7016
7017 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
7018 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7019 let Some((target, handler)) = self.proxy_parts(object)? else {
7020 return Ok(None);
7021 };
7022 let key_value = self.key_value(key);
7023 let Some(result) = self.proxy_trap(
7024 &handler,
7025 "has",
7026 vec![Value::Object(target.clone()), key_value],
7027 )?
7028 else {
7029 return Ok(Some(self.has_own_or_inherited(&target, key)?));
7030 };
7031 if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7032 return Err(self.type_error(format!(
7033 "proxy 'has' denied the non-configurable property '{key}'"
7034 )));
7035 }
7036 // A non-extensible target cannot grow, so every own property it *has* is fixed.
7037 if !result.to_boolean()
7038 && !self.object_is_extensible(&target)?
7039 && self.object_get_own_property(&target, key)?.is_some()
7040 {
7041 return Err(self.type_error(format!(
7042 "proxy 'has' denied the own property '{key}' of a non-extensible target"
7043 )));
7044 }
7045 Ok(Some(result.to_boolean()))
7046 }
7047
7048 /// `[[Delete]]` on a proxy.
7049 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7050 let Some((target, handler)) = self.proxy_parts(object)? else {
7051 return Ok(None);
7052 };
7053 let key_value = self.key_value(key);
7054 let Some(result) = self.proxy_trap(
7055 &handler,
7056 "deleteProperty",
7057 vec![Value::Object(target.clone()), key_value],
7058 )?
7059 else {
7060 return Ok(Some(self.delete_property_key(&target, key)?));
7061 };
7062 if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7063 return Err(self.type_error(format!(
7064 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
7065 )));
7066 }
7067 if result.to_boolean()
7068 && !self.object_is_extensible(&target)?
7069 && self.object_get_own_property(&target, key)?.is_some()
7070 {
7071 return Err(self.type_error(format!(
7072 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
7073 )));
7074 }
7075 Ok(Some(result.to_boolean()))
7076 }
7077
7078 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
7079 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
7080 let Some((target, handler)) = self.proxy_parts(object)? else {
7081 return Ok(None);
7082 };
7083 let Some(result) =
7084 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
7085 else {
7086 // No trap: the target's own keys, already in the order an object reports.
7087 return Ok(Some(self.object_own_property_keys(&target)?));
7088 };
7089 // `CreateListFromArrayLike` with the string-or-symbol restriction.
7090 let list = self.list_from_array_like(&result, true)?;
7091 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
7092 for value in list {
7093 let key = self.propkey(&value)?;
7094 if keys.contains(&key) {
7095 return Err(self.type_error(format!(
7096 "proxy 'ownKeys' returned the duplicate key '{key}'"
7097 )));
7098 }
7099 keys.push(key);
7100 }
7101 // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
7102 // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
7103 // table is empty, which made every check below vacuous.
7104 let target_keys = self.object_own_property_keys(&target)?;
7105 let extensible = self.object_is_extensible(&target)?;
7106 for key in &target_keys {
7107 if keys.contains(key) {
7108 continue;
7109 }
7110 if self.fixed_property(&target, key)?.is_some() {
7111 return Err(self.type_error(format!(
7112 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
7113 )));
7114 }
7115 if !extensible {
7116 return Err(self.type_error(format!(
7117 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
7118 )));
7119 }
7120 }
7121 if !extensible {
7122 // §10.5.11 step 12: the lists must match one for one, in any order.
7123 if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
7124 {
7125 return Err(
7126 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
7127 );
7128 }
7129 }
7130 Ok(Some(keys))
7131 }
7132
7133 /// `[[GetOwnProperty]]` on a proxy.
7134 fn proxy_get_own_property(
7135 &mut self,
7136 object: &Gc<JsObject>,
7137 key: &PropertyKey,
7138 ) -> JsResult<Option<Option<Property>>> {
7139 let Some((target, handler)) = self.proxy_parts(object)? else {
7140 return Ok(None);
7141 };
7142 let key_value = self.key_value(key);
7143 let Some(result) = self.proxy_trap(
7144 &handler,
7145 "getOwnPropertyDescriptor",
7146 vec![Value::Object(target.clone()), key_value],
7147 )?
7148 else {
7149 // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
7150 // property table. Two things ride on that choice: a target that is itself a
7151 // proxy has to re-dispatch (its own table is empty, so reading it reported
7152 // `undefined` for every key, `Object.keys` then dropped them all), and an array's
7153 // indices and `length` live outside the table and need the ordinary synthesis.
7154 // `object_get_own_property` does both.
7155 return Ok(Some(self.object_get_own_property(&target, key)?));
7156 };
7157 // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
7158 // `ToPropertyDescriptor` runs, because that operation would box the primitive
7159 // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
7160 // empty descriptor instead of refusing.
7161 if !matches!(result, Value::Undefined | Value::Object(_)) {
7162 return Err(self.type_error(
7163 "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
7164 ));
7165 }
7166 let target_desc = self.object_get_own_property(&target, key)?;
7167 let extensible = self.object_is_extensible(&target)?;
7168 let Some(descriptor) = (match result {
7169 Value::Undefined => None,
7170 _ => Some(self.property_from_descriptor(&result)?),
7171 }) else {
7172 // Steps 12.a–12.d: reporting absent is allowed only when the target's own
7173 // descriptor is configurable *and* the target can still grow back.
7174 if let Some(target_desc) = &target_desc {
7175 if !target_desc.configurable {
7176 return Err(self.type_error(format!(
7177 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
7178 )));
7179 }
7180 if !extensible {
7181 return Err(self.type_error(format!(
7182 "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
7183 )));
7184 }
7185 }
7186 return Ok(Some(None));
7187 };
7188 // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
7189 // which is a stronger requirement than "the target is not contradicting it" — the
7190 // four branches below are each one test262 case.
7191 if !descriptor.configurable {
7192 let Some(target_desc) = &target_desc else {
7193 return Err(self.type_error(format!(
7194 "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
7195 )));
7196 };
7197 if target_desc.configurable {
7198 return Err(self.type_error(format!(
7199 "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
7200 )));
7201 }
7202 let target_is_data = !target_desc.is_accessor();
7203 let result_is_data = !descriptor.is_accessor();
7204 if result_is_data && !target_is_data {
7205 return Err(self.type_error(format!(
7206 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7207 )));
7208 }
7209 if target_is_data && !target_desc.writable {
7210 if !result_is_data {
7211 return Err(self.type_error(format!(
7212 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7213 )));
7214 }
7215 if descriptor.writable {
7216 return Err(self.type_error(format!(
7217 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7218 )));
7219 }
7220 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7221 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
7222 if !fixed_value.same_value(&reported) {
7223 return Err(self.type_error(format!(
7224 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
7225 )));
7226 }
7227 }
7228 // Step 16.d: a reported *read-only* data property needs a real read-only data
7229 // property behind it. Missing this let a trap bolt a frozen property onto a
7230 // writable target intent (`resultdesc-is-not-configurable-not-writable-
7231 // targetdesc-is-writable`).
7232 if result_is_data && !descriptor.writable {
7233 if !target_is_data {
7234 return Err(self.type_error(format!(
7235 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7236 )));
7237 }
7238 if target_desc.writable {
7239 return Err(self.type_error(format!(
7240 "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
7241 )));
7242 }
7243 }
7244 if descriptor.is_accessor() {
7245 // Step 16.e: a getter the target does not have may not be invented, and
7246 // vice versa.
7247 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7248 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7249 (Some(a), Some(b)) => a.same_value(b),
7250 _ => false,
7251 };
7252 if !same(&target_desc.getter, &descriptor.getter)
7253 || !same(&target_desc.setter, &descriptor.setter)
7254 {
7255 return Err(self.type_error(format!(
7256 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7257 )));
7258 }
7259 }
7260 }
7261 // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
7262 // where the target's own is locked. Without it a handler could advertise
7263 // `{value: 1, configurable: true}` for a non-configurable property, and a caller
7264 // that believed it would try to redefine something it cannot.
7265 if descriptor.configurable
7266 && let Some(target_desc) = &target_desc
7267 && !target_desc.configurable
7268 {
7269 return Err(self.type_error(format!(
7270 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
7271 )));
7272 }
7273 // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
7274 // through the trap either, however well-formed the descriptor is. This is the
7275 // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
7276 // the frozen target does not own.
7277 if !extensible {
7278 let Some(target_desc) = &target_desc else {
7279 return Err(self.type_error(format!(
7280 "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
7281 )));
7282 };
7283 if target_desc.is_accessor() == descriptor.is_accessor() {
7284 let target_is_data = !target_desc.is_accessor();
7285 let result_is_data = !descriptor.is_accessor();
7286 if target_is_data && !target_desc.writable && descriptor.writable {
7287 return Err(self.type_error(format!(
7288 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7289 )));
7290 }
7291 if !result_is_data && !target_is_data {
7292 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7293 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7294 (Some(a), Some(b)) => a.same_value(b),
7295 _ => false,
7296 };
7297 if !same(&target_desc.getter, &descriptor.getter)
7298 || !same(&target_desc.setter, &descriptor.setter)
7299 {
7300 return Err(self.type_error(format!(
7301 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7302 )));
7303 }
7304 }
7305 }
7306 }
7307 Ok(Some(Some(descriptor)))
7308 }
7309
7310 /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
7311 ///
7312 /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
7313 /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
7314 /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
7315 /// for a data property. `Property` cannot express "this field is absent", so the whole
7316 /// property path is skipped and the descriptor is assembled here field by field.
7317 ///
7318 /// `current` is the property the trap reported, used only to tell a data property from
7319 /// an accessor.
7320 pub fn proxy_seal_property(
7321 &mut self,
7322 object: &Gc<JsObject>,
7323 key: &PropertyKey,
7324 frozen: bool,
7325 current: &Property,
7326 ) -> JsResult<bool> {
7327 let Some((_target, handler)) = self.proxy_parts(object)? else {
7328 return Err(self.type_error("not a proxy"));
7329 };
7330 let descriptor = self.new_object(None);
7331 descriptor.define_data("configurable", Value::Bool(false));
7332 if frozen && !current.is_accessor() {
7333 descriptor.define_data("writable", Value::Bool(false));
7334 }
7335 let key_value = self.key_value(key);
7336 let target = object
7337 .proxy_state()
7338 .and_then(|state| state.borrow().target.clone());
7339 let Some(target) = target else {
7340 return Err(self.type_error("cannot use a proxy that has been revoked"));
7341 };
7342 let Some(result) = self.proxy_trap(
7343 &handler,
7344 "defineProperty",
7345 vec![Value::Object(target), key_value, Value::Object(descriptor)],
7346 )?
7347 else {
7348 // No trap means the definition belongs to the target; `false` is its answer.
7349 return Ok(false);
7350 };
7351 Ok(result.to_boolean())
7352 }
7353
7354 /// `[[DefineOwnProperty]]` on a proxy.
7355 fn proxy_define_property(
7356 &mut self,
7357 object: &Gc<JsObject>,
7358 key: &PropertyKey,
7359 property: Property,
7360 ) -> JsResult<Option<bool>> {
7361 let Some((target, handler)) = self.proxy_parts(object)? else {
7362 return Ok(None);
7363 };
7364 let key_value = self.key_value(key);
7365 let descriptor = self.descriptor_from_property(&property);
7366 let Some(result) = self.proxy_trap(
7367 &handler,
7368 "defineProperty",
7369 vec![Value::Object(target.clone()), key_value, descriptor],
7370 )?
7371 else {
7372 // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7373 // going" answer and `object_define_own_property` turns it into exactly that
7374 // forwarding — see the note there. (Reading it as "not a proxy" would define
7375 // the property on the proxy object itself, whose table is empty and which no
7376 // read ever consults.)
7377 return Ok(None);
7378 };
7379 if !result.to_boolean() {
7380 return Ok(Some(false));
7381 }
7382 // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7383 // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7384 // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7385 // and treating them alike made four cases pass a descriptor the target contradicts.
7386 let target_desc = self.object_get_own_property(&target, key)?;
7387 let extensible = self.object_is_extensible(&target)?;
7388 let named = property
7389 .descriptor_fields
7390 .unwrap_or(crate::object::DescriptorFields {
7391 value: false,
7392 writable: false,
7393 enumerable: false,
7394 configurable: false,
7395 get: false,
7396 set: false,
7397 });
7398 if named.configurable && !property.configurable {
7399 let Some(target_desc) = &target_desc else {
7400 return Err(self.type_error(format!(
7401 "proxy 'defineProperty' invented the non-configurable '{key}'"
7402 )));
7403 };
7404 if target_desc.configurable {
7405 return Err(self.type_error(format!(
7406 "proxy 'defineProperty' made '{key}' non-configurable"
7407 )));
7408 }
7409 }
7410 // Step 11's other half: reporting that a property was made *configurable* needs a
7411 // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7412 // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7413 // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7414 // target`).
7415 if named.configurable
7416 && property.configurable
7417 && let Some(target_desc) = &target_desc
7418 && !target_desc.configurable
7419 {
7420 return Err(
7421 self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7422 );
7423 }
7424 // Step 12: a property cannot be reported *made writable* when the target's copy is
7425 // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7426 // the trap is allowed to claim a definition it did not perform, as long as the
7427 // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7428 // legal, and refusing it broke the commonest way to seed a proxy).
7429 if named.writable
7430 && property.writable
7431 && let Some(target_desc) = &target_desc
7432 && !target_desc.writable
7433 {
7434 return Err(self.type_error(format!(
7435 "proxy 'defineProperty' made the read-only '{key}' writable"
7436 )));
7437 }
7438 // Step 13: making a property read-only needs an existing read-only property.
7439 if named.writable
7440 && !property.writable
7441 && let Some(target_desc) = &target_desc
7442 && !target_desc.is_accessor()
7443 && target_desc.writable
7444 {
7445 return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7446 }
7447 // Step 14: a non-writable, non-configurable property's value is fixed.
7448 if named.value
7449 && let Some(target_desc) = &target_desc
7450 && !target_desc.is_accessor()
7451 && !target_desc.writable
7452 && !target_desc.configurable
7453 {
7454 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7455 let reported = property.value.clone().unwrap_or(Value::Undefined);
7456 if !fixed_value.same_value(&reported) {
7457 return Err(self.type_error(format!(
7458 "proxy 'defineProperty' changed the value of '{key}'"
7459 )));
7460 }
7461 }
7462 // Step 15: a non-extensible target cannot grow.
7463 if target_desc.is_none() && !extensible {
7464 return Err(self.type_error(format!(
7465 "proxy 'defineProperty' added '{key}' to a non-extensible target"
7466 )));
7467 }
7468 Ok(Some(true))
7469 }
7470
7471 /// `[[GetPrototypeOf]]` on a proxy.
7472 fn proxy_get_prototype_of(
7473 &mut self,
7474 object: &Gc<JsObject>,
7475 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7476 let Some((target, handler)) = self.proxy_parts(object)? else {
7477 return Ok(None);
7478 };
7479 let Some(result) = self.proxy_trap(
7480 &handler,
7481 "getPrototypeOf",
7482 vec![Value::Object(target.clone())],
7483 )?
7484 else {
7485 // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7486 // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7487 // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7488 // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7489 // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7490 return Ok(Some(self.object_prototype_of(&target)?));
7491 };
7492 let proto = match &result {
7493 Value::Null => None,
7494 Value::Object(proto) => Some(proto.clone()),
7495 _ => {
7496 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7497 }
7498 };
7499 if !self.object_is_extensible(&target)? {
7500 let actual = self.object_prototype_of(&target)?;
7501 if !same_proto(proto.as_ref(), actual.as_ref()) {
7502 return Err(self.type_error(
7503 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7504 ));
7505 }
7506 }
7507 Ok(Some(proto))
7508 }
7509
7510 /// `[[SetPrototypeOf]]` on a proxy.
7511 fn proxy_set_prototype_of(
7512 &mut self,
7513 object: &Gc<JsObject>,
7514 proto: Option<Gc<JsObject>>,
7515 ) -> JsResult<Option<bool>> {
7516 let Some((target, handler)) = self.proxy_parts(object)? else {
7517 return Ok(None);
7518 };
7519 let proto_value = match &proto {
7520 Some(proto) => Value::Object(proto.clone()),
7521 None => Value::Null,
7522 };
7523 let Some(result) = self.proxy_trap(
7524 &handler,
7525 "setPrototypeOf",
7526 vec![Value::Object(target.clone()), proto_value],
7527 )?
7528 else {
7529 // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7530 // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7531 // its stored prototype overwritten behind its back.
7532 return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7533 };
7534 if result.to_boolean()
7535 && !self.object_is_extensible(&target)?
7536 && !same_proto(
7537 Some(&proto).and_then(|p| p.clone()).as_ref(),
7538 self.object_prototype_of(&target)?.as_ref(),
7539 )
7540 {
7541 return Err(self.type_error(
7542 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7543 ));
7544 }
7545 Ok(Some(result.to_boolean()))
7546 }
7547
7548 /// `[[IsExtensible]]` on a proxy.
7549 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7550 let Some((target, handler)) = self.proxy_parts(object)? else {
7551 return Ok(None);
7552 };
7553 let Some(result) = self.proxy_trap(
7554 &handler,
7555 "isExtensible",
7556 vec![Value::Object(target.clone())],
7557 )?
7558 else {
7559 return Ok(Some(self.object_is_extensible(&target)?));
7560 };
7561 // The answer is not the proxy's to invent: it must agree with the target, or a
7562 // script could learn `false` while the target keeps accepting new properties.
7563 if result.to_boolean() != self.object_is_extensible(&target)? {
7564 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7565 }
7566 Ok(Some(result.to_boolean()))
7567 }
7568
7569 /// `[[PreventExtensions]]` on a proxy.
7570 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7571 let Some((target, handler)) = self.proxy_parts(object)? else {
7572 return Ok(None);
7573 };
7574 let Some(result) = self.proxy_trap(
7575 &handler,
7576 "preventExtensions",
7577 vec![Value::Object(target.clone())],
7578 )?
7579 else {
7580 // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7581 // its answer can be `false`.
7582 return Ok(Some(self.object_prevent_extensions(&target)?));
7583 };
7584 if result.to_boolean() && self.object_is_extensible(&target)? {
7585 return Err(self.type_error(
7586 "proxy 'preventExtensions' reported success but the target is still extensible",
7587 ));
7588 }
7589 Ok(Some(result.to_boolean()))
7590 }
7591
7592 /// `[[Call]]` on a proxy, through the `apply` trap.
7593 fn proxy_apply(
7594 &mut self,
7595 object: &Gc<JsObject>,
7596 this: Value,
7597 args: Vec<Value>,
7598 ) -> JsResult<Option<Value>> {
7599 let Some((target, handler)) = self.proxy_parts(object)? else {
7600 return Ok(None);
7601 };
7602 // The trap gets the arguments as one array, which is the shape the spec passes
7603 // and the shape `apply` traps are written against (`args[0]` is the first one).
7604 let arguments = self.new_array(args.clone());
7605 let this_for_trap = this.clone();
7606 let Some(result) = self.proxy_trap(
7607 &handler,
7608 "apply",
7609 vec![
7610 Value::Object(target.clone()),
7611 this_for_trap,
7612 Value::Object(arguments),
7613 ],
7614 )?
7615 else {
7616 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7617 };
7618 Ok(Some(result))
7619 }
7620
7621 /// `[[Construct]]` on a proxy, through the `construct` trap.
7622 fn proxy_construct(
7623 &mut self,
7624 object: &Gc<JsObject>,
7625 args: Vec<Value>,
7626 new_target: &Value,
7627 ) -> JsResult<Option<Value>> {
7628 let Some((target, handler)) = self.proxy_parts(object)? else {
7629 return Ok(None);
7630 };
7631 if !target.is_callable() {
7632 return Err(self.type_error("proxy target is not a constructor"));
7633 }
7634 let arguments = self.new_array(args.clone());
7635 let Some(result) = self.proxy_trap(
7636 &handler,
7637 "construct",
7638 vec![
7639 Value::Object(target.clone()),
7640 Value::Object(arguments),
7641 new_target.clone(),
7642 ],
7643 )?
7644 else {
7645 return Ok(Some(self.construct(
7646 Value::Object(target),
7647 new_target.clone(),
7648 args,
7649 )?));
7650 };
7651 if !matches!(result, Value::Object(_)) {
7652 return Err(self.type_error("proxy 'construct' must return an object"));
7653 }
7654 Ok(Some(result))
7655 }
7656
7657 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7658 pub(crate) fn has_own_or_inherited(
7659 &mut self,
7660 object: &Gc<JsObject>,
7661 key: &PropertyKey,
7662 ) -> JsResult<bool> {
7663 // The object itself first: it may be a proxy, and then the answer is its trap's.
7664 if let Some(answer) = self.proxy_has(object, key)? {
7665 return Ok(answer);
7666 }
7667 // An integer-indexed exotic object answers a canonical numeric index from
7668 // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7669 // prototype chain. That is observable twice: a view the buffer has been resized
7670 // away from has no indices, so `2 in view` is `false` even when
7671 // `Object.getPrototypeOf(view)[2]` exists (what
7672 // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7673 // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7674 // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7675 // goes through here, which is why the same rule is repeated in `has_property_key`
7676 // rather than living only there.
7677 if object.typed_array_parts().is_some()
7678 && let Some(numeric) = canonical_numeric_index(key)
7679 {
7680 return Ok(typed_array_index_is_valid(object, numeric));
7681 }
7682 // A host class answers `in` for its own keys, which may live nowhere in a property
7683 // table — `"x" in point` is true because the class says so, not because a property
7684 // exists.
7685 if let Some(exotic) = object.exotic()
7686 && let Some(answer) = exotic.has_property(self, object, key)?
7687 {
7688 return Ok(answer);
7689 }
7690 // `has_own` rather than `own_property_key`: an array's elements and its derived
7691 // `length` are invisible to the property table, and `Array.prototype` is an array.
7692 // A host class's `get_own_property` counts too, because the reference's
7693 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7694 // lives — a class with only `get_own_property` answers `in` through it.
7695 if self.exotic_has_own(object, key)? {
7696 return Ok(true);
7697 }
7698 // A hole is *not* the end of the search: the chain may still have the key, which
7699 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7700 for ancestor in object.chain() {
7701 // A proxy further up the chain answers for itself.
7702 if let Some(answer) = self.proxy_has(&ancestor, key)? {
7703 return Ok(answer);
7704 }
7705 // Same for a host class: a prototype may be one, and `in` reaches it.
7706 if let Some(exotic) = ancestor.exotic()
7707 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7708 {
7709 return Ok(answer);
7710 }
7711 if self.exotic_has_own(&ancestor, key)? {
7712 return Ok(true);
7713 }
7714 }
7715 Ok(false)
7716 }
7717
7718 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7719 /// trap included.
7720 ///
7721 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7722 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7723 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7724 if let Some(exotic) = object.exotic()
7725 && let Some(answer) = exotic.get_own_property(self, object, key)?
7726 {
7727 return Ok(answer.is_some());
7728 }
7729 Ok(has_own(object, key))
7730 }
7731
7732 /// `CreateListFromArrayLike`, optionally restricted to property keys.
7733 ///
7734 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7735 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7736 /// `TypeError` instead of a property named `"1.5"`.
7737 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7738 let object = self.object_from(value)?;
7739 let length = self
7740 .get_property(&object, "length")?
7741 .map(|value| value.to_number())
7742 .unwrap_or(0.0);
7743 if !length.is_finite() || length < 0.0 {
7744 return Err(self.type_error("invalid array-like length"));
7745 }
7746 let length = length as usize;
7747 let mut items = Vec::with_capacity(length.min(1024));
7748 for index in 0..length {
7749 let item = self
7750 .get_property(&object, &index.to_string())?
7751 .unwrap_or(Value::Undefined);
7752 if keys_only && matches!(&item, Value::Symbol(_)) {
7753 items.push(item);
7754 continue;
7755 }
7756 if keys_only && !matches!(&item, Value::String(_)) {
7757 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7758 }
7759 items.push(item);
7760 }
7761 Ok(items)
7762 }
7763
7764 /// A `Property` from the descriptor object a trap returned.
7765 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7766 let object = self.object_from(value)?;
7767 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7768 interp.get_property(&object, name)
7769 };
7770 let getter = field(self, "get")?;
7771 let setter = field(self, "set")?;
7772 let accessor = getter.is_some() || setter.is_some();
7773 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7774 Ok(interp
7775 .get_property(&object, name)?
7776 .is_some_and(|value| value.to_boolean()))
7777 };
7778 let enumerable = boolean(self, "enumerable")?;
7779 let configurable = boolean(self, "configurable")?;
7780 if accessor {
7781 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7782 return Err(
7783 self.type_error("a descriptor cannot be both a data property and an accessor")
7784 );
7785 }
7786 Ok(Property {
7787 getter: getter.or(Some(Value::Undefined)),
7788 setter: setter.or(Some(Value::Undefined)),
7789 enumerable,
7790 configurable,
7791 writable: false,
7792 value: None,
7793 descriptor_fields: None,
7794 })
7795 } else {
7796 Ok(Property {
7797 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7798 writable: boolean(self, "writable")?,
7799 enumerable,
7800 configurable,
7801 getter: None,
7802 setter: None,
7803 descriptor_fields: None,
7804 })
7805 }
7806 }
7807
7808 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7809 fn descriptor_from_property(&mut self, property: &Property) -> Value {
7810 let object = self.new_object(None);
7811 // A partial descriptor names only some fields, and the trap must see exactly those:
7812 // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7813 // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7814 // case, where every field is present.
7815 let fields = property.descriptor_fields;
7816 let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7817 fields.is_none_or(|fields| field(&fields))
7818 };
7819 if property.is_accessor() {
7820 let getter = property.getter.clone().unwrap_or(Value::Undefined);
7821 let setter = property.setter.clone().unwrap_or(Value::Undefined);
7822 object.define_data("get", getter);
7823 object.define_data("set", setter);
7824 } else {
7825 if names(|fields| fields.value) {
7826 let value = property.value.clone().unwrap_or(Value::Undefined);
7827 object.define_data("value", value);
7828 }
7829 if names(|fields| fields.writable) {
7830 object.define_data("writable", Value::Bool(property.writable));
7831 }
7832 }
7833 if names(|fields| fields.enumerable) {
7834 object.define_data("enumerable", Value::Bool(property.enumerable));
7835 }
7836 if names(|fields| fields.configurable) {
7837 object.define_data("configurable", Value::Bool(property.configurable));
7838 }
7839 Value::Object(object)
7840 }
7841
7842 // -- calling ------------------------------------------------------------
7843
7844 /// Call `callee` with `this` and `args`.
7845 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
7846 let Value::Object(function) = &callee else {
7847 // `typeof x === "function"` is not enough to make `x()` legal: only a
7848 // callable object is. `null` and `undefined` need no special wording
7849 // here — their `ToString` already reads the way the reference's does.
7850 let what = format!("{} is not a function", callee.to_js_string());
7851 return Err(Signal::Throw(self.make_error("TypeError", &what)));
7852 };
7853 // A proxy of a function is called through its `apply` trap. It has no
7854 // `ObjectKind::Function` of its own, so this has to come before the dispatch
7855 // below, and a proxy of a non-function has nothing to forward to.
7856 if function.proxy_state().is_some() {
7857 return match self.proxy_apply(function, this, args)? {
7858 Some(result) => Ok(result),
7859 None => Err(Signal::Throw(
7860 self.make_error("TypeError", "proxy target is not callable"),
7861 )),
7862 };
7863 }
7864 let callable = function.with(|data| match &data.kind {
7865 ObjectKind::Function(callable) => match callable {
7866 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
7867 // The `Rc` is cloned out so the borrow of this object's data is released
7868 // before the closure runs: the closure may touch the same object.
7869 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
7870 Callable::Bound {
7871 target,
7872 this,
7873 args: leading,
7874 } => Some(NativeCall::Bound {
7875 target: target.clone(),
7876 this: this.clone(),
7877 leading: leading.clone(),
7878 }),
7879 Callable::Bytecode { code, env } => {
7880 Some(NativeCall::Bytecode(code.clone(), env.clone()))
7881 }
7882 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
7883 Callable::PromiseResolve(promise) => {
7884 Some(NativeCall::PromiseResolve(promise.clone()))
7885 }
7886 Callable::PromiseReject(promise) => {
7887 Some(NativeCall::PromiseReject(promise.clone()))
7888 }
7889 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
7890 state: state.clone(),
7891 }),
7892 Callable::ThenShim {
7893 handler,
7894 resolve,
7895 reject,
7896 fulfilled,
7897 } => Some(NativeCall::ThenShim {
7898 handler: handler.clone(),
7899 resolve: resolve.clone(),
7900 reject: reject.clone(),
7901 fulfilled: *fulfilled,
7902 }),
7903 Callable::AwaitResume {
7904 coroutine,
7905 promise,
7906 kind,
7907 } => Some(NativeCall::AwaitResume {
7908 coroutine: coroutine.clone(),
7909 promise: promise.clone(),
7910 kind: *kind,
7911 }),
7912 Callable::CombinatorSettle {
7913 state,
7914 index,
7915 fulfilled,
7916 } => Some(NativeCall::CombinatorSettle {
7917 state: state.clone(),
7918 index: *index,
7919 fulfilled: *fulfilled,
7920 }),
7921 Callable::FinallyShim {
7922 callback,
7923 fulfilled,
7924 constructor,
7925 } => Some(NativeCall::FinallyShim {
7926 callback: callback.clone(),
7927 fulfilled: *fulfilled,
7928 constructor: constructor.clone(),
7929 }),
7930 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
7931 Callable::CompletedReturn {
7932 generator,
7933 promise,
7934 rejected,
7935 } => Some(NativeCall::CompletedReturn {
7936 generator: generator.clone(),
7937 promise: promise.clone(),
7938 rejected: *rejected,
7939 }),
7940 Callable::YieldResult {
7941 generator,
7942 promise,
7943 done,
7944 } => Some(NativeCall::YieldResult {
7945 generator: generator.clone(),
7946 promise: promise.clone(),
7947 done: *done,
7948 }),
7949 Callable::DisposeStep {
7950 remaining,
7951 promise,
7952 error,
7953 rejected,
7954 awaited,
7955 needs_await,
7956 } => Some(NativeCall::DisposeStep {
7957 remaining: remaining.clone(),
7958 promise: promise.clone(),
7959 error: error.clone(),
7960 rejected: *rejected,
7961 awaited: *awaited,
7962 needs_await: *needs_await,
7963 }),
7964 Callable::GeneratorResume {
7965 generator,
7966 promise,
7967 kind,
7968 } => Some(NativeCall::GeneratorResume {
7969 generator: generator.clone(),
7970 promise: promise.clone(),
7971 kind: *kind,
7972 }),
7973 Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
7974 Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
7975 Callable::SettlePromise {
7976 promise,
7977 value,
7978 rejected,
7979 } => Some(NativeCall::SettlePromise {
7980 promise: promise.clone(),
7981 value: value.clone(),
7982 rejected: *rejected,
7983 }),
7984 },
7985 _ => None,
7986 });
7987 match callable {
7988 Some(NativeCall::Host(func)) => {
7989 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
7990 // function by name rather than stopping at the caller.
7991 let frame_less = function
7992 .own_property("_frame_less")
7993 .and_then(|property| property.value)
7994 .is_some_and(|value| value.to_boolean());
7995 let outer = if frame_less {
7996 None
7997 } else {
7998 self.native_frames
7999 .push((function.clone(), self.frames.len()));
8000 Some(self.current_native.replace(function.clone()))
8001 };
8002 // Same frame bookkeeping as a `Native`, plus `new.target`: a host
8003 // constructor reads it through `current_new_target` because it is handed
8004 // `undefined` for `this`. Taking the parked value here is what stops a
8005 // *plain* call made from inside a constructor body from seeing the
8006 // enclosing `new.target`.
8007 let parked = self.pending_new_target.take();
8008 let result = {
8009 let outer_new_target = std::mem::replace(
8010 &mut self.active_new_target,
8011 parked.unwrap_or(Value::Undefined),
8012 );
8013 let result = {
8014 let mut body = func.borrow_mut();
8015 body(self, this, &args)
8016 };
8017 self.active_new_target = outer_new_target;
8018 result
8019 };
8020 if !frame_less {
8021 self.native_frames.pop();
8022 self.current_native = outer.flatten();
8023 }
8024 result
8025 }
8026 Some(NativeCall::Native(func)) => {
8027 // A function marked `_frame_less` is one the reference implements
8028 // without a call frame — `eval` is the only one so far.
8029 let frame_less = function
8030 .own_property("_frame_less")
8031 .and_then(|property| property.value)
8032 .is_some_and(|value| value.to_boolean());
8033 let outer = if frame_less {
8034 None
8035 } else {
8036 self.native_frames
8037 .push((function.clone(), self.frames.len()));
8038 Some(self.current_native.replace(function.clone()))
8039 };
8040 let parked = self.pending_new_target.take();
8041 let outer_new_target = std::mem::replace(
8042 &mut self.active_new_target,
8043 parked.unwrap_or(Value::Undefined),
8044 );
8045 let result = func(self, this, &args);
8046 self.active_new_target = outer_new_target;
8047 if !frame_less {
8048 self.native_frames.pop();
8049 self.current_native = outer.flatten();
8050 }
8051 result
8052 }
8053 Some(NativeCall::Revoker(slots)) => {
8054 // Idempotent: revoking twice answers `undefined` again rather than
8055 // complaining, which is what the spec says and what a `finally` block
8056 // relies on.
8057 let mut state = slots.borrow_mut();
8058 state.target = None;
8059 state.handler = None;
8060 Ok(Value::Undefined)
8061 }
8062 Some(NativeCall::PromiseResolve(promise)) => {
8063 // §27.2.1.3.2 step 4: `[[AlreadyResolved]]` is checked **before** anything
8064 // else, so a resolve after a reject does nothing *and* a resolve after a
8065 // resolve-with-thenable does nothing — the promise is still `Pending` then,
8066 // because the adoption is a queued job.
8067 let value = args.first().cloned().unwrap_or(Value::Undefined);
8068 if !self.claim_resolution(&promise) {
8069 return Ok(Value::Undefined);
8070 }
8071 // §27.2.1.3.2 steps 7–8: a self-resolution is **rejected, not thrown** —
8072 // the resolve function performs `RejectPromise` and returns `undefined`.
8073 // (`ResolvePromise` itself throws as well, so the engine's own callers see
8074 // it; only this wrapper swallows it.)
8075 let _ = self.resolve_promise_with(&promise, value);
8076 Ok(Value::Undefined)
8077 }
8078 Some(NativeCall::PromiseReject(promise)) => {
8079 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8080 // §27.2.1.3.1 step 3: same one-shot record as `resolve`.
8081 if !self.claim_resolution(&promise) {
8082 return Ok(Value::Undefined);
8083 }
8084 self.reject_promise(&promise, reason);
8085 Ok(Value::Undefined)
8086 }
8087 Some(NativeCall::ThenShim {
8088 handler,
8089 resolve,
8090 reject,
8091 fulfilled,
8092 }) => {
8093 // `PerformPromiseThen` with a capability: run the handler, then settle
8094 // through the capability's own pair. A throw from the handler is the
8095 // rejection, and a throw from the capability's `resolve` is not caught —
8096 // exactly the spec's `?`.
8097 let value = args.first().cloned().unwrap_or(Value::Undefined);
8098 match handler {
8099 Some(handler) => {
8100 match self.call_value(handler, Value::Undefined, vec![value]) {
8101 Ok(result) => {
8102 self.call_value(resolve, Value::Undefined, vec![result])?;
8103 }
8104 Err(Signal::Throw(reason)) => {
8105 self.call_value(reject, Value::Undefined, vec![reason])?;
8106 }
8107 Err(signal) => return Err(signal),
8108 }
8109 }
8110 None => {
8111 let handler = if fulfilled { resolve } else { reject };
8112 self.call_value(handler, Value::Undefined, vec![value])?;
8113 }
8114 }
8115 Ok(Value::Undefined)
8116 }
8117 Some(NativeCall::CapabilityExecutor { state }) => {
8118 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
8119 // slot holds a value yet. The test is on the *values*, not on a call count —
8120 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
8121 // called-twice`'s first case does exactly that), while a second call after a
8122 // real pair is the `TypeError`.
8123 let defined = |name: &str| {
8124 state
8125 .own_property(name)
8126 .and_then(|property| property.value)
8127 .is_some_and(|value| !matches!(value, Value::Undefined))
8128 };
8129 if defined("resolve") || defined("reject") {
8130 return Err(self.type_error("promise capability executor called twice"));
8131 }
8132 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
8133 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
8134 state.define_data("resolve", resolve);
8135 state.define_data("reject", reject);
8136 Ok(Value::Undefined)
8137 }
8138 Some(NativeCall::CombinatorSettle {
8139 state,
8140 index,
8141 fulfilled,
8142 }) => {
8143 let value = args.first().cloned().unwrap_or(Value::Undefined);
8144 self.settle_combinator(&state, index, fulfilled, value)?;
8145 Ok(Value::Undefined)
8146 }
8147 Some(NativeCall::AwaitResume {
8148 coroutine,
8149 promise,
8150 kind,
8151 }) => {
8152 // Resume *inline*, in the reaction that delivered the value. Deferring it
8153 // by another job inserts a tick between every `await` and its
8154 // continuation, which reorders `await` against unrelated `then` chains —
8155 // `f().then(g)` then runs before `f`'s own next statement.
8156 self.drive_async(
8157 &coroutine,
8158 &promise,
8159 kind,
8160 args.first().cloned().unwrap_or(Value::Undefined),
8161 )
8162 .map(|()| Value::Undefined)
8163 }
8164 Some(NativeCall::ReturnValue(value)) => Ok(value),
8165 Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
8166 Some(NativeCall::FinallyShim {
8167 callback,
8168 fulfilled,
8169 constructor,
8170 }) => {
8171 // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
8172 // own value is discarded; what the caller sees is the *original* outcome,
8173 // delayed until `PromiseResolve(C, result)` has settled.
8174 //
8175 // Two details are observable and both have a test:
8176 //
8177 // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
8178 // `PerformPromiseThen`. A callback that returns a thenable with its own
8179 // `then` must have that `then` called
8180 // (`resolved-observable-then-calls` counts it);
8181 // * only the **fulfil** handler is supplied. A returned promise that
8182 // *rejects* rejects the whole `finally`, rather than having its failure
8183 // swallowed and the original value passed through.
8184 let original = args.first().cloned().unwrap_or(Value::Undefined);
8185 let result = match &callback {
8186 Some(callback) => {
8187 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
8188 }
8189 None => Value::Undefined,
8190 };
8191 // `PromiseResolve(C, result)`: a `result` that is already a promise of this
8192 // constructor is reused rather than rewrapped, which is what keeps
8193 // `mp1.finally(() => mp2)` from gaining a layer.
8194 let resolved = self.promise_resolve_for(&constructor, result)?;
8195 let thunk = if fulfilled {
8196 Callable::ReturnValue(original)
8197 } else {
8198 Callable::ThrowValue(original)
8199 };
8200 // `length: 0` and `name: ""`, and **not** a constructor — the three things
8201 // `resolved-observable-then-calls-argument` reads off the thunk while it has
8202 // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
8203 // function with no `length` at all.
8204 let thunk = self.builtin_function("", 0, thunk);
8205 let then = self.read_field(&resolved, "then")?;
8206 if !matches!(&then, Value::Object(object) if object.is_callable()) {
8207 return Err(self.type_error("then is not a function"));
8208 }
8209 self.call_value(then, resolved, vec![Value::Object(thunk)])
8210 }
8211 Some(NativeCall::DisposeStep {
8212 remaining,
8213 promise,
8214 error,
8215 rejected,
8216 awaited,
8217 needs_await,
8218 }) => {
8219 let error = if rejected {
8220 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8221 self.merge_dispose_error(reason, error)
8222 } else {
8223 error
8224 };
8225 self.dispose_step(&remaining, &promise, error, awaited, needs_await)?;
8226 Ok(Value::Undefined)
8227 }
8228 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
8229 Some(NativeCall::CompletedReturn {
8230 generator,
8231 promise,
8232 rejected,
8233 }) => {
8234 let value = args.first().cloned().unwrap_or(Value::Undefined);
8235 let outcome = if rejected {
8236 AsyncOutcome::Error(value)
8237 } else {
8238 AsyncOutcome::Value(self.iterator_result(value, true)?)
8239 };
8240 self.settle_async_request(&generator, &promise, outcome)?;
8241 Ok(Value::Undefined)
8242 }
8243 Some(NativeCall::YieldResult {
8244 generator,
8245 promise,
8246 done,
8247 }) => {
8248 let value = args.first().cloned().unwrap_or(Value::Undefined);
8249 let result = self.iterator_result(value, done)?;
8250 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
8251 Ok(Value::Undefined)
8252 }
8253 Some(NativeCall::GeneratorResume {
8254 generator,
8255 promise,
8256 kind,
8257 }) => {
8258 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
8259 // tick and reorders the generator against other chains.
8260 self.step_async_generator(
8261 &generator,
8262 &promise,
8263 kind,
8264 args.first().cloned().unwrap_or(Value::Undefined),
8265 )
8266 .map(|()| Value::Undefined)
8267 }
8268 Some(NativeCall::SettlePromise {
8269 promise,
8270 value,
8271 rejected,
8272 }) => {
8273 if rejected {
8274 self.reject_promise(&promise, value);
8275 } else {
8276 self.fulfill_promise(&promise, value);
8277 }
8278 Ok(Value::Undefined)
8279 }
8280 Some(NativeCall::Bound {
8281 target,
8282 this: bound_this,
8283 leading,
8284 }) => {
8285 let mut all = leading;
8286 all.extend(args);
8287 self.call_value(target, bound_this, all)
8288 }
8289 Some(NativeCall::Bytecode(code, env)) => {
8290 if code.code.kind.is_generator() {
8291 return self.new_generator(callee, this, args);
8292 }
8293 if code.code.kind.is_async() {
8294 // Same coroutine machinery as a generator; the difference is only in
8295 // what the completion does — see `new_async_function`.
8296 return self.new_async_function(callee, this, args);
8297 }
8298 self.execute(code, env, this, args, callee)
8299 }
8300 None => Err(Signal::Throw(
8301 self.make_error("TypeError", "not a function"),
8302 )),
8303 }
8304 }
8305
8306 /// Give a freshly built function its own `prototype` object.
8307 ///
8308 /// Every function that can be used with `new` carries one, and its
8309 /// `constructor` points back at the function — a reference cycle, which is
8310 /// exactly what the collector's cycle pass exists to reclaim.
8311 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
8312 self.install_function_prototype_with(function, None);
8313 }
8314
8315 /// [`Interp::install_function_prototype`] with an explicit parent for the new
8316 /// `prototype` object.
8317 ///
8318 /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
8319 /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
8320 /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
8321 /// `None` means `%Object.prototype%`.
8322 fn install_function_prototype_with(
8323 &mut self,
8324 function: &Gc<JsObject>,
8325 parent: Option<Gc<JsObject>>,
8326 ) {
8327 let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
8328 let prototype = self.new_object(Some(parent));
8329 let constructor = Value::Object(function.clone());
8330 prototype.define(
8331 "constructor",
8332 Property::with_attributes(constructor, true, false),
8333 );
8334 let value = Value::Object(prototype);
8335 function.define("prototype", Property::prototype_of(value, true));
8336 }
8337
8338 /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
8339 /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
8340 /// [`Interp::install_function_prototype`] — **no `constructor` property**.
8341 ///
8342 /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
8343 /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
8344 /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
8345 /// is `[]` there.
8346 fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
8347 let prototype = self.new_object(Some(parent));
8348 let value = Value::Object(prototype);
8349 function.define("prototype", Property::prototype_of(value, true));
8350 }
8351
8352 /// The `[[Prototype]]` a newly created generator object gets:
8353 /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
8354 ///
8355 /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
8356 /// function's `prototype` is writable, so a script can replace it with anything, and
8357 /// only an *object* is consulted.
8358 fn generator_instance_proto(
8359 &mut self,
8360 function: &Gc<JsObject>,
8361 default: Gc<JsObject>,
8362 ) -> JsResult<Gc<JsObject>> {
8363 match self.get_property(function, "prototype")? {
8364 Some(Value::Object(prototype)) => Ok(prototype),
8365 _ => Ok(default),
8366 }
8367 }
8368
8369 /// A getter or setter that reads or writes the reference cell behind a mapped
8370 /// `arguments` index.
8371 ///
8372 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
8373 /// count — which is what the collector treats as "a reference from outside the
8374 /// heap". The closure therefore keeps the cell alive for exactly as long as the
8375 /// accessor is reachable, which is the same lifetime the arguments object has.
8376 ///
8377 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8378 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8379 /// parameter value and the arguments object reaches the closure, never the other
8380 /// way round. Nothing the collector has to see is hidden.
8381 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8382 let name = if is_setter { "set" } else { "get" };
8383 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8384 if is_setter {
8385 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8386 Ok(Value::Undefined)
8387 } else {
8388 Ok(cell.get())
8389 }
8390 };
8391 self.new_host_function(name, 1, Box::new(func))
8392 }
8393
8394 /// The object `special_object` builds.
8395 ///
8396 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8397 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8398 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8399 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8400 /// write through `arguments` does not reach the parameter.
8401 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8402 match magic {
8403 0 | 1 => {
8404 let args = self.frame().passed().to_vec();
8405 let proto = self.realm.object_proto.clone();
8406 let object = self.new_object(Some(proto));
8407 // The marker `Object.prototype.toString` needs: an arguments object is an
8408 // ordinary object apart from reporting `[object Arguments]`, and that has
8409 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8410 // show up ahead of them in a key listing anyway — it is non-enumerable.
8411 self.internal_set(&object, "_class", self.string("Arguments"));
8412 // `length` is writable and configurable but neither enumerable nor a
8413 // plain data property: `Object.keys(arguments)` lists the indices only,
8414 // which is how `{...arguments}` copies them without the length.
8415 object.define(
8416 "length",
8417 Property::with_attributes(Value::Int(args.len() as i32), true, false),
8418 );
8419 // `magic == 1` is sloppy mode, where each index is *mapped* to the
8420 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8421 // change `a`, and assigning `a` has to change `arguments[0]`.
8422 //
8423 // The shared storage is the parameter's reference cell. The compiler
8424 // gives every parameter of such a function one (see
8425 // `provide_body_arguments`), and the cell outlives the frame, so this
8426 // keeps working after the arguments object escapes.
8427 //
8428 // The index becomes an accessor rather than a data property. A mapped
8429 // index reports as a plain writable/enumerable data property through
8430 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8431 // the getter/setter pair is only the plumbing underneath.
8432 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8433 let frame = self.frame();
8434 frame
8435 .code
8436 .arg_cell
8437 .iter()
8438 .map(|cell| {
8439 (*cell >= 0)
8440 .then(|| frame.cells.get(*cell as usize).cloned())
8441 .flatten()
8442 })
8443 .collect()
8444 } else {
8445 Vec::new()
8446 };
8447 // Tell the object which indices are mapped, so
8448 // `Object.getOwnPropertyDescriptor` can report them as the data
8449 // properties the spec describes instead of the accessors that
8450 // implement the aliasing.
8451 if magic == 1 {
8452 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8453 for cell in &mapped_cells {
8454 table.push(cell.clone());
8455 }
8456 object.set_mapped_arguments(table);
8457 }
8458 for (index, value) in args.into_iter().enumerate() {
8459 match mapped_cells.get(index).cloned().flatten() {
8460 Some(cell) => {
8461 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8462 let setter = self.new_mapped_arguments_accessor(cell, true);
8463 object.define(
8464 &index.to_string(),
8465 Property::accessor_with(
8466 Some(Value::Object(getter)),
8467 Some(Value::Object(setter)),
8468 true,
8469 ),
8470 );
8471 }
8472 None => object.define_data(&index.to_string(), value),
8473 }
8474 }
8475 // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8476 // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8477 // non-enumerable and non-configurable. It is not a nicety — it is the only
8478 // documented way to reach `%ThrowTypeError%`:
8479 //
8480 // Object.getOwnPropertyDescriptor(function(){"use strict";
8481 // return arguments;}(), "callee").get
8482 //
8483 // and the whole `ThrowTypeError/` directory is written against that
8484 // expression. Without it 13 cases failed with `cannot read property 'get'
8485 // of undefined`, which reads like a test harness bug rather than a missing
8486 // accessor.
8487 //
8488 // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8489 // writable data property holding the function being called, and
8490 // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8491 // `hasOwnProperty("callee")` hold there.
8492 if magic == 1 {
8493 let callee = self.frame().callee.clone();
8494 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8495 object.define("callee", Property::with_attributes(callee, true, false));
8496 } else if let Some(thrower) = self.realm.throw_type_error.clone()
8497 && object.own_property("callee").is_none()
8498 {
8499 object.define(
8500 "callee",
8501 Property {
8502 getter: Some(Value::Object(thrower.clone())),
8503 setter: Some(Value::Object(thrower)),
8504 enumerable: false,
8505 configurable: false,
8506 ..Property::default()
8507 },
8508 );
8509 }
8510 // An arguments object is iterable: `[...arguments]` and
8511 // `for (const a of arguments)` both work, through the *array* iterator
8512 // because the object is array-like. Without this the whole spread form
8513 // reported "not iterable".
8514 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8515 let values = self
8516 .realm
8517 .array_proto
8518 .own_property("values")
8519 .and_then(|property| property.value);
8520 if let Some(values) = values {
8521 object.define_key(
8522 &iterator_key,
8523 Property::with_attributes(values, true, false),
8524 );
8525 }
8526 Ok(Value::Object(object))
8527 }
8528 // `this.active_func`: the constructor `super()` resolves against.
8529 //
8530 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8531 // own, so it inherits this from the function it was written in along with `this`
8532 // — and that is a lexical relationship, not a stack one: an arrow that escaped
8533 // the constructor and is called back later (`iter.return = () => super()`) has
8534 // the constructor nowhere on the stack. The compiler therefore reads it out of
8535 // a closure variable of the enclosing function, exactly as the reference does
8536 // with its `this_active_func` local.
8537 2 => Ok(self
8538 .current_callee()
8539 .map_or(Value::Undefined, Value::Object)),
8540 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8541 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8542 // its own either, so the lookup walks out to the nearest non-arrow frame for
8543 // the same reason as `this.active_func` above — without that, `super()` inside
8544 // an arrow passed `undefined` as the new target and the parent constructor was
8545 // then rejected for being invoked without `new`.
8546 3 => Ok(self
8547 .eval_new_target
8548 .clone()
8549 .unwrap_or_else(|| self.frame().new_target.clone())),
8550 // `[[HomeObject]]` of the function being run: what `super` is relative to.
8551 // An arrow has none of its own, so the lookup walks out to the enclosing
8552 // method — which is why `super` works inside an arrow inside a method.
8553 4 => Ok(self
8554 .frames
8555 .iter()
8556 .rev()
8557 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8558 .map_or(Value::Undefined, Value::Object)),
8559 // `import.meta`: the innermost module body's meta object. Outside a module
8560 // the compiler never emits this, so an empty fallback is unreachable rather
8561 // than permissive.
8562 6 => {
8563 let name = self.module_stack.last().cloned();
8564 let meta = name
8565 .and_then(|name| self.modules.get(&name).cloned())
8566 .and_then(|module| module.with(|r| r.import_meta.clone()));
8567 Ok(meta.map_or(Value::Undefined, Value::Object))
8568 }
8569 other => Err(Signal::Throw(self.make_error(
8570 "InternalError",
8571 &format!("special_object {other} is not implemented yet"),
8572 ))),
8573 }
8574 }
8575
8576 /// `[[HomeObject]]` of the innermost function that has one, if any.
8577 ///
8578 /// An arrow has none, so the search walks out to the enclosing method — the same
8579 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8580 /// inside a method.
8581 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8582 self.frames
8583 .iter()
8584 .rev()
8585 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8586 }
8587
8588 /// The dispose method a `using` declaration should snapshot, or an error.
8589 ///
8590 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8591 /// is what makes a resource that only knows the synchronous protocol usable in both
8592 /// forms.
8593 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8594 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8595 if value.is_nullish() {
8596 return Ok(Value::Undefined);
8597 }
8598 let Some(object) = value.as_object() else {
8599 return Err(self.type_error("not an object"));
8600 };
8601 let mut method = if await_form {
8602 let found = self.get_property_key(
8603 object,
8604 &self.realm.well_known_key(WellKnown::AsyncDisposable),
8605 )?;
8606 match found {
8607 Some(found) if !found.is_nullish() => Some(found),
8608 _ => self
8609 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8610 }
8611 } else {
8612 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8613 };
8614 let Some(found) = method.take() else {
8615 return Err(self.type_error("value is not disposable"));
8616 };
8617 if found.is_nullish() {
8618 return Err(self.type_error("value is not disposable"));
8619 }
8620 let callable = found.as_object().is_some_and(|object| object.is_callable());
8621 if !callable {
8622 return Err(self.type_error("dispose method is not a function"));
8623 }
8624 Ok(found)
8625 }
8626
8627 /// Call one resource's disposer, folding a failure into `error_state`.
8628 ///
8629 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8630 /// because a captured `using` binding lives in its reference cell and the local slot is
8631 /// stale — a closure over the resource is legal and must not change what is disposed.
8632 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8633 let value = self.get_loc(slot);
8634 let method = self.get_loc(slot + 1);
8635 // A resource that was never initialised — its declaration threw — or that is
8636 // `null`/`undefined` has nothing to dispose.
8637 if value.is_nullish() || matches!(value, Value::Uninitialized) {
8638 return Ok(error_state);
8639 }
8640 if matches!(method, Value::Undefined | Value::Uninitialized) {
8641 return Ok(error_state);
8642 }
8643 match self.call_value(method, value, Vec::new()) {
8644 Ok(_) => Ok(error_state),
8645 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8646 Err(other) => Err(other),
8647 }
8648 }
8649
8650 /// Combine a disposal failure with whatever was already going wrong.
8651 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8652 if matches!(error_state, Value::Uninitialized) {
8653 return new_error;
8654 }
8655 self.new_suppressed_error(new_error, error_state)
8656 }
8657
8658 /// A `SuppressedError` instance built straight from its prototype.
8659 ///
8660 /// Not through the constructor: a script that rewrites
8661 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8662 /// error wrapping.
8663 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8664 let proto = self
8665 .realm
8666 .suppressed_error_proto
8667 .clone()
8668 .unwrap_or_else(|| self.realm.error_proto.clone());
8669 let object = self.new_object(Some(proto));
8670 object.define("error", Property::with_attributes(error, true, true));
8671 object.define(
8672 "suppressed",
8673 Property::with_attributes(suppressed, true, true),
8674 );
8675 object.define(
8676 "message",
8677 Property::with_attributes(self.string("SuppressedError"), true, true),
8678 );
8679 self.internal_set(&object, "_class", self.string("Error"));
8680 self.add_stack(&object);
8681 Value::Object(object)
8682 }
8683
8684 /// Call `callee`, or push its frame and let the main loop run it.
8685 ///
8686 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8687 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8688 /// continues, so `function f(){ return f() }` costs heap and stops at
8689 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8690 /// is entered directly, and natives do not re-enter JavaScript in this
8691 /// milestone.
8692 ///
8693 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8694 /// because the returning frame will.
8695 /// The elements of an array-like value, as a call argument list.
8696 ///
8697 /// `apply` accepts any array-like, not only a real array: the reference reads
8698 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8699 /// `ToIndex(value)`: `ToIntegerOrInfinity` and then the `2^53 - 1` bound.
8700 ///
8701 /// Used by the paths that take a *length* from script data — the typed-array
8702 /// constructor's array-like argument, `Array.from`. `ToIntegerOrInfinity` runs
8703 /// `ToNumber`, so a Symbol is a `TypeError`; a value past `2^53 - 1` is a
8704 /// `RangeError` rather than a silently clamped count.
8705 pub fn to_index(&mut self, value: &Value) -> JsResult<usize> {
8706 let number = self.to_js_number(value)?;
8707 if number.is_nan() {
8708 return Ok(0);
8709 }
8710 let number = number.trunc();
8711 if number < 0.0 || number > 9_007_199_254_740_991.0 {
8712 return Err(self.range_error("invalid length"));
8713 }
8714 Ok(number as usize)
8715 }
8716
8717 /// `CreateListFromArrayLike(value)`: the elements of an array-like, for `apply` and the
8718 /// other callers that take an argument list from script data.
8719 ///
8720 /// The length is `ToLength`, which *clamps* rather than refusing — the typed-array
8721 /// constructor and `Array.from` need `ToIndex` instead (see
8722 /// [`Interp::to_index`]), which is why they do not go through here.
8723 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8724 let Some(object) = value.as_object().cloned() else {
8725 if value.is_nullish() {
8726 // `f.apply(this, null)` passes no arguments at all.
8727 return Ok(Vec::new());
8728 }
8729 return Err(self.type_error("createListFromArrayLike called on non-object"));
8730 };
8731 let length = match self.get_property(&object, "length")? {
8732 Some(length) => length.to_number(),
8733 None => 0.0,
8734 };
8735 if !length.is_finite() || length <= 0.0 {
8736 return Ok(Vec::new());
8737 }
8738 let length = (length as usize).min(1_000_000);
8739 let mut args = Vec::with_capacity(length);
8740 for index in 0..length {
8741 let element = self.get_property(&object, &index.to_string())?;
8742 args.push(element.unwrap_or(Value::Undefined));
8743 }
8744 Ok(args)
8745 }
8746
8747 /// Turn a call to a generator function into a generator object.
8748 ///
8749 /// The frame is built exactly as an ordinary call would build it, then detached and
8750 /// stored in the generator before any body instruction runs — which is what makes
8751 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8752 /// is `initial_yield`, the first instruction of every suspending body.
8753 pub fn new_generator(
8754 &mut self,
8755 function: Value,
8756 this: Value,
8757 args: Vec<Value>,
8758 ) -> JsResult<Value> {
8759 let Some(object) = function.as_object().cloned() else {
8760 return Err(self.type_error("not a generator function"));
8761 };
8762 let Some((code, env)) = bytecode_of(&object) else {
8763 return Err(self.type_error("not a generator function"));
8764 };
8765 let is_async = code.code.kind.is_async();
8766 self.push_frame(code, env, this, args, function)?;
8767 let frame = self.frames.pop().expect("push_frame just pushed it");
8768 // A fresh generator is *suspended at start*: the body has not run, so a
8769 // `return`/`throw` on it finishes without executing anything.
8770 let mut state = GeneratorState {
8771 frame: Some(frame),
8772 phase: GeneratorPhase::SuspendedStart,
8773 parked_on_await: false,
8774 parked_on_yield_star: false,
8775 requests: std::collections::VecDeque::new(),
8776 async_busy: false,
8777 is_async,
8778 };
8779 // Run to the first suspension. For a generator that is `initial_yield`, so no
8780 // body code runs; for a malformed body it would be the first `yield`.
8781 // An `async function*` answers an async generator: same coroutine, but its
8782 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8783 let default_proto = if is_async {
8784 self.realm
8785 .async_generator_proto
8786 .clone()
8787 .unwrap_or_else(|| self.realm.generator_proto.clone())
8788 } else {
8789 self.realm.generator_proto.clone()
8790 };
8791 // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
8792 // `prototype` object when it is one, the intrinsic otherwise. Every generator having
8793 // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
8794 // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
8795 let proto = self.generator_instance_proto(&object, default_proto)?;
8796 let generator = self.new_object(Some(proto));
8797 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8798 Ok(_) => {}
8799 Err(error) => return Err(error),
8800 }
8801 generator.with_mut(|data| {
8802 data.kind = ObjectKind::Generator(Box::new(state));
8803 });
8804 Ok(Value::Object(generator))
8805 }
8806
8807 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8808 ///
8809 /// Returns the `{value, done}` object itself rather than the pair, because a
8810 /// `yield*` suspension already has one — the inner iterator's own result — and the
8811 /// protocol says to hand that straight through rather than nest it.
8812 /// Advance a generator and report *why* it parked.
8813 ///
8814 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
8815 /// "hand this value to the caller" — but an async generator does: an `await` has to
8816 /// settle before it can answer, while a `yield` is the answer.
8817 fn resume_generator_detailed(
8818 &mut self,
8819 generator: &Gc<JsObject>,
8820 kind: ResumeKind,
8821 value: Value,
8822 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8823 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
8824 ObjectKind::Generator(state) => {
8825 let is_async = state.is_async;
8826 Some(std::mem::replace(
8827 state.as_mut(),
8828 GeneratorState {
8829 frame: None,
8830 phase: GeneratorPhase::Executing,
8831 parked_on_await: false,
8832 parked_on_yield_star: false,
8833 requests: std::collections::VecDeque::new(),
8834 // **Busy while the body runs**, so a `next()` called *from inside*
8835 // the body queues instead of being served. §27.6.3.7
8836 // `AsyncGeneratorResumeNext` returns immediately for the state
8837 // "executing", and the request is served once the body suspends;
8838 // with `false` here the re-entrant call found an empty frame and
8839 // rejected (`request-queue-order-state-executing`).
8840 async_busy: is_async,
8841 is_async,
8842 },
8843 ))
8844 }
8845 _ => None,
8846 }) else {
8847 return Err(self.type_error("not a generator"));
8848 };
8849 let result = self.step_generator(&mut state, kind, value);
8850 // Requests queued *while* the body ran live on the placeholder, because the real
8851 // state is out of the object for the duration. They have to be folded back in
8852 // before the placeholder is overwritten, or the promise they carry never settles.
8853 let queued = generator.with_mut(|data| match &mut data.kind {
8854 ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
8855 _ => std::collections::VecDeque::new(),
8856 });
8857 state.requests.extend(queued);
8858 generator.with_mut(|data| {
8859 data.kind = ObjectKind::Generator(Box::new(state));
8860 });
8861 result
8862 }
8863
8864 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8865 ///
8866 /// Returns the `{value, done}` object itself rather than the pair, because a
8867 /// `yield*` suspension already has one — the inner iterator's own result — and the
8868 /// protocol says to hand that straight through rather than nest it.
8869 pub fn resume_generator(
8870 &mut self,
8871 generator: &Gc<JsObject>,
8872 kind: ResumeKind,
8873 value: Value,
8874 ) -> JsResult<Value> {
8875 let (value, done, ready, _reason) =
8876 self.resume_generator_detailed(generator, kind, value)?;
8877 if ready {
8878 return Ok(value);
8879 }
8880 self.iterator_result(value, done)
8881 }
8882
8883 /// `next`/`return`/`throw` on an async generator, which answer a promise.
8884 ///
8885 /// The body is the same coroutine a sync generator runs; what changes is that an
8886 /// `await` inside it has to settle before the method can answer, so the step is
8887 /// driven off the job queue rather than returning inline.
8888 pub fn resume_async_generator(
8889 &mut self,
8890 generator: &Gc<JsObject>,
8891 kind: ResumeKind,
8892 value: Value,
8893 ) -> JsResult<Value> {
8894 let promise = self.new_promise();
8895 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
8896 // that order, and the second value must reach the *second* `yield`.
8897 let idle = generator.with_mut(|data| match &mut data.kind {
8898 ObjectKind::Generator(state) => {
8899 state.requests.push_back(AsyncRequest {
8900 kind,
8901 value,
8902 promise: promise.clone(),
8903 });
8904 !state.async_busy
8905 }
8906 _ => false,
8907 });
8908 if idle {
8909 self.next_async_request(generator)?;
8910 }
8911 Ok(Value::Object(promise))
8912 }
8913
8914 /// Serve the front queued request, if the generator is free to run one.
8915 ///
8916 /// A finished generator answers from the queue without running anything:
8917 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
8918 /// first, and `throw(e)` rejects.
8919 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
8920 enum Front {
8921 Idle,
8922 Run(ResumeKind, Value, Gc<JsObject>),
8923 Finished(ResumeKind, Value, Gc<JsObject>),
8924 }
8925 let front = generator.with_mut(|data| match &mut data.kind {
8926 ObjectKind::Generator(state) => {
8927 let Some(request) = state.requests.front() else {
8928 return Front::Idle;
8929 };
8930 // Busy means a request is still in flight — awaiting inside the body, not
8931 // finished. Serving another now would interleave two requests.
8932 if state.async_busy && state.phase != GeneratorPhase::Completed {
8933 return Front::Idle;
8934 }
8935 let kind = request.kind;
8936 let value = request.value.clone();
8937 let promise = request.promise.clone();
8938 state.async_busy = true;
8939 if state.phase == GeneratorPhase::Completed {
8940 Front::Finished(kind, value, promise)
8941 } else {
8942 Front::Run(kind, value, promise)
8943 }
8944 }
8945 _ => Front::Idle,
8946 });
8947 match front {
8948 Front::Idle => Ok(()),
8949 Front::Run(kind, value, promise) => {
8950 self.step_async_generator(generator, &promise, kind, value)
8951 }
8952 Front::Finished(kind, value, promise) => match kind {
8953 ResumeKind::Throw => {
8954 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
8955 }
8956 ResumeKind::Next | ResumeKind::Start => {
8957 let result = self.iterator_result(Value::Undefined, true)?;
8958 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
8959 }
8960 ResumeKind::Return => {
8961 // `js_async_generator_completed_return`: the value is awaited before it
8962 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
8963 // finished generator answers `1`, not a promise.
8964 let resolved = match self.promise_resolve_intrinsic(value) {
8965 Ok(resolved) => resolved,
8966 Err(Signal::Throw(reason)) => {
8967 return self.settle_async_request(
8968 generator,
8969 &promise,
8970 AsyncOutcome::Error(reason),
8971 );
8972 }
8973 Err(other) => return Err(other),
8974 };
8975 let done = JsObject::function(
8976 self.heap,
8977 Some(self.realm.function_proto.clone()),
8978 Callable::CompletedReturn {
8979 generator: generator.clone(),
8980 promise: promise.clone(),
8981 rejected: false,
8982 },
8983 );
8984 let failed = JsObject::function(
8985 self.heap,
8986 Some(self.realm.function_proto.clone()),
8987 Callable::CompletedReturn {
8988 generator: generator.clone(),
8989 promise: promise.clone(),
8990 rejected: true,
8991 },
8992 );
8993 let Value::Object(resolved) = resolved else {
8994 return self.settle_async_request(
8995 generator,
8996 &promise,
8997 AsyncOutcome::Error(Value::Undefined),
8998 );
8999 };
9000 self.perform_then(
9001 &resolved,
9002 Some(Value::Object(done)),
9003 Some(Value::Object(failed)),
9004 )?;
9005 Ok(())
9006 }
9007 },
9008 }
9009 }
9010
9011 /// Settle the front request and start the next one.
9012 ///
9013 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
9014 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
9015 /// generator would strand every later request.
9016 fn settle_async_request(
9017 &mut self,
9018 generator: &Gc<JsObject>,
9019 promise: &Gc<JsObject>,
9020 outcome: AsyncOutcome,
9021 ) -> JsResult<()> {
9022 let settled = generator.with_mut(|data| match &mut data.kind {
9023 ObjectKind::Generator(state) => {
9024 let front = state.requests.front();
9025 debug_assert!(
9026 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
9027 "a request settled outside its turn"
9028 );
9029 state.requests.pop_front();
9030 state.async_busy = false;
9031 true
9032 }
9033 _ => false,
9034 });
9035 if settled {
9036 match outcome {
9037 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
9038 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
9039 }
9040 }
9041 self.next_async_request(generator)
9042 }
9043
9044 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
9045 ///
9046 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
9047 /// disposer runs **synchronously** — the reference starts it before returning, which
9048 /// a test can observe by logging after the call — and the rest follow once their
9049 /// predecessor settles.
9050 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
9051 let promise = self.new_promise();
9052 // §24.4.3.6 `DisposeResources` step 1: `needsAwait` is true as soon as the stack holds
9053 // any resource at all, because every `await using` resource has the async-dispose
9054 // hint — including the null/undefined ones that have nothing to call. If none of them
9055 // turned out to be awaitable, step 4 still performs one `Await(undefined)`, which is
9056 // why `stack.use(null); stack.disposeAsync()` settles one microtask later rather than
9057 // in the tick it was called from (`disposeAsync/explicit-await-for-null`).
9058 let needs_await = !resources.is_empty();
9059 let mut pairs = Vec::with_capacity(resources.len());
9060 for (value, method) in resources {
9061 let pair = self.new_array(vec![value, method]);
9062 pairs.push(Value::Object(pair));
9063 }
9064 let remaining = self.new_array(pairs);
9065 self.dispose_step(
9066 &remaining,
9067 &promise,
9068 Value::Uninitialized,
9069 false,
9070 needs_await,
9071 )?;
9072 Ok(Value::Object(promise))
9073 }
9074
9075 /// One link of the `disposeAsync` chain.
9076 ///
9077 /// Loops while the disposers finish synchronously, and parks on the first thenable it
9078 /// meets — pushing itself back in as the continuation, with the accumulated error
9079 /// carried along so a later failure can still be folded into the `SuppressedError`.
9080 fn dispose_step(
9081 &mut self,
9082 remaining: &Gc<JsObject>,
9083 promise: &Gc<JsObject>,
9084 mut error: Value,
9085 awaited: bool,
9086 needs_await: bool,
9087 ) -> JsResult<()> {
9088 loop {
9089 let length = remaining.array_length().unwrap_or(0);
9090 if length == 0 {
9091 // Step 4: `needsAwait` true and `hasAwaited` false means one `Await(undefined)`
9092 // still has to happen. Re-entering this same step past an already-fulfilled
9093 // promise is exactly one tick, and it keeps the folding of `error` in one place.
9094 if needs_await && !awaited {
9095 let finished = self.new_array(Vec::new());
9096 let thunk = JsObject::function(
9097 self.heap,
9098 Some(self.realm.function_proto.clone()),
9099 Callable::DisposeStep {
9100 remaining: finished.clone(),
9101 promise: promise.clone(),
9102 error,
9103 rejected: false,
9104 awaited: true,
9105 needs_await: false,
9106 },
9107 );
9108 let tick = self.promise_resolve_value(Value::Undefined)?;
9109 if let Value::Object(tick) = tick {
9110 self.perform_then(
9111 &tick,
9112 Some(Value::Object(thunk.clone())),
9113 Some(Value::Object(thunk)),
9114 )?;
9115 }
9116 return Ok(());
9117 }
9118 if matches!(error, Value::Uninitialized) {
9119 self.fulfill_promise(promise, Value::Undefined);
9120 } else {
9121 self.reject_promise(promise, error);
9122 }
9123 return Ok(());
9124 }
9125 let Some(Value::Object(pair)) = remaining
9126 .array_get(length - 1)
9127 .filter(|v| !matches!(v, Value::Hole))
9128 else {
9129 remaining.array_truncate(self.heap, length - 1);
9130 continue;
9131 };
9132 remaining.array_truncate(self.heap, length - 1);
9133 let value = pair.array_get(0).unwrap_or(Value::Undefined);
9134 let Some(Value::Object(method)) = pair.array_get(1) else {
9135 continue;
9136 };
9137 if !method.is_callable() {
9138 continue;
9139 }
9140 match self.call_value(Value::Object(method), value, Vec::new()) {
9141 Ok(result) => {
9142 if !self.is_thenable(&result)? {
9143 // Finished synchronously; the next disposer is the next iteration.
9144 continue;
9145 }
9146 let awaited = match self.promise_resolve_value(result) {
9147 Ok(awaited) => awaited,
9148 Err(Signal::Throw(reason)) => {
9149 self.reject_promise(promise, reason);
9150 return Ok(());
9151 }
9152 Err(other) => return Err(other),
9153 };
9154 let Value::Object(awaited) = awaited else {
9155 continue;
9156 };
9157 let ok = JsObject::function(
9158 self.heap,
9159 Some(self.realm.function_proto.clone()),
9160 Callable::DisposeStep {
9161 remaining: remaining.clone(),
9162 promise: promise.clone(),
9163 error: error.clone(),
9164 rejected: false,
9165 awaited: true,
9166 needs_await,
9167 },
9168 );
9169 let failed = JsObject::function(
9170 self.heap,
9171 Some(self.realm.function_proto.clone()),
9172 Callable::DisposeStep {
9173 remaining: remaining.clone(),
9174 promise: promise.clone(),
9175 error,
9176 rejected: true,
9177 awaited: true,
9178 needs_await,
9179 },
9180 );
9181 self.perform_then(
9182 &awaited,
9183 Some(Value::Object(ok)),
9184 Some(Value::Object(failed)),
9185 )?;
9186 return Ok(());
9187 }
9188 Err(Signal::Throw(thrown)) => {
9189 error = self.merge_dispose_error(thrown, error);
9190 }
9191 Err(other) => return Err(other),
9192 }
9193 }
9194 }
9195
9196 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
9197 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
9198 let Value::Object(object) = value else {
9199 return Ok(false);
9200 };
9201 Ok(matches!(
9202 self.get_property(object, "then")?,
9203 Some(Value::Object(then)) if then.is_callable()
9204 ))
9205 }
9206
9207 /// One step of an async generator, settling `promise` with an `{value, done}` result.
9208 fn step_async_generator(
9209 &mut self,
9210 generator: &Gc<JsObject>,
9211 promise: &Gc<JsObject>,
9212 kind: ResumeKind,
9213 value: Value,
9214 ) -> JsResult<()> {
9215 // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
9216 // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
9217 // is abrupt — a `constructor` getter that throws — the generator is resumed with a
9218 // *throw* completion instead, so the body's own `try { yield } catch` sees it:
9219 // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
9220 // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
9221 // out of the same read, one as a rejection and one as a rethrow.
9222 //
9223 // Narrow on purpose: only a value that is *already a promise* is inspected, so
9224 // nothing changes for `return 1` and the extra read is a plain data-property
9225 // lookup on the intrinsic case.
9226 if kind == ResumeKind::Return
9227 && let Value::Object(object) = &value
9228 && self.promise_state(object).is_some()
9229 && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
9230 {
9231 return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
9232 }
9233 let stepped = self.resume_generator_detailed(generator, kind, value);
9234 let (value, done, ready, reason) = match stepped {
9235 Ok(stepped) => stepped,
9236 Err(Signal::Throw(reason)) => {
9237 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
9238 }
9239 Err(other) => return Err(other),
9240 };
9241 // Only an `await` has to wait before the method can answer.
9242 if !done && reason == Some(SuspendKind::Await) {
9243 let awaited = match self.promise_resolve_value(value) {
9244 Ok(awaited) => awaited,
9245 Err(Signal::Throw(reason)) => {
9246 return self.settle_async_request(
9247 generator,
9248 promise,
9249 AsyncOutcome::Error(reason),
9250 );
9251 }
9252 Err(other) => return Err(other),
9253 };
9254 let Value::Object(awaited) = awaited else {
9255 return Ok(());
9256 };
9257 let resumed = JsObject::function(
9258 self.heap,
9259 Some(self.realm.function_proto.clone()),
9260 Callable::GeneratorResume {
9261 generator: generator.clone(),
9262 promise: promise.clone(),
9263 kind: ResumeKind::Next,
9264 },
9265 );
9266 let raised = JsObject::function(
9267 self.heap,
9268 Some(self.realm.function_proto.clone()),
9269 Callable::GeneratorResume {
9270 generator: generator.clone(),
9271 promise: promise.clone(),
9272 kind: ResumeKind::Throw,
9273 },
9274 );
9275 self.perform_then(
9276 &awaited,
9277 Some(Value::Object(resumed)),
9278 Some(Value::Object(raised)),
9279 )?;
9280 return Ok(());
9281 }
9282 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
9283 // completes it — both arrive as the settled value rather than as the promise
9284 // object. A plain value skips the round trip, which is also what keeps `yield 1`
9285 // from costing an extra tick.
9286 let awaits_value = self.is_thenable(&value)?;
9287 if awaits_value {
9288 // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
9289 // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
9290 // value that merely gets `yield`ed is awaited by the body's own `Await`, where
9291 // no `PromiseResolve` appears, so that path keeps the shortcut.
9292 let awaited = match if done {
9293 self.promise_resolve_intrinsic(value)
9294 } else {
9295 self.promise_resolve_value(value)
9296 } {
9297 Ok(awaited) => awaited,
9298 Err(Signal::Throw(reason)) => {
9299 return self.settle_async_request(
9300 generator,
9301 promise,
9302 AsyncOutcome::Error(reason),
9303 );
9304 }
9305 Err(other) => return Err(other),
9306 };
9307 let Value::Object(awaited) = awaited else {
9308 return Ok(());
9309 };
9310 // A rejected yield throws *at the yield* inside the body, so the rejection
9311 // resumes the generator rather than the method's promise.
9312 let answer = JsObject::function(
9313 self.heap,
9314 Some(self.realm.function_proto.clone()),
9315 Callable::YieldResult {
9316 generator: generator.clone(),
9317 promise: promise.clone(),
9318 done,
9319 },
9320 );
9321 let raise = JsObject::function(
9322 self.heap,
9323 Some(self.realm.function_proto.clone()),
9324 Callable::GeneratorResume {
9325 generator: generator.clone(),
9326 promise: promise.clone(),
9327 kind: ResumeKind::Throw,
9328 },
9329 );
9330 self.perform_then(
9331 &awaited,
9332 Some(Value::Object(answer)),
9333 Some(Value::Object(raise)),
9334 )?;
9335 return Ok(());
9336 }
9337 let result = if ready {
9338 // `yield*` handed back the inner iterator's own result object.
9339 value
9340 } else {
9341 self.iterator_result(value, done)?
9342 };
9343 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
9344 }
9345
9346 /// The `{value, done}` object an iterator method answers with.
9347 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
9348 let result = self.new_object(Some(self.realm.object_proto.clone()));
9349 result.define_data("value", value);
9350 result.define_data("done", Value::Bool(done));
9351 Ok(Value::Object(result))
9352 }
9353
9354 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
9355 fn step_generator(
9356 &mut self,
9357 state: &mut GeneratorState,
9358 kind: ResumeKind,
9359 value: Value,
9360 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9361 match state.phase {
9362 GeneratorPhase::Executing => {
9363 return Err(self.type_error("cannot invoke a running generator"));
9364 }
9365 GeneratorPhase::Completed => {
9366 // A finished generator answers every resumption without running.
9367 return Ok(match kind {
9368 ResumeKind::Throw => return Err(Signal::Throw(value)),
9369 ResumeKind::Return => (value, true, false, None),
9370 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
9371 });
9372 }
9373 GeneratorPhase::SuspendedStart => {
9374 if kind != ResumeKind::Next && kind != ResumeKind::Start {
9375 // The body never started, so there is nothing to unwind or return
9376 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
9377 state.frame = None;
9378 state.phase = GeneratorPhase::Completed;
9379 return Ok(match kind {
9380 ResumeKind::Throw => return Err(Signal::Throw(value)),
9381 _ => (value, true, false, None),
9382 });
9383 }
9384 }
9385 GeneratorPhase::SuspendedYield => {}
9386 }
9387
9388 let Some(mut frame) = state.frame.take() else {
9389 return Ok((Value::Undefined, true, false, None));
9390 };
9391 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
9392 // number that says which method resumed it; the emitted `if_false` branches on
9393 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
9394 let mut raised = None;
9395 match kind {
9396 ResumeKind::Next | ResumeKind::Start => {
9397 if state.phase == GeneratorPhase::SuspendedYield {
9398 frame.stack.push(value);
9399 // An `await` resumes with its value alone; only a `yield` gets the
9400 // magic number that says which of `next`/`return` resumed it.
9401 if !state.parked_on_await {
9402 frame.stack.push(Value::Int(RESUME_NEXT));
9403 }
9404 }
9405 }
9406 ResumeKind::Return => {
9407 // A `return` on a not-yet-started generator is handled above, so this is
9408 // always a real resumption.
9409 frame.stack.push(value);
9410 frame.stack.push(Value::Int(RESUME_RETURN));
9411 }
9412 ResumeKind::Throw => {
9413 // At a `yield*` the exception is *data* for the delegation: the compiled
9414 // code resumes with the value and magic `2` and calls the inner iterator's
9415 // `throw`. Everywhere else it is raised at the suspension point, so the
9416 // body's own handler sees it.
9417 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
9418 frame.stack.push(value);
9419 frame.stack.push(Value::Int(RESUME_THROW));
9420 } else {
9421 raised = Some(value);
9422 }
9423 }
9424 }
9425 state.phase = GeneratorPhase::Executing;
9426
9427 let depth = self.frames.len();
9428 self.frames.push(frame);
9429 // A `throw` unwinds from where the frame parked, exactly as if the exception had
9430 // happened at the `yield`.
9431 if let Some(exception) = raised {
9432 if self.catch_here(exception.clone()).is_none() {
9433 self.pop_frame();
9434 state.phase = GeneratorPhase::Completed;
9435 return Err(Signal::Throw(exception));
9436 }
9437 }
9438
9439 // Only the generator's *own* frame ends the generator. The body may call ordinary
9440 // functions, and those push frames of their own: a `Step::Return` from one of them
9441 // is a nested call finishing, not the generator completing. Miscounting that is
9442 // silent — the generator reports the callee's value as its own result and marks
9443 // itself done — so the depth comparison is load-bearing, not defensive.
9444 let own_frame = depth + 1;
9445 loop {
9446 match self.step() {
9447 Ok(Step::Continue) => {}
9448 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9449 let mut frame = self.frames.pop().expect("a frame is live");
9450 // `yield` left the value on the stack; `initial_yield` left nothing.
9451 let yielded = if reason == SuspendKind::Initial {
9452 Value::Undefined
9453 } else {
9454 frame.stack.pop().unwrap_or(Value::Undefined)
9455 };
9456 state.frame = Some(frame);
9457 state.parked_on_await = reason == SuspendKind::Await;
9458 state.parked_on_yield_star =
9459 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9460 state.phase = if reason == SuspendKind::Initial {
9461 GeneratorPhase::SuspendedStart
9462 } else {
9463 GeneratorPhase::SuspendedYield
9464 };
9465 // `yield*` hands the inner iterator's own result object straight
9466 // back, so the caller sees one `{value, done}` rather than a nested
9467 // one — which is why the third field says "already a result".
9468 return Ok((
9469 yielded,
9470 false,
9471 reason == SuspendKind::YieldStar,
9472 Some(reason),
9473 ));
9474 }
9475 Ok(Step::Suspend(_)) => {
9476 // A `yield` in a frame other than the generator's would mean a
9477 // generator body entered as an ordinary call, which
9478 // `call_or_push` prevents.
9479 self.unwind_to(depth);
9480 state.phase = GeneratorPhase::Completed;
9481 return Err(Signal::Throw(self.make_error(
9482 "InternalError",
9483 "a generator body ran as an ordinary call",
9484 )));
9485 }
9486 Ok(Step::Return(value)) => {
9487 self.pop_frame();
9488 if self.frames.len() > depth {
9489 // A nested call finished: hand the value back to its caller and
9490 // keep running the generator body.
9491 self.frames
9492 .last_mut()
9493 .expect("a caller is live")
9494 .stack
9495 .push(value);
9496 continue;
9497 }
9498 state.phase = GeneratorPhase::Completed;
9499 // The reference closes the generator's closure variables here; ours
9500 // live in cells the frame owned, which the drop below releases.
9501 return Ok((value, true, false, None));
9502 }
9503 Err(Signal::Throw(exception)) => {
9504 // The frame that threw gets the first chance to catch, exactly as in
9505 // the ordinary call loop; a frame above the generator's is popped and
9506 // the exception carries on down.
9507 let exception = exception;
9508 loop {
9509 if self.frames.len() <= depth {
9510 // The generator's own frame is gone, so nothing here caught it.
9511 state.phase = GeneratorPhase::Completed;
9512 return Err(Signal::Throw(exception));
9513 }
9514 if self.catch_here(exception.clone()).is_some() {
9515 break;
9516 }
9517 self.pop_frame();
9518 }
9519 }
9520 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9521 }
9522 }
9523 }
9524
9525 /// Pop frames until `depth` are left, keeping their buffers.
9526 fn unwind_to(&mut self, depth: usize) {
9527 while self.frames.len() > depth {
9528 self.pop_frame();
9529 }
9530 }
9531 fn call_or_push(
9532 &mut self,
9533 callee: Value,
9534 this: Value,
9535 args: Vec<Value>,
9536 ) -> JsResult<Option<Value>> {
9537 if let Value::Object(function) = &callee
9538 && let Some((code, env)) = bytecode_of(function)
9539 {
9540 // Calling a generator function does not run anything: it captures the
9541 // arguments in a frame and hands back the generator object.
9542 if code.code.kind.is_generator() {
9543 return self.new_generator(callee, this, args).map(Some);
9544 }
9545 // An async function answers a promise and runs its body as a coroutine, so it
9546 // takes the same path as a plain call into it.
9547 if code.code.kind.is_async() {
9548 return self.new_async_function(callee, this, args).map(Some);
9549 }
9550 self.push_frame(code, env, this, args, callee)?;
9551 return Ok(None);
9552 }
9553 self.call_value(callee, this, args).map(Some)
9554 }
9555
9556 /// `new callee(args)`.
9557 ///
9558 /// A constructor differs from a plain call in three ways: it gets a fresh object
9559 /// as `this` whose prototype is the constructor's `prototype` property, its
9560 /// return value is *replaced* by that object unless it returns an object itself,
9561 /// and a native constructor is expected to initialise the object it is given
9562 /// rather than build one.
9563 pub fn construct(
9564 &mut self,
9565 callee: Value,
9566 new_target: Value,
9567 args: Vec<Value>,
9568 ) -> JsResult<Value> {
9569 // `new` on a bound function constructs its *target*, prepending the arguments
9570 // the bind fixed and ignoring the bound `this` — a bound function is a
9571 // constructor only when its target is one, and `new` always makes a fresh
9572 // object of the target's prototype rather than reusing the bound receiver.
9573 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9574 // ran the body with `this === null` and threw on `this.x = a`.
9575 let mut callee = callee;
9576 let mut new_target = new_target;
9577 let mut args = args;
9578 loop {
9579 let Some(object) = callee.as_object().cloned() else {
9580 return Err(Signal::Throw(
9581 self.make_error("TypeError", "not a constructor"),
9582 ));
9583 };
9584 // A proxy of a function constructs through its `construct` trap, and the
9585 // trap's answer is the result directly — no fresh object is made here.
9586 if object.proxy_state().is_some() {
9587 return match self.proxy_construct(&object, args, &new_target)? {
9588 Some(result) => Ok(result),
9589 None => Err(Signal::Throw(
9590 self.make_error("TypeError", "proxy target is not a constructor"),
9591 )),
9592 };
9593 }
9594 // A generator function has no `[[Construct]]`, and the reference names it in
9595 // the message: `new (function* G(){})()` reports "G is not a constructor".
9596 if object.with(|data| match &data.kind {
9597 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9598 code.code.kind.is_generator()
9599 }
9600 _ => false,
9601 }) {
9602 let name = object
9603 .own_property("name")
9604 .and_then(|property| property.value)
9605 .map(|value| value.to_js_string())
9606 .unwrap_or_default();
9607 return Err(Signal::Throw(
9608 self.make_error("TypeError", &format!("{name} is not a constructor")),
9609 ));
9610 }
9611 let bound = object.with(|data| match &data.kind {
9612 ObjectKind::Function(Callable::Bound {
9613 target,
9614 args: leading,
9615 ..
9616 }) => Some((target.clone(), leading.clone())),
9617 _ => None,
9618 });
9619 let Some((target, leading)) = bound else {
9620 // Not a bound function, so this object is the callee. §7.2.4
9621 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9622 // refusals above cover only the built-ins the reference also refuses by
9623 // name. Everything else — a method, an arrow, an async function — has no
9624 // `[[Construct]]` either, and answering "yes" here made
9625 // `new (Array.prototype.map)` build an object instead of throwing.
9626 if !object.is_constructor() {
9627 let name = object
9628 .own_property("name")
9629 .and_then(|property| property.value)
9630 .map(|value| value.to_js_string())
9631 .unwrap_or_default();
9632 return Err(Signal::Throw(
9633 self.make_error("TypeError", &format!("{name} is not a constructor")),
9634 ));
9635 }
9636 break;
9637 };
9638 let mut all = leading;
9639 all.extend(args);
9640 args = all;
9641 // A bound function that is its own `new.target` stands in for its target:
9642 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9643 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9644 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9645 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9646 _ => false,
9647 };
9648 if same_wrapper {
9649 new_target = target.clone();
9650 }
9651 callee = target;
9652 }
9653 let Value::Object(function) = &callee else {
9654 unreachable!("the loop above only breaks on an object");
9655 };
9656 // The fresh object's prototype comes from `new.target`, not from the callee: a
9657 // derived constructor reaches here through `super()`, and the instance must be a
9658 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9659 // an object inheriting `D.prototype` rather than `C.prototype`.
9660 let prototype_source = match new_target.as_object() {
9661 Some(target) => target.clone(),
9662 None => function.clone(),
9663 };
9664 // A native constructor builds its own instance, through `new_ctor_instance`, once it
9665 // has validated its arguments. Pre-building one here would read
9666 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9667 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9668 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9669 let is_native = function.native_creates_own_instance();
9670 let this = if is_native {
9671 Value::Undefined
9672 } else {
9673 let prototype = self.get_property(&prototype_source, "prototype")?;
9674 let prototype = match prototype {
9675 Some(Value::Object(proto)) => Some(proto),
9676 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
9677 // object, the answer is the realm's *intrinsic* prototype for this
9678 // constructor, not `%Object.prototype%`.
9679 _ => {
9680 // `GetPrototypeFromConstructor` step 4 is `GetFunctionRealm(constructor)`,
9681 // and that is a `TypeError` for a revoked proxy. Without it, `new
9682 // revokedProxy()` quietly produced an `%Object.prototype%` instance —
9683 // `base-ctor-revoked-proxy` revokes the proxy from inside its own `get`
9684 // trap, so it is already revoked when this fallback runs.
9685 if prototype_source.proxy_state().is_some() {
9686 self.proxy_parts(&prototype_source)?;
9687 }
9688 let fallback = self.get_property(function, "prototype")?;
9689 match fallback {
9690 Some(Value::Object(proto)) => Some(proto),
9691 _ => Some(self.realm.object_proto.clone()),
9692 }
9693 }
9694 };
9695 Value::Object(self.new_object(prototype))
9696 };
9697 // `new.target` inside the body is the constructor that was written, so a bound
9698 // function's target sees itself rather than the bound wrapper.
9699 //
9700 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
9701 // `?`, so assigning `None` after the call would be skipped and the failed
9702 // `new.target` would stay visible to every later native call. The symptom was a
9703 // native constructor refusing a plain call — `var s = Symbol(); new
9704 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
9705 // "FinalizationRegistry is not a constructor".
9706 let outer_new_target = self.pending_new_target.replace(new_target);
9707 let callee = callee.clone();
9708 let result = self.call_value(callee, this.clone(), args);
9709 self.pending_new_target = outer_new_target;
9710 let result = result?;
9711 // A constructor that returns an object overrides `this`; any other return value
9712 // (including `undefined`) is ignored — **except** in a derived constructor, where
9713 // §15.7.1 step 12 makes a non-object return a `TypeError`
9714 // (`Function/internals/Construct/derived-return-val`).
9715 let derived = function.with(|data| match &data.kind {
9716 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9717 code.code.is_derived_constructor
9718 }
9719 _ => false,
9720 });
9721 Ok(match result {
9722 Value::Object(_) => result,
9723 // A bare `return;` answers `undefined`, which is **legal** even in a derived
9724 // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
9725 Value::Undefined => this,
9726 _ if derived => {
9727 return Err(Signal::Throw(self.make_error(
9728 "TypeError",
9729 "derived constructor may only return an object or undefined",
9730 )));
9731 }
9732 _ => this,
9733 })
9734 }
9735
9736 /// `new.target` for the call currently being made.
9737 ///
9738 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9739 /// it as `this`), but a *host* constructor that builds its own instance is handed
9740 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9741 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9742 /// it here.
9743 ///
9744 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9745 /// receives for a plain call.
9746 pub fn current_new_target(&self) -> Value {
9747 self.active_new_target.clone()
9748 }
9749
9750 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9751 ///
9752 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9753 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9754 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9755 let constructor = self.realm.errors.get("AggregateError").cloned();
9756 let Some(constructor) = constructor else {
9757 return self.make_error("AggregateError", message);
9758 };
9759 let list = self.new_array(errors);
9760 match self.construct(
9761 Value::Object(constructor.clone()),
9762 Value::Object(constructor),
9763 vec![Value::Object(list), self.string(message)],
9764 ) {
9765 Ok(value) => value,
9766 // A user could have replaced `AggregateError` with something that throws; the
9767 // engine still owes the caller a rejection, so it falls back rather than
9768 // turning `Promise.any`'s rejection into a throw.
9769 Err(_) => self.make_error("AggregateError", message),
9770 }
9771 }
9772
9773 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9774 ///
9775 /// The error classes themselves arrive with the builtins milestone; what
9776 /// matters here is that the thrown value stringifies the way a script printing
9777 /// the caught value expects.
9778 ///
9779 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9780 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9781 /// rely on when they print a caught value.
9782 pub fn make_error(&self, name: &str, message: &str) -> Value {
9783 let proto = self
9784 .realm
9785 .errors
9786 .get(name)
9787 .map(|constructor| self.prototype_of(constructor))
9788 .unwrap_or_else(|| self.realm.error_proto.clone());
9789 let error = self.new_object(Some(proto));
9790 // `name` and `message` are own properties of the instance, which is what
9791 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9792 // `Error`.
9793 error.define(
9794 "name",
9795 Property::with_attributes(self.string(name), true, false),
9796 );
9797 error.define(
9798 "message",
9799 Property::with_attributes(self.string(message), true, false),
9800 );
9801 // The internal class, which is what tells a printer this is an error rather than a
9802 // plain object with `name` and `message` properties. The constructor path sets it
9803 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9804 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
9805 // literally `"Error"` in both places — the *name* is read from `name`, which is why
9806 // a `RangeError` still prints as `RangeError`.
9807 self.internal_set(&error, "_class", self.string("Error"));
9808 // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
9809 // answered `false` from `Error.isError` while a constructed one answered `true`,
9810 // because only the constructor set the slot. The reference answers `true` for both
9811 // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
9812 // accessor gated on this slot the omission stopped being cosmetic: `print_error`
9813 // tests `typeof stack === "string"` to decide on a trailing newline, so every
9814 // engine-thrown error lost its blank line.
9815 self.internal_set(&error, "_error_data", Value::Bool(true));
9816 // The trace is captured where the error is *made*, which is where the reference
9817 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
9818 // way out, so a caught engine error already has its stack even if the handler
9819 // never rethrows it.
9820 self.add_stack(&error);
9821 Value::Object(error)
9822 }
9823
9824 /// Give an error object its `stack` property, from the current frame stack.
9825 ///
9826 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
9827 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
9828 /// `stack` a script set, is not rewritten.
9829 pub fn add_stack(&self, object: &Gc<JsObject>) {
9830 self.add_stack_skipping(object, 0);
9831 }
9832
9833 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
9834 ///
9835 /// An `Error` constructor passes 1: the reference builds those traces with
9836 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
9837 /// constructor itself, while a `RangeError` raised inside `toISOString` does
9838 /// report `at toISOString (native)`.
9839 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
9840 if object.has_own("stack") {
9841 return;
9842 }
9843 // The trace is *captured* here but not installed as a property: `stack` is an
9844 // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
9845 // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
9846 // is kept in a hidden slot and the getter materialises it on first read.
9847 //
9848 // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
9849 // shows it — this is the same discipline `_error_data` and `_class` follow.
9850 let trace = self.stack_trace_skipping(skip);
9851 let text = self.string(trace);
9852 self.internal_set(object, "_stack_trace", text);
9853 }
9854
9855 /// The function object currently being called, if any.
9856 ///
9857 /// A native function is a bare `fn` pointer, so it cannot capture which class
9858 /// it belongs to; it reads that from the callee instead. This is also what a
9859 /// stack trace would use.
9860 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
9861 match &self.frames.last()?.callee {
9862 Value::Object(object) => Some(object.clone()),
9863 _ => None,
9864 }
9865 }
9866
9867 /// The `prototype` property of a constructor, falling back to
9868 /// `Object.prototype` for anything that is not shaped like one.
9869 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
9870 constructor
9871 .own_property("prototype")
9872 .and_then(|property| property.value)
9873 .and_then(|value| value.as_object().cloned())
9874 .unwrap_or_else(|| self.realm.object_proto.clone())
9875 }
9876
9877 /// Throw a `TypeError` carrying `message`.
9878 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
9879 Signal::Throw(self.make_error("TypeError", message.as_ref()))
9880 }
9881
9882 /// Throw a `RangeError` carrying `message`.
9883 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
9884 Signal::Throw(self.make_error("RangeError", message.as_ref()))
9885 }
9886
9887 /// A `ReferenceError`, as the value to throw.
9888 ///
9889 /// `throw` uses it for "called on a disposed stack": `DisposableStack.prototype.defer`
9890 /// and its siblings report a `ReferenceError` there, which is what
9891 /// `adopt|defer|move/throws-if-disposed` assert.
9892 pub fn reference_error(&self, message: impl AsRef<str>) -> Signal {
9893 Signal::Throw(self.make_error("ReferenceError", message.as_ref()))
9894 }
9895
9896 /// The `ReferenceError` a read of an uninitialised binding raises.
9897 /// The name of the binding `slot` refers to, for an error message.
9898 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
9899 match kind {
9900 VarSlot::Loc => self
9901 .frame()
9902 .code
9903 .code
9904 .vars
9905 .get(slot)
9906 .map(|v| v.name.clone()),
9907 VarSlot::Closure => self
9908 .frame()
9909 .code
9910 .code
9911 .closure_vars
9912 .get(slot)
9913 .map(|c| c.name.clone()),
9914 }
9915 .unwrap_or_default()
9916 }
9917
9918 /// Whether `slot` names a `const` binding, which rejects every store after its
9919 /// initialiser.
9920 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
9921 match kind {
9922 VarSlot::Loc => self
9923 .frame()
9924 .code
9925 .code
9926 .vars
9927 .get(slot)
9928 .is_some_and(|v| v.is_const),
9929 VarSlot::Closure => self
9930 .frame()
9931 .code
9932 .code
9933 .closure_vars
9934 .get(slot)
9935 .is_some_and(|c| c.is_const),
9936 }
9937 }
9938
9939 /// The `TypeError` a store to a `const` binding raises.
9940 ///
9941 /// `const` is enforced here rather than at compile time because the binding can be
9942 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
9943 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
9944 /// both halves of what "checked store" means: the dead zone is over, and the
9945 /// binding is writable.
9946 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
9947 let name = self.binding_name(slot, kind);
9948 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
9949 }
9950
9951 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
9952 let name = match kind {
9953 VarSlot::Loc => self
9954 .frame()
9955 .code
9956 .code
9957 .vars
9958 .get(slot)
9959 .map(|v| v.name.clone()),
9960 VarSlot::Closure => self
9961 .frame()
9962 .code
9963 .code
9964 .closure_vars
9965 .get(slot)
9966 .map(|c| c.name.clone()),
9967 }
9968 .unwrap_or_default();
9969 Signal::Throw(self.make_error(
9970 "ReferenceError",
9971 &format!("cannot access '{name}' before initialization"),
9972 ))
9973 }
9974
9975 fn throw_reference(&self, name: &str) -> Signal {
9976 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
9977 }
9978
9979 // -- the instruction loop -----------------------------------------------
9980
9981 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
9982 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
9983 // measured at 16% of a tight arithmetic loop's total time.
9984 #[inline(always)]
9985 fn step(&mut self) -> JsResult<Step> {
9986 // The instruction is already decoded (see [`crate::insn`]), so this is an index
9987 // and a `Copy` read rather than a table lookup plus a width switch. Only the
9988 // borrow lives across the boundary; nothing is cloned.
9989 // **One** borrow of the frame: fetch the record, then advance in the same scope.
9990 // The obvious version borrowed it three times (`last` to read, `last_mut` to
9991 // write, and once more inside the handler), and each is a bounds check plus an
9992 // `Option` unwrap — on the one path every instruction takes.
9993 let Some((insn, next)) = ({
9994 let frame = self
9995 .frames
9996 .last_mut()
9997 .expect("step() is only called with a live frame");
9998 // Past the last instruction is a normal return: the compiler ends a function
9999 // with `return`, and a jump to the end of a block lands here.
10000 let insn = frame.insns().get(frame.pc).copied();
10001 match insn {
10002 None => None,
10003 Some(insn) => {
10004 // A fused record stands for the next few instructions, so the next
10005 // `pc` is its width ahead — the instructions it replaces are never
10006 // dispatched. `at` is the byte offset a stack trace reports; it stays
10007 // an offset because the line table is keyed by bytes.
10008 frame.at = insn.offset as usize;
10009 frame.pc += insn.width();
10010 Some((insn, frame.pc))
10011 }
10012 }
10013 }) else {
10014 return Ok(Step::Return(Value::Undefined));
10015 };
10016 self.check_memory()?;
10017 self.check_interrupt()?;
10018 if insn.fused == crate::insn::Fused::None {
10019 self.execute_instruction(insn.op, insn.a, insn.b, next)
10020 } else {
10021 self.execute_fused(insn)
10022 }
10023 }
10024
10025 /// Run a fused instruction: several bytecode instructions in one dispatch.
10026 ///
10027 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
10028 /// it cannot throw and cannot allocate — and anything else falls back to the real
10029 /// instructions, in their real order, so an exception leaves the operand stack
10030 /// exactly as it would have been.
10031 #[inline]
10032 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
10033 use crate::insn::Fused;
10034 let slot = insn.a as usize;
10035 match insn.fused {
10036 // `x = k`: `push k; put_loc x`.
10037 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
10038 // `x += k`: `get_loc x; push k; add; put_loc x`.
10039 Fused::AddImmLoc => {
10040 let delta = insn.b as i32;
10041 match self.get_loc(slot) {
10042 Value::Int(left) => {
10043 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
10044 // that built two `Value`s, called a function, and matched on them
10045 // again to reach this same `checked_add`. It is the innermost
10046 // operation of every accumulator in every program.
10047 let answer = match left.checked_add(delta) {
10048 Some(sum) => Value::Int(sum),
10049 None => Value::Float(left as f64 + delta as f64),
10050 };
10051 self.put_loc(slot, answer);
10052 }
10053 other => {
10054 self.push(other);
10055 self.push(Value::Int(delta));
10056 self.binary_add()?;
10057 let value = self.pop();
10058 self.put_loc(slot, value);
10059 }
10060 }
10061 }
10062 // `x += "literal"` and `x += y`: the two shapes that can append in place.
10063 Fused::AddAtomLoc => {
10064 let text = self.atom_wtf8(insn.b as usize);
10065 let right = self.string_wtf8(text);
10066 self.add_into_loc(slot, right)?;
10067 }
10068 Fused::AddLocLoc => {
10069 let source = (insn.a & 0xFFFF) as usize;
10070 let target = (insn.a >> 16) as usize;
10071 let right = self.get_loc(source);
10072 self.add_into_loc(target, right)?;
10073 }
10074 Fused::AddArgLoc => {
10075 let source = (insn.a & 0xFFFF) as usize;
10076 let target = (insn.a >> 16) as usize;
10077 let right = self.get_arg(source);
10078 self.add_into_loc(target, right)?;
10079 }
10080 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
10081 Fused::PostIncLoc => match self.get_loc(slot) {
10082 Value::Int(left) => {
10083 let answer = match left.checked_add(1) {
10084 Some(sum) => Value::Int(sum),
10085 None => Value::Float(left as f64 + 1.0),
10086 };
10087 self.put_loc(slot, answer);
10088 }
10089 other => {
10090 self.push(other);
10091 let raw = self.pop();
10092 let (old, updated) = self.advance_numeric(raw, true)?;
10093 self.push(old);
10094 self.push(updated);
10095 let value = self.pop();
10096 self.put_loc(slot, value);
10097 self.pop();
10098 }
10099 },
10100 // `if (!(x < arg)) goto target`: a loop header.
10101 //
10102 // The comparison is computed rather than replayed on the operand stack. That
10103 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
10104 // that throws: the effects happen in the same order, and a handler truncates
10105 // the stack down to its marker, so the intermediate values are unobservable.
10106 Fused::LtLocArgJump => {
10107 let loc = (insn.a >> 16) as usize;
10108 let arg = (insn.a & 0xFFFF) as usize;
10109 let left = self.get_loc(loc);
10110 let right = self.get_arg(arg);
10111 let taken = match (&left, &right) {
10112 (Value::Int(left), Value::Int(right)) => !(left < right),
10113 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10114 };
10115 if taken {
10116 self.frame_mut().pc = insn.b as usize;
10117 }
10118 }
10119 // `i < k` in a loop header, where `k` is an integer literal.
10120 Fused::LtLocImmJump => {
10121 let left = self.get_loc(insn.a as usize);
10122 let right = Value::Int(insn.imm as i32);
10123 let taken = match &left {
10124 Value::Int(left) => !(*left < insn.imm as i32),
10125 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10126 };
10127 if taken {
10128 self.frame_mut().pc = insn.b as usize;
10129 }
10130 }
10131 Fused::None => unreachable!("only called for a fused record"),
10132 }
10133 Ok(Step::Continue)
10134 }
10135
10136 /// Run records that cannot call script, cannot throw and cannot change frames.
10137 ///
10138 /// Returns `Some(value)` when the function ran off the end of its instructions (a
10139 /// normal return), and `None` when it stopped in front of an instruction the slow path
10140 /// has to handle — `pc` is written back either way, so `step` resumes at the right
10141 /// place.
10142 ///
10143 /// **The invariant is the whole point.** Every arm here is restricted to work that
10144 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
10145 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
10146 /// that the memory limit has to see. An opcode whose operands turn out to need any of
10147 /// that **stops the loop** instead of trying, so the slow path gets the instruction
10148 /// untouched and with its operands still on the stack. That is why the fallback is a
10149 /// `break` and not a duplicated slow arm: a second implementation of the same
10150 /// semantics is how a wrong answer gets in with no test noticing.
10151 ///
10152 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
10153 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
10154 fn run_fast(&mut self) -> JsResult<Option<Value>> {
10155 use crate::insn::Fused;
10156 // The outer loop exists only so a `Call` can come back through here: once a
10157 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
10158 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
10159 // frame. Re-entering re-reads both from whichever frame is now on top. Every
10160 // other exit from the inner loop returns, so this costs one loop per call.
10161 'outer: loop {
10162 // One reference-count bump per *slow* instruction (a call, an allocation, a
10163 // property access), never one per instruction — that distinction is worth
10164 // two orders of magnitude and was measured as such.
10165 let (code, mut pc) = {
10166 let frame = self.frame();
10167 (frame.code.clone(), frame.pc)
10168 };
10169 let insns = &code.insns;
10170 loop {
10171 let Some(insn) = insns.get(pc).copied() else {
10172 self.frame_mut().pc = pc;
10173 return Ok(Some(Value::Undefined));
10174 };
10175 match insn.fused {
10176 // `x = k`
10177 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
10178 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
10179 // object — stops the loop so `binary_add` can decide.
10180 Fused::AddImmLoc => {
10181 let slot = insn.a as usize;
10182 let delta = insn.b as i32;
10183 let Value::Int(left) = self.get_loc(slot) else {
10184 return Ok(self.stop(pc));
10185 };
10186 let sum = match left.checked_add(delta) {
10187 Some(sum) => Value::Int(sum),
10188 None => Value::Float(left as f64 + delta as f64),
10189 };
10190 self.put_loc(slot, sum);
10191 }
10192 // `x += "literal"` / `x += y`: the operand is a string, so the append
10193 // either allocates one or grows one. Both are the slow path's business;
10194 // the fusion's job is only to make the *slot* the sole owner, which is what
10195 // `execute_fused` needs and what `get_loc` alone destroys.
10196 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
10197 return Ok(self.stop(pc));
10198 }
10199 // `x++` on an integer, old value dropped.
10200 Fused::PostIncLoc => {
10201 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
10202 // value is read in place and overwritten in place, so the reference
10203 // count it held is released by the same assignment that stores the
10204 // new one. `get_loc` plus `put_loc` did two borrows, two table
10205 // lookups and a clone, and this arm is the whole body of a counting
10206 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
10207 let slot = insn.a as usize;
10208 let frame = self.frames.last_mut().expect("a frame is live");
10209 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
10210 let target = if cell < 0 {
10211 frame.locals.get_mut(slot)
10212 } else {
10213 None
10214 };
10215 let Some(target) = target else {
10216 return Ok(self.stop(pc));
10217 };
10218 let Value::Int(left) = *target else {
10219 return Ok(self.stop(pc));
10220 };
10221 *target = match left.checked_add(1) {
10222 Some(sum) => Value::Int(sum),
10223 None => Value::Float(left as f64 + 1.0),
10224 };
10225 }
10226 // A loop header, `if (!(x < arg)) goto target`, with both sides already
10227 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
10228 // bound stayed small integers.
10229 Fused::LtLocArgJump => {
10230 let loc = (insn.a >> 16) as usize;
10231 let arg = (insn.a & 0xFFFF) as usize;
10232 // One borrow for both slots: this arm *is* the whole loop of a
10233 // `for (i = 0; i < n; i++)` with an argument bound, so a second
10234 // `frames.last()` here is paid on every iteration. Measured 7.5% on
10235 // `dispatch:empty-loop`.
10236 let (left, right) = {
10237 let frame = self.frame();
10238 (frame.read_loc(loc), frame.read_arg(arg))
10239 };
10240 // Heavily measured: the bound is very often a `Float` even when the
10241 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
10242 // `JSON.parse` or a division is one — so requiring both sides to be
10243 // `Int` sent every iteration of those loops down the slow path. The
10244 // comparison below is the same one `relational` makes for two numbers.
10245 if !is_number(&left) || !is_number(&right) {
10246 return Ok(self.stop(pc));
10247 }
10248 // `if_false` branches on the comparison being false, which is **not**
10249 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
10250 // `>=` is also false and would keep it running forever. Clippy wants the
10251 // negation folded; that would be a wrong answer.
10252 let ordered = left.to_number() < right.to_number();
10253 let take_branch = !ordered;
10254 if take_branch {
10255 pc = insn.b as usize;
10256 continue;
10257 }
10258 }
10259 // The same header with a literal bound: `if (!(x < k)) goto target`.
10260 // The bound is an immediate, so only the counter needs a type test.
10261 #[allow(clippy::neg_cmp_op_on_partial_ord)]
10262 Fused::LtLocImmJump => {
10263 let left = self.get_loc(insn.a as usize);
10264 if !is_number(&left) {
10265 return Ok(self.stop(pc));
10266 }
10267 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
10268 if take_branch {
10269 pc = insn.b as usize;
10270 continue;
10271 }
10272 }
10273 Fused::None => match insn.op {
10274 // -- branches ---------------------------------------------------
10275 // A jump is an assignment now, because the target is an instruction
10276 // index. No arithmetic, no resolution table.
10277 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10278 let target = insn.a as usize;
10279 // A **back-edge** is a loop, and it is the only place an
10280 // instruction-level checkpoint can stop one: `for(;;){}` compiles
10281 // to a jump to itself and never leaves this loop, so the
10282 // per-instruction checks in `step` never run. That is exactly the
10283 // hole this arm closes — a host's `JS_SetInterruptHandler` did
10284 // nothing to a `for(;;){}` until it did, which is what
10285 // `tests/c/embed.c` is for.
10286 //
10287 // Polling here rather than on every instruction in this loop is
10288 // also the reference's choice (`OP_goto` calls
10289 // `js_poll_interrupts`), and it costs one compare per branch
10290 // instead of one decrement per instruction.
10291 if target <= pc {
10292 self.frame_mut().pc = target;
10293 self.check_memory()?;
10294 self.check_interrupt()?;
10295 }
10296 pc = target;
10297 continue;
10298 }
10299 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
10300 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
10301 let taken = self.pop().to_boolean();
10302 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
10303 if taken == want {
10304 pc = insn.a as usize;
10305 continue;
10306 }
10307 }
10308 // -- slot access -------------------------------------------------
10309 // A load's slot is already an operand (see `insn::implicit_operand`);
10310 // a captured one goes through its cell, which runs no script.
10311 Opcode::GetLoc
10312 | Opcode::GetLoc8
10313 | Opcode::GetLoc0
10314 | Opcode::GetLoc1
10315 | Opcode::GetLoc2
10316 | Opcode::GetLoc3 => {
10317 let value = self.get_loc(insn.a as usize);
10318 self.push(value);
10319 }
10320 Opcode::PutLoc
10321 | Opcode::PutLoc8
10322 | Opcode::PutLoc0
10323 | Opcode::PutLoc1
10324 | Opcode::PutLoc2
10325 | Opcode::PutLoc3 => {
10326 let value = self.pop();
10327 self.put_loc(insn.a as usize, value);
10328 }
10329 Opcode::GetArg
10330 | Opcode::GetArg0
10331 | Opcode::GetArg1
10332 | Opcode::GetArg2
10333 | Opcode::GetArg3 => {
10334 let value = self.get_arg(insn.a as usize);
10335 self.push(value);
10336 }
10337 Opcode::PutArg
10338 | Opcode::PutArg0
10339 | Opcode::PutArg1
10340 | Opcode::PutArg2
10341 | Opcode::PutArg3 => {
10342 let value = self.pop();
10343 self.put_arg(insn.a as usize, value);
10344 }
10345 // `a[i]` with an integer index on a dense array: see `fast_array_get`
10346 // for why a non-hole own element is exactly the slow path's answer.
10347 // The two operands are *peeked*, so a miss leaves the stack as the
10348 // slow path expects to find it.
10349 Opcode::GetArrayEl => {
10350 // One lookup, not two. The guard used `if …is_some()` and the arm
10351 // then called it again to get the value — two `peek`s, two
10352 // `array_get`s and two `Value` clones for one element.
10353 // `fast_array_get` was 13.1% of `array:indexed`, and the same
10354 // double call was the first version of the `get_field` fast path.
10355 let Some(value) = self.fast_array_get() else {
10356 return Ok(self.stop(pc));
10357 };
10358 // `a[i]` consumes both operands and leaves the element in their
10359 // place: one `truncate` and one write, no `pop`/`push` pair.
10360 let frame = self.frame_mut();
10361 frame.stack.truncate(frame.stack.len() - 2);
10362 frame.stack.push(value);
10363 }
10364 // `a[i] = v` on a dense array with an integer index: see
10365 // `fast_array_set` for why the whole store is one step.
10366 Opcode::PutArrayEl if self.fast_array_set() => {}
10367 // `o.x` resolved from the inline cache without leaving the loop.
10368 //
10369 // The cache is keyed by `(receiver identity, atom, site)` and a
10370 // monomorphic read re-validates the same chain every iteration, so
10371 // each one used to cost a `stop(pc)` — a write of `pc` into the
10372 // frame, a return out of this loop, a re-dispatch through `step` and
10373 // a re-entry. `property:monomorphic` spent 18% in
10374 // `read_field_cached` and 21% in `push`, both across that boundary.
10375 //
10376 // The site is `pc + width`, which is exactly the `next` the slow arm
10377 // passes — the two must agree or every fast lookup misses and
10378 // re-records the same entry forever.
10379 //
10380 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
10381 // slow arm finds the receiver where it expects it.
10382 // `name` resolved from the global-variable cache inside the loop.
10383 //
10384 // Same shape as `get_field` above and for the same reason: `get_var`
10385 // was not in the fast loop, so reading a global — which `fib` does
10386 // once per recursive call, for its own name — cost a `stop(pc)`, a
10387 // return out of the loop, a `step` re-dispatch and a re-entry, before
10388 // `get_global` even started its `scopes_are_plain` checks.
10389 //
10390 // Everything here is exactly `get_global`'s first branch: not lexical,
10391 // no `eval` scope, cache hit. Anything else leaves the stack untouched
10392 // and lets the slow arm decide.
10393 Opcode::GetVar => {
10394 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
10395 return Ok(self.stop(pc));
10396 };
10397 self.push(value);
10398 }
10399 Opcode::GetField | Opcode::GetField2 => {
10400 let Some(value) =
10401 self.fast_field_get(insn.a as usize, pc + insn.width())
10402 else {
10403 return Ok(self.stop(pc));
10404 };
10405 if insn.op == Opcode::GetField2 {
10406 // `get_field2` keeps the receiver for the `call_method` that
10407 // follows.
10408 self.push(value);
10409 } else {
10410 // `get_field` replaces the receiver, so this is one store over
10411 // the top slot rather than a `pop` and a `push`: the length
10412 // never changes, so neither `Vec` arm has a capacity check or a
10413 // drop to run beyond the one the overwrite itself does.
10414 let frame = self.frame_mut();
10415 match frame.stack.last_mut() {
10416 Some(slot) => *slot = value,
10417 None => return Ok(self.stop(pc)),
10418 }
10419 }
10420 }
10421 // -- constants ---------------------------------------------------
10422 Opcode::PushMinus1
10423 | Opcode::Push0
10424 | Opcode::Push1
10425 | Opcode::Push2
10426 | Opcode::Push3
10427 | Opcode::Push4
10428 | Opcode::Push5
10429 | Opcode::Push6
10430 | Opcode::Push7
10431 | Opcode::PushI8
10432 | Opcode::PushI16
10433 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
10434 // -- stack shuffling ---------------------------------------------
10435 Opcode::Drop => {
10436 self.pop();
10437 }
10438 // -- arithmetic on two integers ----------------------------------
10439 //
10440 // The operands are *looked at* before they are popped, so a non-integer
10441 // pair leaves the stack exactly as the slow path expects to find it.
10442 Opcode::Add if self.numeric_pair() => {
10443 let right = self.pop();
10444 let left = self.pop();
10445 // Exactly [`add_numbers`], which is what the slow arm reaches.
10446 let answer = match (&left, &right) {
10447 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10448 Some(sum) => Value::Int(sum),
10449 None => Value::Float(*a as f64 + *b as f64),
10450 },
10451 _ => Value::Float(left.to_number() + right.to_number()),
10452 };
10453 self.push(answer);
10454 }
10455 Opcode::Sub
10456 | Opcode::And
10457 | Opcode::Or
10458 | Opcode::Xor
10459 | Opcode::Shl
10460 | Opcode::Sar
10461 | Opcode::Shr
10462 if self.numeric_pair() =>
10463 {
10464 let right = self.pop();
10465 let left = self.pop();
10466 let answer =
10467 arithmetic(insn.op, left, right).expect("numbers cannot throw");
10468 self.push(answer);
10469 }
10470 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10471 if self.numeric_pair() =>
10472 {
10473 let right = self.pop();
10474 let left = self.pop();
10475 let answer = self
10476 .relational(insn.op, left, right)
10477 .expect("numbers cannot throw");
10478 self.push(answer);
10479 }
10480 // -- calls -------------------------------------------------------
10481 //
10482 // A plain call: `callee(arg0, …, argN) -> result`.
10483 //
10484 // This arm exists because of one measurement. `call:recursion` had
10485 // **20.4% of its profile in `execute_instruction`** — the *slow*
10486 // executor — and `fib`'s recursive call is the only thing in that
10487 // function which is not a fast arm. Every call therefore left this
10488 // loop via `stop()`, went through `step()`'s dispatch and
10489 // `execute_instruction`'s match over every opcode, and came back here
10490 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
10491 //
10492 // Two things make it safe to do here rather than only in the slow path:
10493 //
10494 // * the caller's `pc` is stored *before* the call, which is what
10495 // `step` does too — so when the callee returns, the caller resumes
10496 // after the call and not at it;
10497 // * `check_memory` runs, because `step` calls it once per instruction
10498 // and a call allocates a frame, its locals and its cells. Skipping
10499 // the checkpoint here would let a `--memory-limit` script overshoot
10500 // by one call per instruction.
10501 Opcode::Call
10502 | Opcode::Call0
10503 | Opcode::Call1
10504 | Opcode::Call2
10505 | Opcode::Call3 => {
10506 let argc = self.argc_operand(insn.op, insn.a);
10507 let next = pc + insn.width();
10508 {
10509 let frame = self
10510 .frames
10511 .last_mut()
10512 .expect("run_fast() is only called with a live frame");
10513 // `at` is what a stack trace reports for this frame, so a throw
10514 // inside the callee has to see the call site and not whatever
10515 // the last `stop()` left there.
10516 frame.at = insn.offset as usize;
10517 frame.pc = next;
10518 }
10519 self.check_memory()?;
10520 self.check_interrupt()?;
10521 let args = self.pop_n(argc);
10522 let callee = self.pop();
10523 // A plain call has no receiver; the callee decides what to do with
10524 // `undefined` (a sloppy function substitutes the global object).
10525 if let Some(result) =
10526 self.call_or_push(callee, Value::Undefined, args)?
10527 {
10528 // Native, host, generator, async, bound — no frame was pushed,
10529 // so this loop is still describing the right function. `pc`
10530 // is advanced by the loop tail like every other arm; only the
10531 // frame's copy had to be written here, and it already was.
10532 self.push(result);
10533 } else {
10534 // A bytecode callee: its frame is on top now, and `insns` and
10535 // `pc` both belong to the caller. Start over on the new frame.
10536 continue 'outer;
10537 }
10538 }
10539 // -- return ------------------------------------------------------
10540 Opcode::Return => {
10541 let value = self.pop();
10542 self.frame_mut().pc = pc + insn.width();
10543 return Ok(Some(value));
10544 }
10545 Opcode::ReturnUndef => {
10546 self.frame_mut().pc = pc + insn.width();
10547 return Ok(Some(Value::Undefined));
10548 }
10549 // Everything else needs the slow path.
10550 _ => return Ok(self.stop(pc)),
10551 },
10552 }
10553 pc += insn.width();
10554 }
10555 }
10556 }
10557
10558 /// Whether the top two operand-stack values are both numbers.
10559 ///
10560 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
10561 /// cannot run script, so the arm may not throw and may not change frames.
10562 fn numeric_pair(&self) -> bool {
10563 is_number(&self.peek(0)) && is_number(&self.peek(1))
10564 }
10565
10566 /// `a[i]` for a dense array and an integer index, without the string round trip.
10567 ///
10568 /// The slow path answers this by turning `i` into a string (`propkey` →
10569 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
10570 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
10571 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
10572 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
10573 /// without even the cheap `Int` formatting.
10574 ///
10575 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
10576 /// unambiguously the one the slow path would give:
10577 ///
10578 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
10579 /// `2^32-1` is the length, not an index),
10580 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
10581 /// typed array or an ordinary object, all of which have their own rules),
10582 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
10583 /// starts walking the prototype chain, and `a[i]` on a hole must find
10584 /// `Array.prototype[i]` if it exists rather than `undefined`.
10585 ///
10586 /// The last condition is the one that makes this safe rather than merely fast: an own
10587 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
10588 /// `get_var` answered from the global-variable cache, or `None`.
10589 ///
10590 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10591 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10592 /// records nothing — the slow arm is about to walk the chain and record it.
10593 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10594 let frame = self.frame();
10595 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10596 // "Lexical" is presence in the realm's table, not the closure var's flag: a
10597 // `GlobalRef` forwarded through a nested function has its flags cleared.
10598 if self.realm.globals.contains_key(name) {
10599 return None;
10600 }
10601 if !self.scopes_are_plain() {
10602 return None;
10603 }
10604 let object = &self.realm.global;
10605 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10606 let cached = self.global_cache[site].as_ref()?;
10607 if !object.upgrades_to(&cached.object) {
10608 return None;
10609 }
10610 object.data_property_at(cached.index, name)
10611 }
10612
10613 /// `o.x` answered entirely from the inline cache, or `None`.
10614 ///
10615 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
10616 /// about to do exactly that and recording it twice would rebuild the chain for every
10617 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
10618 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
10619 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
10620 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
10621 // an object receiver is a reference-count bump that the answer never needs.
10622 let frame = self.frame();
10623 let object = frame.stack.last()?;
10624 let Value::Object(target) = object else {
10625 return None;
10626 };
10627 // A proxy traps the lookup, so no cache entry ever describes it.
10628 if target.proxy_state().is_some() {
10629 return None;
10630 }
10631 let key = frame.code.atom_keys.get(atom)?;
10632 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
10633 if cached.key != *key {
10634 return None;
10635 }
10636 Self::cached_hit(target, cached)
10637 }
10638
10639 fn fast_array_get(&self) -> Option<Value> {
10640 let Value::Int(index) = self.peek(0) else {
10641 return None;
10642 };
10643 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
10644 // set for an `i32`.
10645 if index < 0 {
10646 return None;
10647 }
10648 let Value::Object(object) = self.peek(1) else {
10649 return None;
10650 };
10651 match object.array_get(index as usize) {
10652 Some(value) if !matches!(value, Value::Hole) => Some(value),
10653 _ => None,
10654 }
10655 }
10656
10657 /// `a[i] = v` on a dense array with an integer index, as one store.
10658 ///
10659 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
10660 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
10661 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
10662 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
10663 /// reference at the time it was measured (14.7x).
10664 ///
10665 /// Every condition here is one the slow path would also have to satisfy before
10666 /// storing into the element vector:
10667 ///
10668 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
10669 /// accepts as an index;
10670 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
10671 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
10672 /// one inside a recorded descriptor, reports `false` and the caller stops.
10673 ///
10674 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
10675 /// writes the own element too once `array_set` says it did.
10676 fn fast_array_set(&mut self) -> bool {
10677 // Every test runs *before* anything is popped: a refusal has to leave the stack
10678 // exactly as the slow path expects to find it. Popping first and reporting the
10679 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
10680 // then ran the slow path with nothing to write.
10681 let Value::Int(index) = self.peek(1) else {
10682 return false;
10683 };
10684 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
10685 if index < 0 {
10686 return false;
10687 }
10688 // Only a real array: a typed array's elements live in its buffer, a string-like
10689 // object has no element vector, and `array_set` on either does nothing.
10690 let Value::Object(object) = self.peek(2) else {
10691 return false;
10692 };
10693 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
10694 return false;
10695 }
10696 // A non-extensible array reports `false` here, but the *slow* path has to decide
10697 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
10698 // that with the key and the stack still intact.
10699 if !object.is_extensible() {
10700 return false;
10701 }
10702 // Inside the logical length, so the store cannot change `length`. Combined with
10703 // extensibility above, the only growth left for `array_set` is filling a hole in
10704 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
10705 // shape this fast path exists for. A store past the length would grow the array,
10706 // and whether that is allowed is the slow path's question.
10707 if index as usize >= object.array_length().unwrap_or(0) {
10708 return false;
10709 }
10710 // Only an *own element* can take the inline store. A hole is not an own property,
10711 // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
10712 // trap or a setter decides, and where `new Array(1)` with a proxy above it must
10713 // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
10714 // the one case this path used to swallow.
10715 //
10716 // The cost is small: `array:indexed` only reads after a 64-element fill, and
10717 // `array:push` appends past the length, which this path already refused.
10718 if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
10719 {
10720 return false;
10721 }
10722 // The bound `array_set` refuses past. Checking it here keeps that arm from having
10723 // to report a failure after the operands are gone.
10724 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
10725 return false;
10726 }
10727 let value = self.pop();
10728 self.pop();
10729 self.pop();
10730 object.array_store(self.heap, index as usize, value)
10731 }
10732
10733 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
10734 fn stop(&mut self, pc: usize) -> Option<Value> {
10735 self.frame_mut().pc = pc;
10736 None
10737 }
10738
10739 fn push(&mut self, value: Value) {
10740 self.frame_mut().stack.push(value);
10741 }
10742
10743 fn pop(&mut self) -> Value {
10744 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10745 }
10746
10747 fn pop_n(&mut self, count: usize) -> Vec<Value> {
10748 let frame = self.frame_mut();
10749 let start = frame.stack.len().saturating_sub(count);
10750 frame.stack.split_off(start)
10751 }
10752
10753 fn peek(&self, back: usize) -> Value {
10754 let frame = self.frame();
10755 frame
10756 .stack
10757 .get(frame.stack.len().wrapping_sub(1 + back))
10758 .cloned()
10759 .unwrap_or(Value::Undefined)
10760 }
10761
10762 #[allow(clippy::too_many_lines)]
10763 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10764 use Opcode::*;
10765 match op {
10766 // -- constants and stack shuffling -----------------------------
10767 Nop => {}
10768 PushMinus1 => self.push(Value::Int(-1)),
10769 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10770 let value = match op {
10771 Push0 => 0,
10772 Push1 => 1,
10773 Push2 => 2,
10774 Push3 => 3,
10775 Push4 => 4,
10776 Push5 => 5,
10777 Push6 => 6,
10778 _ => 7,
10779 };
10780 self.push(Value::Int(value));
10781 }
10782 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
10783 PushBigintI32 => {
10784 // The immediate form of a `BigInt` literal; the reference has the same
10785 // split between this and a constant-pool entry.
10786 let value = crate::bigint::BigInt::from_i64(a as i64);
10787 self.push(self.bigint(value));
10788 }
10789 PushTrue => self.push(Value::Bool(true)),
10790 PushFalse => self.push(Value::Bool(false)),
10791 PushEmptyString => self.push(self.string("")),
10792 Undefined => self.push(Value::Undefined),
10793 Null => self.push(Value::Null),
10794 Object => {
10795 let proto = self.realm.object_proto.clone();
10796 self.push(Value::Object(self.new_object(Some(proto))));
10797 }
10798 PushThis => {
10799 let this = self.frame().this.clone();
10800 self.push(this);
10801 }
10802 PushConst | PushConst8 => {
10803 let value = self.constant(a as usize)?;
10804 self.push(value);
10805 }
10806 PushAtomValue => {
10807 let text = self.atom_wtf8(a as usize);
10808 self.push(self.string_wtf8(text));
10809 }
10810 Dup => {
10811 let value = self.peek(0);
10812 self.push(value);
10813 }
10814 Dup2 => {
10815 // `a b -> a b a b`
10816 let b = self.peek(0);
10817 let a = self.peek(1);
10818 self.push(a);
10819 self.push(b);
10820 }
10821 Dup3 => {
10822 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
10823 // prototype and key while reading the current value through them.
10824 let c = self.peek(0);
10825 let b = self.peek(1);
10826 let a = self.peek(2);
10827 self.push(a);
10828 self.push(b);
10829 self.push(c);
10830 }
10831 Swap => {
10832 // `a b -> b a`
10833 let bottom = self.pop();
10834 let top = self.pop();
10835 self.push(bottom);
10836 self.push(top);
10837 }
10838 Perm3 => {
10839 // `a b c -> b a c`, the reference's reordering for a spread method
10840 // call: `obj func array` becomes the `func this array` that `apply`
10841 // takes.
10842 let c = self.pop();
10843 let b = self.pop();
10844 let a = self.pop();
10845 self.push(b);
10846 self.push(a);
10847 self.push(c);
10848 }
10849 Dup1 => {
10850 let value = self.peek(1);
10851 self.push(value);
10852 }
10853 Drop => {
10854 self.pop();
10855 }
10856 Nip => {
10857 // `a b -> b`
10858 let top = self.pop();
10859 self.pop();
10860 self.push(top);
10861 }
10862 Perm4 => {
10863 // `obj prop a b -> a obj prop b`, the reference's reordering for a
10864 // postfix update of a computed element: it puts the *old* value
10865 // underneath the receiver and key so `put_array_el` can consume them
10866 // and leave the old value as the expression's result.
10867 let d = self.pop();
10868 let c = self.pop();
10869 let b = self.pop();
10870 let a = self.pop();
10871 self.push(c);
10872 self.push(a);
10873 self.push(b);
10874 self.push(d);
10875 }
10876 Insert2 => {
10877 // `obj a -> a obj a`
10878 let value = self.pop();
10879 let object = self.pop();
10880 self.push(value.clone());
10881 self.push(object);
10882 self.push(value);
10883 }
10884 Insert3 => {
10885 // `obj prop a -> a obj prop a`
10886 let value = self.pop();
10887 let key = self.pop();
10888 let object = self.pop();
10889 self.push(value.clone());
10890 self.push(object);
10891 self.push(key);
10892 self.push(value);
10893 }
10894 Insert4 => {
10895 // `this obj prop a -> a this obj prop a`
10896 //
10897 // `put_super_value` consumes all four and yields nothing, so the copy
10898 // underneath is what leaves the assignment an expression value.
10899 let value = self.pop();
10900 let key = self.pop();
10901 let object = self.pop();
10902 let receiver = self.pop();
10903 self.push(value.clone());
10904 self.push(receiver);
10905 self.push(object);
10906 self.push(key);
10907 self.push(value);
10908 }
10909 Swap2 => {
10910 // `a b c d -> c d a b`
10911 let d = self.pop();
10912 let c = self.pop();
10913 let b = self.pop();
10914 let a = self.pop();
10915 self.push(c);
10916 self.push(d);
10917 self.push(a);
10918 self.push(b);
10919 }
10920 Rot3l => {
10921 // `x a b -> a b x`
10922 let b = self.pop();
10923 let a = self.pop();
10924 let x = self.pop();
10925 self.push(a);
10926 self.push(b);
10927 self.push(x);
10928 }
10929 Rot3r => {
10930 // `a b c -> c a b`
10931 let c = self.pop();
10932 let b = self.pop();
10933 let a_value = self.pop();
10934 self.push(c);
10935 self.push(a_value);
10936 self.push(b);
10937 }
10938
10939 Rest => {
10940 // `...rest` in a parameter list: the arguments from index `a` on, as a
10941 // real array. It takes nothing off the stack — the arguments are in the
10942 // frame, not on it.
10943 let frame = self.frame();
10944 let from = a as usize;
10945 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
10946 let array = self.new_array(collected);
10947 self.push(Value::Object(array));
10948 }
10949
10950 // -- slots ------------------------------------------------------
10951 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
10952 let slot = self.slot_operand(op, a);
10953 let value = self.get_loc(slot);
10954 self.push(value);
10955 }
10956 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
10957 let slot = self.slot_operand(op, a);
10958 let value = self.pop();
10959 self.put_loc(slot, value);
10960 }
10961 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
10962 let slot = self.slot_operand(op, a);
10963 let value = self.pop();
10964 self.put_loc(slot, value.clone());
10965 self.push(value);
10966 }
10967 // The `_check` forms are the temporal dead zone: they throw when the
10968 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
10969 // *reads*, so only the two writes may pop — mishandling that quietly
10970 // consumes the value the caller pushed just before.
10971 GetLocCheck => {
10972 let slot = self.slot_operand(op, a);
10973 let value = self.get_loc(slot);
10974 if matches!(value, Value::Uninitialized) {
10975 return Err(self.dead_zone(slot, VarSlot::Loc));
10976 }
10977 self.push(value);
10978 }
10979 PutLocCheck | SetLocCheck => {
10980 let slot = self.slot_operand(op, a);
10981 let value = self.pop();
10982 if matches!(value, Value::Uninitialized) {
10983 return Err(self.dead_zone(slot, VarSlot::Loc));
10984 }
10985 // The initialiser goes through `put_loc`, not this, so any store that
10986 // reaches here is a later assignment — which a `const` refuses.
10987 if self.is_read_only(slot, VarSlot::Loc) {
10988 return Err(self.read_only(slot, VarSlot::Loc));
10989 }
10990 if op == SetLocCheck {
10991 self.put_loc(slot, value.clone());
10992 self.push(value);
10993 } else {
10994 self.put_loc(slot, value);
10995 }
10996 }
10997 PutLocCheckInit => {
10998 // The one store that *initialises* a lexical slot: `this` in a derived
10999 // constructor, which only exists after `super()` has run. A second
11000 // initialisation is the error the reference reports as
11001 // "'this' can be initialized only once".
11002 let slot = self.slot_operand(op, a);
11003 let value = self.pop();
11004 if !matches!(self.get_loc(slot), Value::Uninitialized) {
11005 return Err(Signal::Throw(self.make_error(
11006 "ReferenceError",
11007 "'this' can be initialized only once",
11008 )));
11009 }
11010 self.put_loc(slot, value);
11011 }
11012 CheckCtor => {
11013 // A class constructor may only run under `new`, which is what makes
11014 // `class A {}; A()` a TypeError.
11015 if matches!(self.frame().new_target, Value::Undefined) {
11016 return Err(Signal::Throw(self.make_error(
11017 "TypeError",
11018 "class constructors must be invoked with 'new'",
11019 )));
11020 }
11021 }
11022 InitCtor => {
11023 // The body a derived class gets when it declares no constructor:
11024 // forward every argument to the parent constructor, keeping `new.target`.
11025 if matches!(self.frame().new_target, Value::Undefined) {
11026 return Err(Signal::Throw(self.make_error(
11027 "TypeError",
11028 "class constructors must be invoked with 'new'",
11029 )));
11030 }
11031 let Some(callee) = self.current_callee() else {
11032 return Err(Signal::Throw(
11033 self.make_error("TypeError", "no constructor to inherit from"),
11034 ));
11035 };
11036 let parent = callee.proto().map_or(Value::Null, Value::Object);
11037 let new_target = self.frame().new_target.clone();
11038 let args = self.frame().passed().to_vec();
11039 let result = self.construct(parent, new_target, args)?;
11040 self.push(result);
11041 }
11042 SetLocUninitialized => {
11043 let slot = self.slot_operand(op, a);
11044 self.put_loc(slot, Value::Uninitialized);
11045 }
11046 CloseLoc => {
11047 // "Close" a binding: give it a *fresh* cell holding the current
11048 // value. Closures created before this point keep the old cell and the
11049 // ones created after see the new one, which is what makes every
11050 // iteration of `for (let i ...)` capture its own `i`, and what freezes
11051 // a block-scoped binding when the block ends.
11052 //
11053 // Clearing the slot instead (which this used to do) broke both: a
11054 // closure over a captured block variable read `undefined`, and a loop
11055 // terminated after one iteration.
11056 let slot = self.slot_operand(op, a);
11057 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
11058 if index >= 0 {
11059 let current = self.frame().cells[index as usize].get();
11060 let fresh = self.new_cell(current);
11061 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
11062 *cell = fresh;
11063 }
11064 }
11065 }
11066 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
11067 let slot = self.slot_operand(op, a);
11068 let value = self.get_arg(slot);
11069 self.push(value);
11070 }
11071 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
11072 let slot = self.slot_operand(op, a);
11073 let value = self.pop();
11074 self.put_arg(slot, value);
11075 }
11076 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
11077 let slot = self.slot_operand(op, a);
11078 let value = self.pop();
11079 self.put_arg(slot, value.clone());
11080 self.push(value);
11081 }
11082
11083 // -- closure variables ------------------------------------------
11084 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
11085 let slot = self.slot_operand(op, a);
11086 // A name a direct `eval` created shadows the binding the compiler chose.
11087 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
11088 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
11089 // and only a runtime lookup can know that.
11090 if let Some(cell) = self.eval_created_local(slot) {
11091 self.push(cell.get());
11092 return self.step();
11093 }
11094 let value = self.cell_value(slot)?;
11095 self.push(value);
11096 }
11097 GetVarRefCheck => {
11098 let slot = self.slot_operand(op, a);
11099 let value = self.cell_value(slot)?;
11100 if matches!(value, Value::Uninitialized) {
11101 return Err(self.dead_zone(slot, VarSlot::Closure));
11102 }
11103 self.push(value);
11104 }
11105 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
11106 let slot = self.slot_operand(op, a);
11107 let value = self.pop();
11108 if let Some(cell) = self.eval_created_local(slot) {
11109 cell.set(value);
11110 return self.step();
11111 }
11112 // Same rule as `PutLocCheck`: a checked store to a captured binding
11113 // refuses a `const` once its initialiser has run.
11114 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
11115 return Err(self.read_only(slot, VarSlot::Closure));
11116 }
11117 self.set_cell(slot, value)?;
11118 }
11119 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
11120 let slot = self.slot_operand(op, a);
11121 let value = self.pop();
11122 if let Some(cell) = self.eval_created_local(slot) {
11123 cell.set(value.clone());
11124 self.push(value);
11125 return self.step();
11126 }
11127 self.set_cell(slot, value.clone())?;
11128 self.push(value);
11129 }
11130
11131 // -- globals ----------------------------------------------------
11132 GetVar => {
11133 let value = self.get_global(a as usize)?;
11134 self.push(value);
11135 }
11136 GetVarUndef => {
11137 let slot = a as usize;
11138 // `typeof undeclared` answers `"undefined"`; `typeof x` where `x` is in its
11139 // **dead zone** still throws (§13.5.3 evaluates the operand as a Reference
11140 // and `GetValue`s it, and only the unresolvable case is forgiven).
11141 //
11142 // The distinction is made by asking whether a binding exists at all: a name
11143 // in the realm's lexical table is declared, so a `ReferenceError` from
11144 // reading it is the dead zone talking. Swallowing every error made
11145 // `eval("typeof x; let x;")` print `"undefined"`.
11146 let declared = self.realm.globals.contains_key(&self.global_name(slot));
11147 let value = if declared {
11148 self.get_global(slot)?
11149 } else {
11150 match self.get_global(slot) {
11151 Ok(value) => value,
11152 Err(Signal::Throw(_)) => Value::Undefined,
11153 Err(other) => return Err(other),
11154 }
11155 };
11156 self.push(value);
11157 }
11158 DeleteVar => {
11159 // `delete name` for a name that is not a declared binding. A lexical
11160 // global lives in the reference table and cannot be deleted; anything
11161 // reachable only as a property of the global object is *implicit* —
11162 // `x = 1` with no declaration — and goes away if it is configurable,
11163 // which is what `delete` on an implicit global answers.
11164 let name = self.atom_text(a as usize);
11165 let global = self.realm.global.clone();
11166 let deleted = if self.realm.globals.contains_key(&name) {
11167 false
11168 } else if global.own_property(&name).is_some() {
11169 self.delete_property(&global, &name)?
11170 } else {
11171 true
11172 };
11173 self.push(Value::Bool(deleted));
11174 }
11175 PutVar => {
11176 let value = self.pop();
11177 self.put_global(a as usize, value)?;
11178 }
11179 PutVarInit => {
11180 let slot = a as usize;
11181 let value = self.pop();
11182 self.init_global(slot, value)?;
11183 }
11184
11185 // -- arithmetic -------------------------------------------------
11186 Add => self.binary_add()?,
11187 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
11188 let raw_right = self.pop();
11189 let raw_left = self.pop();
11190 // BigInt arithmetic is a separate path, and not only for the type of the
11191 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
11192 // rather than a silent conversion.
11193 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
11194 let left = self.primitive_of(raw_left)?;
11195 let right = self.primitive_of(raw_right)?;
11196 let value = self.bigint_arithmetic(op, left, right)?;
11197 self.push(value);
11198 } else {
11199 let right = self.numeric(raw_right)?;
11200 let left = self.numeric(raw_left)?;
11201 self.push(arithmetic(op, left, right)?);
11202 }
11203 }
11204 Neg => {
11205 let raw = self.pop();
11206 match raw {
11207 // A bigint negates exactly, however wide it is.
11208 Value::BigInt(big) => {
11209 let negated = big.negate();
11210 self.push(self.bigint(negated));
11211 }
11212 other => {
11213 let value = self.numeric(other)?;
11214 self.push(negate(value));
11215 }
11216 }
11217 }
11218 Plus => {
11219 let value = self.pop();
11220 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
11221 // unary plus is defined to produce a *number*, which a bigint cannot
11222 // become without loss. It used to fall through to `NaN`.
11223 if matches!(value, Value::BigInt(_)) {
11224 return Err(self.type_error("cannot convert bigint to number"));
11225 }
11226 let numeric = self.numeric_of(value)?;
11227 self.push(numeric);
11228 }
11229 Inc => {
11230 let raw = self.pop();
11231 let (_, updated) = self.advance_numeric(raw, true)?;
11232 self.push(updated);
11233 }
11234 Dec => {
11235 let raw = self.pop();
11236 let (_, updated) = self.advance_numeric(raw, false)?;
11237 self.push(updated);
11238 }
11239 PostInc | PostDec => {
11240 // `x -> x x+1`: the *new* value ends up on top, so the store the
11241 // compiler emits right after (`put_var`) writes the incremented
11242 // one, while the old value stays underneath for the expression's
11243 // own result. Getting this backwards makes `i++` a no-op, which
11244 // turns `while (i < 3)` into an infinite loop.
11245 let raw = self.pop();
11246 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
11247 self.push(old);
11248 self.push(updated);
11249 }
11250 Not => {
11251 let raw = self.pop();
11252 match raw {
11253 // `~x` on a bigint is `-x - 1`, exact at any width.
11254 Value::BigInt(big) => {
11255 let inverted = big.bitnot();
11256 self.push(self.bigint(inverted));
11257 }
11258 other => {
11259 let value = self.numeric(other)?;
11260 self.push(Value::Int(!value.to_int32()));
11261 }
11262 }
11263 }
11264 Lnot => {
11265 let value = self.pop();
11266 self.push(Value::Bool(!value.to_boolean()));
11267 }
11268
11269 // -- comparison -------------------------------------------------
11270 Lt | Lte | Gt | Gte => {
11271 let right = self.pop();
11272 let left = self.pop();
11273 let answer = self.relational(op, left, right)?;
11274 self.push(answer);
11275 }
11276 Eq | Neq => {
11277 let right = self.pop();
11278 let left = self.pop();
11279 let equal = self.abstract_equals(left, right)?;
11280 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
11281 }
11282 StrictEq => {
11283 let right = self.pop();
11284 let left = self.pop();
11285 self.push(Value::Bool(left.strict_equals(&right)));
11286 }
11287 StrictNeq => {
11288 let right = self.pop();
11289 let left = self.pop();
11290 self.push(Value::Bool(!left.strict_equals(&right)));
11291 }
11292 IsUndefined => {
11293 // `=== undefined`, which is what a destructuring default tests. It is
11294 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
11295 let value = self.pop();
11296 self.push(Value::Bool(matches!(value, Value::Undefined)));
11297 }
11298 IsUndefinedOrNull => {
11299 let value = self.pop();
11300 self.push(Value::Bool(value.is_nullish()));
11301 }
11302 Typeof => {
11303 let value = self.pop();
11304 self.push(self.string(value.type_of()));
11305 }
11306 ToObject => {
11307 // A destructuring *object* pattern starts here, which is why
11308 // `var {} = null` throws. Only `undefined` and `null` are refused; a
11309 // primitive is boxed.
11310 let value = self.pop();
11311 let object = self.object_from(&value)?;
11312 self.push(Value::Object(object));
11313 }
11314 Instanceof => {
11315 let constructor = self.pop();
11316 let object = self.pop();
11317 let answer = self.instance_of(&object, &constructor)?;
11318 self.push(Value::Bool(answer));
11319 }
11320 In => {
11321 let object = self.pop();
11322 let key = self.pop();
11323 let answer = self.has_property(&key, &object)?;
11324 self.push(Value::Bool(answer));
11325 }
11326
11327 // -- control flow -----------------------------------------------
11328 Goto | Goto8 | Goto16 => {
11329 self.frame_mut().pc = a as usize;
11330 }
11331 IfTrue | IfTrue8 => {
11332 let value = self.pop();
11333 if value.to_boolean() {
11334 self.frame_mut().pc = a as usize;
11335 }
11336 }
11337 IfFalse | IfFalse8 => {
11338 let value = self.pop();
11339 if !value.to_boolean() {
11340 self.frame_mut().pc = a as usize;
11341 }
11342 }
11343 Catch => {
11344 // Pushes the handler target onto the value stack; `unwind` finds it.
11345 self.push(Value::CatchOffset(a));
11346 }
11347 Gosub => {
11348 self.push(Value::ReturnAddress(next as u32));
11349 self.frame_mut().pc = a as usize;
11350 }
11351 Ret => {
11352 let value = self.pop();
11353 match value {
11354 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
11355 _ => {
11356 return Err(Signal::Throw(
11357 self.make_error("InternalError", "invalid return address"),
11358 ));
11359 }
11360 }
11361 }
11362 NipCatch => {
11363 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
11364 // including the marker, keeping the top value.
11365 let top = self.pop();
11366 loop {
11367 match self.pop() {
11368 Value::CatchOffset(_) | Value::Undefined => break,
11369 _ => {}
11370 }
11371 if self.frame().stack.is_empty() {
11372 break;
11373 }
11374 }
11375 self.push(top);
11376 }
11377 Throw => {
11378 let value = self.pop();
11379 return Err(Signal::Throw(value));
11380 }
11381 ThrowError => {
11382 let name = self.atom_text(a as usize);
11383 let (class, message) = match b {
11384 0 => ("TypeError", format!("'{name}' is read-only")),
11385 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
11386 2 => ("ReferenceError", format!("'{name}' is not initialized")),
11387 // `delete super.x` is a syntax-level mistake the reference reports
11388 // with this wording, not a property-access failure.
11389 3 => (
11390 "ReferenceError",
11391 "unsupported reference to 'super'".to_string(),
11392 ),
11393 4 => (
11394 "TypeError",
11395 "iterator does not have a throw method".to_string(),
11396 ),
11397 5 => (
11398 "ReferenceError",
11399 "invalid assignment left-hand side".to_string(),
11400 ),
11401 _ => ("TypeError", format!("invalid operation on '{name}'")),
11402 };
11403 return Err(Signal::Throw(self.make_error(class, &message)));
11404 }
11405 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
11406 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
11407 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
11408 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
11409 Await => return Ok(Step::Suspend(SuspendKind::Await)),
11410 ReturnAsync => {
11411 // The reference's `return_async` returns `undefined` and lets the resume
11412 // machinery pick the real value off `sp[-1]`, which is how it tells a
11413 // completion from a suspension. Carrying the value explicitly says the
11414 // same thing without the implicit stack slot.
11415 let value = self.pop();
11416 return Ok(Step::Return(value));
11417 }
11418 Return => {
11419 let value = self.pop();
11420 return Ok(Step::Return(value));
11421 }
11422 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
11423
11424 // -- calls ------------------------------------------------------
11425 Call | Call0 | Call1 | Call2 | Call3 => {
11426 let argc = self.argc_operand(op, a);
11427 let args = self.pop_n(argc);
11428 let callee = self.pop();
11429 // A plain call has no receiver; the callee decides what to do with
11430 // `undefined` (a sloppy function substitutes the global object).
11431 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
11432 self.push(result);
11433 }
11434 }
11435 CallConstructor => {
11436 // `constructor this_obj args… -> object`. The duplicated
11437 // constructor is `new.target`; this milestone does not expose it,
11438 // so the extra copy is simply consumed here.
11439 let argc = a as usize;
11440 let args = self.pop_n(argc);
11441 let new_target = self.pop();
11442 let callee = self.pop();
11443 let result = self.construct(callee, new_target, args)?;
11444 self.push(result);
11445 }
11446 CallMethod => {
11447 let argc = a as usize;
11448 let args = self.pop_n(argc);
11449 let callee = self.pop();
11450 let this = self.pop();
11451 if let Some(result) = self.call_or_push(callee, this, args)? {
11452 self.push(result);
11453 }
11454 }
11455 Apply => {
11456 // `func this array -> result`, the spread-call form: the compiler
11457 // builds one array of arguments, and all that is left here is to
11458 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
11459 let array = self.pop();
11460 let this = self.pop();
11461 let callee = self.pop();
11462 let args = self.array_like_to_args(&array)?;
11463 if a & 1 != 0 {
11464 let result = self.construct(callee, this, args)?;
11465 self.push(result);
11466 } else if let Some(result) = self.call_or_push(callee, this, args)? {
11467 self.push(result);
11468 }
11469 }
11470 TailCall | TailCallMethod => {
11471 // `tail_call` is `call` whose result is returned immediately — the
11472 // reference jumps straight to `done` instead of storing the value and
11473 // running on. The callee still gets its own frame, so deep tail
11474 // recursion hits the stack limit exactly like plain recursion does;
11475 // marking this frame lets the return path unwind without needing
11476 // instructions after the call.
11477 let argc = if op == TailCallMethod {
11478 a as usize
11479 } else {
11480 self.argc_operand(op, a)
11481 };
11482 let args = self.pop_n(argc);
11483 let callee = self.pop();
11484 let this = if op == TailCallMethod {
11485 self.pop()
11486 } else {
11487 Value::Undefined
11488 };
11489 if let Value::Object(function) = &callee
11490 && let Some((code, env)) = bytecode_of(function)
11491 {
11492 // A generator or async body is not run here at all: calling it only
11493 // *creates* the generator/coroutine, so it must not inherit this
11494 // frame. Doing so made `function f(){ return g() }` push `g`'s body
11495 // onto `f`'s frame, and the first `yield`/`await` then reported
11496 // "a generator body ran as an ordinary call".
11497 if code.code.kind.is_generator() || code.code.kind.is_async() {
11498 let value = self.call_value(callee, this, args)?;
11499 return Ok(Step::Return(value));
11500 }
11501 self.frame_mut().tail = true;
11502 self.push_frame(code, env, this, args, callee)?;
11503 return Ok(Step::Continue);
11504 }
11505 // A native callee has no frame to reuse, so its value is simply
11506 // returned.
11507 let value = self.call_value(callee, this, args)?;
11508 return Ok(Step::Return(value));
11509 }
11510
11511 // -- objects ----------------------------------------------------
11512 SpecialObject => {
11513 let value = self.special_object(a)?;
11514 self.push(value);
11515 }
11516 PrivateSymbol => {
11517 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
11518 // symbol each time it is evaluated, which is why the compiler evaluates it
11519 // once (at class definition) and stores it in a class-scope binding.
11520 let name = self.atom_text(a as usize);
11521 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
11522 self.push(Value::Symbol(symbol));
11523 }
11524 GetPrivateField => {
11525 // `obj symbol -> value`. A missing private field is a TypeError, which is what
11526 // makes `#x` inaccessible on any object not built by this class.
11527 let symbol = self.pop();
11528 let object = self.pop();
11529 let value = self.read_private_field(&object, &symbol)?;
11530 self.push(value);
11531 }
11532 PutPrivateField => {
11533 // `obj value symbol ->`, and the store is a plain assignment to a property the
11534 // class already created, so there is no setter to consult.
11535 let symbol = self.pop();
11536 let value = self.pop();
11537 let object = self.pop();
11538 self.write_private_field(&object, &symbol, value)?;
11539 }
11540 DefinePrivateField => {
11541 // `obj symbol value -> obj`: a field initialiser creates the property, and
11542 // redefining one is a TypeError ("already exists").
11543 let value = self.pop();
11544 let symbol = self.pop();
11545 let object = self.pop();
11546 self.define_private_field(&object, &symbol, value)?;
11547 self.push(object);
11548 }
11549 PrivateIn => {
11550 // `obj key -> bool`: `#x in o`. The second operand decides which question is
11551 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
11552 // is a field, so this is an own-property test; a *function* is a method or
11553 // accessor, so this is a brand check.
11554 let key = self.pop();
11555 let object = self.pop();
11556 let Some(target) = object.as_object() else {
11557 return Err(Signal::Throw(
11558 self.make_error("TypeError", "invalid 'in' operand"),
11559 ));
11560 };
11561 let present = match &key {
11562 Value::Object(_) => self.check_brand(target, &key)?,
11563 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
11564 };
11565 self.push(Value::Bool(present));
11566 }
11567 AddBrand => {
11568 // `obj home ->`: create the class brand on `home` if it has none, then give
11569 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
11570 // class definition: only the prototype's copy of the symbol is wanted.
11571 let home = self.pop();
11572 let object = self.pop();
11573 self.add_brand(&object, &home)?;
11574 }
11575 CheckBrand => {
11576 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
11577 // Both stay, because the caller needs them — `nip` halves a read into its
11578 // value and `call_method` uses the pair as receiver and callee.
11579 let function = self.peek(0);
11580 let object = self.peek(1);
11581 let Some(target) = object.as_object() else {
11582 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11583 };
11584 if !self.check_brand(target, &function)? {
11585 return Err(Signal::Throw(
11586 self.make_error("TypeError", "invalid brand on object"),
11587 ));
11588 }
11589 }
11590 GetLength => {
11591 // `get_length` is the `.length` read; an array and a string answer
11592 // from their own length, anything else from the property.
11593 let target = self.pop();
11594 let value = match &target {
11595 Value::Object(object) => match object.array_length() {
11596 Some(length) => crate::object::length_value(length),
11597 None => self.read_field(&target, "length")?,
11598 },
11599 Value::String(text) => Value::Int(text.utf16_len() as i32),
11600 _ => self.read_field(&target, "length")?,
11601 };
11602 self.push(value);
11603 }
11604 GetField | GetField2 => {
11605 let object = self.pop();
11606 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
11607 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
11608 // just below is what lets the borrow outlive the `&mut self` the lookup
11609 // needs — one refcount bump instead of a key clone plus its drop, on the
11610 // hottest property path there is: every `o.x` and every `o.m()` receiver.
11611 let code = self.frame().code.clone();
11612 let key = &code.atom_keys[a as usize];
11613 let value = self.read_field_cached(&object, key, next)?;
11614 if op == GetField2 {
11615 self.push(object);
11616 }
11617 self.push(value);
11618 }
11619 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
11620 let key = self.pop();
11621 let object = self.pop();
11622 let key = self.propkey(&key)?;
11623 let value = self.read_field_key(&object, &key)?;
11624 if matches!(op, GetArrayEl2 | GetArrayEl3) {
11625 self.push(object);
11626 }
11627 if op == GetArrayEl3 {
11628 // The key goes back in its *value* form, which the compiler stores
11629 // into the target of a destructuring assignment.
11630 self.push(match &key {
11631 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11632 PropertyKey::String(text) => self.string_wtf8(text.clone()),
11633 });
11634 }
11635 self.push(value);
11636 }
11637 PutField => {
11638 let value = self.pop();
11639 let object = self.pop();
11640 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
11641 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
11642 // only reads. `this.value = …` is the write half of the hottest loop in
11643 // `property:method-call`, and `own_property_key` was 4.8% of the case.
11644 let code = self.frame().code.clone();
11645 let key = &code.atom_keys[a as usize];
11646 self.write_field_key(&object, key, value)?;
11647 }
11648 PutArrayEl => {
11649 let value = self.pop();
11650 let key = self.pop();
11651 let object = self.pop();
11652 let key = self.propkey(&key)?;
11653 self.write_field_key(&object, &key, value)?;
11654 }
11655 DefineField => {
11656 let value = self.pop();
11657 let object = self.pop();
11658 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
11659 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
11660 // three U+FFFD — a property under a different name from the one
11661 // `o["\uD800"]` reads.
11662 let code = self.frame().code.clone();
11663 let key = code.atom_keys[a as usize].clone();
11664 // No naming here. `{m: function(){}}` is named by the *compiler*, which
11665 // emits `set_name` — and only where `NamedEvaluation` applies, so
11666 // `{m: (0, function(){})}` stays anonymous. Naming every function that
11667 // reaches a property definition got that case wrong, and the compiler is
11668 // the only place that can tell the two apart.
11669 if let Some(target) = object.as_object() {
11670 // Only an *array* stores into the element vector. A numeric key
11671 // on an ordinary object is an ordinary property, which is what
11672 // makes `{1: 'a'}` iterate as a key rather than disappear.
11673 let stored = target.is_array()
11674 && key.as_str().and_then(array_index).is_some_and(|index| {
11675 target.array_set(self.heap, index as usize, value.clone())
11676 });
11677 if !stored {
11678 target.define_data_key(&key, value);
11679 }
11680 }
11681 self.push(object);
11682 }
11683 DefineArrayEl => {
11684 // `obj key value -> obj key`. The *value* form of the key is what goes
11685 // back on the stack — the compiler stores it into the pattern's binding —
11686 // so the symbol is not stringified on the way through.
11687 let value = self.pop();
11688 let key_value = self.pop();
11689 let object = self.peek(0);
11690 let key = self.propkey(&key_value)?;
11691 self.write_field_key(&object, &key, value)?;
11692 self.push(key_value);
11693 }
11694 SetHomeObject => {
11695 // `obj func -> obj func`: records the object a method was defined on so
11696 // `super` inside it resolves against that object's prototype.
11697 let function = self.peek(0);
11698 let home = self.peek(1);
11699 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
11700 function.set_home_object(Some(home.clone()));
11701 }
11702 }
11703 Regexp => {
11704 // `pattern flags -> regexp`. A literal compiles here rather than through the
11705 // constructor, which is both what the reference's dedicated opcode is for
11706 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
11707 let flags = self.pop();
11708 let pattern = self.pop();
11709 let pattern = self.to_js_string(&pattern)?;
11710 let flags = self.to_js_string(&flags)?;
11711 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
11712 self.push(Value::Object(object));
11713 }
11714 UsingDisposeInit => {
11715 // The error state a disposal accumulates into. Uninitialised means "no
11716 // failure yet"; anything else is the exception being propagated.
11717 self.push(Value::Uninitialized);
11718 }
11719 UsingCheck => {
11720 // `value -> value, method`: validate and snapshot the disposer now, so a
11721 // later change to `Symbol.dispose` cannot change what gets called, and so a
11722 // value that is not disposable fails before the body runs.
11723 let value = self.pop();
11724 let method = self.using_method_for(&value, a as u8 == 1)?;
11725 self.push(value);
11726 self.push(method);
11727 }
11728 UsingDispose => {
11729 // `error_state -> error_state'`: dispose the variable at `slot` — its value
11730 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
11731 // the pending error.
11732 let slot = self.slot_operand(op, a);
11733 let error_state = self.pop();
11734 let merged = self.using_dispose_once(slot, error_state)?;
11735 self.push(merged);
11736 }
11737 UsingDisposeMerge => {
11738 let new_error = self.pop();
11739 let error_state = self.pop();
11740 let merged = self.merge_dispose_error(new_error, error_state);
11741 self.push(merged);
11742 }
11743 UsingDisposeEnd => {
11744 // A disposal that failed replaces the block's normal completion, so the
11745 // error state becomes a real throw here rather than at the call site.
11746 let error_state = self.pop();
11747 if !matches!(error_state, Value::Uninitialized) {
11748 return Err(Signal::Throw(error_state));
11749 }
11750 }
11751 UsingDisposeAsync => {
11752 // `await using` needs a promise to await and this runtime has no
11753 // `Promise` builtin, so the disposer is called synchronously and its result
11754 // discarded. That is correct for a disposer that returns nothing and is
11755 // reported as a gap rather than silently skipped.
11756 let slot = self.slot_operand(op, a);
11757 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
11758 self.push(error_state);
11759 }
11760 GetSuper => {
11761 // `obj -> obj's prototype`: the starting point of a `super` lookup.
11762 let object = self.pop();
11763 let proto = match &object {
11764 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
11765 _ => Value::Null,
11766 };
11767 self.push(proto);
11768 }
11769 GetSuperValue => {
11770 // `receiver proto key -> value`, searching from `proto` but reporting to
11771 // `receiver`, which is what `super.g` must do for a getter to see `this`.
11772 //
11773 // Three values in, one out: the receiver is *consumed*, not left under the
11774 // result. Leaving it there was invisible for `super.x` in `return` or
11775 // statement position (the result is what gets popped) and corrupted the
11776 // frame everywhere else — `print(super.x)` left the class where the call
11777 // opcode looks for the receiver and called the class itself.
11778 let key = self.pop();
11779 let proto = self.pop();
11780 let receiver = self.pop();
11781 let value = self.super_read(&receiver, &proto, &key)?;
11782 self.push(value);
11783 }
11784 PutSuperValue => {
11785 // `receiver proto key value ->`: a store that starts at `proto` but
11786 // assigns to `receiver`.
11787 let value = self.pop();
11788 let key = self.pop();
11789 let proto = self.pop();
11790 let receiver = self.pop();
11791 self.super_write(&receiver, &proto, &key, value)?;
11792 }
11793 DefineClass => {
11794 // `parent ctor -> ctor proto`: the constructor becomes the class and a
11795 // fresh prototype object lands on top for the methods to go on.
11796 let name = self.atom_text(a as usize);
11797 let (ctor, proto) = self.define_class(&name, b)?;
11798 self.push(ctor);
11799 self.push(Value::Object(proto));
11800 }
11801 DefineClassComputed => {
11802 // `parent ctor key -> ctor proto key`: the computed name stays put so
11803 // `define_field`-style consumers can still read it.
11804 let key = self.pop();
11805 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11806 let (ctor, proto) = self.define_class(&name, b)?;
11807 self.push(ctor);
11808 self.push(Value::Object(proto));
11809 self.push(key);
11810 }
11811 DefineMethod => {
11812 let function = self.pop();
11813 let object = self.pop();
11814 // The exact key, like `define_field`: a quoted method key may hold an
11815 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
11816 // that `o["\uD800"]` finds.
11817 let code = self.frame().code.clone();
11818 let key = code.atom_keys[a as usize].clone();
11819 // A method's `[[HomeObject]]` is the object it was defined on, which is
11820 // what `super` inside it resolves against.
11821 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11822 function.set_home_object(Some(object.clone()));
11823 }
11824 if let Some(text) = key.as_wtf8() {
11825 self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
11826 } else {
11827 self.set_function_name(
11828 &function,
11829 &key_with_accessor_prefix(&key.to_string(), b),
11830 );
11831 }
11832 if let Some(array) = object.as_object() {
11833 define_function_property(array, &key, function, b);
11834 }
11835 self.push(object);
11836 }
11837 DefineMethodComputed => {
11838 let function = self.pop();
11839 let key = self.pop();
11840 let object = self.pop();
11841 let key = self.propkey(&key)?;
11842 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
11843 // the name: `super` inside a computed method resolves through it. Without
11844 // this, `class B extends A { [k]() { return super.m() } }` read the
11845 // home object as null and threw.
11846 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11847 function.set_home_object(Some(object.clone()));
11848 }
11849 match key.as_wtf8() {
11850 Some(text) => {
11851 let name = accessor_prefixed(text, a);
11852 self.set_function_name_wtf8(&function, &name);
11853 }
11854 None => self.set_function_name(
11855 &function,
11856 &key_with_accessor_prefix(&key.to_string(), a),
11857 ),
11858 }
11859 if let Some(array) = object.as_object() {
11860 define_function_property(array, &key, function, a);
11861 }
11862 self.push(object);
11863 }
11864 SetProto => {
11865 let proto = self.pop();
11866 let object = self.pop();
11867 if let Some(target) = object.as_object() {
11868 target.set_proto(proto.as_object().cloned());
11869 }
11870 self.push(object);
11871 }
11872 CopyDataProperties => {
11873 let exclusion = self.pop();
11874 let source = self.pop();
11875 let target = self.peek(0);
11876 self.copy_properties(&target, &source, &exclusion)?;
11877 self.push(source);
11878 self.push(exclusion);
11879 }
11880 ToPropkey => {
11881 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
11882 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
11883 // ordinary `"Symbol(b)"` property.
11884 let value = self.pop();
11885 let key = match self.propkey(&value)? {
11886 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
11887 PropertyKey::String(text) => self.string_wtf8(text),
11888 };
11889 self.push(key);
11890 }
11891 SetName => {
11892 let function = self.peek(0);
11893 let name = self.atom_wtf8(a as usize);
11894 self.set_function_name_wtf8(&function, &name);
11895 }
11896 SetNameComputed => {
11897 let key = self.peek(1);
11898 let function = self.peek(0);
11899 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11900 self.set_function_name(&function, &name);
11901 }
11902
11903 // -- arrays -----------------------------------------------------
11904 ArrayFrom => {
11905 let count = a as usize;
11906 let elements = self.pop_n(count);
11907 let array = self.new_array(elements);
11908 self.push(Value::Object(array));
11909 }
11910 Append => {
11911 // `array index iterable -> array new_index`
11912 let iterable = self.pop();
11913 self.pop();
11914 let array = self.peek(0);
11915 let added = self.append_enumerate(&array, &iterable)?;
11916 self.push(Value::Int(added));
11917 }
11918
11919 // -- iteration --------------------------------------------------
11920 ForInStart => {
11921 let value = self.pop();
11922 let record = self.for_in_record(&value)?;
11923 self.push(Value::Object(record));
11924 }
11925 ForInNext => {
11926 // `record -> record key done`. The flag is *done*, not "found":
11927 // the compiler tests it with `if_false` to jump back into the body,
11928 // so reporting `true` while keys remain would end the loop at once.
11929 let record = self.peek(0);
11930 match self.for_in_advance(&record)? {
11931 Some(key) => {
11932 let text = self.string(key);
11933 self.push(text);
11934 self.push(Value::Bool(false));
11935 }
11936 None => {
11937 self.push(Value::Undefined);
11938 self.push(Value::Bool(true));
11939 }
11940 }
11941 }
11942 ForOfStart => {
11943 let value = self.pop();
11944 let iterator = self.get_iterator(&value)?;
11945 self.push(iterator.object);
11946 self.push(iterator.next);
11947 self.push(Value::CatchOffset(0));
11948 }
11949 ForOfNext => {
11950 // `iter next catch_offset -> iter next catch_offset value done`.
11951 //
11952 // The operand is how many values sit *above* the iterator triple: a
11953 // destructuring rest element keeps its target array and running index
11954 // there while draining the iterator, so the triple is not at the top.
11955 let extra = a as usize;
11956 let iterator_slot = 2 + extra;
11957 // An exhausted iterator is replaced by `undefined` (see below), so a
11958 // second step must not call `next` again — `Array.from` and a
11959 // destructuring pattern both keep stepping past the end.
11960 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
11961 (Value::Undefined, true)
11962 } else {
11963 let iterator = Iterator {
11964 object: self.peek(iterator_slot),
11965 next: self.peek(1 + extra),
11966 };
11967 self.iterator_step(&iterator)?
11968 };
11969 if done {
11970 // The result's `value` is meaningless once the iterator is done:
11971 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
11972 // rather than binding the generator's return value.
11973 let top = self.frame().stack.len() - 1 - iterator_slot;
11974 self.frame_mut().stack[top] = Value::Undefined;
11975 self.push(Value::Undefined);
11976 self.push(Value::Bool(true));
11977 } else {
11978 self.push(value);
11979 self.push(Value::Bool(false));
11980 }
11981 }
11982 IteratorNext => {
11983 // `iter next catch val -> iter next catch val'`: replace the argument with
11984 // the result of `next(val)`. The triple below stays put, which is why the
11985 // three instructions of the `yield*` loop all address the stack the same way.
11986 let value = self.pop();
11987 let object = self.peek(2);
11988 let next = self.peek(1);
11989 let result = self.call_value(next, object, vec![value])?;
11990 self.push(result);
11991 }
11992 IteratorCall => {
11993 // `iter next catch val -> iter next catch val' flag`.
11994 //
11995 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
11996 // The flag is `true` when the method was missing, which is how the
11997 // caller learns that the inner iterator cannot take part in the
11998 // unwinding.
11999 let value = self.pop();
12000 let object = self.peek(2);
12001 let key = if a & 1 != 0 { "throw" } else { "return" };
12002 let method = self.read_field(&object, key)?;
12003 if matches!(method, Value::Undefined | Value::Null) {
12004 self.push(value);
12005 self.push(Value::Bool(true));
12006 } else {
12007 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
12008 let result = self.call_value(method, object, argument)?;
12009 self.push(result);
12010 self.push(Value::Bool(false));
12011 }
12012 }
12013 IteratorCheckObject => {
12014 if !matches!(self.peek(0), Value::Object(_)) {
12015 return Err(Signal::Throw(
12016 self.make_error("TypeError", "iterator must return an object"),
12017 ));
12018 }
12019 }
12020 IteratorClose => {
12021 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
12022 // calling the iterator's `return` so it can release whatever it holds.
12023 //
12024 // The catch offset goes first, so an exception from `return` is not caught
12025 // by the loop being abandoned. This used to pop the three operands and call
12026 // nothing at all, which made `break` out of a `for of` invisible to an
12027 // iterator with a `return` method.
12028 self.pop();
12029 self.pop();
12030 let iterator = self.pop();
12031 if !matches!(iterator, Value::Undefined) {
12032 let method = self.read_field(&iterator, "return")?;
12033 if !matches!(method, Value::Undefined | Value::Null) {
12034 let result = self.call_value(method, iterator.clone(), Vec::new())?;
12035 // §7.4.6: a `return` that answers a non-object is a TypeError.
12036 if !matches!(result, Value::Object(_)) {
12037 return Err(Signal::Throw(
12038 self.make_error("TypeError", "iterator must return an object"),
12039 ));
12040 }
12041 }
12042 }
12043 }
12044 Import => {
12045 // `import(specifier, options)`: the options slot is on top. Both are
12046 // `GetValue`-ed by the compiler, which is why this pops values rather than
12047 // references — and why the validation of `options` (§13.3.10.1 step 10)
12048 // happens inside `dynamic_import`, where its failures can be turned into a
12049 // rejection instead of a throw.
12050 let options = self.pop();
12051 let specifier = self.pop();
12052 let promise = self.dynamic_import(specifier, options)?;
12053 self.push(promise);
12054 }
12055 ForAwaitOfStart => {
12056 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
12057 // `Symbol.iterator` fallback.
12058 let value = self.pop();
12059 let iterator = self.get_async_iterator(&value)?;
12060 self.push(iterator.object);
12061 self.push(iterator.next);
12062 self.push(Value::CatchOffset(0));
12063 }
12064 ForAwaitOfNext => {
12065 // `for await` steps the iterator and leaves the *result* wrapped in a
12066 // promise, so the `await` the compiler emits right after this can suspend
12067 // on it. Unwrapping happens in `iterator_get_value_done`.
12068 let extra = a as usize;
12069 let iterator_slot = 2 + extra;
12070 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
12071 Value::Undefined
12072 } else {
12073 let iterator = Iterator {
12074 object: self.peek(iterator_slot),
12075 next: self.peek(1 + extra),
12076 };
12077 let next = iterator.next.clone();
12078 self.call_value(next, iterator.object, Vec::new())?
12079 };
12080 let promise = self.promise_resolve_value(result)?;
12081 self.push(promise);
12082 }
12083 IteratorGetValueDone => {
12084 // `result -> value done`. A missing result object means the iterator was
12085 // already exhausted, which the loop treats as `done`.
12086 let result = self.pop();
12087 let done = match &result {
12088 Value::Object(object) => self
12089 .get_property(object, "done")?
12090 .is_some_and(|value| value.to_boolean()),
12091 _ => true,
12092 };
12093 if done {
12094 // Clear the iterator object so the `iterator_close` the loop emits on
12095 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
12096 // on normal completion, and this is where a normal completion is
12097 // recognised — the same trick `for_of_next` uses, which also replaces
12098 // the slot with `undefined`.
12099 //
12100 // The layout is fixed because only `for await` emits this opcode:
12101 // `iter next catch [result]`, so the iterator is three below the top.
12102 let depth = self.frame().stack.len();
12103 if depth >= 3 {
12104 self.frame_mut().stack[depth - 3] = Value::Undefined;
12105 }
12106 self.push(Value::Undefined);
12107 self.push(Value::Bool(true));
12108 } else {
12109 let Value::Object(object) = &result else {
12110 self.push(Value::Undefined);
12111 self.push(Value::Bool(true));
12112 return Ok(Step::Continue);
12113 };
12114 let value = self
12115 .get_property(object, "value")?
12116 .unwrap_or(Value::Undefined);
12117 self.push(value);
12118 self.push(Value::Bool(false));
12119 }
12120 }
12121
12122 Delete => {
12123 // `delete obj[key]`, where the key was just pushed. Deleting an array
12124 // index leaves a *hole* rather than closing the gap, and a
12125 // non-configurable property answers `false` and stays.
12126 let key = self.pop();
12127 let target = self.pop();
12128 let key = self.propkey(&key)?;
12129 let text_label = key.as_str().unwrap_or("").to_string();
12130 let deleted = match &target {
12131 Value::Object(object) => {
12132 let object = object.clone();
12133 self.delete_property_key(&object, &key)?
12134 }
12135 // A string's `length` and its index properties are
12136 // non-configurable, so deleting one answers `false`.
12137 Value::String(text) => {
12138 !(text_label == "length"
12139 || array_index(&text_label)
12140 .is_some_and(|index| (index as usize) < text.utf16_len()))
12141 }
12142 // "delete null.a" is a TypeError, not a no-op: the operator needs an
12143 // object to delete from, and only a *boxable* primitive has one.
12144 Value::Undefined | Value::Null => {
12145 return Err(Signal::Throw(
12146 self.make_error("TypeError", "cannot convert to object"),
12147 ));
12148 }
12149 // Any other primitive has no own properties; deleting nothing
12150 // succeeds.
12151 _ => true,
12152 };
12153 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
12154 // `TypeError` rather than a `false` result. Sloppy mode silently reports
12155 // the refusal, which is why the same statement throws here but not there.
12156 if !deleted && self.current_strict() {
12157 return Err(Signal::Throw(
12158 self.make_error("TypeError", "cannot delete property"),
12159 ));
12160 }
12161 self.push(Value::Bool(deleted));
12162 }
12163
12164 // -- exceptions and bookkeeping ---------------------------------
12165 Fclosure | Fclosure8 => {
12166 let value = self.closure(a as usize)?;
12167 self.push(value);
12168 }
12169
12170 other => {
12171 let name = other.info().name;
12172 return Err(Signal::Throw(self.make_error(
12173 "InternalError",
12174 &format!("{name} is not implemented yet"),
12175 )));
12176 }
12177 }
12178 Ok(Step::Continue)
12179 }
12180
12181 // -- operand helpers ----------------------------------------------------
12182
12183 /// The slot index an operand names, taking short forms into account.
12184 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
12185 use Opcode::*;
12186 match op {
12187 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
12188 | SetVarRef0 => 0,
12189 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
12190 | SetVarRef1 => 1,
12191 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
12192 | SetVarRef2 => 2,
12193 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
12194 | SetVarRef3 => 3,
12195 _ => a as usize,
12196 }
12197 }
12198
12199 /// The argument count of a call, taking `call0`…`call3` into account.
12200 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
12201 use Opcode::*;
12202 match op {
12203 Call0 => 0,
12204 Call1 => 1,
12205 Call2 => 2,
12206 Call3 => 3,
12207 _ => a as usize,
12208 }
12209 }
12210
12211 /// The atom's name as a property key.
12212 ///
12213 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
12214 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
12215 /// `String::clone` was a heap allocation and a copy — per property access.
12216 /// The atom at `index`, as a property key.
12217 ///
12218 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
12219 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
12220 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
12221 /// 5.3% of `property:monomorphic`.
12222 /// The atom's text, exactly — including an unpaired surrogate.
12223 ///
12224 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
12225 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
12226 /// `atom_text` below is for the other kind of use, where the atom is a key in the
12227 /// engine's own tables.
12228 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
12229 self.frame()
12230 .code
12231 .code
12232 .atoms
12233 .get(index)
12234 .map(|atom| match atom {
12235 Atom::Str(text) => text.clone(),
12236 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
12237 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
12238 Atom::Null => crate::value::Wtf8::new(String::new()),
12239 })
12240 .unwrap_or_default()
12241 }
12242
12243 fn atom_text(&self, index: usize) -> String {
12244 self.frame()
12245 .code
12246 .code
12247 .atoms
12248 .get(index)
12249 .map(|atom| match atom {
12250 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
12251 // compare it to an identifier, and a surrogate-bearing name is reachable
12252 // through `atom_wtf8` where it matters.
12253 Atom::Str(text) => text.to_string_lossy().into_owned(),
12254 Atom::Index(value) => value.to_string(),
12255 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
12256 // `throw_error`, `delete super.x`) never read it.
12257 Atom::Null => String::new(),
12258 })
12259 .unwrap_or_default()
12260 }
12261
12262 fn constant(&mut self, index: usize) -> JsResult<Value> {
12263 let constant = self.frame().code.code.cpool.get(index).cloned();
12264 Ok(match &constant {
12265 Some(Constant::Number(number)) => Value::Float(*number),
12266 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
12267 Some(Constant::BigInt { digits, radix }) => {
12268 match crate::bigint::BigInt::from_radix(digits, *radix) {
12269 Some(big) => self.bigint(big),
12270 // A literal the parser accepted is always parseable; a failure here
12271 // would be a compiler bug, so it reads as an `InternalError`.
12272 None => {
12273 return Err(Signal::Throw(
12274 self.make_error("InternalError", "unparseable bigint literal"),
12275 ));
12276 }
12277 }
12278 }
12279 Some(Constant::Function(_)) => {
12280 return Err(Signal::Throw(
12281 self.make_error("InternalError", "a bare function constant"),
12282 ));
12283 }
12284 // A tagged template's call site: a frozen array of the cooked chunks with a
12285 // frozen `raw` array beside it, which is what `String.raw` reads back.
12286 Some(Constant::Template { cooked, raw }) => {
12287 let cooked_values: Vec<Value> = cooked
12288 .iter()
12289 .map(|chunk| match chunk {
12290 Some(text) => self.string_wtf8(text.clone()),
12291 None => Value::Undefined,
12292 })
12293 .collect();
12294 let raw_values: Vec<Value> =
12295 raw.iter().map(|text| self.string(text.clone())).collect();
12296 let raw_array = self.new_array(raw_values);
12297 raw_array.set_extensible(false);
12298 let template = self.new_array(cooked_values);
12299 template.define(
12300 "raw",
12301 Property::with_attributes(Value::Object(raw_array), false, false),
12302 );
12303 template.set_extensible(false);
12304 Value::Object(template)
12305 }
12306 _ => Value::Undefined,
12307 })
12308 }
12309
12310 /// The reference cell a closure-variable slot names.
12311 ///
12312 /// Two kinds of binding share this addressing: a genuine closure variable
12313 /// (captured from an enclosing function) lives in this frame's environment,
12314 /// while a *declared global* lives in the realm so that a script, a function
12315 /// declaration and their uses all see one binding. A plain `Global` — an
12316 /// undeclared name that may be satisfied by the global object — has no cell at
12317 /// all, which is how `typeof x` still works for a name that does not exist.
12318 /// The reference cell a closure-variable slot names.
12319 ///
12320 /// The environment is resolved once, when the closure is built, and this is
12321 /// just the lookup afterwards. A *declared global* is in there too, pointing at
12322 /// the realm's cell, so a script, a hoisted function declaration and their uses
12323 /// all share one binding. A plain `Global` — a name the script never declared —
12324 /// is read and written through `get_var`/`put_var` by name instead, which is
12325 /// what lets the global object satisfy it.
12326 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
12327 self.frame().env.cells.get(slot).cloned()
12328 }
12329
12330 /// Whether `slot` refers to a global binding through the reference table.
12331 ///
12332 /// A global's cell in the closure environment only exists so the slot has
12333 /// something to point at; the binding itself lives on the global object (a `var`)
12334 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
12335 /// be routed, not performed on the placeholder.
12336 fn is_global_slot(&self, slot: usize) -> bool {
12337 self.frame()
12338 .code
12339 .code
12340 .closure_vars
12341 .get(slot)
12342 .is_some_and(|c| {
12343 // A module's declarations and imports are *not* globals: their cells are
12344 // the module environment's, filled by the host, so the placeholder routing
12345 // must not apply to them.
12346 matches!(
12347 c.closure_type,
12348 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
12349 )
12350 })
12351 }
12352
12353 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
12354 if self.is_global_slot(slot) {
12355 return self.get_global(slot);
12356 }
12357 Ok(self
12358 .var_ref_cell(slot)
12359 .map(|cell| cell.get())
12360 .unwrap_or(Value::Undefined))
12361 }
12362
12363 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
12364 // A function declaration is hoisted by storing into a global reference before
12365 // the body runs, so this path is also what puts it on the global object.
12366 if self.is_global_slot(slot) {
12367 return self.put_global(slot, value);
12368 }
12369 if let Some(cell) = self.var_ref_cell(slot) {
12370 cell.set(value);
12371 }
12372 Ok(())
12373 }
12374
12375 // -- closures -----------------------------------------------------------
12376
12377 /// Build the closure for the function constant `index`.
12378 ///
12379 /// Every entry in the child's closure table names where its binding lives in
12380 /// *this* frame: a local or argument slot that was marked captured, or a cell
12381 /// this frame is itself holding. That is how a variable three functions deep
12382 /// stays one binding.
12383 fn closure(&mut self, index: usize) -> JsResult<Value> {
12384 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
12385 else {
12386 return Err(Signal::Throw(
12387 self.make_error("InternalError", "fclosure of a non-function"),
12388 ));
12389 };
12390 let mut cells = Vec::with_capacity(function.closure_vars.len());
12391 for closure_var in &function.closure_vars {
12392 let cell = match closure_var.closure_type {
12393 ClosureType::Arg => {
12394 let slot = closure_var.var_idx as usize;
12395 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
12396 }
12397 ClosureType::Local => {
12398 let slot = closure_var.var_idx as usize;
12399 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
12400 }
12401 ClosureType::Ref | ClosureType::GlobalRef => {
12402 // A `Ref` names a cell in this frame's own closure table; a
12403 // `GlobalRef` also starts there, then resolves by name below.
12404 let slot = closure_var.var_idx as usize;
12405 if let Some(cell) = self.frame().env.cells.get(slot) {
12406 cells.push(cell.clone());
12407 continue;
12408 }
12409 -1
12410 }
12411 _ => -1,
12412 };
12413 if cell >= 0 {
12414 let cell = self.frame().cells[cell as usize].clone();
12415 cells.push(cell);
12416 continue;
12417 }
12418 // A global: the cell is created on demand and shared through the realm,
12419 // so every function sees one binding.
12420 let name = closure_var.name.clone();
12421 let cell = match self.realm.globals.get(&name) {
12422 Some(cell) => cell.clone(),
12423 None => {
12424 let cell = self.new_cell(Value::Undefined);
12425 self.realm.globals.insert(name.clone(), cell.clone());
12426 cell
12427 }
12428 };
12429 cells.push(cell);
12430 }
12431 let name = function.name.clone();
12432 // `.length` is the arity before any default or rest parameter, not the number
12433 // of slots a pattern parameter needs.
12434 let length = function.defined_args;
12435 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
12436 // function and an arrow function do not. A *method* also does not, but that is not
12437 // known here — the method is marked when the `[[HomeObject]]` is attached (see
12438 // `set_home_object`), which is the moment it becomes a method.
12439 let function_kind = function.kind;
12440 let constructible =
12441 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
12442 let code = Gc::new(self.heap, CompiledCode::new(*function));
12443 // A closure built inside an `eval` inherits the eval's view of the enclosing
12444 // bindings, so it can still read them once the eval has returned.
12445 let eval_scope = self
12446 .active_eval_scope
12447 .clone()
12448 .or_else(|| self.frame().env.eval_scope.clone());
12449 // A closure sees the variables a direct `eval` declared in the frame it was
12450 // created in — the ones declared before *and after* it, so the same object is
12451 // shared; only the phase bounds which of them are visible.
12452 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
12453 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
12454 let env = Gc::new(
12455 self.heap,
12456 ClosureEnv {
12457 cells,
12458 eval_scope,
12459 local_vars,
12460 local_phase,
12461 },
12462 );
12463 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
12464 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
12465 // the only thing that carries `Symbol.toStringTag`, so without it
12466 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
12467 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
12468 let proto = match function_kind {
12469 js_compile::bytecode::FunctionKind::AsyncGenerator => self
12470 .realm
12471 .async_generator_function_proto
12472 .clone()
12473 .or_else(|| self.realm.function_proto.clone().into()),
12474 js_compile::bytecode::FunctionKind::Generator => self
12475 .realm
12476 .generator_function_proto
12477 .clone()
12478 .or_else(|| self.realm.function_proto.clone().into()),
12479 js_compile::bytecode::FunctionKind::Async => self
12480 .realm
12481 .async_function_proto
12482 .clone()
12483 .or_else(|| self.realm.function_proto.clone().into()),
12484 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
12485 };
12486 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
12487 object.set_constructible(constructible);
12488 object.define(
12489 "length",
12490 Property::name_or_length(Value::Int(length as i32)),
12491 );
12492 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
12493 // that checks the own-property descriptor fails if the property is missing.
12494 object.define("name", Property::name_or_length(self.string(name)));
12495 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
12496 // when `[[Construct]]` is created, so an async function and an arrow function have
12497 // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
12498 // function) an own `prototype` property, which `builtin.js` checks for absence.
12499 //
12500 // A **generator** function is the exception that is not constructible: it still
12501 // gets a `prototype` field, because that object is what a generator *instance*
12502 // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
12503 // made `function* g(){}; g.prototype` `undefined` and every generator share
12504 // `%GeneratorPrototype%` as its direct prototype.
12505 if constructible {
12506 self.install_function_prototype(&object);
12507 } else if matches!(
12508 function_kind,
12509 js_compile::bytecode::FunctionKind::Generator
12510 | js_compile::bytecode::FunctionKind::AsyncGenerator
12511 ) {
12512 let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
12513 self.realm.generator_proto.clone()
12514 } else {
12515 self.realm
12516 .async_generator_proto
12517 .clone()
12518 .unwrap_or_else(|| self.realm.generator_proto.clone())
12519 };
12520 self.install_generator_prototype(&object, parent);
12521 }
12522 Ok(Value::Object(object))
12523 }
12524
12525 // -- conversions used by the operators ----------------------------------
12526
12527 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
12528 // `+x` is `ToNumber`, which for a string parses it and for an object runs
12529 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
12530 // string, which then behaves differently in every later comparison.
12531 match value {
12532 Value::Int(_) | Value::Float(_) => Ok(value),
12533 other => Ok(Value::Float(self.to_js_number(&other)?)),
12534 }
12535 }
12536
12537 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
12538 ///
12539 /// Returns the *converted* old value and the new one, because the two callers need
12540 /// different halves: `++x` yields the new value, while `x++` yields the old one and
12541 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
12542 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
12543 /// boolean.
12544 ///
12545 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
12546 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
12547 /// a bigint algorithm then ran exactly once.
12548 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
12549 if let Value::BigInt(big) = &value {
12550 let one = crate::bigint::BigInt::from_i64(1);
12551 let next = if up { big.add(&one) } else { big.sub(&one) };
12552 return Ok((value, self.bigint(next)));
12553 }
12554 let old = self.numeric(value)?;
12555 let new = if up {
12556 increment(old.clone())
12557 } else {
12558 decrement(old.clone())
12559 };
12560 Ok((old, new))
12561 }
12562
12563 fn numeric(&mut self, value: Value) -> JsResult<Value> {
12564 // `ToNumber` on an object runs `ToPrimitive` first, which is how
12565 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
12566 // heard at all. Reading the object's own tag instead (`other.to_number()`)
12567 // turned the whole operand into `NaN` and swallowed the exception.
12568 match value {
12569 Value::Int(_) | Value::Float(_) => Ok(value),
12570 other => Ok(Value::Float(self.to_js_number(&other)?)),
12571 }
12572 }
12573
12574 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
12575 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
12576 match value {
12577 Value::BigInt(big) => Ok((**big).clone()),
12578 // The reference words this the same way for every operator, so a failing
12579 // script reads identically; the operator itself adds nothing a caller can use.
12580 _ => Err(Signal::Throw(
12581 self.make_error("TypeError", "cannot convert bigint to number"),
12582 )),
12583 }
12584 }
12585
12586 /// Arithmetic where at least one operand is a `BigInt`.
12587 ///
12588 /// The two numeric types never mix, so a bigint paired with anything else is an error
12589 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
12590 /// that the relational operators handle it separately.
12591 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12592 use Opcode::*;
12593 let a = self.bigint_operand(&left)?;
12594 let b = self.bigint_operand(&right)?;
12595 let result = match op {
12596 Add => a.add(&b),
12597 Sub => a.sub(&b),
12598 Mul => a.mul(&b),
12599 Div | Mod => {
12600 let Some((quotient, remainder)) = a.div_rem(&b) else {
12601 return Err(Signal::Throw(
12602 self.make_error("RangeError", "division by zero"),
12603 ));
12604 };
12605 if op == Div { quotient } else { remainder }
12606 }
12607 Pow => {
12608 let Some(value) = a.pow(&b) else {
12609 return Err(Signal::Throw(self.make_error(
12610 "RangeError",
12611 "BigInt exponent must be non-negative and not absurdly large",
12612 )));
12613 };
12614 value
12615 }
12616 And => a.bitand(&b),
12617 Or => a.bitor(&b),
12618 Xor => a.bitxor(&b),
12619 Shl | Sar => {
12620 // A shift count is a `BigInt` here, and both directions are exact; a
12621 // negative count would be the other direction, which the spec forbids.
12622 let Some(count) = b.to_i64() else {
12623 return Err(Signal::Throw(
12624 self.make_error("RangeError", "BigInt shift count is too large"),
12625 ));
12626 };
12627 if count < 0 {
12628 return Err(Signal::Throw(self.make_error(
12629 "RangeError",
12630 "BigInt shift count must be non-negative",
12631 )));
12632 }
12633 if op == Shl {
12634 a.shl(count as u64)
12635 } else {
12636 a.shr(count as u64)
12637 }
12638 }
12639 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
12640 _ => {
12641 return Err(Signal::Throw(self.make_error(
12642 "TypeError",
12643 "BigInts have no unsigned right shift, use >> instead",
12644 )));
12645 }
12646 };
12647 Ok(self.bigint(result))
12648 }
12649
12650 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
12651 ///
12652 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
12653 /// is on the mathematical values, and nothing is rounded first.
12654 /// `<`, `<=`, `>`, `>=`.
12655 ///
12656 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
12657 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
12658 /// It is a `?`-returning function for exactly that reason: an object operand can run
12659 /// script, and script can throw. The old version compared `to_number` of the raw
12660 /// values, which answered `false` for every object instead of calling `valueOf` —
12661 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
12662 /// never ran.
12663 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12664 // The hot arm first: `i < n` with both sides already integers. No conversion, no
12665 // call, nothing that can throw.
12666 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12667 let ordering = Some(left.cmp(right));
12668 return Ok(ordering_answer(op, ordering));
12669 }
12670 // Anything that can run script has to be converted first, in this order.
12671 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
12672 {
12673 (
12674 self.to_primitive(left, Hint::Number)?,
12675 self.to_primitive(right, Hint::Number)?,
12676 )
12677 } else {
12678 (left, right)
12679 };
12680 let ordering = match (&left, &right) {
12681 // The loop condition `i < n` is integer against integer, and it runs once
12682 // per iteration of every loop in every program. Without this arm it took the
12683 // `to_number` path twice, which is a `match` plus a conversion each.
12684 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
12685 (Value::String(a), Value::String(b)) => {
12686 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
12687 }
12688 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
12689 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
12690 // is true even though `2.5` has no bigint form.
12691 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
12692 let b = other.to_number();
12693 if b.is_nan() {
12694 None
12695 } else {
12696 compare_bigint_and_f64(a, b)
12697 }
12698 }
12699 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
12700 let a = other.to_number();
12701 if a.is_nan() {
12702 None
12703 } else {
12704 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
12705 }
12706 }
12707 // `ToNumeric` on the pair, which refuses a Symbol rather than answering `NaN`:
12708 // `Object(Symbol()) <= ""` is a `TypeError`, and the total `to_number` made it
12709 // `false` (`Symbol/prototype/Symbol.toPrimitive/…-ordinary-toprimitive`).
12710 _ => self
12711 .to_js_number(&left)?
12712 .partial_cmp(&self.to_js_number(&right)?),
12713 };
12714 Ok(ordering_answer(op, ordering))
12715 }
12716
12717 fn binary_add(&mut self) -> JsResult<()> {
12718 let right = self.pop();
12719 let left = self.pop();
12720 // Two integers add without any of the machinery below: no `ToPrimitive` (an
12721 // `Int` is already primitive), no string check, no bigint check, no allocation.
12722 // `x += 1` in a loop is the single most common instruction sequence in real
12723 // script, and it used to walk every one of those checks before reaching the
12724 // same `checked_add`.
12725 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12726 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
12727 return Ok(());
12728 }
12729 let left = self.primitive_of(left)?;
12730 let right = self.primitive_of(right)?;
12731 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
12732 // that check comes before the bigint one: `"" + 1n` is a string, not a
12733 // mixed-type error.
12734 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
12735 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
12736 // `TypeError`, the one place a symbol and a string do not mix.
12737 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
12738 // between a copy and a rope from their lengths, and a rope is what turns
12739 // `text += "abc"` in a loop from quadratic into linear.
12740 if let (Value::String(left), Value::String(right)) = (&left, &right) {
12741 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
12742 // reports as `InternalError: string too long`.
12743 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
12744 return Err(Signal::Throw(
12745 self.make_error("InternalError", "string too long"),
12746 ));
12747 };
12748 self.push(Value::String(Gc::new(self.heap, joined)));
12749 return Ok(());
12750 }
12751 // At least one operand was not a string, so `ToString` it. This rejects a
12752 // symbol, which is the one place a symbol and a string do not mix.
12753 let left = self.checked_to_wtf8(&left)?;
12754 let right = self.checked_to_wtf8(&right)?;
12755 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
12756 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
12757 let text = left.concat(&right);
12758 self.push(self.string_wtf8(text));
12759 return Ok(());
12760 }
12761 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
12762 // not a conversion.
12763 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
12764 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
12765 self.push(value);
12766 return Ok(());
12767 }
12768 let left = self.numeric(left)?;
12769 let right = self.numeric(right)?;
12770 self.push(add_numbers(left, right));
12771 Ok(())
12772 }
12773
12774 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
12775 self.to_primitive(value, Hint::Default)
12776 }
12777
12778 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
12779 ///
12780 /// The order depends on the hint: the "number" order tries `valueOf` first and
12781 /// `toString` second, the "string" order the other way round, and the default
12782 /// hint uses the number order. A result that is still an object is a `TypeError`,
12783 /// because no built-in `valueOf`/`toString` returns one.
12784 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
12785 let Value::Object(object) = &value else {
12786 return Ok(value);
12787 };
12788 // A Date overrides the default hint to mean "string", which is what
12789 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
12790 // this, `"" + new Date()` would print the milliseconds, not the date.
12791 let hint = if hint == Hint::Default && is_date_object(self, object) {
12792 Hint::String
12793 } else {
12794 hint
12795 };
12796 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
12797 // handed the hint as a string. This is the hook a Date uses for its default hint
12798 // and a script uses to take over conversion entirely.
12799 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
12800 // `GetMethod`, not "is it a callable object": the property has to be read and then
12801 // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
12802 // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
12803 // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
12804 // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
12805 // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
12806 // callable.
12807 match self.get_property_key(object, &key)? {
12808 None | Some(Value::Undefined) | Some(Value::Null) => {}
12809 Some(Value::Object(function)) if function.is_callable() => {
12810 let hint = match hint {
12811 Hint::String => "string",
12812 Hint::Number => "number",
12813 Hint::Default => "default",
12814 };
12815 let hint = self.string(hint);
12816 let result = self.call_value(
12817 Value::Object(function),
12818 Value::Object(object.clone()),
12819 vec![hint],
12820 )?;
12821 if !matches!(result, Value::Object(_)) {
12822 return Ok(result);
12823 }
12824 return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
12825 }
12826 Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
12827 }
12828 let order: [&str; 2] = match hint {
12829 Hint::String => ["toString", "valueOf"],
12830 Hint::Number | Hint::Default => ["valueOf", "toString"],
12831 };
12832 let receiver = object.clone();
12833 for method in order {
12834 if let Some(function) = self.get_property(&receiver, method)?
12835 && matches!(&function, Value::Object(object) if object.is_callable())
12836 {
12837 let result =
12838 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
12839 if !matches!(result, Value::Object(_)) {
12840 return Ok(result);
12841 }
12842 }
12843 }
12844 Err(self.type_error("cannot convert object to primitive value"))
12845 }
12846
12847 /// `ToString` with the object case going through `ToPrimitive`.
12848 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
12849 if matches!(value, Value::Object(_)) {
12850 let primitive = self.to_primitive(value.clone(), Hint::String)?;
12851 return Ok(primitive.to_js_string());
12852 }
12853 // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
12854 // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
12855 // callers that want that strictness call [`Interp::to_string_strict`] — putting the
12856 // check here broke `String(Symbol())` and 45 cases that print a symbol.
12857 Ok(value.to_js_string())
12858 }
12859
12860 /// `ToString(value)`, with §7.1.19's symbol refusal.
12861 ///
12862 /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
12863 /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
12864 /// operations and conflating them cost 45 cases in one direction and 6 in the other.
12865 pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
12866 if matches!(value, Value::Symbol(_)) {
12867 return Err(self.type_error("cannot convert a Symbol to a string"));
12868 }
12869 if matches!(value, Value::Object(_)) {
12870 let primitive = self.to_primitive(value.clone(), Hint::String)?;
12871 if matches!(primitive, Value::Symbol(_)) {
12872 return Err(self.type_error("cannot convert a Symbol to a string"));
12873 }
12874 return Ok(primitive.to_js_string());
12875 }
12876 Ok(value.to_js_string())
12877 }
12878
12879 /// `ToString` that keeps the string's code units instead of flattening them.
12880 ///
12881 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
12882 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
12883 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12884 if matches!(value, Value::Symbol(_)) {
12885 return Err(Signal::Throw(
12886 self.make_error("TypeError", "cannot convert symbol to string"),
12887 ));
12888 }
12889 // An object runs `ToPrimitive` first, which may itself produce a symbol.
12890 let value = self.to_primitive(value.clone(), Hint::String)?;
12891 match value {
12892 Value::Symbol(_) => Err(Signal::Throw(
12893 self.make_error("TypeError", "cannot convert symbol to string"),
12894 )),
12895 Value::String(text) => Ok(text.wtf8().clone()),
12896 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
12897 }
12898 }
12899
12900 /// `ToNumber` with the object case going through `ToPrimitive`.
12901 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
12902 let value = if matches!(value, Value::Object(_)) {
12903 self.to_primitive(value.clone(), Hint::Number)?
12904 } else {
12905 value.clone()
12906 };
12907 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
12908 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
12909 // `NaN` to stay total, and the operators check for the bigint themselves — but
12910 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
12911 // refuse, and answering `NaN` made them silently wrong instead.
12912 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
12913 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
12914 match value {
12915 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
12916 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
12917 other => Ok(other.to_number()),
12918 }
12919 }
12920
12921 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
12922 /// [`ElementType::write`].
12923 ///
12924 /// This is separated from the write because both conversions are observable script —
12925 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
12926 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
12927 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
12928 /// setters, and a plain `a[i] = v`.
12929 pub(crate) fn element_value(
12930 &mut self,
12931 element: crate::builtins::typedarray::ElementType,
12932 value: Value,
12933 ) -> JsResult<Value> {
12934 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
12935 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
12936 let primitive = match &value {
12937 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
12938 _ => value,
12939 };
12940 if element.is_bigint() {
12941 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
12942 Ok(Value::BigInt(Gc::new(self.heap, big)))
12943 } else {
12944 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
12945 Ok(Value::Float(self.to_js_number(&primitive)?))
12946 }
12947 }
12948
12949 /// `ToPropertyKey`: what a computed member access uses as its key.
12950 ///
12951 /// A symbol is returned as itself, never stringified — that is what keeps
12952 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
12953 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
12954 match value {
12955 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
12956 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
12957 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
12958 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
12959 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12960 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
12961 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
12962 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
12963 other.to_js_string(),
12964 ))),
12965 },
12966 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
12967 }
12968 }
12969
12970 /// `ToPropertyKey` for the callers that can only use a string key.
12971 ///
12972 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
12973 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
12974 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
12975 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
12976 /// program continues with a value nobody asked for.
12977 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12978 use crate::value::Wtf8;
12979 Ok(match value {
12980 // A string key keeps its code units. Going through a lossy `String` would make
12981 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
12982 Value::String(text) => text.wtf8().clone(),
12983 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
12984 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
12985 // falling back to its `ToString` would print `[object Object]`.
12986 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12987 Value::String(text) => text.wtf8().clone(),
12988 other => Wtf8::new(other.to_js_string()),
12989 },
12990 other => Wtf8::new(other.to_js_string()),
12991 })
12992 }
12993
12994 // -- object operations used by instructions -----------------------------
12995
12996 /// Read `object[key]`, returning `undefined` when the property is missing.
12997 ///
12998 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
12999 /// primitive (looking through its prototype) as well as an object — which is what
13000 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
13001 /// argument needs too.
13002 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
13003 self.read_field_key(object, &PropertyKey::from(key))
13004 }
13005
13006 /// [`Interp::read_field`] with a key that may be a symbol.
13007 ///
13008 /// A symbol key never reaches the string shortcuts: a string's `length` and its
13009 /// indices are string properties, and a symbol named `length` is a different
13010 /// property that a string primitive cannot have.
13011 /// [`Interp::read_field_key`], with an inline cache in front of it.
13012 ///
13013 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
13014 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
13015 /// without this the engine walked the chain and compared ~40 property names on each
13016 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
13017 ///
13018 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
13019 /// missing property. Those answers depend on running code or on state the guard below
13020 /// does not cover, and a wrong answer here is far more expensive than a lookup.
13021 ///
13022 /// A hit is re-validated against the *whole* walked chain, not just the level that
13023 /// answered: the receiver and every prototype down to that level must still be the same
13024 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
13025 /// property-table *lengths* — which is what catches a property appearing on an
13026 /// intermediate prototype and shadowing the cached one.
13027 pub fn read_field_cached(
13028 &mut self,
13029 object: &Value,
13030 key: &PropertyKey,
13031 slot: usize,
13032 ) -> JsResult<Value> {
13033 let index = Self::field_cache_slot(object, key, slot);
13034 let Value::Object(target) = object else {
13035 return self.read_field_key(object, key);
13036 };
13037 if target.proxy_state().is_some() {
13038 return self.read_field_key(object, key);
13039 }
13040 if let Some(cached) = &self.field_cache[index]
13041 && cached.key == *key
13042 && let Some(value) = Self::cached_hit(target, cached)
13043 {
13044 return Ok(value);
13045 }
13046 let value = self.read_field_key(object, key)?;
13047 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
13048 Ok(value)
13049 }
13050
13051 /// Whether a cache entry still describes this lookup, and if so the value.
13052 ///
13053 /// The guard is the whole point of the entry: identity plus property-table length for
13054 /// every level walked. Re-checked per level rather than once at the receiving end,
13055 /// because a shadowing property can appear anywhere along the chain.
13056 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
13057 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
13058 // starts with: a clone is a reference-count bump and a drop, and for
13059 // `property:monomorphic` every single hit takes only this arm.
13060 let (weak, len) = cached.chain[0].as_ref()?;
13061 if !target.upgrades_to(weak) {
13062 return None;
13063 }
13064 if cached.level == 0 {
13065 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
13066 return target.cached_property_at(cached.index, &cached.key, *len);
13067 }
13068 if target.props_len() != *len {
13069 return None;
13070 }
13071 let mut level = 1;
13072 let mut current = target.proto()?;
13073 loop {
13074 let (weak, len) = cached.chain[level].as_ref()?;
13075 if !current.upgrades_to(weak) || current.props_len() != *len {
13076 return None;
13077 }
13078 if level == cached.level as usize {
13079 // The level that answered: the value is only reusable while the key is
13080 // still there and still a plain data property.
13081 return current.cached_data_property(cached.index, &cached.key);
13082 }
13083 current = current.proto()?;
13084 level += 1;
13085 }
13086 }
13087
13088 /// Build a cache entry for a lookup that just went through the slow path.
13089 ///
13090 /// Records the chain only when the answer came from a plain data property at a level
13091 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
13092 /// costs the next lookup the walk it would have cost anyway.
13093 fn record_field_lookup(
13094 target: &Gc<JsObject>,
13095 key: &PropertyKey,
13096 _value: Value,
13097 ) -> Option<FieldCache> {
13098 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
13099 [None, None, None];
13100 let mut current = target.clone();
13101 for level in 0..MAX_CACHED_CHAIN {
13102 chain[level] = Some((current.downgrade(), current.props_len()));
13103 if let Some((found, _)) = current.own_property_index(key) {
13104 // `own_property_index` declines an accessor and a hole, which is exactly
13105 // the set that must not be cached.
13106 return Some(FieldCache {
13107 key: key.clone(),
13108 index: found,
13109 level: level as u8,
13110 chain,
13111 });
13112 }
13113 current = current.proto()?;
13114 }
13115 None
13116 }
13117
13118 /// Which cache slot a lookup uses.
13119 ///
13120 /// Mixes the object's address, the name and the site, so that two properties of one
13121 /// object, and one property of two objects, land in different slots — which is what lets
13122 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
13123 /// other iteration.
13124 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
13125 let mut hash = match object {
13126 Value::Object(object) => object.address(),
13127 _ => 0,
13128 };
13129 hash = hash
13130 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
13131 .rotate_left(17)
13132 .wrapping_add(key.hash_code());
13133 hash = hash.wrapping_add(site.wrapping_mul(31));
13134 // The table is a power of two, so the low bits are the slot.
13135 hash & (FIELD_CACHE_SLOTS - 1)
13136 }
13137
13138 /// Read `key` from `object`, without the inline cache.
13139 ///
13140 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
13141 /// prototype chain, while the cached form answers an own data property from memory.
13142 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
13143 let text = key.as_str().unwrap_or("");
13144 let Value::Object(object) = object else {
13145 // Reading a property of `undefined`/`null` is the classic TypeError.
13146 if object.is_nullish() {
13147 return Err(Signal::Throw(self.make_error(
13148 "TypeError",
13149 &format!("cannot read property '{key}' of {}", object.to_js_string()),
13150 )));
13151 }
13152 // A string has `length` and index access without being boxed.
13153 if let Value::String(value) = object {
13154 if text == "length" {
13155 return Ok(Value::Int(value.utf16_len() as i32));
13156 }
13157 if let Some(index) = array_index(text) {
13158 return Ok(match value.wtf8().unit_at(index as usize) {
13159 Some(unit) => self.string_wtf8(unit),
13160 None => Value::Undefined,
13161 });
13162 }
13163 }
13164 // A property of a primitive is looked up on its prototype: this is what
13165 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
13166 let prototype = match object {
13167 Value::String(_) => self.realm.string_proto.clone(),
13168 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13169 Value::Bool(_) => self.realm.boolean_proto.clone(),
13170 // A symbol's methods live on `Symbol.prototype`, reached the same way —
13171 // `sym.description` reads through the prototype, not off the symbol.
13172 Value::Symbol(_) => self.realm.symbol_proto.clone(),
13173 // …and a bigint's on `BigInt.prototype`, which is how
13174 // `(255n).toString(16)` reaches its method.
13175 Value::BigInt(_) => self.realm.bigint_proto.clone(),
13176 _ => None,
13177 };
13178 if let Some(prototype) = prototype
13179 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
13180 {
13181 return Ok(value);
13182 }
13183 return Ok(Value::Undefined);
13184 };
13185 Ok(self
13186 .get_property_key(object, key)?
13187 .unwrap_or(Value::Undefined))
13188 }
13189
13190 /// The `#name` a private symbol stands for, for error messages.
13191 ///
13192 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
13193 /// was made from.
13194 fn private_name(symbol: &Value) -> Option<String> {
13195 match symbol {
13196 Value::Symbol(symbol) if symbol.is_private() => Some(
13197 symbol
13198 .description()
13199 .map(|text| text.to_string())
13200 .unwrap_or_default(),
13201 ),
13202 _ => None,
13203 }
13204 }
13205
13206 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
13207 ///
13208 /// Every private-field opcode takes the symbol the class stored in its own scope; a
13209 /// non-symbol here would be a compiler bug, and the reference guards it with
13210 /// `JS_ThrowTypeErrorNotASymbol`.
13211 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
13212 match symbol {
13213 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
13214 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
13215 }
13216 }
13217
13218 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
13219 ///
13220 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
13221 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
13222 /// would hit if the parser did not reject it first.
13223 fn define_private_field(
13224 &mut self,
13225 object: &Value,
13226 symbol: &Value,
13227 value: Value,
13228 ) -> JsResult<()> {
13229 let key = self.private_key(symbol)?;
13230 let Some(target) = object.as_object() else {
13231 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13232 };
13233 if !target.is_extensible() {
13234 return Err(Signal::Throw(
13235 self.make_error("TypeError", "object is not extensible"),
13236 ));
13237 }
13238 if target.own_property_key(&key).is_some() {
13239 let name = Self::private_name(symbol).unwrap_or_default();
13240 return Err(Signal::Throw(self.make_error(
13241 "TypeError",
13242 &format!("private class field '{name}' already exists"),
13243 )));
13244 }
13245 target.define_data_key(&key, value);
13246 Ok(())
13247 }
13248
13249 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
13250 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
13251 let key = self.private_key(symbol)?;
13252 let Some(target) = object.as_object() else {
13253 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13254 };
13255 match target.own_property_key(&key) {
13256 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
13257 None => {
13258 let name = Self::private_name(symbol).unwrap_or_default();
13259 Err(Signal::Throw(self.make_error(
13260 "TypeError",
13261 &format!("private class field '{name}' does not exist"),
13262 )))
13263 }
13264 }
13265 }
13266
13267 /// `JS_SetPrivateField`: the store half of the same rule.
13268 fn write_private_field(
13269 &mut self,
13270 object: &Value,
13271 symbol: &Value,
13272 value: Value,
13273 ) -> JsResult<()> {
13274 let key = self.private_key(symbol)?;
13275 let Some(target) = object.as_object() else {
13276 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13277 };
13278 if target.write_value_key(&key, value) {
13279 return Ok(());
13280 }
13281 let name = Self::private_name(symbol).unwrap_or_default();
13282 Err(Signal::Throw(self.make_error(
13283 "TypeError",
13284 &format!("private class field '{name}' does not exist"),
13285 )))
13286 }
13287
13288 /// The `in` half: does `object` have this private field?
13289 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
13290 ///
13291 /// The symbol is created once per class — the first `add_brand` on a given home object
13292 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
13293 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
13294 /// emit for the *instance* brand passes null because all it wants is the symbol.
13295 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
13296 let Some(home_object) = home.as_object() else {
13297 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13298 };
13299 let symbol = match home_object.private_brand() {
13300 Some(symbol) => symbol,
13301 None => {
13302 let symbol = Gc::new(
13303 self.heap,
13304 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
13305 );
13306 home_object.set_private_brand(symbol.clone());
13307 symbol
13308 }
13309 };
13310 let Some(target) = object.as_object() else {
13311 // Not an object: nothing to brand. The reference does the same, and `undefined`
13312 // here would otherwise turn a field initialiser into a TypeError.
13313 return Ok(());
13314 };
13315 if !target.is_extensible() {
13316 return Err(Signal::Throw(
13317 self.make_error("TypeError", "object is not extensible"),
13318 ));
13319 }
13320 if target.carries_brand(&symbol) {
13321 return Err(Signal::Throw(
13322 self.make_error("TypeError", "private method is already present"),
13323 ));
13324 }
13325 target.add_brand(symbol);
13326 Ok(())
13327 }
13328
13329 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
13330 ///
13331 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
13332 /// decides whether to throw.
13333 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
13334 let Some(function) = function.as_object() else {
13335 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13336 };
13337 let Some(home) = function.home_object() else {
13338 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13339 };
13340 let Some(brand) = home.private_brand() else {
13341 return Err(Signal::Throw(
13342 self.make_error("TypeError", "expecting <brand> private field"),
13343 ));
13344 };
13345 Ok(object.carries_brand(&brand))
13346 }
13347
13348 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
13349 let Value::Object(object) = object else {
13350 // `PutValue` on a property of a primitive is a silent no-op in sloppy mode and a
13351 // `TypeError` in strict mode: `sym.a = 1` on a Symbol must leave `sym.a`
13352 // `undefined` rather than throwing (`Symbol/auto-boxing-non-strict`). `null` and
13353 // `undefined` still throw, with their own message.
13354 if !self.current_strict() && !matches!(object, Value::Null | Value::Undefined) {
13355 return Ok(());
13356 }
13357 return Err(Signal::Throw(self.make_error(
13358 "TypeError",
13359 &format!("cannot set property '{key}' of {}", object.to_js_string()),
13360 )));
13361 };
13362 // The write half of the property inline cache, in effect: an own, writable,
13363 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
13364 // decide — no prototype walk (an own property shadows the chain before a setter
13365 // there could matter), no extensibility check (the object already has the key),
13366 // and no `[[DefineOwnProperty]]`.
13367 //
13368 // `this.value = …` inside a method is the whole write side of
13369 // `property:method-call`, and it was reaching `set_property_with_key` with its
13370 // proxy test, its typed-array test, its array-index test and finally a linear
13371 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
13372 //
13373 // Every disqualifier is checked here: a proxy traps the set, an array index and
13374 // `length` live outside the property table, and a typed array's element is stored
13375 // through its view's element type.
13376 if object.proxy_state().is_none()
13377 && !object.is_array()
13378 && object.typed_array_element_type().is_none()
13379 && object.write_value_key(key, value.clone())
13380 {
13381 return Ok(());
13382 }
13383 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
13384 let on_failure = if self.frame().code.code.strict {
13385 DeleteFailure::Throw
13386 } else {
13387 DeleteFailure::Ignore
13388 };
13389 self.set_property_with_key(object, key, value, on_failure)
13390 }
13391
13392 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
13393 ///
13394 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
13395 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
13396 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
13397 /// `Number.parseInt(sym)` — so those callers use this instead.
13398 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
13399 if matches!(value, Value::Symbol(_)) {
13400 return Err(Signal::Throw(
13401 self.make_error("TypeError", "cannot convert symbol to string"),
13402 ));
13403 }
13404 // An object runs `ToPrimitive` first, which may itself produce a symbol —
13405 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
13406 let value = self.to_primitive(value.clone(), Hint::String)?;
13407 if matches!(value, Value::Symbol(_)) {
13408 return Err(Signal::Throw(
13409 self.make_error("TypeError", "cannot convert symbol to string"),
13410 ));
13411 }
13412 Ok(value.to_js_string())
13413 }
13414
13415 /// `ToPropertyKey` for a builtin that takes a key argument.
13416 ///
13417 /// Fallible: a key whose `toString` throws has to propagate that error, both for
13418 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
13419 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
13420 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
13421 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
13422 self.propkey(value)
13423 }
13424
13425 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
13426 ///
13427 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
13428 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
13429 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
13430 /// `RangeError` — and why this cannot be a plain `ToNumber`.
13431 /// `ToNumber(value)` for `ArraySetLength`, which the spec performs **twice**.
13432 ///
13433 /// §10.4.2.4 steps 3–5 are `ToUint32(Desc.[[Value]])`, then `ToNumber(Desc.[[Value]])`,
13434 /// then a `RangeError` when they disagree. Two conversions rather than one is
13435 /// observable: a `valueOf` that runs the first time can make `length` non-writable
13436 /// before the second, which turns the store into a refused write
13437 /// (`length/define-own-prop-length-coercion-order`, `…-set`).
13438 pub fn coerce_array_length_twice(&mut self, value: &Value) -> JsResult<u32> {
13439 let first = self.array_length_of(value)?;
13440 let second = self.array_length_of(value)?;
13441 debug_assert_eq!(first, second);
13442 Ok(first)
13443 }
13444
13445 /// `ArraySetLength`'s `ToNumber(value)`, then the `ToUint32` round-trip check.
13446 ///
13447 /// Separate from [`Interp::coerce_array_length_twice`] so the callers that need one
13448 /// conversion can say so; a caller that needs the spec's two uses that instead.
13449 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
13450 let number = match value {
13451 Value::Int(number) => *number as f64,
13452 Value::Float(number) => *number,
13453 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
13454 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
13455 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
13456 // reference answers 0.
13457 Value::Null | Value::Bool(_) | Value::Undefined => value.to_number(),
13458 // A string goes through the full numeric-literal grammar: `"0x00B"` is 11 and
13459 // `" 5 "` is 5, which is exactly what `string_to_number` implements.
13460 Value::String(text) => crate::value::string_to_number(&text.to_string_lossy()),
13461 _ => {
13462 // The primitive comes back through this same conversion, so a wrapper of a
13463 // boolean (`new Boolean(false)`) is `0` rather than the `NaN` that
13464 // `ToNumber("false")` would give — `S15.4.5.1_A1.3_T1` walks every wrapper.
13465 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
13466 return self.array_length_of(&primitive);
13467 }
13468 };
13469 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
13470 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
13471 // is a `RangeError`, not `0`.
13472 if !number.is_finite()
13473 || number.fract() != 0.0
13474 || !(0.0..=u32::MAX as f64).contains(&number)
13475 {
13476 return Err(self.range_error("invalid array length"));
13477 }
13478 Ok(number as u32)
13479 }
13480
13481 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
13482 /// `Object.getOwnPropertySymbols` put in their result array.
13483 pub fn key_value(&self, key: &PropertyKey) -> Value {
13484 match key {
13485 PropertyKey::String(text) => self.string_wtf8(text.clone()),
13486 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
13487 }
13488 }
13489
13490 /// Fill in a String exotic object: `_value`, `length` and the index properties.
13491 ///
13492 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
13493 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
13494 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
13495 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
13496 /// the two paths had drifted; this is the one both now use.
13497 ///
13498 /// The indices are *code units*, so an astral character occupies two of them — the
13499 /// same rule `s.length` and `s[i]` follow.
13500 /// Give an already-created object the internal slot that makes it a wrapper of
13501 /// `value`, so the primitive's prototype methods work on it.
13502 ///
13503 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
13504 /// which are wrappers of their own type holding the empty value.
13505 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
13506 self.internal_set(object, "_value", value);
13507 }
13508
13509 pub(crate) fn init_string_wrapper(
13510 &mut self,
13511 object: &Gc<JsObject>,
13512 text: &Gc<crate::value::JsString>,
13513 ) {
13514 object.define(
13515 "length",
13516 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
13517 );
13518 for index in 0..text.utf16_len() {
13519 if let Some(unit) = text.wtf8().unit_at(index) {
13520 object.define(
13521 &index.to_string(),
13522 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
13523 Property::with_attributes(self.string_wtf8(unit), false, true),
13524 );
13525 }
13526 }
13527 object.define_key(
13528 &self.internal_slot("_value"),
13529 Property::with_attributes(Value::String(text.clone()), false, false),
13530 );
13531 }
13532
13533 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
13534 ///
13535 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
13536 /// throws. The wrapper carries its primitive in `_value` — the same slot
13537 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
13538 /// on a boxed value no constructor ever built.
13539 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13540 let (prototype, primitive) = match value {
13541 Value::Object(object) => return Ok(object.clone()),
13542 Value::String(text) => {
13543 let object = self.new_object(self.realm.string_proto.clone());
13544 self.init_string_wrapper(&object, text);
13545 return Ok(object);
13546 }
13547 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
13548 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
13549 // A symbol and a bigint box into wrappers whose methods live on
13550 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
13551 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
13552 // branch below instead produced an object with *no* prototype, so those
13553 // methods were unreachable on a box.
13554 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
13555 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
13556 Value::Undefined | Value::Null => {
13557 return Err(Signal::Throw(self.make_error(
13558 "TypeError",
13559 &format!("cannot convert {} to object", value.to_js_string()),
13560 )));
13561 }
13562 _ => (None, value.clone()),
13563 };
13564 let object = self.new_object(prototype);
13565 self.internal_set(&object, "_value", primitive);
13566 Ok(object)
13567 }
13568
13569 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
13570 ///
13571 /// Split out for a reader that has to create the object *before* it knows what it wraps:
13572 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
13573 /// written before its primitive, so the placeholder has to exist first and be filled in
13574 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
13575 /// than a second in the deserialiser.
13576 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
13577 let prototype = match value {
13578 Value::String(_) => self.realm.string_proto.clone(),
13579 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13580 Value::Bool(_) => self.realm.boolean_proto.clone(),
13581 Value::Symbol(_) => self.realm.symbol_proto.clone(),
13582 Value::BigInt(_) => self.realm.bigint_proto.clone(),
13583 _ => {
13584 return Err(Signal::Throw(self.make_error(
13585 "TypeError",
13586 &format!("cannot box {}", value.to_js_string()),
13587 )));
13588 }
13589 };
13590 object.set_proto(prototype);
13591 if let Value::String(text) = value {
13592 self.init_string_wrapper(object, text);
13593 return Ok(());
13594 }
13595 self.internal_set(object, "_value", value.clone());
13596 Ok(())
13597 }
13598
13599 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
13600 ///
13601 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
13602 /// through the `Symbol` function object, so the registry is reachable as a method rather
13603 /// than only from `builtins::symbol`.
13604 pub fn symbol_for(&mut self, key: &str) -> Value {
13605 if let Some(existing) = self.realm.symbol_registry.get(key) {
13606 return existing.clone();
13607 }
13608 let symbol = crate::builtins::symbol::symbol_value(
13609 self,
13610 crate::value::JsSymbol::registered(key.to_string()),
13611 );
13612 self.realm
13613 .symbol_registry
13614 .insert(key.to_string(), symbol.clone());
13615 symbol
13616 }
13617
13618 /// `a == b`, the coercing comparison.
13619 ///
13620 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
13621 /// which is what makes `[] == ""` true: `[]` becomes `""` via
13622 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
13623 /// because the conversion is allowed to call script code, so the two primitive
13624 /// operands are handed back to it.
13625 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
13626 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
13627 return Ok(left.loose_equals(&right));
13628 }
13629 // `null == undefined` holds even though neither is an object.
13630 if matches!(left, Value::Undefined | Value::Null)
13631 && matches!(right, Value::Undefined | Value::Null)
13632 {
13633 return Ok(true);
13634 }
13635 if matches!(left, Value::Undefined | Value::Null)
13636 || matches!(right, Value::Undefined | Value::Null)
13637 {
13638 return Ok(false);
13639 }
13640 // Two objects compare by identity. Only an object *against a primitive* is
13641 // converted, which is why `{} == {}` is false while `[] == ""` is true.
13642 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
13643 return Ok(a.ptr_eq(b));
13644 }
13645 let left = self.to_primitive(left, Hint::Default)?;
13646 let right = self.to_primitive(right, Hint::Default)?;
13647 Ok(left.loose_equals(&right))
13648 }
13649
13650 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
13651 let Value::Object(object) = object else {
13652 return Err(Signal::Throw(
13653 self.make_error("TypeError", "cannot use 'in' on a non-object"),
13654 ));
13655 };
13656 let key = self.propkey(key)?;
13657 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
13658 // trap. One implementation, so an array's derived `length` and its inherited holes
13659 // cannot be right in one caller and wrong in another.
13660 self.has_own_or_inherited(object, &key)
13661 }
13662
13663 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
13664 ///
13665 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
13666 /// whole reason the operator is a hook rather than a prototype walk.
13667 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13668 if let Value::Object(function) = constructor {
13669 let key = self.realm.well_known_key(WellKnown::HasInstance);
13670 let method = self.get_property_key(function, &key)?;
13671 if let Some(method) = method
13672 && !matches!(method, Value::Undefined)
13673 {
13674 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
13675 return Ok(answer.to_boolean());
13676 }
13677 }
13678 self.instance_of(object, constructor)
13679 }
13680
13681 /// `OrdinaryHasInstance`: the prototype walk on its own.
13682 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13683 self.instance_of(object, constructor)
13684 }
13685
13686 /// `IsArray`: an array, or a proxy whose target is one.
13687 ///
13688 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
13689 /// makes `Array.isArray(new Proxy([], {}))` true.
13690 pub fn is_array_value(&self, value: &Value) -> bool {
13691 match value {
13692 Value::Object(object) => {
13693 if let Some(state) = object.proxy_state() {
13694 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
13695 }
13696 object.is_array()
13697 }
13698 _ => false,
13699 }
13700 }
13701
13702 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
13703 ///
13704 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
13705 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
13706 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
13707 /// see [`Interp::enqueue_job_function`].
13708 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
13709 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
13710 // the handler is reported rather than lost — the same reason a `then` reaction needs a
13711 // promise to settle.
13712 let promise = self.new_promise();
13713 self.fulfill_promise(&promise, Value::Undefined);
13714 self.jobs.push_back(Job::Reaction {
13715 handler: Some(function),
13716 argument: Value::Undefined,
13717 rejected: false,
13718 promise,
13719 });
13720 Ok(())
13721 }
13722
13723 /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
13724 ///
13725 /// Four of its steps were missing or wrong, and each one is a test262 case in
13726 /// `Function/prototype/Symbol.hasInstance/`:
13727 ///
13728 /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
13729 /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
13730 /// `[[BoundThis]]` standing in for the object when that is an object), which is why
13731 /// `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
13732 /// `prototype` of its own, so without this step the walk below gives `false`;
13733 /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
13734 /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
13735 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13736 let Value::Object(function) = constructor else {
13737 return Ok(false);
13738 };
13739 if !function.is_callable() {
13740 return Ok(false);
13741 }
13742 // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
13743 // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
13744 // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
13745 if let Some((target, this)) = function.bound_target_and_this() {
13746 let object = if this.as_object().is_some() {
13747 this
13748 } else {
13749 object.clone()
13750 };
13751 return self.instance_of(&object, &target);
13752 }
13753 let Value::Object(target) = object else {
13754 return Ok(false);
13755 };
13756 let prototype = self.get_property(function, "prototype")?;
13757 let Some(Value::Object(prototype)) = prototype else {
13758 return Err(Signal::Throw(self.make_error(
13759 "TypeError",
13760 "function has non-object prototype in instanceof check",
13761 )));
13762 };
13763 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
13764 // which is also what makes `proxyOfInstance instanceof C` work.
13765 let mut current = Some(target.clone());
13766 while let Some(object) = current {
13767 if object.ptr_eq(&prototype) {
13768 return Ok(true);
13769 }
13770 current = self.object_prototype_of(&object)?;
13771 }
13772 Ok(false)
13773 }
13774
13775 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
13776 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
13777 if let Some(proto) = self.proxy_get_prototype_of(object)? {
13778 return Ok(proto);
13779 }
13780 if let Some(exotic) = object.exotic()
13781 && let Some(proto) = exotic.get_prototype(self, object)?
13782 {
13783 return Ok(proto);
13784 }
13785 Ok(object.proto())
13786 }
13787
13788 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
13789 pub fn object_set_prototype_of(
13790 &mut self,
13791 object: &Gc<JsObject>,
13792 proto: Option<Gc<JsObject>>,
13793 ) -> JsResult<bool> {
13794 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
13795 return Ok(answer);
13796 }
13797 if let Some(exotic) = object.exotic()
13798 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
13799 {
13800 return Ok(answer);
13801 }
13802 // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
13803 // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
13804 // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
13805 // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
13806 if self
13807 .internal_get(object, "_immutable_proto")
13808 .is_some_and(|flag| flag.to_boolean())
13809 && !same_proto(object.proto().as_ref(), proto.as_ref())
13810 {
13811 return Ok(false);
13812 }
13813 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
13814 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
13815 // inheriting from itself, which every later prototype walk then had to defend
13816 // against — and `Reflect.setPrototypeOf` reported success for an operation the
13817 // language says is impossible.
13818 if let Some(proto) = &proto {
13819 let mut current = Some(proto.clone());
13820 let mut guard = 0;
13821 while let Some(node) = current {
13822 if node.ptr_eq(object) {
13823 // §10.1.2.1 step 5.a: a cycle is `return false`, not a throw —
13824 // `Object.setPrototypeOf` turns that `false` into the `TypeError`,
13825 // while `Reflect.setPrototypeOf` reports it
13826 // (`setPrototypeOf/return-false-if-target-is-prototype-of-proto`).
13827 return Ok(false);
13828 }
13829 guard += 1;
13830 if guard > 1000 {
13831 break;
13832 }
13833 current = node.proto();
13834 }
13835 }
13836 // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
13837 // re-setting it to the *same* one is a no-op `true`. Missing this made
13838 // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
13839 // actually reparent the object — and it is what
13840 // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
13841 // forwarding path has nothing else left to refuse it.
13842 if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
13843 return Ok(false);
13844 }
13845 object.set_proto(proto);
13846 Ok(true)
13847 }
13848
13849 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
13850 ///
13851 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
13852 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
13853 /// already one.
13854 /// `HasProperty(O, P)`.
13855 ///
13856 /// One implementation, shared with the `in` operator. It used to be a second copy that
13857 /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
13858 /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
13859 /// proxy ran the wrong hook and could even disagree with `in`. The
13860 /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
13861 /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
13862 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
13863 self.has_own_or_inherited(object, key)
13864 }
13865
13866 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
13867 ///
13868 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
13869 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
13870 /// boolean as well, and it needs the receiver to be the one the caller named.
13871 pub fn set_property_with_key_receiver(
13872 &mut self,
13873 object: &Gc<JsObject>,
13874 key: &PropertyKey,
13875 value: Value,
13876 receiver: Option<&Value>,
13877 on_failure: DeleteFailure,
13878 ) -> JsResult<bool> {
13879 let receiver = receiver
13880 .cloned()
13881 .unwrap_or_else(|| Value::Object(object.clone()));
13882 if object.proxy_state().is_some() {
13883 return match self.proxy_set(object, key, value, &receiver)? {
13884 Some(accepted) => Ok(accepted),
13885 None => Ok(true),
13886 };
13887 }
13888 // §10.4.6.7: a module namespace's `[[Set]]` always answers false, whatever the
13889 // receiver. This has to be answered here as well as in the storing path below,
13890 // because `Reflect.set` reports the refusal as a `bool` instead of raising.
13891 if object.module_namespace_marker() {
13892 return Ok(false);
13893 }
13894 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
13895 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
13896 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
13897 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
13898 //
13899 // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
13900 //
13901 // * `SameValue(O, Receiver)` stores into the buffer, converting first;
13902 // * an *invalid* index with a different receiver answers `true` and does nothing,
13903 // not even converting `V` (`valueOfCalls` stays 0);
13904 // * a valid index with a different receiver falls through to
13905 // `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
13906 // value lands on the **receiver**, unconverted, and can be refused by a
13907 // non-extensible receiver, an accessor, or a read-only index there.
13908 //
13909 // The last one used to write into the view itself, which left `target[0]` changed
13910 // and `receiver[0]` untouched — backwards.
13911 if object.typed_array_element_type().is_some()
13912 && let Some(numeric) = canonical_numeric_index(key)
13913 {
13914 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13915 if same {
13916 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13917 return Ok(true);
13918 }
13919 if !typed_array_index_is_valid(object, numeric) {
13920 return Ok(true);
13921 }
13922 let Some(receiver) = receiver.as_object().cloned() else {
13923 return Ok(false);
13924 };
13925 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
13926 if existing.is_accessor() || !existing.writable {
13927 return Ok(false);
13928 }
13929 let property = Property {
13930 value: Some(value),
13931 ..existing
13932 };
13933 return self.object_define_own_property(&receiver, key, property);
13934 }
13935 return self.object_define_own_property(&receiver, key, Property::data(value));
13936 }
13937 // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
13938 // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
13939 // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
13940 // `Reflect.set` to *report* the refusal instead of raising.
13941 //
13942 // A receiver that is not the object turns the whole operation into
13943 // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
13944 // `[[Set]]` rather than a lookup — that is what makes
13945 // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
13946 // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
13947 // writes to `object`, so it cannot express that and is only used when the two are
13948 // the same.
13949 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13950 if !same {
13951 return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
13952 }
13953 // Same receiver: the plain path below writes into `object`, which is right, but it
13954 // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
13955 // boolean, so the two step-1 refusals have to be read off the own descriptor here.
13956 if let Some(existing) = self.object_get_own_property(object, key)? {
13957 if existing.is_accessor() {
13958 return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
13959 Some(setter) => {
13960 self.call_value(setter, receiver, vec![value])?;
13961 Ok(true)
13962 }
13963 None => Ok(false),
13964 };
13965 }
13966 if !existing.writable {
13967 return Ok(false);
13968 }
13969 }
13970 // Otherwise it is an ordinary create-or-write into `object` itself.
13971 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13972 Ok(true)
13973 }
13974
13975 /// `[[IsExtensible]]`, with the proxy trap when there is one.
13976 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13977 if let Some(answer) = self.proxy_is_extensible(object)? {
13978 return Ok(answer);
13979 }
13980 if let Some(exotic) = object.exotic()
13981 && let Some(answer) = exotic.is_extensible(self, object)?
13982 {
13983 return Ok(answer);
13984 }
13985 Ok(object.is_extensible())
13986 }
13987
13988 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
13989 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13990 if let Some(answer) = self.proxy_prevent_extensions(object)? {
13991 return Ok(answer);
13992 }
13993 // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
13994 //
13995 // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
13996 //
13997 // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
13998 // created with an explicit length, because the buffer can still move it. That is
13999 // what makes `Object.freeze` refuse every such view, including a zero-length one
14000 // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
14001 // plain buffer is allowed.
14002 if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
14003 && buffer
14004 .array_buffer_storage()
14005 .is_some_and(|storage| storage.borrow().is_resizable())
14006 {
14007 return Err(
14008 self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
14009 );
14010 }
14011 if let Some(exotic) = object.exotic()
14012 && let Some(answer) = exotic.prevent_extensions(self, object)?
14013 {
14014 return Ok(answer);
14015 }
14016 object.set_extensible(false);
14017 Ok(true)
14018 }
14019
14020 fn copy_properties(
14021 &mut self,
14022 target: &Value,
14023 source: &Value,
14024 exclusion: &Value,
14025 ) -> JsResult<()> {
14026 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
14027 // does contribute: its index properties are own, enumerable and writable, which
14028 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
14029 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
14030 // is a no-op.
14031 let Some(target) = target.as_object() else {
14032 return Ok(());
14033 };
14034 let source_object = match source {
14035 Value::Object(object) => object.clone(),
14036 Value::String(text) => {
14037 // Untaken keys are the string's indices, which are code units.
14038 for index in 0..text.utf16_len() {
14039 if let Some(unit) = text.wtf8().unit_at(index) {
14040 target.define_data(&index.to_string(), self.string_wtf8(unit));
14041 }
14042 }
14043 return Ok(());
14044 }
14045 _ => return Ok(()),
14046 };
14047 // An object *rest* element passes the keys already taken by the literal part as
14048 // an array of strings; a spread passes `null`, which excludes nothing. Only the
14049 // string keys of the exclusion array are meaningful, so an array is read by its
14050 // elements rather than by its own property names.
14051 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
14052 if let Value::Object(list) = exclusion
14053 && let Some(length) = list.array_length()
14054 {
14055 for index in 0..length {
14056 if let Some(value) = list.array_get(index) {
14057 excluded.push(self.propkey_of(&value)?);
14058 }
14059 }
14060 }
14061 let source = &source_object;
14062 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
14063 // Reading the property table directly made every spread of a proxy empty.
14064 let keys = self.object_own_property_keys(source)?;
14065 for as_key in keys {
14066 if as_key.is_symbol() {
14067 // A spread copies string-keyed properties only.
14068 continue;
14069 }
14070 if excluded.contains(&crate::value::Wtf8::new(
14071 as_key.as_str().unwrap_or_default(),
14072 )) {
14073 continue;
14074 }
14075 let enumerable = self
14076 .object_get_own_property(source, &as_key)?
14077 .is_some_and(|property| property.enumerable);
14078 if !enumerable {
14079 continue;
14080 }
14081 let value = self
14082 .get_property_key(source, &as_key)?
14083 .unwrap_or(Value::Undefined);
14084 target.define_data_key(&as_key, value);
14085 }
14086 Ok(())
14087 }
14088
14089 // -- iteration ---------------------------------------------------------
14090
14091 /// One object's own keys in enumeration order: array indices ascending, then the
14092 /// rest in insertion order.
14093 ///
14094 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
14095 /// whether the key is enumerable, which the caller resolves per key because an
14096 /// array's elements are not in the same store as its named properties.
14097 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
14098 // An index can arrive twice, once from the array's element store and once from
14099 // its property map, so the numeric keys go through a map that keeps the
14100 // enumerable answer if either source gave one.
14101 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
14102 for (key, enumerable) in &own {
14103 if let Some(index) = key.as_str().and_then(array_index) {
14104 let entry = numeric.entry(index).or_insert(false);
14105 *entry = *entry || *enumerable;
14106 }
14107 }
14108 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
14109 .into_iter()
14110 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
14111 .collect();
14112 ordered.extend(
14113 own.into_iter()
14114 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
14115 );
14116 ordered
14117 }
14118
14119 /// Build the key list a `for-in` loop walks.
14120 ///
14121 /// The order is the specification's: own properties before inherited ones, and
14122 /// within one object the integer-like keys in ascending numeric order ahead of the
14123 /// string keys in insertion order. A shadowed key only appears once, and a key that
14124 /// is a non-enumerable own property anywhere nearer is skipped entirely.
14125 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
14126 let record = self.new_object(None);
14127 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
14128 // A proxy supplies its own key list, and — the reason this is not just another
14129 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
14130 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
14131 // descriptor there.
14132 if let Value::Object(object) = value
14133 && object.proxy_state().is_some()
14134 {
14135 let own = self
14136 .proxy_own_keys(object)?
14137 .unwrap_or_else(|| object.own_property_keys());
14138 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
14139 let mut numeric: Vec<u32> = Vec::new();
14140 let mut rest: Vec<PropertyKey> = Vec::new();
14141 for key in own {
14142 match key.as_str().and_then(array_index) {
14143 Some(index) => numeric.push(index),
14144 None => rest.push(key),
14145 }
14146 }
14147 numeric.sort_unstable();
14148 ordered.extend(
14149 numeric
14150 .into_iter()
14151 .map(|index| PropertyKey::from(index.to_string())),
14152 );
14153 ordered.extend(rest);
14154 for (index, key) in ordered.into_iter().enumerate() {
14155 record.define_data(&index.to_string(), self.key_value(&key));
14156 }
14157 record.define_data("__index", Value::Int(0));
14158 // The mark that makes `for_in_advance` re-ask the proxy per key.
14159 record.define_data("__proxy", Value::Object(object.clone()));
14160 return Ok(record);
14161 }
14162 if let Value::Object(object) = value {
14163 let mut chain = vec![object.clone()];
14164 chain.extend(object.chain());
14165 // Every own string key the walk has seen, enumerable or not. A
14166 // non-enumerable own property still hides a same-named enumerable one
14167 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
14168 // keeps `x` out of the loop even when the prototype has one.
14169 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
14170 for object in chain {
14171 let mut own: Vec<(crate::value::Wtf8, bool)> = object
14172 .own_property_keys()
14173 .iter()
14174 .filter_map(|key| key.as_wtf8().cloned())
14175 .map(|key| {
14176 let enumerable = object
14177 .own_property(&key.to_string_lossy())
14178 .map(|property| property.enumerable)
14179 .unwrap_or(false);
14180 (key, enumerable)
14181 })
14182 .collect();
14183 if let Some(length) = object.array_length() {
14184 own.retain(|(key, _)| key.as_str() != Some("length"));
14185 for index in 0..length {
14186 // A dense element is enumerable; a **hole** is not there at all —
14187 // and a hole is also what an index with a recorded descriptor
14188 // leaves behind, in which case the table entry above already
14189 // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
14190 // defines index 0 non-enumerable and `for…in` must skip it).
14191 if let Some(value) = object.array_get(index)
14192 && !matches!(value, Value::Hole)
14193 {
14194 own.push((crate::value::Wtf8::new(index.to_string()), true));
14195 }
14196 }
14197 }
14198 // Integer-like keys come first in ascending order, then the rest in
14199 // insertion order — and the ordering is *per object*, not for the chain
14200 // as a whole: one pass over every collected key lifted a prototype's
14201 // `"4"` above the target's own `x`/`y`, which is not the order
14202 // `for…in` reports.
14203 for (key, enumerable) in Self::order_own_keys(own) {
14204 if visited.contains(&key) {
14205 continue;
14206 }
14207 visited.push(key.clone());
14208 if enumerable {
14209 keys.push(key);
14210 }
14211 }
14212 }
14213 }
14214 for (index, key) in keys.into_iter().enumerate() {
14215 record.define_data(&index.to_string(), self.string_wtf8(key));
14216 }
14217 record.define_data("__index", Value::Int(0));
14218 Ok(record)
14219 }
14220
14221 /// The next key of a `for…in` record, `None` when the loop is done.
14222 ///
14223 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
14224 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
14225 /// the loop reaches it, so a handler that stops reporting a key partway through drops
14226 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
14227 /// key the handler had already withdrawn.
14228 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
14229 let Value::Object(record) = record else {
14230 return Ok(None);
14231 };
14232 let proxy = record
14233 .own_property("__proxy")
14234 .and_then(|property| property.value);
14235 loop {
14236 let index = record
14237 .own_property("__index")
14238 .and_then(|property| property.value)
14239 .map(|value| value.to_int32())
14240 .unwrap_or(0);
14241 let Some(candidate) = record
14242 .own_property(&index.to_string())
14243 .and_then(|property| property.value)
14244 else {
14245 return Ok(None);
14246 };
14247 record.define_data("__index", Value::Int(index + 1));
14248 let text = candidate.to_js_string();
14249 let Some(Value::Object(proxy)) = &proxy else {
14250 return Ok(Some(text));
14251 };
14252 // The candidate is already a key string here, so the lookup does not need a
14253 // second `ToPropertyKey` conversion.
14254 let key = PropertyKey::from(text.as_str());
14255 let live = match self.proxy_get_own_property(proxy, &key)? {
14256 Some(descriptor) => descriptor,
14257 // Not a proxy after all, or it lost its state: fall back to the target.
14258 None => proxy.own_property_key(&key),
14259 };
14260 if live.is_some_and(|property| property.enumerable) {
14261 return Ok(Some(text));
14262 }
14263 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
14264 // next one.
14265 }
14266 }
14267
14268 /// The iterator for `for-of`: the object and its `next` method.
14269 ///
14270 /// An object that already carries a `next` method is used as it is — that is what
14271 /// `arr.values()` returns — and only arrays and strings get the built-in
14272 /// sequence iterator.
14273 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
14274 ///
14275 /// Callers that must choose between the iterable and the array-like protocol — the
14276 /// typed-array constructor is the main one — need to ask *before* committing to one.
14277 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
14278 let key = self.realm.well_known_key(WellKnown::Iterator);
14279 let method = self.read_field_key(value, &key)?;
14280 if matches!(method, Value::Undefined | Value::Null) {
14281 return Ok(false);
14282 }
14283 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14284 return Err(Signal::Throw(
14285 self.make_error("TypeError", "Symbol.iterator is not callable"),
14286 ));
14287 }
14288 Ok(true)
14289 }
14290
14291 /// Collect everything an iterable yields.
14292 ///
14293 /// The cap is a guard against a generator that never ends: an unbounded collect would
14294 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
14295 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
14296 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
14297 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
14298 const MAX_ITEMS: usize = 1 << 24;
14299 let iterator = self.get_iterator(value)?;
14300 let mut out = Vec::new();
14301 loop {
14302 let (element, done) = self.iterator_step(&iterator)?;
14303 if done {
14304 return Ok(out);
14305 }
14306 out.push(element);
14307 if out.len() > MAX_ITEMS {
14308 // Close before refusing: the walk is being abandoned, so the iterator's
14309 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
14310 // unrun and a locked resource unreleased.
14311 self.close_iterator_after_throw(&iterator)?;
14312 return Err(self.range_error("iterable is too long to collect"));
14313 }
14314 }
14315 }
14316
14317 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
14318 ///
14319 /// A native constructor calls this once it has validated its arguments, which is the
14320 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
14321 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
14322 /// never reached. The prototype comes from `new.target` when it is an object, and from
14323 /// `default_proto` otherwise.
14324 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14325 let proto = self.ctor_prototype(default_proto)?;
14326 Ok(self.new_object(Some(proto)))
14327 }
14328
14329 /// An **array** whose prototype comes from `new.target`.
14330 ///
14331 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
14332 /// instance from `new.target.prototype`, and building a plain array instead made every
14333 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
14334 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
14335 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
14336 Ok(JsObject::array(self.heap, Some(proto), 0))
14337 }
14338
14339 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
14340 ///
14341 /// The `Option` form is for the constructors that build their instance in a helper which
14342 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
14343 /// from `await`'s internal promise, and only the first has a `new.target`.
14344 fn ctor_prototype_opt(
14345 &mut self,
14346 default_proto: Option<Gc<JsObject>>,
14347 ) -> JsResult<Option<Gc<JsObject>>> {
14348 // `active_new_target`: by the time a native constructor runs, `call_value` has
14349 // already consumed the parked value.
14350 let Some(target) = self
14351 .active_new_target
14352 .as_object()
14353 .cloned()
14354 .map(Value::Object)
14355 else {
14356 return Ok(default_proto);
14357 };
14358 let Some(target) = target.as_object().cloned() else {
14359 return Ok(default_proto);
14360 };
14361 match self.get_property(&target, "prototype")? {
14362 Some(Value::Object(proto)) => Ok(Some(proto)),
14363 _ => Ok(default_proto),
14364 }
14365 }
14366
14367 /// `new.target.prototype`, or `default_proto` when this is a plain call.
14368 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14369 let Some(target) = self.active_new_target.as_object().cloned() else {
14370 return Ok(default_proto);
14371 };
14372 match self.get_property(&target, "prototype")? {
14373 Some(Value::Object(proto)) => Ok(proto),
14374 _ => Ok(default_proto),
14375 }
14376 }
14377
14378 /// `CreateDataPropertyOrThrow(O, key, value)`.
14379 ///
14380 /// A *definition*, not an assignment. The difference is visible the moment the target
14381 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
14382 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
14383 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
14384 /// refused (`configurable: false`).
14385 ///
14386 /// The fast path exists because this is called once per element by `map`, `filter`,
14387 /// `slice` and friends: a plain array with no custom element descriptors and a writable
14388 /// `length` can store straight into its element vector.
14389 pub fn create_data_property_or_throw(
14390 &mut self,
14391 object: &Gc<JsObject>,
14392 index: usize,
14393 value: Value,
14394 ) -> JsResult<()> {
14395 // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
14396 // an array (that is what `Array.isArray` must say), so the element fast path would
14397 // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
14398 // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
14399 // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
14400 // records the exact trap sequence.
14401 if object.proxy_state().is_none()
14402 && object.is_array()
14403 && object.elements_writable()
14404 && !object.has_element_descriptors()
14405 && object.is_extensible()
14406 && object.array_set(self.heap, index, value.clone())
14407 {
14408 return Ok(());
14409 }
14410 let key = PropertyKey::from(index.to_string());
14411 let property = Property {
14412 value: Some(value),
14413 writable: true,
14414 enumerable: true,
14415 configurable: true,
14416 ..Property::default()
14417 };
14418 // `CreateDataProperty` always asks for the default attributes, so it can only ever
14419 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
14420 // the rest. Checking here rather than inside `object_define_own_property` is
14421 // deliberate: that function receives a fully-populated `Property` and cannot tell
14422 // an omitted attribute from an explicit `false`, so the generic check it would need
14423 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
14424 // writable property (that cost eight `Object/defineProperty` tests).
14425 if object.proxy_state().is_none()
14426 && let Some(existing) = self.object_get_own_property(object, &key)?
14427 && !existing.configurable
14428 {
14429 return Err(self.type_error("cannot create the property"));
14430 }
14431 if self.object_define_own_property(object, &key, property)? {
14432 return Ok(());
14433 }
14434 Err(self.type_error("cannot create the property"))
14435 }
14436
14437 /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
14438 ///
14439 /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
14440 /// its callers have; this is the same operation for the named properties a built-in
14441 /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
14442 /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
14443 /// `Array.prototype` cannot see it — while `Set` would run that accessor.
14444 pub fn create_named_data_property_or_throw(
14445 &mut self,
14446 object: &Gc<JsObject>,
14447 key: &str,
14448 value: Value,
14449 ) -> JsResult<()> {
14450 let key = PropertyKey::from(key);
14451 let property = Property {
14452 value: Some(value),
14453 writable: true,
14454 enumerable: true,
14455 configurable: true,
14456 ..Property::default()
14457 };
14458 if object.proxy_state().is_none()
14459 && let Some(existing) = self.object_get_own_property(object, &key)?
14460 && !existing.configurable
14461 {
14462 return Err(self.type_error("cannot create the property"));
14463 }
14464 if self.object_define_own_property(object, &key, property)? {
14465 return Ok(());
14466 }
14467 Err(self.type_error("cannot create the property"))
14468 }
14469
14470 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
14471 ///
14472 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
14473 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
14474 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
14475 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
14476 /// run user code and both can throw.
14477 pub fn species_constructor(
14478 &mut self,
14479 object: &Gc<JsObject>,
14480 default: Value,
14481 ) -> JsResult<Value> {
14482 let Some(constructor) = self.get_property(object, "constructor")? else {
14483 return Ok(default);
14484 };
14485 let constructor = match constructor {
14486 Value::Undefined => return Ok(default),
14487 Value::Object(constructor) => constructor,
14488 _ => return Err(self.type_error("constructor is not an object")),
14489 };
14490 let key = self.realm.well_known_key(WellKnown::Species);
14491 let species = self.get_property_key(&constructor, &key)?;
14492 match species {
14493 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
14494 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
14495 Some(_) => Err(self.type_error("species is not a constructor")),
14496 }
14497 }
14498
14499 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
14500 ///
14501 /// The result is an array of `length` holes whose prototype comes from
14502 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
14503 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
14504 /// is why the `IsArray` check is the first step and not an optimisation.
14505 pub fn array_species_create(
14506 &mut self,
14507 original: &Value,
14508 length: usize,
14509 ) -> JsResult<Gc<JsObject>> {
14510 // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
14511 // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
14512 // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
14513 // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
14514 // `new_array_of_length` (`slice/create-non-array-invalid-len`).
14515 // `ArrayCreate(length)` is only reached when the result is a **plain array of this
14516 // realm** — the species may be a user function that ignores the length entirely, and
14517 // then `2**53 - 1` is not its problem
14518 // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
14519 // a short proxy and expects the copy loop to run).
14520 let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
14521 if length > ARRAY_CREATE_LIMIT {
14522 return Err(interp.range_error("invalid array length"));
14523 }
14524 Ok(interp.new_array_of_length(length))
14525 };
14526 let Some(object) = original.as_object().cloned() else {
14527 return default(self);
14528 };
14529 if !object.is_array() {
14530 return default(self);
14531 }
14532 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
14533 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
14534 let Some(constructor) = self.get_property(&object, "constructor")? else {
14535 return default(self);
14536 };
14537 let species = match constructor {
14538 Value::Undefined => return Ok(self.new_array_of_length(length)),
14539 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
14540 return default(self);
14541 }
14542 Value::Object(constructor) => {
14543 let key = self.realm.well_known_key(WellKnown::Species);
14544 match self.get_property_key(&constructor, &key)? {
14545 None | Some(Value::Undefined) | Some(Value::Null) => {
14546 return default(self);
14547 }
14548 Some(species) => species,
14549 }
14550 }
14551 // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
14552 // is a `TypeError`, not "the default". Treating it as the default made
14553 // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
14554 // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
14555 // `concat/create-ctor-non-object` are the same rule three times.
14556 _ => return Err(self.type_error("constructor is not an object")),
14557 };
14558 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
14559 // that is merely callable is the `create-species-non-ctor` case.
14560 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
14561 return Err(self.type_error("species is not a constructor"));
14562 }
14563 // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
14564 // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
14565 // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
14566 let created = self.construct(
14567 species.clone(),
14568 species,
14569 vec![crate::object::length_value(length)],
14570 )?;
14571 let Some(created) = created.as_object().cloned() else {
14572 return Err(self.type_error("species constructor did not answer an object"));
14573 };
14574 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
14575 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
14576 // object, and `create-species-with-non-writable-property` asserts exactly that.
14577 // The length is set for the array case; the generic case is the caller's
14578 // `Set(A, "length", …)`.
14579 if created.is_array() {
14580 created.array_set_length(self.heap, length);
14581 }
14582 Ok(created)
14583 }
14584
14585 /// Whether `object` is this realm's `%Array%`.
14586 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
14587 self.realm
14588 .array_constructor
14589 .as_ref()
14590 .is_some_and(|array| array.ptr_eq(object))
14591 }
14592
14593 /// A fresh `length`-hole array with the intrinsic prototype.
14594 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
14595 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
14596 array.array_set_length(self.heap, length);
14597 array
14598 }
14599
14600 /// Whether this call is a construction, i.e. `new.target` is defined.
14601 ///
14602 /// A native constructor receives `this = undefined` (it builds its own instance), so it
14603 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
14604 /// The native function currently executing, if any.
14605 pub fn current_native(&self) -> Option<Gc<JsObject>> {
14606 self.current_native.clone()
14607 }
14608
14609 /// Whether this call is a construction, i.e. `new.target` is defined.
14610 pub fn is_constructing(&self) -> bool {
14611 // `active_new_target`, not `pending_new_target`: the parked value is consumed by
14612 // `call_value` before a native runs, so by the time a constructor body asks, the
14613 // answer is only in the active slot.
14614 matches!(self.active_new_target, Value::Object(_))
14615 }
14616
14617 /// The `TypeError` a constructor too primitive to have a wrapper raises.
14618 ///
14619 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
14620 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
14621 /// happens inside the native function, which is why the trace carries an
14622 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
14623 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
14624 /// constructor`, and an unnamed one reports the leading space of `" is not a
14625 /// constructor"` because the reference formats the empty name as it is.
14626 ///
14627 /// It is also the answer for a `new.target` that cannot be named at all — not a
14628 /// function, or a throwing `name` getter — where the reference falls back to the bare
14629 /// `not a constructor`.
14630 pub fn not_a_constructor_error(&mut self) -> Signal {
14631 let target = self.active_new_target.clone();
14632 self.not_a_constructor_error_for(target)
14633 }
14634
14635 /// The same `TypeError` for an explicit target, for the callers that check
14636 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
14637 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
14638 let target = match target {
14639 Value::Object(target) if target.is_callable() => target,
14640 _ => return self.type_error("not a constructor"),
14641 };
14642 let name = match self.get_property(&target, "name") {
14643 Ok(Some(value)) => value.to_js_string(),
14644 _ => return self.type_error("not a constructor"),
14645 };
14646 self.type_error(format!("{name} is not a constructor"))
14647 }
14648
14649 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
14650 ///
14651 /// True whenever `new.target` is not the callee itself, or when it has no usable
14652 /// `prototype` — the cases where reading the property is observable at all.
14653 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
14654 match &self.active_new_target {
14655 Value::Object(target) => !target.ptr_eq(callee),
14656 Value::Undefined => false,
14657 _ => true,
14658 }
14659 }
14660
14661 /// The symbol key for one of the engine's own hidden slots.
14662 ///
14663 /// Cached on the realm, so every object of a kind shares one key and a slot can be
14664 /// read back by name.
14665 /// Whether any object on `object`'s **prototype chain** owns an array index.
14666 ///
14667 /// The one question the array methods' dense fast paths have to ask before touching the
14668 /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
14669 /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
14670 /// vector an unreliable answer. Walking the chain once per call is cheap because a
14671 /// prototype almost never holds an index.
14672 pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
14673 let mut current = object.proto();
14674 // Bounded, like every other prototype walk here: a proxy can answer a cycle.
14675 for _ in 0..10_000 {
14676 let Some(proto) = current else {
14677 return false;
14678 };
14679 if proto.has_indexed_own_property() {
14680 return true;
14681 }
14682 current = proto.proto();
14683 }
14684 false
14685 }
14686
14687 /// The hidden symbol a named internal slot is keyed by, created on first use.
14688 ///
14689 /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
14690 /// either keeping a table of its own.
14691 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
14692 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
14693 return PropertyKey::Symbol(symbol.clone());
14694 }
14695 let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
14696 self.realm
14697 .internal_slots
14698 .borrow_mut()
14699 .insert(name, Value::Symbol(symbol.clone()));
14700 PropertyKey::Symbol(symbol)
14701 }
14702
14703 /// Read a hidden slot, or `None` when the object has none of that name.
14704 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
14705 let slots = self.realm.internal_slots.borrow();
14706 let Value::Symbol(symbol) = slots.get(name)? else {
14707 return None;
14708 };
14709 object
14710 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
14711 .and_then(|property| property.value)
14712 }
14713
14714 /// Define a hidden slot.
14715 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
14716 let key = self.internal_slot(name);
14717 object.define_key(&key, Property::with_attributes(value, false, false));
14718 }
14719
14720 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
14721 ///
14722 /// The method is looked up on the value (through its prototype), called with no
14723 /// arguments, and its result becomes the iterator. A generator gets here through
14724 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
14725 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
14726 ///
14727 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
14728 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
14729 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
14730 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
14731 /// does, and a user-defined iterable works without a special case.
14732 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
14733 /// `Symbol.iterator`.
14734 ///
14735 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
14736 /// iterable is legal there, and each value it produces is simply already settled by
14737 /// the time the `await` around it runs.
14738 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14739 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
14740 let method = self.read_field_key(value, &async_key)?;
14741 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
14742 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
14743 // is *present but not callable* is a TypeError — it does not mean "try the other
14744 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
14745 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
14746 // guard is there to catch.
14747 let absent = matches!(method, Value::Undefined | Value::Null);
14748 if !absent {
14749 let Value::Object(object) = &method else {
14750 return Err(Signal::Throw(
14751 self.make_error("TypeError", "value is not iterable"),
14752 ));
14753 };
14754 if !object.is_callable() {
14755 return Err(Signal::Throw(
14756 self.make_error("TypeError", "value is not iterable"),
14757 ));
14758 }
14759 }
14760 if absent {
14761 // §7.4.2 step 5: the synchronous iterator is **wrapped**. `for await` and an async
14762 // generator's `yield*` both reach here, and the wrapper is what puts
14763 // `PromiseResolve(%Promise%, value)` between the sync iterator's `value` and the
14764 // caller — a poisoned `constructor` on that value rejects instead of being
14765 // yielded, and a rejection closes the synchronous iterator first.
14766 let sync = self.get_iterator(value)?;
14767 return self.async_from_sync_iterator(sync);
14768 }
14769 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14770 if !matches!(iterator, Value::Object(_)) {
14771 return Err(Signal::Throw(
14772 self.make_error("TypeError", "iterator is not an object"),
14773 ));
14774 }
14775 // §7.4.2 `GetIteratorFromMethod` step 3.b: `GetIteratorDirect` reads `next` and
14776 // §7.4.1 requires it to be **callable** straight away — a throwing `return` must
14777 // not be reached, because the `TypeError` comes before any stepping
14778 // (`fromEntries/iterator-not-closed-for-uncallable-next`).
14779 let next = self.read_field(&iterator, "next")?;
14780 if !matches!(&next, Value::Object(function) if function.is_callable()) {
14781 return Err(Signal::Throw(
14782 self.make_error("TypeError", "iterator's next method is not callable"),
14783 ));
14784 }
14785 Ok(Iterator {
14786 object: iterator,
14787 next,
14788 })
14789 }
14790
14791 /// `CreateAsyncFromSyncIterator(syncIteratorRecord)` (§27.1.4.1).
14792 ///
14793 /// The wrapper itself is script (see [`crate::builtins::async_from_sync`]); this only
14794 /// hands it the record and reads back its `next`. Both are properties of the wrapper, so
14795 /// the returned [`Iterator`] steps through `%AsyncFromSyncIteratorPrototype%.next`.
14796 fn async_from_sync_iterator(&mut self, sync: Iterator) -> JsResult<Iterator> {
14797 let Some(factory) = self.realm.async_from_sync.clone() else {
14798 // No wrapper installed (a realm whose heap refused to hold it): fall back to the
14799 // raw synchronous iterator rather than refusing to iterate at all.
14800 return Ok(sync);
14801 };
14802 let wrapper = self.call_value(factory, Value::Undefined, vec![sync.object, sync.next])?;
14803 let next = self.read_field(&wrapper, "next")?;
14804 Ok(Iterator {
14805 object: wrapper,
14806 next,
14807 })
14808 }
14809
14810 /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
14811 /// read — `@@iterator` is **not** consulted.
14812 ///
14813 /// The distinction is observable and test262 exercises it: a set-like object's `keys`
14814 /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
14815 /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
14816 /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
14817 /// refused it with "[object Object] is not iterable".
14818 pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
14819 if !matches!(value, Value::Object(_)) {
14820 return Err(self.type_error("iterator is not an object"));
14821 }
14822 let next = self.read_field(&value, "next")?;
14823 Ok(Iterator {
14824 object: value,
14825 next,
14826 })
14827 }
14828
14829 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14830 let key = self.realm.well_known_key(WellKnown::Iterator);
14831 let method = self.read_field_key(value, &key)?;
14832 let Value::Object(function) = &method else {
14833 return Err(Signal::Throw(self.make_error(
14834 "TypeError",
14835 &format!("{} is not iterable", value.to_js_string()),
14836 )));
14837 };
14838 if !function.is_callable() {
14839 return Err(Signal::Throw(self.make_error(
14840 "TypeError",
14841 &format!("{} is not iterable", value.to_js_string()),
14842 )));
14843 }
14844 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14845 // The spec requires an object here; a primitive iterator has no `next` to call
14846 // and would fail one step later with a confusing message.
14847 if !matches!(iterator, Value::Object(_)) {
14848 return Err(Signal::Throw(
14849 self.make_error("TypeError", "iterator is not an object"),
14850 ));
14851 }
14852 // `GetIteratorDirect` requires `next` to be **callable** right away, before any
14853 // stepping and therefore before any `return` can be reached
14854 // (`fromEntries/iterator-not-closed-for-uncallable-next`).
14855 let next = self.read_field(&iterator, "next")?;
14856 if !matches!(&next, Value::Object(function) if function.is_callable()) {
14857 return Err(Signal::Throw(
14858 self.make_error("TypeError", "iterator's next method is not callable"),
14859 ));
14860 }
14861 Ok(Iterator {
14862 object: iterator,
14863 next,
14864 })
14865 }
14866
14867 /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
14868 /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
14869 /// exception from `return` propagates normally instead of being swallowed. That is the
14870 /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
14871 /// because confusing them is exactly the bug both exist to avoid.
14872 pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
14873 let method = self.read_field(&iterator.object, "return")?;
14874 if matches!(method, Value::Undefined | Value::Null) {
14875 return Ok(());
14876 }
14877 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14878 return Err(self.type_error("iterator return is not a function"));
14879 }
14880 self.call_value(method, iterator.object.clone(), Vec::new())?;
14881 Ok(())
14882 }
14883
14884 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
14885 /// cannot replace it.
14886 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
14887 let method = self.read_field(&iterator.object, "return")?;
14888 if matches!(method, Value::Undefined | Value::Null) {
14889 return Ok(());
14890 }
14891 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14892 return Err(self.type_error("iterator return is not a function"));
14893 }
14894 self.call_value(method, iterator.object.clone(), Vec::new())?;
14895 Ok(())
14896 }
14897
14898 /// One step of an internal iterator: the value and whether it is exhausted.
14899 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
14900 // A real iterator (`next` is a function) answers with a result object.
14901 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
14902 let result =
14903 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
14904 let Some(result) = result.as_object().cloned() else {
14905 return Err(self.type_error("iterator result is not an object"));
14906 };
14907 let done = self
14908 .get_property(&result, "done")?
14909 .is_some_and(|value| value.to_boolean());
14910 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
14911 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
14912 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
14913 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
14914 // made an unrelated `value` getter observable after the loop was over.
14915 if done {
14916 return Ok((Value::Undefined, true));
14917 }
14918 let value = self
14919 .get_property(&result, "value")?
14920 .unwrap_or(Value::Undefined);
14921 return Ok((value, false));
14922 }
14923 // An iterator whose `next` is not callable is treated as exhausted, which is
14924 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
14925 // that are not iterable at all.
14926 Ok((Value::Undefined, true))
14927 }
14928
14929 /// `[...iterable]`: append everything the iterator yields, and answer the next
14930 /// index.
14931 ///
14932 /// This goes through the same iterator machinery `for-of` uses rather than copying
14933 /// an array's elements, because a spread source is any iterable: a string spreads
14934 /// into its characters and an array iterator spreads into its results. Handling
14935 /// only arrays made `[..."ab"]` come out empty with no error at all.
14936 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
14937 let Some(target) = array.as_object().cloned() else {
14938 return Ok(0);
14939 };
14940 let start = target.array_length().unwrap_or(0);
14941 let mut added = 0;
14942 let iterator = self.get_iterator(iterable)?;
14943 loop {
14944 let (value, done) = self.iterator_step(&iterator)?;
14945 if done {
14946 break;
14947 }
14948 target.array_set(self.heap, start + added, value);
14949 added += 1;
14950 }
14951 Ok((start + added) as i32)
14952 }
14953
14954 /// How an uncaught exception is reported.
14955 ///
14956 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
14957 /// with `ToString` — `js_std_dump_error` is three lines that end in
14958 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
14959 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
14960 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
14961 ///
14962 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
14963 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
14964 /// `toString`"; it does call it, but only for objects of a class it does not know how
14965 /// to walk, and never for errors, arrays or plain objects.
14966 ///
14967 /// A printer that fails must not take the reporter down with it, so that case falls
14968 /// back to the `ToString` rendering.
14969 pub fn describe_exception(&mut self, value: &Value) -> String {
14970 match crate::print::sprint(self, value) {
14971 Ok(text) => text,
14972 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
14973 }
14974 }
14975
14976 /// The file name of whatever is running, innermost frame first.
14977 ///
14978 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
14979 /// innermost frame's file name, without distinguishing a module body from a plain
14980 /// script. `import()` uses it as the base for a relative specifier, which is why
14981 /// `import('./x.js')` inside a script resolves next to the script and not next to the
14982 /// process's working directory.
14983 pub fn script_or_module_name(&self) -> Option<String> {
14984 self.script_or_module_name_at(0)
14985 }
14986
14987 /// [`Interp::script_or_module_name`] `level` frames further out.
14988 ///
14989 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
14990 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
14991 /// frame without a file name is skipped rather than counted, because a native call
14992 /// pushes no frame of its own and so cannot be a level.
14993 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
14994 self.frames
14995 .iter()
14996 .rev()
14997 .filter_map(|frame| frame.code.code.filename.clone())
14998 .nth(level)
14999 }
15000
15001 /// The innermost frame name that could be a *file*, skipping `<eval>`-style pseudo-names.
15002 ///
15003 /// `eval` and `std.evalScript` compile their bodies under `<input>` / `<evalScript>`
15004 /// because that is what a stack trace should print, but §19.2.1.1's
15005 /// `GetActiveScriptOrModule` makes an eval'd body belong to the script that called it —
15006 /// never to something called `<input>`. Resolving `import('./x.js')` against a pseudo-name
15007 /// produced the bare specifier `x.js`, which the loader then looked for in the working
15008 /// directory instead of beside the file that called `eval`.
15009 pub fn script_or_module_file_name(&self) -> Option<String> {
15010 self.frames.iter().rev().find_map(|frame| {
15011 let name = frame.code.code.filename.as_deref()?;
15012 (!name.starts_with('<')).then(|| name.to_string())
15013 })
15014 }
15015
15016 /// The current call stack, formatted the way `qjs` prints `error.stack`.
15017 ///
15018 /// One ` at name (file:line:col)` line per active frame, innermost first. The
15019 /// position is the one recorded for the instruction each frame is stopped on, which
15020 /// is why the compiler builds a pc-to-position table per function: without it a
15021 /// trace could only name the function, not the line inside it.
15022 ///
15023 /// A frame whose code has no positions prints just `(file)`, matching the
15024 /// reference's output for stripped bytecode.
15025 pub fn stack_trace(&self) -> String {
15026 self.stack_trace_skipping(0)
15027 }
15028
15029 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
15030 fn stack_trace_skipping(&self, skip: usize) -> String {
15031 // One ordered list, innermost first, so `skip` counts the same thing whether the
15032 // frames it leaves out are native or bytecode. Indices rather than references: a
15033 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
15034 let depth = self.frames.len();
15035 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
15036 // A native entered while `at` bytecode frames were live was called *from* the
15037 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
15038 // entered at the current depth are therefore innermost of all.
15039 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
15040 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
15041 if *at == wanted {
15042 order.push((true, index));
15043 }
15044 }
15045 };
15046 push_natives(&mut order, depth);
15047 for index in (0..depth).rev() {
15048 order.push((false, index));
15049 push_natives(&mut order, index);
15050 }
15051 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
15052 // barrier. Natives entered at exactly the barrier depth are the eval entry point
15053 // itself (`evalScript (native)`), and the reference leaves those out too.
15054 if let Some(barrier) = self.trace_barriers.last().copied() {
15055 order.retain(|(is_native, index)| match is_native {
15056 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
15057 false => *index >= barrier,
15058 });
15059 }
15060
15061 let mut out = String::new();
15062 for (is_native, index) in order.into_iter().skip(skip) {
15063 match is_native {
15064 true => {
15065 out.push_str(" at ");
15066 let (native, _) = &self.native_frames[index];
15067 let name = native
15068 .own_property("name")
15069 .and_then(|property| property.value)
15070 .map(|value| value.to_js_string())
15071 .unwrap_or_default();
15072 out.push_str(&name);
15073 out.push_str(" (native)\n");
15074 }
15075 false => {
15076 let frame = &self.frames[index];
15077 let code = &frame.code.code;
15078 let file = code.filename.as_deref().unwrap_or("<input>");
15079 // The name comes from the function *object*, not from the compiled code:
15080 // an anonymous function expression is named by the property it is stored
15081 // in (`{valueOf: function(){}}`), which only the object knows.
15082 let bound_name = match &frame.callee {
15083 Value::Object(object) => {
15084 object
15085 .own_property("name")
15086 .and_then(|property| match property.value {
15087 Some(Value::String(text)) if !text.wtf8().is_empty() => {
15088 Some(text.to_string_lossy().into_owned())
15089 }
15090 _ => None,
15091 })
15092 }
15093 _ => None,
15094 };
15095 // No callee object means the body was entered by the host, so the
15096 // name has to come from the compiled code. Two cases differ:
15097 //
15098 // * an *unnamed* function of any kind — the reference reads the
15099 // `name` property, finds it empty, and prints `<anonymous>`;
15100 // * a *module* body, which has no `name` property at all: the
15101 // reference builds that function object with `js_closure2` and
15102 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
15103 // so a trace reaching it also prints `<anonymous>` — while a
15104 // *script* body prints `<eval>`, its `name`.
15105 let unnamed = code.name.is_empty() || code.module.is_some();
15106 out.push_str(" at ");
15107 match bound_name.as_deref() {
15108 Some(name) => out.push_str(name),
15109 None if unnamed => out.push_str("<anonymous>"),
15110 None => out.push_str(&code.name),
15111 }
15112 match code.position_at(frame.at as u32) {
15113 Some((line, column)) => {
15114 out.push_str(&format!(" ({file}:{line}:{column})\n"));
15115 }
15116 None => out.push_str(&format!(" ({file})\n")),
15117 }
15118 }
15119 }
15120 }
15121 out
15122 }
15123
15124 /// Give an anonymous function the name of the property it is stored in.
15125 ///
15126 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
15127 /// enumerable and not configurable, and a function that already has a real name
15128 /// keeps it.
15129 ///
15130 /// "Already named" means a *non-empty* name: every function object is created with
15131 /// a `name` of `""` so the property exists on all of them, and treating that empty
15132 /// string as a name left every anonymous function nameless — which is how a stack
15133 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
15134 /// `SetFunctionName`, for a name that came from source text.
15135 fn set_function_name(&mut self, function: &Value, name: &str) {
15136 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
15137 }
15138
15139 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
15140 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
15141 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
15142 let Value::Object(object) = function else {
15143 return;
15144 };
15145 // `SetFunctionName` applies to *functions* and classes only, and only when they are
15146 // anonymous. Without the callability guard, `{value: someObject}` renamed
15147 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
15148 // on the right-hand side of a property. That is how a `zipKeyed` result object
15149 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
15150 // has no `NamedEvaluation` at all.
15151 if !object.is_callable() {
15152 return;
15153 }
15154 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
15155 && !existing.wtf8().is_empty()
15156 {
15157 return;
15158 }
15159 let text = self.string_wtf8(name.clone());
15160 object.define("name", Property::name_or_length(text));
15161 }
15162
15163 // -- global declarations -----------------------------------------------
15164
15165 /// Declare a global binding, creating its reference cell.
15166 /// Declare a `var` or function global, whose home is the global object.
15167 ///
15168 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
15169 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
15170 /// such as `print`, or a redeclaration — is left alone.
15171 pub fn declare_var_global(&mut self, name: &str) {
15172 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
15173 // global object is exactly the leak `typeof my_var === "undefined"` after
15174 // `eval("var my_var=2")` rules out.
15175 if let Some(scope) = self.eval_scope.as_mut() {
15176 scope.entry(name.to_string()).or_insert(Value::Undefined);
15177 return;
15178 }
15179 // A sloppy direct eval declares into its *caller's* variable environment. Doing
15180 // this on the global object instead made `eval("var c = 1")` inside a parameter
15181 // list overwrite a global `c`, and made two calls to the same function share one
15182 // binding.
15183 if let Some(cell) = self.declare_eval_local(name) {
15184 cell.set(Value::Undefined);
15185 return;
15186 }
15187 let global = self.realm.global.clone();
15188 if global.own_property(name).is_some() {
15189 return;
15190 }
15191 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
15192 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
15193 // whole point of that trick and what lets `Object.defineProperty` reshape it
15194 // afterwards. `eval_scope` is `Some` while an eval is running.
15195 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
15196 global.define(
15197 name,
15198 Property {
15199 value: Some(Value::Undefined),
15200 writable: true,
15201 enumerable: true,
15202 configurable: from_eval,
15203 ..Property::default()
15204 },
15205 );
15206 }
15207
15208 /// Declare a *lexical* global binding, which starts in its dead zone.
15209 ///
15210 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
15211 /// global object and is created when its initialiser runs.
15212 pub fn declare_global(&mut self, name: &str, is_const: bool) {
15213 if is_const {
15214 self.realm.lexical_consts.insert(name.to_string());
15215 }
15216 if !self.realm.globals.contains_key(name) {
15217 // `Uninitialized` rather than `Undefined`: the binding exists but is not
15218 // readable until its initialiser runs, and that is what `let x` before
15219 // `x = 1` has to observe.
15220 let cell = self.new_cell(Value::Uninitialized);
15221 self.realm.globals.insert(name.to_string(), cell);
15222 self.realm.declared.push(name.to_string());
15223 }
15224 }
15225}
15226
15227/// The bytecode and environment of a function object, if it is a bytecode function.
15228///
15229/// Extracted before a call so no borrow of the object is held across it.
15230fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
15231 function.with(|data| match &data.kind {
15232 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
15233 _ => None,
15234 })
15235}
15236
15237/// A native call target, extracted before the call so no borrow is held.
15238enum NativeCall {
15239 Native(NativeFn),
15240 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
15241 /// not hold that object's `RefCell` borrow.
15242 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
15243 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
15244 Bound {
15245 target: Value,
15246 this: Value,
15247 leading: Vec<Value>,
15248 },
15249 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
15250 Revoker(crate::object::ProxyRef),
15251 /// A promise's `resolve`.
15252 PromiseResolve(Gc<JsObject>),
15253 /// A promise's `reject`.
15254 PromiseReject(Gc<JsObject>),
15255 /// The executor `NewPromiseCapability(C)` hands a user constructor.
15256 CapabilityExecutor {
15257 state: Gc<JsObject>,
15258 },
15259 /// One leg of a `then` that settles through a user capability.
15260 ThenShim {
15261 handler: Option<Value>,
15262 resolve: Value,
15263 reject: Value,
15264 fulfilled: bool,
15265 },
15266 /// One continuation of an `await`.
15267 AwaitResume {
15268 coroutine: Gc<JsObject>,
15269 promise: Gc<JsObject>,
15270 kind: ResumeKind,
15271 },
15272 /// One element of a `Promise` combinator settling.
15273 CombinatorSettle {
15274 state: Gc<JsObject>,
15275 index: usize,
15276 fulfilled: bool,
15277 },
15278 /// One of `Promise.prototype.finally`'s two shims.
15279 FinallyShim {
15280 callback: Option<Value>,
15281 fulfilled: bool,
15282 constructor: Value,
15283 },
15284 /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
15285 ReturnValue(Value),
15286 /// A thunk that throws a fixed value, for `finally`'s `thrower`.
15287 ThrowValue(Value),
15288 /// Settle a promise with a fixed outcome.
15289 SettlePromise {
15290 promise: Gc<JsObject>,
15291 value: Value,
15292 rejected: bool,
15293 },
15294 /// Continue an async generator after its `await` settled.
15295 GeneratorResume {
15296 generator: Gc<JsObject>,
15297 promise: Gc<JsObject>,
15298 kind: ResumeKind,
15299 },
15300 /// Read a module namespace's binding out of its cell.
15301 ModuleBinding(Gc<Cell>),
15302 /// Finish a completed async generator's `return(v)` once `v` has settled.
15303 CompletedReturn {
15304 generator: Gc<JsObject>,
15305 promise: Gc<JsObject>,
15306 rejected: bool,
15307 },
15308 /// Answer a pending async-generator method with `{value, done}`.
15309 YieldResult {
15310 generator: Gc<JsObject>,
15311 promise: Gc<JsObject>,
15312 done: bool,
15313 },
15314 /// One step of `AsyncDisposableStack.disposeAsync`.
15315 DisposeStep {
15316 remaining: Gc<JsObject>,
15317 promise: Gc<JsObject>,
15318 error: Value,
15319 rejected: bool,
15320 awaited: bool,
15321 needs_await: bool,
15322 },
15323}
15324
15325/// What a store does when the object refuses the write.
15326#[derive(Clone, Copy, PartialEq, Eq)]
15327pub enum DeleteFailure {
15328 /// Raise a `TypeError`, which is what strict mode and every built-in does.
15329 Throw,
15330 /// Ignore the write, which is what a sloppy-mode assignment does.
15331 Ignore,
15332}
15333
15334/// Whether `object` is a `Date` instance, by the class tag it carries.
15335///
15336/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
15337/// builtins module depending on the interpreter's conversion order.
15338fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
15339 interp
15340 .internal_get(object, "_class")
15341 .is_some_and(|value| value.to_js_string() == "Date")
15342}
15343
15344/// Which type `ToPrimitive` prefers when it converts an object.
15345#[derive(Clone, Copy, PartialEq, Eq)]
15346pub enum Hint {
15347 /// The default hint, which behaves like [`Hint::Number`].
15348 Default,
15349 /// `Number(obj)` and the arithmetic operators.
15350 Number,
15351 /// `String(obj)` and `ToPropertyKey`.
15352 String,
15353}
15354
15355/// Which table a binding slot indexes, for the messages that name it.
15356#[derive(Clone, Copy)]
15357enum VarSlot {
15358 Loc,
15359 Closure,
15360}
15361
15362/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
15363fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
15364 Ok(this)
15365}
15366
15367/// An internal iterator: the sequence plus a cursor.
15368pub(crate) struct Iterator {
15369 pub(crate) object: Value,
15370 pub(crate) next: Value,
15371}
15372
15373/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
15374/// and plain `a` for a method.
15375///
15376/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
15377/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
15378/// reads `at get a (file:1:2)`.
15379/// The same prefixing, for a name that may hold an unpaired surrogate.
15380fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
15381 let prefix = match flags & 3 {
15382 1 => "get ",
15383 2 => "set ",
15384 _ => return key.clone(),
15385 };
15386 let mut units: Vec<u16> = prefix.encode_utf16().collect();
15387 units.extend_from_slice(&key.to_units());
15388 crate::value::Wtf8::from_units(&units)
15389}
15390
15391fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
15392 match flags & 3 {
15393 1 => format!("get {key}"),
15394 2 => format!("set {key}"),
15395 _ => key.to_string(),
15396 }
15397}
15398
15399/// Define a method or accessor property, per the `define_method` flag byte.
15400///
15401/// The low two bits pick value/getter/setter and bit 2 marks the property
15402/// enumerable.
15403///
15404/// A getter and a setter arrive as two separate `define_method` instructions, and the
15405/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
15406/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
15407/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
15408/// `JS_DefineProperty`, which leaves the other half alone.
15409fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
15410 let enumerable = flags & 4 != 0;
15411 let kind = flags & 3;
15412 let existing = object.own_property_key(key);
15413 let property = match kind {
15414 1 => Property {
15415 getter: Some(function),
15416 // The setter half, if this literal already defined one.
15417 setter: existing
15418 .filter(Property::is_accessor)
15419 .and_then(|p| p.setter),
15420 enumerable,
15421 configurable: true,
15422 ..Property::default()
15423 },
15424 2 => Property {
15425 getter: existing
15426 .filter(Property::is_accessor)
15427 .and_then(|p| p.getter),
15428 setter: Some(function),
15429 enumerable,
15430 configurable: true,
15431 ..Property::default()
15432 },
15433 _ => Property {
15434 value: Some(function),
15435 writable: true,
15436 enumerable,
15437 configurable: true,
15438 ..Property::default()
15439 },
15440 };
15441 object.define_key(key, property);
15442}
15443
15444// ---------------------------------------------------------------------------
15445// Operand decoding
15446// ---------------------------------------------------------------------------
15447
15448/// How `print` renders a value: the reference's `JS_PrintValue`.
15449///
15450/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
15451/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
15452/// The format is reproduced closely because the test suite compares output text:
15453///
15454/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
15455/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
15456/// * a cycle prints `[circular N]` with `N` the stack index of the object;
15457/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
15458/// end print as `<N empty item(s)>`;
15459/// * a string is quoted inside a container but raw at the top level, which is why
15460/// `print("x")` and `print(["x"])` differ.
15461pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
15462 // A string argument is printed raw: `js_print` converts it with `ToString`
15463 // instead of dumping it, and the quoting only appears inside a container.
15464 if let Value::String(text) = value {
15465 return text.to_string_lossy().into_owned();
15466 }
15467 let mut printer = Printer {
15468 interp,
15469 out: String::new(),
15470 stack: Vec::new(),
15471 };
15472 printer.value(value, 0);
15473 printer.out
15474}
15475
15476/// The internal class name an object carries, when it has one.
15477fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
15478 interp
15479 .internal_get(object, "_class")
15480 .map(|value| value.to_js_string())
15481}
15482
15483/// A string property, looked up the way `GetProperty` does: own first, then the
15484/// prototype chain. Needed because the print formatter holds the interpreter
15485/// immutably and so cannot run getters.
15486fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
15487 let mut current = Some(object.clone());
15488 // Bounded, because a prototype cycle would otherwise loop forever.
15489 for _ in 0..100 {
15490 let node = current?;
15491 if let Some(property) = node.own_property(name)
15492 && let Some(value) = property.value
15493 {
15494 return Some(value.to_js_string());
15495 }
15496 current = node.with(|data| data.proto.clone());
15497 }
15498 None
15499}
15500
15501/// The `JS_PrintValue` state: output, and the objects currently being printed.
15502struct Printer<'a, 'rt> {
15503 /// Kept for the class-name lookups that typed arrays and `Date` will need.
15504 #[allow(dead_code)]
15505 interp: &'a Interp<'rt>,
15506 out: String,
15507 stack: Vec<Gc<JsObject>>,
15508}
15509
15510impl Printer<'_, '_> {
15511 /// Depth past which a container is summarised by its class name.
15512 const MAX_DEPTH: usize = 2;
15513
15514 fn value(&mut self, value: &Value, level: usize) {
15515 match value {
15516 Value::Undefined
15517 | Value::Uninitialized
15518 | Value::Hole
15519 | Value::CatchOffset(_)
15520 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
15521 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
15522 // The printer writes a bigint the way the language spells one, so a dump is
15523 // unambiguous about which kind of number it is showing.
15524 Value::BigInt(big) => {
15525 self.out.push_str(&big.to_decimal_string());
15526 self.out.push('n');
15527 }
15528 Value::Null => self.out.push_str("null"),
15529 Value::Bool(true) => self.out.push_str("true"),
15530 Value::Bool(false) => self.out.push_str("false"),
15531 Value::Int(number) => self.out.push_str(&number.to_string()),
15532 Value::Float(number) => {
15533 self.out
15534 .push_str(&crate::value::number_to_string_for_print(*number));
15535 }
15536 Value::String(text) => self.print_string(&text.to_string_lossy()),
15537 Value::Object(object) => self.object(object, level),
15538 }
15539 }
15540
15541 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
15542 // A cycle is reported rather than followed; the index is where the object
15543 // already sits in the print stack, which is what the reference shows.
15544 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
15545 self.out.push_str(&format!("[circular {index}]"));
15546 return;
15547 }
15548 if object.is_callable() {
15549 let name = object
15550 .own_property("name")
15551 .and_then(|property| property.value)
15552 .map(|value| value.to_js_string())
15553 .unwrap_or_default();
15554 if name.is_empty() {
15555 self.out.push_str("[Function (anonymous)]");
15556 } else {
15557 self.out.push_str(&format!("[Function {name}]"));
15558 }
15559 return;
15560 }
15561 if level >= Self::MAX_DEPTH {
15562 let class = if object.is_array() { "Array" } else { "Object" };
15563 self.out.push_str(&format!("[{class}]"));
15564 return;
15565 }
15566 // `Date` and `Error` print as themselves rather than as bags of properties:
15567 // the ISO string, and `Name: message` followed by the trace.
15568 if let Some(class) = class_of(self.interp, object) {
15569 if class == "Date" {
15570 self.date(object);
15571 return;
15572 }
15573 if class == "Error" {
15574 self.error(object);
15575 return;
15576 }
15577 }
15578 self.stack.push(object.clone());
15579 if object.is_array() {
15580 self.array(object, level);
15581 } else {
15582 self.plain_object(object, level);
15583 }
15584 self.stack.pop();
15585 }
15586
15587 /// A Date prints as its ISO string; an invalid one falls through to the plain
15588 /// object form, the way the reference falls back when `toISOString` throws.
15589 fn date(&mut self, object: &Gc<JsObject>) {
15590 let value = self
15591 .interp
15592 .internal_get(object, "_date_value")
15593 .map(|value| value.to_number());
15594 match value.and_then(crate::builtins::date::iso_string) {
15595 Some(text) => self.out.push_str(&text),
15596 None => self.plain_object(object, 0),
15597 }
15598 }
15599
15600 /// `Name: message`, then the trace with its trailing newline removed.
15601 fn error(&mut self, object: &Gc<JsObject>) {
15602 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
15603 self.out.push_str(&name);
15604 if let Some(message) = inherited(object, "message")
15605 && !message.is_empty()
15606 {
15607 self.out.push_str(": ");
15608 self.out.push_str(&message);
15609 }
15610 if let Some(stack) = inherited(object, "stack") {
15611 self.out.push('\n');
15612 self.out.push_str(stack.trim_end_matches('\n'));
15613 }
15614 }
15615
15616 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
15617 let elements = object.array_elements().unwrap_or_default();
15618 self.out.push_str("[ ");
15619 // An interior hole means the array is "sparse": the reference prints those
15620 // as `index: value` pairs and says nothing about the holes themselves, while
15621 // a hole run at the end becomes a single `<N empty items>` note.
15622 let last_present = elements
15623 .iter()
15624 .rposition(|value| !matches!(value, Value::Hole));
15625 let has_interior_hole = match last_present {
15626 Some(last) => elements[..last]
15627 .iter()
15628 .any(|value| matches!(value, Value::Hole)),
15629 None => false,
15630 };
15631 let mut first = true;
15632 if has_interior_hole {
15633 let mut index = 0;
15634 while index < elements.len() {
15635 let value = &elements[index];
15636 if matches!(value, Value::Hole) {
15637 index += 1;
15638 continue;
15639 }
15640 if !first {
15641 self.out.push_str(", ");
15642 }
15643 first = false;
15644 self.out.push_str(&format!("{index}: "));
15645 self.value(value, level + 1);
15646 index += 1;
15647 }
15648 } else {
15649 for (index, value) in elements.iter().enumerate() {
15650 if matches!(value, Value::Hole) {
15651 continue;
15652 }
15653 if !first {
15654 self.out.push_str(", ");
15655 }
15656 first = false;
15657 let _ = index;
15658 self.value(value, level + 1);
15659 }
15660 if let Some(last) = last_present {
15661 let trailing = elements.len() - last - 1;
15662 if trailing > 0 {
15663 if !first {
15664 self.out.push_str(", ");
15665 }
15666 self.out.push_str(&format!(
15667 "<{trailing} empty item{}>",
15668 if trailing > 1 { "s" } else { "" }
15669 ));
15670 }
15671 } else if !elements.is_empty() {
15672 let count = elements.len();
15673 self.out.push_str(&format!(
15674 "<{count} empty item{}>",
15675 if count > 1 { "s" } else { "" }
15676 ));
15677 }
15678 }
15679 self.out.push_str(" ]");
15680 }
15681
15682 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
15683 self.out.push_str("{ ");
15684 let mut first = true;
15685 for key in object.own_keys() {
15686 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
15687 continue;
15688 };
15689 if !property.enumerable {
15690 continue;
15691 }
15692 if !first {
15693 self.out.push_str(", ");
15694 }
15695 first = false;
15696 self.out
15697 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
15698 &key.to_string_lossy(),
15699 )));
15700 self.out.push_str(": ");
15701 // An accessor has no value to dump; the reference names the half that
15702 // exists instead of calling it.
15703 if property.is_accessor() {
15704 let text = match (property.getter.is_some(), property.setter.is_some()) {
15705 (true, true) => "[Getter/Setter]",
15706 (false, true) => "[Setter]",
15707 _ => "[Getter]",
15708 };
15709 self.out.push_str(text);
15710 } else {
15711 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
15712 }
15713 }
15714 self.out.push_str(" }");
15715 }
15716
15717 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
15718 fn print_string(&mut self, text: &str) {
15719 self.out.push('"');
15720 for character in text.chars() {
15721 match character {
15722 '"' => self.out.push_str("\\\""),
15723 '\\' => self.out.push_str("\\\\"),
15724 '\n' => self.out.push_str("\\n"),
15725 '\r' => self.out.push_str("\\r"),
15726 '\t' => self.out.push_str("\\t"),
15727 c if (c as u32) < 0x20 => {
15728 self.out.push_str(&format!("\\u{:04x}", c as u32));
15729 }
15730 c => self.out.push(c),
15731 }
15732 }
15733 self.out.push('"');
15734 }
15735}
15736
15737/// How `print` renders a value.
15738///
15739/// `ToString`, except that negative zero keeps its sign — the reference's host
15740/// printer does that while `String(-0)` is `"0"`.
15741pub fn display(value: &Value) -> String {
15742 match value {
15743 Value::Float(number) => crate::value::number_to_string_for_print(*number),
15744 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
15745 "undefined".to_string()
15746 }
15747 other => other.to_js_string(),
15748 }
15749}
15750
15751// ---------------------------------------------------------------------------
15752// Numeric operators
15753// ---------------------------------------------------------------------------
15754
15755/// `a + b` keeping the `Int` representation when it fits.
15756fn add_numbers(left: Value, right: Value) -> Value {
15757 match (&left, &right) {
15758 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
15759 Some(sum) => Value::Int(sum),
15760 None => Value::Float(*a as f64 + *b as f64),
15761 },
15762 _ => Value::Float(left.to_number() + right.to_number()),
15763 }
15764}
15765
15766/// The arithmetic operators other than `+`, which needs string concatenation.
15767fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15768 use Opcode::*;
15769 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
15770 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
15771 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
15772 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
15773 return Ok(match op {
15774 And => Value::Int(x & y),
15775 Or => Value::Int(x | y),
15776 Xor => Value::Int(x ^ y),
15777 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
15778 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
15779 Shr => match (*x as u32) >> ((*y as u32) & 31) {
15780 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
15781 shifted => Value::Float(shifted as f64),
15782 },
15783 Sub => match x.checked_sub(*y) {
15784 Some(value) => Value::Int(value),
15785 None => Value::Float(*x as f64 - *y as f64),
15786 },
15787 _ => return arithmetic_slow(op, left, right),
15788 });
15789 }
15790 arithmetic_slow(op, left, right)
15791}
15792
15793/// [`arithmetic`] for everything the integer fast path above does not take.
15794fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15795 use Opcode::*;
15796 let (a, b) = (left.to_number(), right.to_number());
15797 Ok(match op {
15798 Sub => match (&left, &right) {
15799 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
15800 Some(value) => Value::Int(value),
15801 None => Value::Float(a - b),
15802 },
15803 _ => Value::Float(a - b),
15804 },
15805 Mul => Value::Float(a * b),
15806 Div => Value::Float(a / b),
15807 Mod => Value::Float(js_mod(a, b)),
15808 Pow => Value::Float(a.powf(b)),
15809 And => Value::Int(left.to_int32() & right.to_int32()),
15810 Or => Value::Int(left.to_int32() | right.to_int32()),
15811 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
15812 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
15813 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
15814 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
15815 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
15816 // fits the small-integer representation stays an `Int`; the rest become a
15817 // float, which is how the reference keeps `n >>> 0` non-negative.
15818 Shr => {
15819 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
15820 match i32::try_from(shifted) {
15821 Ok(value) => Value::Int(value),
15822 Err(_) => Value::Float(shifted as f64),
15823 }
15824 }
15825 _ => Value::Float(a),
15826 })
15827}
15828
15829/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
15830///
15831/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
15832/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
15833/// slow path where the rules live.
15834fn is_number(value: &Value) -> bool {
15835 matches!(value, Value::Int(_) | Value::Float(_))
15836}
15837
15838/// The `Value::Bool` a comparison operator answers for `ordering`.
15839///
15840/// `None` is the unordered case — a `NaN` on either side — and every operator answers
15841/// false for it, including `<=` and `>=`.
15842fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
15843 use Opcode::*;
15844 let answer = match (op, ordering) {
15845 (_, None) => false,
15846 (Lt, Some(ordering)) => ordering.is_lt(),
15847 (Lte, Some(ordering)) => ordering.is_le(),
15848 (Gt, Some(ordering)) => ordering.is_gt(),
15849 (Gte, Some(ordering)) => ordering.is_ge(),
15850 _ => false,
15851 };
15852 Value::Bool(answer)
15853}
15854
15855/// `%`, which follows the sign of the dividend rather than Rust's.
15856fn js_mod(left: f64, right: f64) -> f64 {
15857 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
15858 return f64::NAN;
15859 }
15860 if right.is_infinite() {
15861 return left;
15862 }
15863 let remainder = left % right;
15864 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
15865 // the spec makes the sign match the dividend.
15866 if remainder == 0.0 {
15867 0.0f64.copysign(left)
15868 } else {
15869 remainder
15870 }
15871}
15872
15873fn negate(value: Value) -> Value {
15874 match value {
15875 Value::Int(0) => Value::Float(-0.0),
15876 Value::Int(i) => Value::Int(-i),
15877 other => Value::Float(-other.to_number()),
15878 }
15879}
15880
15881fn increment(value: Value) -> Value {
15882 match value {
15883 Value::Int(i) => match i.checked_add(1) {
15884 Some(next) => Value::Int(next),
15885 None => Value::Float(i as f64 + 1.0),
15886 },
15887 other => Value::Float(other.to_number() + 1.0),
15888 }
15889}
15890
15891fn decrement(value: Value) -> Value {
15892 match value {
15893 Value::Int(i) => match i.checked_sub(1) {
15894 Some(next) => Value::Int(next),
15895 None => Value::Float(i as f64 - 1.0),
15896 },
15897 other => Value::Float(other.to_number() - 1.0),
15898 }
15899}
15900
15901/// Compare a `BigInt` with an `f64` on their mathematical values.
15902///
15903/// Neither side is rounded to the other's precision: the number is split into its integer
15904/// part (compared as an exact bigint) and its fraction, which is what decides the answer
15905/// when the integer parts are equal. An infinite value is larger than every bigint.
15906fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
15907 use std::cmp::Ordering;
15908 if number.is_nan() {
15909 return None;
15910 }
15911 if number.is_infinite() {
15912 return Some(if number > 0.0 {
15913 Ordering::Less
15914 } else {
15915 Ordering::Greater
15916 });
15917 }
15918 let truncated = number.trunc();
15919 // A number wider than `i128` still has an exact integer part, but no bigint form we can
15920 // build cheaply; the sign of the difference is all that is needed, so compare against
15921 // the bigint's own magnitude instead.
15922 if truncated.abs() >= 1.7e38 {
15923 let big_as_f64 = big.to_f64();
15924 return big_as_f64.partial_cmp(&number);
15925 }
15926 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
15927 match big.cmp(&integer) {
15928 Ordering::Equal => {
15929 // Same integer part: the fraction decides, and a negative number's fraction is
15930 // below the integer (`-1.5` truncates to `-1`).
15931 if number > truncated {
15932 Some(Ordering::Less)
15933 } else if number < truncated {
15934 Some(Ordering::Greater)
15935 } else {
15936 Some(Ordering::Equal)
15937 }
15938 }
15939 other => Some(other),
15940 }
15941}
15942
15943/// `CanonicalNumericIndexString(argument)` (§7.1.21).
15944///
15945/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
15946/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
15947/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
15948/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
15949/// rather than treating it as `0`.
15950fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
15951 let PropertyKey::String(text) = key else {
15952 // A symbol is never an index.
15953 return None;
15954 };
15955 let text = text.to_string_lossy();
15956 if text == "-0" {
15957 return Some(-0.0);
15958 }
15959 let number: f64 = text.parse().ok()?;
15960 // The round-trip test *is* the definition: only the canonical spelling qualifies.
15961 // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
15962 // `"0.10"` does not.
15963 let rendered = Value::Float(number).to_js_string();
15964 (rendered == text).then_some(number)
15965}
15966
15967/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
15968///
15969/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
15970/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
15971/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
15972/// numeric and invalid, which is why they stop the prototype chain instead of falling
15973/// through it.
15974///
15975/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
15976/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
15977/// `in`, `delete` and `defineProperty` separately to make sure it does not.
15978fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
15979 numeric.is_finite()
15980 && numeric.fract() == 0.0
15981 && !(numeric == 0.0 && numeric.is_sign_negative())
15982 && numeric >= 0.0
15983 && object
15984 .typed_array_length()
15985 .is_some_and(|length| (numeric as usize) < length)
15986}
15987
15988/// `ArrayCreate`'s length bound, `2**32 - 1`.
15989///
15990/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
15991/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
15992/// through — can enforce it without depending on a builtin module.
15993const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;