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(), Value::Undefined)?;
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, function)
2839 }
2840
2841 /// Build a coroutine over an already-resolved body.
2842 ///
2843 /// `callee` is the function object the body belongs to, or `undefined` when there is
2844 /// none — a module with top-level `await`. It has to be handed over rather than
2845 /// defaulted: the frame's callee is what `special_object 2` answers, and an async
2846 /// function's body uses that to initialise its own-name binding. Passing `undefined`
2847 /// made `var f = async function Binding(){ return typeof Binding }` answer
2848 /// `"undefined"`, so a named async function expression could not see its own name and
2849 /// `Binding = 1` inside it silently succeeded (`named-reassign-fn-name-in-body`).
2850 fn new_coroutine_from(
2851 &mut self,
2852 code: Gc<CompiledCode>,
2853 env: Gc<ClosureEnv>,
2854 this: Value,
2855 args: Vec<Value>,
2856 callee: Value,
2857 ) -> JsResult<Gc<JsObject>> {
2858 self.push_frame(code, env, this, args, callee)?;
2859 let frame = self.frames.pop().expect("push_frame just pushed it");
2860 let state = GeneratorState {
2861 frame: Some(frame),
2862 phase: GeneratorPhase::SuspendedStart,
2863 parked_on_await: false,
2864 parked_on_yield_star: false,
2865 requests: std::collections::VecDeque::new(),
2866 async_busy: false,
2867 // An `async function` body is driven by `drive_async`, never by the generator
2868 // protocol, and the object is not reachable from script.
2869 is_async: false,
2870 };
2871 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2872 coroutine.with_mut(|data| {
2873 data.kind = ObjectKind::Generator(Box::new(state));
2874 });
2875 Ok(coroutine)
2876 }
2877
2878 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2879 /// `await` and `value` is what it awaited.
2880 fn resume_coroutine(
2881 &mut self,
2882 coroutine: &Gc<JsObject>,
2883 kind: ResumeKind,
2884 value: Value,
2885 ) -> JsResult<(Value, bool)> {
2886 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2887 ObjectKind::Generator(state) => {
2888 let is_async = state.is_async;
2889 Some(std::mem::replace(
2890 state.as_mut(),
2891 GeneratorState {
2892 frame: None,
2893 phase: GeneratorPhase::Executing,
2894 parked_on_await: false,
2895 parked_on_yield_star: false,
2896 requests: std::collections::VecDeque::new(),
2897 async_busy: false,
2898 is_async,
2899 },
2900 ))
2901 }
2902 _ => None,
2903 }) else {
2904 return Err(self.type_error("not a coroutine"));
2905 };
2906 let result = self.step_generator(&mut state, kind, value);
2907 coroutine.with_mut(|data| {
2908 data.kind = ObjectKind::Generator(Box::new(state));
2909 });
2910 let (value, done, _ready, _reason) = result?;
2911 Ok((value, done))
2912 }
2913
2914 /// Advance an async body and settle its promise with the outcome.
2915 fn drive_async(
2916 &mut self,
2917 coroutine: &Gc<JsObject>,
2918 promise: &Gc<JsObject>,
2919 kind: ResumeKind,
2920 value: Value,
2921 ) -> JsResult<()> {
2922 match self.resume_coroutine(coroutine, kind, value) {
2923 Ok((value, true)) => {
2924 // `Ok` with `done` means the body finished *normally*, even when it was
2925 // resumed by a `throw` — `try { await p } catch {}` completes by
2926 // returning. Only the `Err` arm below is a rejection.
2927 //
2928 // Resolving rather than fulfilling matters: `return promise` in an async
2929 // body adopts the inner promise, so `async function f(){ return
2930 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2931 // promise.
2932 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2933 self.reject_promise(promise, reason);
2934 }
2935 Ok(())
2936 }
2937 Ok((value, false)) => {
2938 // Parked on `await`: follow what it awaited and resume with the outcome.
2939 let awaited = match self.promise_resolve_value(value) {
2940 Ok(awaited) => awaited,
2941 Err(Signal::Throw(error)) => {
2942 self.reject_promise(promise, error);
2943 return Ok(());
2944 }
2945 Err(other) => return Err(other),
2946 };
2947 self.hook_await(awaited, coroutine, promise)
2948 }
2949 Err(Signal::Throw(reason)) => {
2950 self.reject_promise(promise, reason);
2951 Ok(())
2952 }
2953 Err(other) => Err(other),
2954 }
2955 }
2956
2957 /// Arrange for `coroutine` to resume when `awaited` settles.
2958 fn hook_await(
2959 &mut self,
2960 awaited: Value,
2961 coroutine: &Gc<JsObject>,
2962 promise: &Gc<JsObject>,
2963 ) -> JsResult<()> {
2964 let resumed = JsObject::function(
2965 self.heap,
2966 Some(self.realm.function_proto.clone()),
2967 Callable::AwaitResume {
2968 coroutine: coroutine.clone(),
2969 promise: promise.clone(),
2970 kind: ResumeKind::Next,
2971 },
2972 );
2973 let raised = JsObject::function(
2974 self.heap,
2975 Some(self.realm.function_proto.clone()),
2976 Callable::AwaitResume {
2977 coroutine: coroutine.clone(),
2978 promise: promise.clone(),
2979 kind: ResumeKind::Throw,
2980 },
2981 );
2982 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2983 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2984 let Value::Object(awaited) = &awaited else {
2985 self.jobs.push_back(Job::Resume {
2986 coroutine: coroutine.clone(),
2987 promise: promise.clone(),
2988 kind: ResumeKind::Next,
2989 value: awaited,
2990 });
2991 return Ok(());
2992 };
2993 self.perform_then(
2994 awaited,
2995 Some(Value::Object(resumed)),
2996 Some(Value::Object(raised)),
2997 )?;
2998 Ok(())
2999 }
3000
3001 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
3002 /// things an engine keeps outside it — array elements and an array's `length`.
3003 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
3004 if let Some(property) = object.own_property_key(key) {
3005 return Some(property);
3006 }
3007 // A typed array's indices are bytes in its buffer, so a descriptor for one has to
3008 // be synthesized too — and every one of them is a plain writable, enumerable,
3009 // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
3010 // `undefined` before this, which made `key-is-numericindex` fail on its own
3011 // side effect check.
3012 //
3013 // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
3014 // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
3015 // likewise not elements however numeric they look.
3016 if object.typed_array_element_type().is_some()
3017 && let Some(numeric) = canonical_numeric_index(key)
3018 && numeric.is_finite()
3019 && numeric.fract() == 0.0
3020 && !(numeric == 0.0 && numeric.is_sign_negative())
3021 && numeric >= 0.0
3022 && (numeric as usize) < object.typed_array_length().unwrap_or(0)
3023 {
3024 let value = object.typed_array_element(numeric as usize)?;
3025 return Some(Property::data(value));
3026 }
3027 // An array's elements live in their own vector rather than the property table, so
3028 // a descriptor for one has to be synthesized — with the attributes an element has.
3029 if let Some(index) = key.as_str().and_then(array_index)
3030 && let Some(value) = object.array_get(index as usize)
3031 && !matches!(value, Value::Hole)
3032 {
3033 return Some(Property::data(value));
3034 }
3035 // `length` is an own property of an array that is not in its property table
3036 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
3037 // and non-enumerable.
3038 if key.as_str() == Some("length")
3039 && let Some(length) = object.array_length()
3040 {
3041 return Some(Property {
3042 value: Some(crate::object::length_value(length)),
3043 writable: object.length_writable(),
3044 enumerable: false,
3045 configurable: false,
3046 getter: None,
3047 setter: None,
3048 descriptor_fields: None,
3049 });
3050 }
3051 None
3052 }
3053
3054 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
3055 pub fn object_get_own_property(
3056 &mut self,
3057 object: &Gc<JsObject>,
3058 key: &PropertyKey,
3059 ) -> JsResult<Option<Property>> {
3060 if let Some(answer) = self.proxy_get_own_property(object, key)? {
3061 return Ok(answer);
3062 }
3063 if let Some(exotic) = object.exotic()
3064 && let Some(answer) = exotic.get_own_property(self, object, key)?
3065 {
3066 return Ok(answer);
3067 }
3068 // A module namespace's bindings are accessors internally and data properties to
3069 // script; see `namespace_own_property`.
3070 if object.module_namespace_marker() {
3071 return self.namespace_own_property(object, key);
3072 }
3073 // A mapped `arguments` index is a data property as far as script can see: the
3074 // accessor pair that aliases the parameter is plumbing, and exposing it would
3075 // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
3076 // report a `get` where the spec has a `[[Value]]`.
3077 if let Some(index) = key.as_str().and_then(crate::object::array_index)
3078 && let Some(cell) = object.mapped_argument_cell(index as usize)
3079 {
3080 // Non-configurable is *not* the default: an ordinary mapped index is
3081 // configurable, and only becomes non-configurable once something
3082 // redefines it. Preserve whatever the property table currently says.
3083 // The attributes come from whatever the property table holds, because they
3084 // can be changed independently of the mapping; only the *value* and the
3085 // data-property *kind* are the accessor's secret.
3086 let flags = Self::ordinary_own_property(object, key);
3087 if let Some(existing) = &flags
3088 && !existing.is_accessor()
3089 {
3090 // Already demapped: the table entry is the answer, not the cell.
3091 return Ok(flags);
3092 }
3093 return Ok(Some(Property {
3094 value: Some(cell.get()),
3095 writable: true,
3096 enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
3097 configurable: flags.as_ref().is_some_and(|p| p.configurable),
3098 ..Property::default()
3099 }));
3100 }
3101 Ok(Self::ordinary_own_property(object, key))
3102 }
3103
3104 /// Whether `object` is a module namespace exotic object (§10.4.6).
3105 ///
3106 /// Recognised by shape rather than by a flag: a namespace is the only object whose
3107 /// properties are all accessors over a `ModuleBinding` cell. That is the same
3108 /// identification `Set`/`Add` membership tests use on function objects, and it keeps the
3109 /// distinction in one place instead of adding a boolean every constructor has to
3110 /// remember to set.
3111 pub fn is_module_namespace(&self, object: &Gc<JsObject>) -> bool {
3112 object.module_namespace_marker()
3113 }
3114
3115 /// `[[GetOwnProperty]]` for a module namespace exotic object.
3116 ///
3117 /// The bindings are stored as getters — that is the only way a live binding can be read
3118 /// through the namespace — but §10.4.6.5 says the *observable* descriptor is a data
3119 /// descriptor:
3120 ///
3121 /// ```text
3122 /// { [[Value]]: current value, [[Writable]]: true,
3123 /// [[Enumerable]]: true, [[Configurable]]: false }
3124 /// ```
3125 ///
3126 /// So `Object.getOwnPropertyDescriptor(ns, "x").writable` is `true`, and `.get` is
3127 /// `undefined`. Reporting the accessor instead — which is what the property table holds
3128 /// — made every one of test262's namespace descriptor assertions fail, in both the
3129 /// `await-ns-*` and `promise-then-ns-*` families.
3130 ///
3131 /// `[[Configurable]]: false` is why `Reflect.defineProperty(ns, "x", {value: 1})` answers
3132 /// `true` only when the new value is `SameValue` the current one (`await-ns-define-own-
3133 /// property`); the ordinary descriptor machinery derives that from these attributes.
3134 pub fn namespace_own_property(
3135 &mut self,
3136 object: &Gc<JsObject>,
3137 key: &PropertyKey,
3138 ) -> JsResult<Option<Property>> {
3139 let Some(stored) = Self::ordinary_own_property(object, key) else {
3140 return Ok(None);
3141 };
3142 let Some(Property {
3143 getter: Some(getter),
3144 ..
3145 }) = Some(&stored)
3146 else {
3147 return Ok(Some(stored));
3148 };
3149 // Reading the binding is what a namespace `[[Get]]` does, and it can run script
3150 // (`export let x` assigned by a getter elsewhere), so the value is materialised here
3151 // rather than stored.
3152 let value = self.call_value(getter.clone(), Value::Object(object.clone()), Vec::new())?;
3153 Ok(Some(Property {
3154 value: Some(value),
3155 writable: true,
3156 enumerable: true,
3157 configurable: false,
3158 ..Property::default()
3159 }))
3160 }
3161
3162 /// `[[DefineOwnProperty]]` for a module namespace exotic object (§10.4.6.6).
3163 ///
3164 /// Modelled as "does this descriptor describe the property that is already there?",
3165 /// because a namespace property's attributes are fixed and its value cannot be changed
3166 /// through the namespace. The three ways to succeed:
3167 ///
3168 /// * a descriptor that names no field at all (`Reflect.defineProperty(ns, k, {})`);
3169 /// * one whose `[[Value]]` is `SameValue` the current binding value;
3170 /// * one whose attribute fields all restate `{writable: true, enumerable: true,
3171 /// configurable: false}`.
3172 ///
3173 /// `@@toStringTag` is a real own property of the namespace (a data property, writable
3174 /// false), so it goes through the same check against its stored value — which is what
3175 /// makes `{value: "Module", writable: false, enumerable: false, configurable: false}`
3176 /// answer `true` while `{value: "Other"}` answers `false`.
3177 fn namespace_define_own_property(
3178 &mut self,
3179 object: &Gc<JsObject>,
3180 key: &PropertyKey,
3181 property: &Property,
3182 ) -> JsResult<bool> {
3183 let Some(current) = self.namespace_own_property(object, key)? else {
3184 // A name the namespace does not export cannot be added to it.
3185 return Ok(false);
3186 };
3187 if let Some(value) = &property.value {
3188 let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3189 if !self.same_value(value, current_value)? {
3190 return Ok(false);
3191 }
3192 }
3193 Ok(true)
3194 }
3195
3196 /// `[[DefineOwnProperty]]` for a namespace, driven by the *descriptor object*.
3197 ///
3198 /// §10.4.6.6 is worded entirely in terms of which fields the descriptor **has**: "If
3199 /// Desc has [[Value]] and SameValue(Desc.[[Value]], current) is false, return false",
3200 /// then the same for [[Writable]], [[Enumerable]] and [[Configurable]], then true. A
3201 /// descriptor with no fields at all therefore succeeds, which is what
3202 /// `Reflect.defineProperty(ns, k, {})` checks.
3203 ///
3204 /// Taking the *merged* `Property` instead cannot work: the merge inherits from the
3205 /// stored property, and a namespace stores its bindings as accessors, so every
3206 /// definition looked like "accessor → data kind changed" or carried `writable: false`
3207 /// from the accessor's own entry. Presence is only available here, before the merge.
3208 pub fn namespace_define_from_descriptor(
3209 &mut self,
3210 object: &Gc<JsObject>,
3211 key: &PropertyKey,
3212 descriptor: &Gc<JsObject>,
3213 ) -> JsResult<bool> {
3214 let Some(current) = self.namespace_own_property(object, key)? else {
3215 return Ok(false);
3216 };
3217 // An accessor descriptor can never describe a namespace binding.
3218 if self.get_property(descriptor, "get")?.is_some()
3219 || self.get_property(descriptor, "set")?.is_some()
3220 {
3221 return Ok(false);
3222 }
3223 if let Some(value) = self.get_property(descriptor, "value")? {
3224 let current_value = current.value.as_ref().unwrap_or(&Value::Undefined);
3225 if !self.same_value(&value, current_value)? {
3226 return Ok(false);
3227 }
3228 }
3229 // The three attribute fields, when named, must restate what the property already
3230 // has. Not a fixed shape: an exported binding reports
3231 // `{writable: true, enumerable: true, configurable: false}` while `@@toStringTag`
3232 // is a real own data property with `{false, false, false}`, and both are namespace
3233 // properties. Comparing against `current` is what makes one rule cover both.
3234 for (name, have) in [
3235 ("writable", current.writable),
3236 ("enumerable", current.enumerable),
3237 ("configurable", current.configurable),
3238 ] {
3239 if let Some(named) = self.get_property(descriptor, name)?
3240 && named.to_boolean() != have
3241 {
3242 return Ok(false);
3243 }
3244 }
3245 Ok(true)
3246 }
3247
3248 /// `SameValue` (§7.2.9), exposed because the namespace's `[[DefineOwnProperty]]` needs to
3249 /// compare a requested value against a live binding.
3250 pub fn same_value(&mut self, a: &Value, b: &Value) -> JsResult<bool> {
3251 Ok(a.same_value(b))
3252 }
3253
3254 ///
3255 /// Written for `Error.prototype.stack`'s setter and the exact mechanism
3256 /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
3257 /// abstract operation here rather than a private helper in `error.rs`.
3258 ///
3259 /// The name is the whole point: the setter must behave as if the prototype were not
3260 /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3261 /// the accessor for every error object in the realm. Everything below follows from that:
3262 ///
3263 /// 1. `thisValue` must be an object — otherwise `TypeError`.
3264 /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3265 /// accessor's own home an error rather than a self-shadow.
3266 /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3267 /// either has a string or has made a mistake.
3268 /// 4. An existing *own* property decides the path — an own setter is called, an own
3269 /// non-writable data property is a `TypeError` — and only a missing own property
3270 /// falls through to defining one.
3271 /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3272 /// traps and a non-extensible receiver is a `TypeError`.
3273 ///
3274 /// The installed shape is writable + configurable, not enumerable.
3275 pub fn setter_that_ignores_prototype_properties(
3276 &mut self,
3277 this_value: Value,
3278 home: &Gc<JsObject>,
3279 property_key: &str,
3280 args: &[Value],
3281 ) -> JsResult<Value> {
3282 self.setter_that_ignores_prototype_properties_key(
3283 this_value,
3284 home,
3285 &PropertyKey::from(property_key),
3286 args,
3287 )
3288 }
3289
3290 /// [`Interp::setter_that_ignores_prototype_properties`] for a key that may be a symbol.
3291 ///
3292 /// `Iterator.prototype[@@toStringTag]`'s setter is the symbol-keyed caller.
3293 pub fn setter_that_ignores_prototype_properties_key(
3294 &mut self,
3295 this_value: Value,
3296 home: &Gc<JsObject>,
3297 key: &PropertyKey,
3298 args: &[Value],
3299 ) -> JsResult<Value> {
3300 let Some(receiver) = this_value.as_object().cloned() else {
3301 return Err(self.type_error("setter called on a non-object"));
3302 };
3303 if Gc::ptr_eq(&receiver, home) {
3304 return Err(self.type_error("cannot assign to the accessor's own home object"));
3305 }
3306 // No type check here: §7.3.40 takes an arbitrary `v`, and
3307 // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3308 // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3309 // before calling this.
3310 let value = args.first().cloned().unwrap_or(Value::Undefined);
3311 // Step 4: an own property on the receiver changes what happens, and there are three
3312 // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3313 // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3314 // `Set` with `throw = true`, and a test exists for each.
3315 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
3316 if existing.is_accessor() && existing.setter.is_none() {
3317 // A getter-only own accessor cannot be written through.
3318 return Err(self.type_error("no setter for the own property"));
3319 }
3320 // Everything else — an own data property, or an own accessor *with* a setter —
3321 // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3322 // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3323 // an own user setter receives the value (`setter-own-accessor`), because
3324 // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3325 // setter directly is the difference between one code path and two that can
3326 // disagree.
3327 self.set_property_with_key(
3328 &receiver,
3329 key,
3330 value.clone(),
3331 crate::interp::DeleteFailure::Throw,
3332 )?;
3333 return Ok(Value::Undefined);
3334 }
3335 let property = Property {
3336 value: Some(value.clone()),
3337 writable: true,
3338 // Enumerable, despite the accessor it shadows not being. The reference installs
3339 // it that way and six cases check it (`setter-creates-own-property` and friends).
3340 enumerable: true,
3341 configurable: true,
3342 ..Property::default()
3343 };
3344 if !self.object_define_own_property(&receiver, key, property)? {
3345 return Err(self.type_error("the receiver refused the definition"));
3346 }
3347 Ok(Value::Undefined)
3348 }
3349
3350 /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3351 ///
3352 /// The indices of a typed array are not properties at all — they are bytes in the
3353 /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3354 /// fly. That makes their descriptor shape fixed: every valid index is writable,
3355 /// enumerable and configurable, so a definition can only ever change the *value*, and
3356 /// every other descriptor is refused rather than applied.
3357 ///
3358 /// The order of the checks is the spec's, and two of them are load-bearing:
3359 ///
3360 /// * the index is validated **before** the value is converted, because the conversion
3361 /// itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3362 /// detaches from a `valueOf` and still expects `true` with no store, which only
3363 /// happens when the index was valid on the way in;
3364 /// * the store is attempted even when the index has gone out of bounds by the time the
3365 /// conversion finishes, because the store is a silent no-op rather than a failure —
3366 /// the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3367 /// the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3368 ///
3369 /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3370 /// the existing element, which is harmless here: every valid index is already
3371 /// writable, enumerable and configurable, so a `false` in the merged property can only
3372 /// have come from the descriptor having named `false`.
3373 fn integer_indexed_define_own_property(
3374 &mut self,
3375 object: &Gc<JsObject>,
3376 numeric: f64,
3377 property: &Property,
3378 ) -> JsResult<bool> {
3379 // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3380 // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3381 if !typed_array_index_is_valid(object, numeric) {
3382 return Ok(false);
3383 }
3384 // Step 6: the indices are data properties, so an accessor descriptor is refused
3385 // rather than converted. `Object.defineProperty` turns the `false` into a
3386 // `TypeError`; `Reflect.defineProperty` reports it.
3387 if property.is_accessor() {
3388 return Ok(false);
3389 }
3390 // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3391 // definition that asks for anything else cannot be honoured.
3392 if !property.writable || !property.enumerable || !property.configurable {
3393 return Ok(false);
3394 }
3395 // Step 10: only a descriptor that names a value stores anything.
3396 let Some(value) = property.value.clone() else {
3397 return Ok(true);
3398 };
3399 let Some(element) = object.typed_array_element_type() else {
3400 return Ok(false);
3401 };
3402 let stored = self.element_value(element, value)?;
3403 if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3404 return Err(self.type_error(reason));
3405 }
3406 Ok(true)
3407 }
3408
3409 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3410 pub fn object_define_own_property(
3411 &mut self,
3412 object: &Gc<JsObject>,
3413 key: &PropertyKey,
3414 property: Property,
3415 ) -> JsResult<bool> {
3416 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3417 return Ok(accepted);
3418 }
3419 // §10.4.6.6 `[[DefineOwnProperty]]` for a module namespace.
3420 //
3421 // The only definitions that can succeed are ones describing the property the
3422 // namespace *already* has: `Reflect.defineProperty(ns, "x", {})` asks for no change
3423 // and answers `true`; so does `{value: <SameValue current>}` or the exact attribute
3424 // set `{writable: true, enumerable: true, configurable: false}`. A different value,
3425 // `writable: false`, `configurable: true`, or any name the namespace does not
3426 // export is `false`.
3427 //
3428 // The ordinary path gets the no-change case right by accident — it compares against
3429 // `[[GetOwnProperty]]` — but cannot describe a namespace binding, because the binding
3430 // is an accessor internally while the definition script writes is a data descriptor.
3431 // Answering here is what makes that attribute-only definition a no-op rather than a
3432 // refusal (`namespace/await-ns-define-own-property`).
3433 if object.module_namespace_marker() {
3434 return self.namespace_define_own_property(object, key, &property);
3435 }
3436 // A proxy always answers above — with `Some` from its trap, or with `None` when
3437 // the trap is absent, and then the definition belongs to the **target**
3438 // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3439 // when there is no trap). Falling through to the ordinary path here defined the
3440 // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3441 // property the target never saw.
3442 if object.proxy_state().is_some() {
3443 let Some((target, _handler)) = self.proxy_parts(object)? else {
3444 return Err(self.type_error("cannot use a proxy that has been revoked"));
3445 };
3446 return self.object_define_own_property(&target, key, property);
3447 }
3448 // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3449 // they accept exactly one descriptor shape. This has to happen before the
3450 // ordinary path, which would happily store a data property next to the buffer —
3451 // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3452 // and `TypedArray/prototype/set` are about this section.
3453 if object.typed_array_element_type().is_some()
3454 && let Some(index) = canonical_numeric_index(key)
3455 {
3456 return self.integer_indexed_define_own_property(object, index, &property);
3457 }
3458 // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3459 // non-extensible object. The check lives here rather than in the callers because
3460 // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3461 // `Array.prototype.filter` uses to store its result, and a species object made
3462 // non-extensible by its own constructor must make that a `TypeError`
3463 // (`target-array-non-extensible`).
3464 // Note the `is_none()`: an already-present property may still be **redefined** on a
3465 // non-extensible object, and only *adding* one is refused (as Distinct from
3466 // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3467 // properties — testing extensibility before looking for the property made every
3468 // `Object.freeze` of an ordinary object refuse its own second step).
3469 if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3470 return Ok(false);
3471 }
3472 // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3473 // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3474 // an omitted field is left alone). Merging here rather than at each call site is
3475 // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3476 // the value and `enumerable` in place.
3477 //
3478 // The merge is a no-op when the property is absent: there is nothing to keep.
3479 let was_partial = property.descriptor_fields.is_some();
3480 let property = match property.descriptor_fields {
3481 None => property,
3482 Some(fields) => {
3483 let base = self.object_get_own_property(object, key)?;
3484 let mut merged = base.clone().unwrap_or_default();
3485 // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3486 // descriptor names, and switching kind discards the other half —
3487 // `{set: f}` on a data property is an accessor with no getter, not a data
3488 // property whose `get` happens to be absent.
3489 let wants_accessor = fields.get || fields.set;
3490 let wants_data = fields.value || fields.writable;
3491 if wants_accessor {
3492 merged.value = None;
3493 merged.writable = false;
3494 merged.getter = property.getter.clone();
3495 merged.setter = property.setter.clone();
3496 } else if wants_data {
3497 merged.getter = None;
3498 merged.setter = None;
3499 if fields.value {
3500 merged.value = property.value.clone();
3501 }
3502 if fields.writable {
3503 merged.writable = property.writable;
3504 }
3505 }
3506 if fields.enumerable {
3507 merged.enumerable = property.enumerable;
3508 }
3509 if fields.configurable {
3510 merged.configurable = property.configurable;
3511 }
3512 merged.descriptor_fields = None;
3513 merged
3514 }
3515 };
3516 // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3517 // descriptor. `define_property_on` runs the same check before it calls here, so an
3518 // ordinary object is already covered; what is *not* is the forwarding a proxy does
3519 // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3520 // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3521 // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3522 // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3523 // own define would have refused.
3524 //
3525 // Only partial descriptors are validated here. A whole `Property` passed by an
3526 // internal caller (`Property::data(…)`) carries attributes that say nothing about
3527 // what the descriptor "named", and those callers rely on the write landing.
3528 if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3529 // Every branch below is gated on `!existing.configurable`: a *configurable*
3530 // property may be reshaped however the descriptor likes, which is why an
3531 // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3532 // must succeed. Testing only `writable` refused that and broke
3533 // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3534 let same_kind = existing.is_accessor() == property.is_accessor();
3535 if !same_kind {
3536 // Step 4: a non-configurable property may not change kind.
3537 if !existing.configurable {
3538 return Ok(false);
3539 }
3540 } else if existing.is_accessor() {
3541 // Step 6: an accessor's halves are its value.
3542 if !existing.configurable
3543 && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3544 || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3545 {
3546 return Ok(false);
3547 }
3548 } else if !existing.configurable && !existing.writable {
3549 // Step 7: a non-configurable *and* non-writable data property's value is
3550 // fixed, and it may not become writable again.
3551 if property.writable {
3552 return Ok(false);
3553 }
3554 let current = existing.value.clone().unwrap_or(Value::Undefined);
3555 let requested = property.value.clone().unwrap_or(Value::Undefined);
3556 if !current.same_value(&requested) {
3557 return Ok(false);
3558 }
3559 }
3560 // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3561 // is frozen with it.
3562 if !existing.configurable
3563 && (property.configurable || property.enumerable != existing.enumerable)
3564 {
3565 return Ok(false);
3566 }
3567 }
3568 // A host class that intercepts definitions owns the attributes of the properties it
3569 // defines: `_class`-style storage on the native side is the usual reason.
3570 if let Some(exotic) = object.exotic()
3571 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3572 {
3573 return Ok(accepted);
3574 }
3575 // An array index is stored in the element vector, which can hold a plain value and
3576 // nothing else. An accessor — or a data property with non-default attributes —
3577 // therefore has to live in the property table, and the element slot is blanked so
3578 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3579 // {get})` stored the accessor where no read ever looked, and the array kept
3580 // answering its old value.
3581 // An array's `length` is not stored in the property table, so defining it has to
3582 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3583 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3584 // {value: 1})` reported success and changed nothing.
3585 if key.as_str() == Some("length") && object.is_array() {
3586 // `{writable: false}` on `length` does not change the length, but it does make
3587 // it read-only — after which neither a later `{writable: true}` nor a store
3588 // past the end may succeed.
3589 if property.value.is_none() {
3590 if !object.length_writable() && property.writable {
3591 return Ok(false);
3592 }
3593 object.set_length_writable(property.writable);
3594 return Ok(true);
3595 }
3596 if !object.length_writable() {
3597 return Ok(false);
3598 }
3599 }
3600 if key.as_str() == Some("length")
3601 && object.is_array()
3602 && let Some(value) = property.value.clone()
3603 {
3604 let requested = value.to_number();
3605 let valid = requested.is_finite()
3606 && requested >= 0.0
3607 && requested.fract() == 0.0
3608 && requested <= u32::MAX as f64;
3609 if !valid {
3610 return Err(self.range_error("invalid array length"));
3611 }
3612 // Truncating deletes the elements above the new length, and a non-configurable
3613 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3614 // makes `a.length = 2` fail rather than quietly drop it.
3615 let current = object.array_length().unwrap_or(0);
3616 let requested = requested as usize;
3617 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3618 // §10.4.2.4 `ArraySetLength` step 3.i.2: the refusal still applies
3619 // `[[Writable]]: false` when the descriptor asked for it — the length is
3620 // left at its old value but locked. Returning `false` alone left it
3621 // writable, which `verifyProperty` catches
3622 // (`defineProperties/15.2.3.7-6-a-164`).
3623 if property
3624 .descriptor_fields
3625 .is_some_and(|fields| fields.writable)
3626 && !property.writable
3627 && object.length_writable()
3628 {
3629 object.set_length_writable(false);
3630 }
3631 return Ok(false);
3632 }
3633 object.array_set_length(self.heap, requested);
3634 return Ok(true);
3635 }
3636 let plain = property.writable
3637 && property.enumerable
3638 && property.configurable
3639 && !property.is_accessor();
3640 if let Some(index) = key.as_str().and_then(array_index)
3641 && object.is_array()
3642 {
3643 // Growing the array needs a writable `length`: after
3644 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3645 // be added.
3646 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3647 return Ok(false);
3648 }
3649 if plain && property.value.is_some() {
3650 // An ordinary element: the vector is where a read looks first, so it has
3651 // to be the vector that changes — unless the index is too far out to be
3652 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3653 // one property, because past its own limit it stores the index as an
3654 // ordinary key. Falling through to `define_key` below is the same choice,
3655 // and the alternative was worse: the store used to be *dropped* and the
3656 // length left at 0, which is a silent wrong answer.
3657 let value = property.value.clone().unwrap_or(Value::Undefined);
3658 object.delete_key(key);
3659 if object.array_set(self.heap, index as usize, value) {
3660 return Ok(true);
3661 }
3662 // Past the dense limit the element lives in the table like any property.
3663 object.note_element_descriptor();
3664 object.define_key(key, property);
3665 // A sparse store past the dense limit still extends `length`, which is what
3666 // `a[a.length] = v` relies on — but only extends: shortening would delete
3667 // the sparse properties above the index, including this one.
3668 if index as usize + 1 > object.array_length().unwrap_or(0) {
3669 object.array_set_length(self.heap, index as usize + 1);
3670 }
3671 return Ok(true);
3672 }
3673 // A non-plain element — an accessor, or an attribute that is not the default —
3674 // lives in the table while the slot becomes a hole. Recording it keeps every
3675 // later `a[i] = v` off the dense path, where the write would have shadowed the
3676 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3677 // replace the accessor with a plain data property.
3678 object.note_element_descriptor();
3679 object.define_key(key, property);
3680 // The slot stays, so `length` does not shrink; a hole is not an element, so
3681 // the table entry is now what a read finds.
3682 object.array_set(self.heap, index as usize, Value::Hole);
3683 // `ArraySetLength` step 2 of `OrdinaryDefineOwnProperty`'s index branch —
3684 // `length = index + 1` — applies whatever the descriptor's *attributes* are,
3685 // not just to a plain one: `Object.defineProperty(a, 4294967294, {value: 100})`
3686 // makes `a.length` 4294967295 (`defineProperty/15.2.3.6-4-183`).
3687 if index as usize + 1 > object.array_length().unwrap_or(0) {
3688 object.array_set_length(self.heap, index as usize + 1);
3689 }
3690 return Ok(true);
3691 }
3692 object.define_key(key, property);
3693 Ok(true)
3694 }
3695
3696 /// Build a proxy object over `target`, with its traps read from `handler`.
3697 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3698 JsObject::proxy(self.heap, target, handler)
3699 }
3700
3701 /// The `revoke` function for a proxy's slots.
3702 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3703 let revoke = JsObject::function(
3704 self.heap,
3705 Some(self.realm.function_proto.clone()),
3706 Callable::Revoker(slots),
3707 );
3708 // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3709 // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3710 // inherited from `Function.prototype` reads the same but fails the three cases that
3711 // check the own-property list (`revocation-function-{length,name,property-order}`).
3712 revoke.define("length", Property::name_or_length(Value::Int(0)));
3713 revoke.define("name", Property::name_or_length(self.string("")));
3714 revoke
3715 }
3716
3717 /// A new array.
3718 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3719 let array = JsObject::array(
3720 self.heap,
3721 Some(self.realm.array_proto.clone()),
3722 elements.len(),
3723 );
3724 for (index, element) in elements.into_iter().enumerate() {
3725 array.array_set(self.heap, index, element);
3726 }
3727 array
3728 }
3729
3730 /// A new native function object.
3731 ///
3732 /// The observable `name` and `length` are installed as properties here, which is
3733 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3734 /// so `f.name = "x"` behaves like the writable property it is.
3735 /// A native constructor that builds its own instance after validating its arguments.
3736 ///
3737 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3738 /// check runs before `new.target.prototype` is read.
3739 pub fn new_native_ctor(
3740 &self,
3741 name: impl Into<String>,
3742 length: u32,
3743 func: NativeFn,
3744 ) -> Gc<JsObject> {
3745 let function = JsObject::function(
3746 self.heap,
3747 Some(self.realm.function_proto.clone()),
3748 Callable::Native {
3749 func,
3750 own_instance: true,
3751 },
3752 );
3753 function.set_constructible(true);
3754 function.define(
3755 "length",
3756 Property::name_or_length(Value::Int(length as i32)),
3757 );
3758 function.define("name", Property::name_or_length(self.string(name)));
3759 function
3760 }
3761
3762 /// A native constructor that lets `new` build the instance first.
3763 ///
3764 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3765 /// validation that must precede reading `new.target.prototype`, so the object can be
3766 /// created before the implementation runs. Distinct from [`Interp::new_native`],
3767 /// which makes a *method* and therefore not a constructor at all.
3768 pub fn new_native_constructor(
3769 &self,
3770 name: impl Into<String>,
3771 length: u32,
3772 func: NativeFn,
3773 ) -> Gc<JsObject> {
3774 let function = self.new_native(name, length, func);
3775 function.set_constructible(true);
3776 function
3777 }
3778
3779 /// A new host function object: a native closure that carries its own state.
3780 ///
3781 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3782 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3783 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3784 /// this safe: the closure must not capture a `Gc`.
3785 pub fn new_host_function(
3786 &self,
3787 name: impl Into<String>,
3788 length: u32,
3789 func: crate::object::HostFn,
3790 ) -> Gc<JsObject> {
3791 self.new_host_inner(name.into(), length, func, false)
3792 }
3793
3794 /// A host constructor: `new` hands it `this = undefined`, so it validates its
3795 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3796 pub fn new_host_ctor(
3797 &self,
3798 name: impl Into<String>,
3799 length: u32,
3800 func: crate::object::HostFn,
3801 ) -> Gc<JsObject> {
3802 let function = self.new_host_inner(name.into(), length, func, true);
3803 function.set_constructible(true);
3804 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3805 // installs its own methods on it, so it starts as a plain object.
3806 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3807 function.define(
3808 "prototype",
3809 Property {
3810 value: Some(Value::Object(proto)),
3811 writable: true,
3812 enumerable: false,
3813 configurable: false,
3814 ..Property::default()
3815 },
3816 );
3817 function
3818 }
3819
3820 fn new_host_inner(
3821 &self,
3822 name: String,
3823 length: u32,
3824 func: crate::object::HostFn,
3825 own_instance: bool,
3826 ) -> Gc<JsObject> {
3827 let function = JsObject::function(
3828 self.heap,
3829 Some(self.realm.function_proto.clone()),
3830 Callable::Host {
3831 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3832 own_instance,
3833 },
3834 );
3835 function.define(
3836 "length",
3837 Property::name_or_length(Value::Int(length as i32)),
3838 );
3839 function.define("name", Property::name_or_length(self.string(name)));
3840 function
3841 }
3842
3843 /// A callable object with the `length`/`name` a built-in function has, in that order.
3844 ///
3845 /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3846 /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3847 /// [`JsObject::function`] defines neither, which is why every capability helper built
3848 /// with it reported no own `length` and no own `name` at all.
3849 ///
3850 /// The attributes are the spec's for a built-in: not writable, not enumerable,
3851 /// configurable.
3852 pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3853 let function =
3854 JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3855 function.define(
3856 "length",
3857 Property::name_or_length(Value::Int(length as i32)),
3858 );
3859 function.define("name", Property::name_or_length(self.string(name)));
3860 function
3861 }
3862
3863 /// A new native function object.
3864 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3865 let function = JsObject::function(
3866 self.heap,
3867 Some(self.realm.function_proto.clone()),
3868 Callable::Native {
3869 func,
3870 own_instance: false,
3871 },
3872 );
3873 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3874 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3875 // `length,name` and this listed `name,length`. A bytecode function already gets it
3876 // the right way round; only native ones were built backwards.
3877 function.define(
3878 "length",
3879 Property::name_or_length(Value::Int(length as i32)),
3880 );
3881 function.define("name", Property::name_or_length(self.string(name)));
3882 function
3883 }
3884
3885 /// A new bound function.
3886 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3887 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3888 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3889 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3890 let constructible = target
3891 .as_object()
3892 .is_some_and(|target| target.is_constructor());
3893 let bound = JsObject::function(
3894 self.heap,
3895 Some(self.realm.function_proto.clone()),
3896 Callable::Bound { target, this, args },
3897 );
3898 bound.set_constructible(constructible);
3899 bound
3900 }
3901
3902 /// A new reference cell.
3903 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3904 Gc::new(self.heap, Cell::new(value))
3905 }
3906
3907 // -- running ------------------------------------------------------------
3908
3909 /// Evaluate `code` as a script body and return its completion value.
3910 /// Compile and run `source` for the engine's own use, returning its completion value.
3911 ///
3912 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3913 /// needs to be a real async function, and the engine already runs those as coroutines,
3914 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3915 ///
3916 /// Differences from [`Self::eval_in_global`], both deliberate:
3917 ///
3918 /// * It does **not** drain the microtask queue. Install runs while the realm is still
3919 /// being built, and the source is an IIFE that only constructs a closure, so there
3920 /// is nothing to drain — and draining here would run script-queued jobs in the
3921 /// middle of `install`.
3922 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3923 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3924 /// and it should not look like the user wrote something wrong.
3925 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3926 let program = match js_parse::parse_script(source) {
3927 Ok(program) => program,
3928 Err(error) => {
3929 let message = format!("builtin source does not parse: {error}");
3930 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3931 }
3932 };
3933 let mut code = match js_compile::compile_script_with_source(&program, source) {
3934 Ok(code) => code,
3935 Err(error) => {
3936 let message = format!("builtin source does not compile: {}", error.message);
3937 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3938 }
3939 };
3940 // The frame has to name something, and `<builtin>` is what a stack trace through
3941 // this code should say.
3942 code.set_filename("<builtin>");
3943 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3944 let closure_vars = compiled.code.closure_vars.clone();
3945 let env = self.global_env(&closure_vars);
3946 let this = Value::Object(self.realm.global.clone());
3947 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3948 }
3949
3950 /// Run an already-parsed script and drain the microtasks it queued.
3951 ///
3952 /// The drain is what lets an `async` function's body advance past its first `await`
3953 /// before the host sees the result: nothing else pumps the job queue.
3954 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3955 let this = Value::Object(self.realm.global.clone());
3956 self.run_script_with_this(code, this)
3957 }
3958
3959 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3960 ///
3961 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3962 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3963 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3964 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3965 /// state the next script evaluation tripped over.
3966 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3967 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3968 let closure_vars = compiled.code.closure_vars.clone();
3969 let env = self.global_env(&closure_vars);
3970 let callee = Value::Undefined;
3971 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3972 // The script is done, so the microtasks it queued run before the host sees the
3973 // result. Without this an `async` function's body would never advance past its
3974 // first `await`, because nothing else drains the queue.
3975 self.drain_jobs()?;
3976 Ok(result)
3977 }
3978
3979 /// Compile and run `source` in global scope, returning its completion value.
3980 ///
3981 /// This is what `eval` and `new Function` use. Running it as a script means it
3982 /// sees the global object and nothing else, which is right for `eval("1+1")` and
3983 /// for a `Function` body; a *direct* eval that reads a local variable would need
3984 /// the compiler to hand its variable environment over, which is not implemented.
3985 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3986 self.eval_in_global_named(source, EVAL_FILE, false)
3987 }
3988
3989 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3990 ///
3991 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3992 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3993 /// through the code, so they cannot share one constant.
3994 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3995 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3996 }
3997
3998 /// Evaluate `source` as a global script, reported under `file`.
3999 ///
4000 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
4001 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
4002 /// from inside a C callback, where the interpreter is the running one rather than a
4003 /// context's own.
4004 pub fn eval_in_global_named(
4005 &mut self,
4006 source: &str,
4007 file: &str,
4008 barrier: bool,
4009 ) -> JsResult<Value> {
4010 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
4011 // eval-created global binding — configurable, unlike a script's own `var`.
4012 self.eval_depth += 1;
4013 if barrier {
4014 let depth = self.frames.len();
4015 self.trace_barriers.push(depth);
4016 }
4017 let result = self.eval_in_global_inner(source, file);
4018 if barrier {
4019 self.trace_barriers.pop();
4020 }
4021 self.eval_depth -= 1;
4022 result
4023 }
4024
4025 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
4026 let compiled = self.compile_global_script(source, file, false)?;
4027 let strict = compiled.strict;
4028 self.run_eval_script(compiled, strict)
4029 }
4030
4031 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
4032 ///
4033 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
4034 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
4035 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
4036 /// direct eval's is.
4037 pub fn eval_script_with_this(
4038 &mut self,
4039 source: &str,
4040 file: &str,
4041 this: Value,
4042 ) -> JsResult<Value> {
4043 let program = match js_parse::parse_script(source) {
4044 Ok(program) => program,
4045 Err(error) => {
4046 return Err(Signal::Throw(self.syntax_error_at(
4047 file,
4048 error.span.start.line,
4049 error.span.start.column,
4050 &error.message,
4051 )));
4052 }
4053 };
4054 let mut compiled = match js_compile::compile_script(&program) {
4055 Ok(compiled) => compiled,
4056 Err(error) => {
4057 return Err(Signal::Throw(self.syntax_error_at(
4058 file,
4059 error.span.start.line,
4060 error.span.start.column,
4061 &error.message,
4062 )));
4063 }
4064 };
4065 compiled.set_filename(file);
4066 self.run_script_with_this(compiled, this)
4067 }
4068
4069 /// Parse and compile `source` as a global script, without running it.
4070 ///
4071 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
4072 /// before a promise exists to reject — while still evaluating in the same eval context
4073 /// (direct-eval strictness, `new.target`, `super`).
4074 fn compile_global_script(
4075 &mut self,
4076 source: &str,
4077 file: &str,
4078 async_body: bool,
4079 ) -> JsResult<CompiledFunction> {
4080 // A *direct* eval inherits the strictness of the code that called it, which is
4081 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
4082 // implicit global. The caller's frame is the innermost one here, because a
4083 // native function does not push a frame of its own.
4084 let strict = self.current_strict();
4085 // `eval` runs in the caller's function context, so `new.target` is legal here
4086 // even though the source is a bare script — and so is `super.x` when the caller
4087 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
4088 // caller's, which is what `special_object 4` already does.
4089 // Nothing of the caller's is inherited by an *indirect* eval: `(0, eval)('super.x')`
4090 // and `(0, eval)('arguments')` are both `SyntaxError`s because there is no caller
4091 // context at all. The site is what tells the two apart — an indirect call leaves no
4092 // site behind, since only a bare `eval(...)` is recorded.
4093 let site = self.eval_site_at_cursor();
4094 let private = site
4095 .map(|site| site.private_names.clone())
4096 .unwrap_or_default();
4097 let context = js_parse::EvalContext {
4098 in_method: site.is_some() && self.enclosing_home_object().is_some(),
4099 // `super()` belongs to a derived constructor, and an eval'd body is not a
4100 // constructor at all: the caller frame's `this` is already built.
4101 in_derived_constructor: false,
4102 // Private names are lexically scoped, so a direct `eval` inside a class body
4103 // can see them; see `Interp::eval_private_names`.
4104 private_names: private.iter().map(|entry| entry.name.clone()).collect(),
4105 arguments_allowed: site.is_none_or(|site| site.arguments_allowed),
4106 new_target_allowed: site.is_some(),
4107 };
4108 // A *global* eval is not a function body: `new.target` and `super` are out of
4109 // reach there. Its `{async: true}` form differs in the other direction — the body
4110 // may `await` — so the two flags are independent and the reference sets both from
4111 // the eval type rather than from the caller.
4112 let parsed = if async_body {
4113 js_parse::parse_suspensible_global_eval(source, strict)
4114 } else {
4115 js_parse::parse_eval_script_in(source, strict, context)
4116 };
4117 let program = match parsed {
4118 Ok(program) => program,
4119 Err(error) => {
4120 // The message is bare: the position lives in `fileName`,
4121 // `lineNumber`, `columnNumber` and the stack frame above, which is where
4122 // the reference puts it. An `invalid source: L:C: ` prefix made
4123 // `e.message` differ from the reference while the stack already agreed.
4124 return Err(Signal::Throw(self.syntax_error_at(
4125 file,
4126 error.span.start.line,
4127 error.span.start.column,
4128 &error.message,
4129 )));
4130 }
4131 };
4132 let mut compiled = match if async_body {
4133 js_compile::compile_eval_with_private(&program, &private, true)
4134 } else {
4135 js_compile::compile_eval_with_private(&program, &private, false)
4136 } {
4137 Ok(compiled) => compiled,
4138 // A construct the compiler does not handle yet is reported the same way a
4139 // parse error is: it happens before anything runs, so the trace is the
4140 // position in the source followed by the caller.
4141 Err(error) => {
4142 return Err(Signal::Throw(self.syntax_error_at(
4143 file,
4144 error.span.start.line,
4145 error.span.start.column,
4146 &error.message,
4147 )));
4148 }
4149 };
4150 compiled.set_filename(file);
4151 Ok(compiled)
4152 }
4153
4154 /// The private names the code at the current position can see, innermost first.
4155 ///
4156 /// Private names are lexically scoped (§15.10.2 `AllPrivateIdentifiersValid`), and a
4157 /// direct `eval` runs inside its caller's scope, so
4158 /// `class C { #m = 44; f() { return eval("this.#m") } }` is legal. The names belong to the
4159 /// *call site's* compilation unit, so they are recorded on the `EvalSite` and read back
4160 /// here rather than being derivable from the eval'd source.
4161 ///
4162 /// An indirect `eval` gets nothing: `(0, eval)("this.#m")` outside a class is a
4163 /// `SyntaxError`, and an indirect call leaves no site behind, which is exactly the test
4164 /// [`Interp::run_eval_script`] uses for "direct".
4165 fn eval_site_at_cursor(&self) -> Option<&js_compile::bytecode::EvalSite> {
4166 let frame = self.frames.last()?;
4167 let (line, column) = frame
4168 .code
4169 .code
4170 .position_at(frame.at as u32)
4171 .unwrap_or_default();
4172 // The nearest site at or before the current position: the recorded position of the
4173 // `call` instruction is the callee's, which sits a few columns inside the call
4174 // expression the compiler recorded, so an exact match would never be found.
4175 frame
4176 .code
4177 .code
4178 .eval_sites
4179 .iter()
4180 .filter(|site| (site.line, site.column) <= (line, column))
4181 .max_by_key(|site| (site.line, site.column))
4182 }
4183
4184 /// Run an `eval`'d script in the caller's scope.
4185 ///
4186 /// Three things have to come from the calling frame, because the eval'd code is a
4187 /// script and would otherwise see only the global object:
4188 ///
4189 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
4190 /// * `arguments`, exposed as a binding of the eval's own scope, so
4191 /// `f("arguments.length", 1)` sees the caller's arguments;
4192 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
4193 /// `eval("var v = 1")` into the global object.
4194 ///
4195 /// Locals of the calling function are *not* reachable: that needs the compiler to
4196 /// hand its variable environment over, which this milestone does not do.
4197 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
4198 // `this` and `arguments` come from the innermost frame only — those are not
4199 // lexical — while the name bindings come from the whole chain of frames, part
4200 // of it being ordinary scope resolution.
4201 // An arrow has no `this` of its own, so an `eval` inside one inherits the
4202 // enclosing function's receiver — the lexical `this` the arrow was compiled to
4203 // read from its closure.
4204 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
4205 // variable environment is the innermost frame of all: an arrow's own body is where
4206 // `var`s declared by an `eval` inside it belong.
4207 let caller_index = self
4208 .frames
4209 .iter()
4210 .rposition(|frame| !frame.code.code.is_arrow)
4211 .or_else(|| self.frames.len().checked_sub(1));
4212 let env_index = self.frames.len().checked_sub(1);
4213 let caller = caller_index.and_then(|index| self.frames.get(index));
4214 let (this, passed) = match caller {
4215 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
4216 // No frame at all: the eval is running at the top level, so there is
4217 // nothing to inherit and the global receiver is right.
4218 None => (Value::Object(self.realm.global.clone()), Vec::new()),
4219 };
4220 // Innermost frame first, so the first binding found for a name is the one that
4221 // shadows the rest. A script frame (`<eval>`) contributes nothing.
4222 let mut bindings: Vec<EvalBinding> = Vec::new();
4223 // The calling function's own bindings, resolved by the compiler at the call
4224 // site. That table is the only reliable answer when a name is declared twice in
4225 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
4226 // body means, and guessing by declaration order picks the wrong one as soon as
4227 // two loops in a row use the same name.
4228 // Only a *direct* eval sees the caller's scope. The compiler records a site for
4229 // every direct call — a bare `eval(...)` callee — so finding one at the current
4230 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
4231 // callee to a value first and leave no site behind.
4232 let mut direct = false;
4233 let mut resolved_here = false;
4234 if let Some(frame) = self.frames.last() {
4235 let (line, column) = frame
4236 .code
4237 .code
4238 .position_at(frame.at as u32)
4239 .unwrap_or_default();
4240 // The nearest site at or before the current position, not an exact match:
4241 // the recorded position of the `call` instruction is the callee's, which
4242 // sits a few columns inside the call expression the compiler recorded. A
4243 // site is unique per call, so "the closest one behind us" identifies it.
4244 if let Some(site) = frame
4245 .code
4246 .code
4247 .eval_sites
4248 .iter()
4249 .filter(|site| (site.line, site.column) <= (line, column))
4250 .max_by_key(|site| (site.line, site.column))
4251 {
4252 direct = true;
4253 resolved_here = true;
4254 for binding in &site.bindings {
4255 // An enclosing function's frame sits `owner` levels below the one
4256 // running the call.
4257 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
4258 else {
4259 continue;
4260 };
4261 bindings.push(EvalBinding {
4262 name: binding.name.clone(),
4263 frame,
4264 slot: if binding.is_arg {
4265 EvalSlot::Arg
4266 } else {
4267 EvalSlot::Local
4268 },
4269 index: binding.index as usize,
4270 });
4271 }
4272 }
4273 }
4274 for frame_index in (0..self.frames.len()).rev() {
4275 // Skip the innermost frame's flat scan when the compiler already answered
4276 // for it; an enclosing frame still needs one, because the eval resolves
4277 // those names dynamically.
4278 if resolved_here && frame_index == self.frames.len() - 1 {
4279 continue;
4280 }
4281 let frame = &self.frames[frame_index];
4282 for (index, arg) in frame.code.code.args.iter().enumerate() {
4283 bindings.push(EvalBinding {
4284 name: arg.name.clone(),
4285 frame: frame_index,
4286 slot: EvalSlot::Arg,
4287 index,
4288 });
4289 }
4290 for (index, local) in frame.code.code.vars.iter().enumerate() {
4291 bindings.push(EvalBinding {
4292 name: local.name.clone(),
4293 frame: frame_index,
4294 slot: EvalSlot::Local,
4295 index,
4296 });
4297 }
4298 }
4299 let mut seen = BTreeSet::new();
4300 bindings.retain(|binding| seen.insert(binding.name.clone()));
4301
4302 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4303 // elements is all the spec's ordinary uses need.
4304 //
4305 // Known divergence: this is bound for a *global* eval too, where there is no
4306 // caller and the reference throws `'arguments' is not defined`. Deciding properly
4307 // needs "does the calling frame have an `arguments` of its own", which is not
4308 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4309 // script or eval body does not, and `eval(b)` passes the callee as a value so even
4310 // the call-site detection does not answer it. Modelled as a binding in the caller's
4311 // variable environment, this would fall out; that is a larger change than the one
4312 // this comment is attached to.
4313 let arguments = Value::Object(self.new_array(passed));
4314
4315 // Only a *strict* eval gets a variable environment of its own. A sloppy one
4316 // declares its `var`s in the caller's — which for a top-level eval is the global
4317 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4318 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4319 // vanish into a scope nobody reads back from.
4320 let previous_scope = if code_strict {
4321 self.eval_scope.replace(BTreeMap::new())
4322 } else {
4323 None
4324 };
4325 // Only a *direct* eval inherits the caller's arguments object. An indirect one runs
4326 // in global scope, where `arguments` means whatever the global object says — which
4327 // is why `var arguments = 1; class C { x = (0, eval)('arguments;') }` answers `1`
4328 // (`indirect-eval-contains-arguments`). Binding the caller's array there made it
4329 // answer the array instead.
4330 let previous_arguments = if direct {
4331 self.eval_arguments.replace(arguments)
4332 } else {
4333 None
4334 };
4335 let previous_with = self.eval_with.replace(self.with_objects());
4336 let inherited_new_target = self
4337 .frames
4338 .iter()
4339 .rev()
4340 .find(|frame| !frame.code.code.is_arrow)
4341 .map(|frame| frame.new_target.clone());
4342 let previous_new_target = self
4343 .eval_new_target
4344 .replace(inherited_new_target.unwrap_or(Value::Undefined));
4345 let eval_cells = self.eval_cells_for(&bindings);
4346 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4347 // A sloppy direct eval declares its `var`s in the caller's variable environment;
4348 // `declare_eval_local` needs to know which frame that is.
4349 // An indirect eval gets the global environment, so nothing of the caller's is
4350 // recorded as the place its `var`s belong.
4351 let previous_caller = self
4352 .eval_caller
4353 .replace(if direct { env_index } else { None });
4354 // The cell-based view of the same bindings, which is what a closure created
4355 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4356 // whose compiler did not put a binding in a cell simply does not appear here —
4357 // reads and writes still work through `eval_bindings`, they just cannot outlive
4358 // the eval.
4359 let previous_eval_scope = self
4360 .active_eval_scope
4361 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4362 let compiled = Gc::new(self.heap, CompiledCode::new(code));
4363 let closure_vars = compiled.code.closure_vars.clone();
4364 // Declaration instantiation is where this belongs: the check needs the caller frame
4365 // (recorded just above) and the eval's own var names, and it raises before any of
4366 // the eval's code runs.
4367 self.check_eval_var_named_arguments(&closure_vars, code_strict)?;
4368 let env = self.global_env(&closure_vars);
4369 let callee = Value::Undefined;
4370 // An async body does not run here: it becomes a coroutine and answers a promise,
4371 // which is what makes `await` legal in it. `this` still has to be the caller's
4372 // (for a global eval, the global object), because `this` is not part of `await`.
4373 let result = if compiled.code.kind.is_async() {
4374 self.run_async_body(compiled, env, this)
4375 } else {
4376 self.execute(compiled, env, this, Vec::new(), callee)
4377 };
4378 self.eval_scope = previous_scope;
4379 self.eval_arguments = previous_arguments;
4380 self.eval_with = previous_with;
4381 self.eval_new_target = previous_new_target;
4382 self.eval_bindings = previous_bindings;
4383 self.eval_caller = previous_caller;
4384 self.active_eval_scope = previous_eval_scope;
4385 result
4386 }
4387
4388 /// The declarations an eval cannot instantiate: they are `SyntaxError`/`TypeError`
4389 /// rather than bindings.
4390 ///
4391 /// Two rules, both from `EvalDeclarationInstantiation` (§19.2.1.3) and both about a
4392 /// declaration that cannot exist:
4393 ///
4394 /// * **`var arguments` in a function's parameter scope.** §10.2.1.3 gives a function with
4395 /// parameter expressions a separate parameter environment, and `arguments` is bound
4396 /// implicitly there, so a `var` of that name collides. An arrow that binds no
4397 /// `arguments` of its own has nothing to collide with and is allowed — see the table in
4398 /// [`Interp::check_eval_var_named_arguments`].
4399 /// * **A global `var` on a non-extensible global object**, where `CanDeclareGlobalVar` is
4400 /// false; the operation is a `TypeError`, and `eval("var x")` with
4401 /// `Object.preventExtensions(this)` must raise rather than quietly do nothing
4402 /// (`non-definable-global-var` and its four siblings).
4403 fn check_eval_var_named_arguments(
4404 &self,
4405 closure_vars: &[js_compile::bytecode::ClosureVar],
4406 strict: bool,
4407 ) -> JsResult<()> {
4408 if strict {
4409 return Ok(());
4410 }
4411 // A `var` this eval would declare on the global object, where there is no room for it.
4412 let global = &self.realm.global;
4413 if !global.is_extensible() {
4414 for var in closure_vars {
4415 if var.is_lexical || var.name == "*default*" {
4416 continue;
4417 }
4418 let declare = matches!(
4419 var.closure_type,
4420 js_compile::bytecode::ClosureType::GlobalDecl
4421 );
4422 if declare && global.own_property(&var.name).is_none() {
4423 return Err(Signal::Throw(self.make_error(
4424 "TypeError",
4425 "cannot declare a global in a non-extensible global object",
4426 )));
4427 }
4428 }
4429 }
4430 // Only a *direct* eval declares into a caller's environment; an indirect one gets the
4431 // global environment, where `var arguments` is an ordinary global.
4432 let Some(caller) = self.eval_caller.flatten() else {
4433 return Ok(());
4434 };
4435 // §19.2.1.1 step 8: in a sloppy eval, a `var` name that the *running lexical
4436 // environment* already binds is a `SyntaxError`. While a default expression is being
4437 // evaluated that environment is the **parameter** scope, so
4438 // `function(a = eval("var a = 42")){}` throws rather than writing to the parameter —
4439 // the eval would otherwise declare into an environment that is about to be copied
4440 // into the body. A *different* name is fine, and so is the same name in a function
4441 // with a simple parameter list, where there is no separate parameter environment and
4442 // the `var` belongs to the function's own.
4443 //
4444 // The names come from `args`, which is exactly the plain-identifier parameters. A
4445 // pattern parameter's bindings are also in that scope but are not recoverable from
4446 // the bytecode, so `function([a] = eval("var a")){}` is still accepted; that gap is
4447 // narrower than the one this closes and needs the parameter scope published in the
4448 // compiled function to fix.
4449 if self.in_parameter_list_at(caller) {
4450 let parameter_names: Vec<String> = self
4451 .frames
4452 .get(caller)
4453 .map(|frame| {
4454 frame
4455 .code
4456 .code
4457 .args
4458 .iter()
4459 .map(|arg| arg.name.clone())
4460 .collect()
4461 })
4462 .unwrap_or_default();
4463 let collides = closure_vars.iter().any(|var| {
4464 !var.is_lexical && var.name != "*default*" && parameter_names.contains(&var.name)
4465 });
4466 if collides {
4467 return Err(Signal::Throw(self.make_error(
4468 "SyntaxError",
4469 "eval declares a var that the parameter scope already binds",
4470 )));
4471 }
4472 }
4473 if !closure_vars
4474 .iter()
4475 .any(|var| var.name == "arguments" && !var.is_lexical)
4476 {
4477 return Ok(());
4478 }
4479 // The body of a function is a different environment from its parameter list, and only
4480 // the parameter list is separate from `arguments`.
4481 if !self.in_parameter_list_at(caller) {
4482 return Ok(());
4483 }
4484 let caller_is_arrow = self
4485 .frames
4486 .get(caller)
4487 .is_some_and(|frame| frame.code.code.is_arrow);
4488 // A *parameter* named `arguments`, not merely a binding of that name: a body
4489 // `let arguments` is in the body's environment, which is the one that is separate and
4490 // therefore cannot collide. The slot tells them apart — an argument lives in
4491 // `EvalSlot::Arg`, a lexical in `EvalSlot::Local`.
4492 let parameter_scope_binds_arguments = self.eval_bindings.iter().any(|binding| {
4493 binding.frame == caller
4494 && binding.name == "arguments"
4495 && matches!(binding.slot, EvalSlot::Arg)
4496 });
4497 if caller_is_arrow && !parameter_scope_binds_arguments {
4498 return Ok(());
4499 }
4500 Err(Signal::Throw(self.make_error(
4501 "SyntaxError",
4502 "eval declares 'arguments' in a function's parameter scope",
4503 )))
4504 }
4505
4506 /// The cell-backed subset of `bindings`, in the same priority order.
4507 ///
4508 /// Both lookup routes have to agree — the eval's own reads go through
4509 /// [`Interp::eval_binding_value`] and the closures it builds go through
4510 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4511 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4512 /// is not in a cell simply does not appear: reads and writes still work, they just
4513 /// cannot be handed to a closure that outlives the eval.
4514 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4515 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4516 for binding in bindings {
4517 let Some(frame) = self.frames.get(binding.frame) else {
4518 continue;
4519 };
4520 let cell = match binding.slot {
4521 EvalSlot::Arg => frame
4522 .code
4523 .arg_cell
4524 .get(binding.index)
4525 .copied()
4526 .unwrap_or(-1),
4527 EvalSlot::Local => frame
4528 .code
4529 .loc_cell
4530 .get(binding.index)
4531 .copied()
4532 .unwrap_or(-1),
4533 };
4534 if cell < 0 {
4535 continue;
4536 }
4537 if let Some(cell) = frame.cells.get(cell as usize) {
4538 names.push((binding.name.clone(), cell.clone()));
4539 }
4540 }
4541 names
4542 }
4543
4544 /// A `SyntaxError` that reports where in the source it happened.
4545 ///
4546 /// Compile-time failures never run, so they have no frame of their own; the
4547 /// reference still puts the position first in the trace, with no function name and
4548 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4549 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4550 /// reference borrows), which is how a script reads the position without parsing
4551 /// the trace.
4552 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4553 ///
4554 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4555 /// `columnNumber`, which is how the reference prints one. A positionless error
4556 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4557 /// the reference raises it from `js_resolve_module`, where there is no position.
4558 pub(crate) fn syntax_error_plain(
4559 &mut self,
4560 error: &js_parse::SyntaxError,
4561 file: &str,
4562 ) -> Value {
4563 if error.positionless {
4564 return self.make_error("SyntaxError", &error.message);
4565 }
4566 self.syntax_error_at(
4567 file,
4568 error.span.start.line,
4569 error.span.start.column,
4570 &error.message,
4571 )
4572 }
4573
4574 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4575 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
4576 let value = self.make_error("SyntaxError", message);
4577 if let Value::Object(object) = &value {
4578 let text = self.string(blamed);
4579 // `stack` is an own data property, and the reference keeps it
4580 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4581 object.define("stack", Property::with_attributes(text, true, false));
4582 let name = self.string(file);
4583 object.define("fileName", Property::with_attributes(name, true, true));
4584 object.define(
4585 "lineNumber",
4586 Property::with_attributes(Value::Int(line as i32), true, true),
4587 );
4588 object.define(
4589 "columnNumber",
4590 Property::with_attributes(Value::Int(column as i32), true, true),
4591 );
4592 }
4593 value
4594 }
4595
4596 /// Run a compiled script whose completion value is a function, returning it.
4597 ///
4598 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4599 /// get the closure out, which keeps the constant-pool plumbing in one place.
4600 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4601 self.run_script(code)
4602 }
4603
4604 /// The environment of a script or of any function compiled at global scope:
4605 /// every entry is a global binding, so each one resolves to the realm's cell.
4606 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4607 let mut cells = Vec::with_capacity(closure_vars.len());
4608 for closure_var in closure_vars {
4609 let cell = match closure_var.closure_type {
4610 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4611 if closure_var.is_lexical =>
4612 {
4613 // A lexical declaration: the cell is created here holding the
4614 // dead-zone marker, which is what makes the binding exist and
4615 // unreadable before its initialiser runs.
4616 self.declare_global(&closure_var.name, closure_var.is_const);
4617 self.realm.globals[&closure_var.name].clone()
4618 }
4619 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4620 // A `var` or function declaration becomes a property of the global
4621 // object, and it exists from here on — which is why
4622 // `print(v); var v = 1` prints `undefined` instead of raising.
4623 // Declaring it at instantiation time (rather than at the
4624 // initialiser) is also what makes it non-configurable: the store
4625 // then lands on an existing property instead of creating one.
4626 self.declare_var_global(&closure_var.name);
4627 // The cell is a placeholder that nothing indexes; it cannot be
4628 // omitted because the slot has to hold something.
4629 self.new_cell(Value::Undefined)
4630 }
4631 _ => {
4632 // An undeclared global is read by name; the cell is a
4633 // placeholder that nothing indexes.
4634 self.new_cell(Value::Undefined)
4635 }
4636 };
4637 cells.push(cell);
4638 }
4639 Gc::new(
4640 self.heap,
4641 ClosureEnv {
4642 cells,
4643 eval_scope: None,
4644 local_vars: None,
4645 local_phase: 1,
4646 },
4647 )
4648 }
4649
4650 /// Push a frame and run until it returns.
4651 pub(crate) fn execute(
4652 &mut self,
4653 code: Gc<CompiledCode>,
4654 env: Gc<ClosureEnv>,
4655 this: Value,
4656 args: Vec<Value>,
4657 callee: Value,
4658 ) -> JsResult<Value> {
4659 let depth = self.frames.len();
4660 if depth == 0 {
4661 // A throw that reached the host ends the *active* mode: the next one is catchable
4662 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4663 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4664 // for the throw that evaluation will raise.
4665 self.uncatchable = false;
4666 }
4667 self.push_frame(code, env, this, args, callee)?;
4668 loop {
4669 // The fast loop first: it runs whole runs of records with `pc` in a register.
4670 //
4671 // `step`'s `pc` lives in the frame, so every instruction writes it back and
4672 // reads it again — a store, a load and two bounds checks that a loop body does
4673 // not need, because nothing outside the loop can run in between. This is the
4674 // classic split: advance a register, and only spill it when leaving.
4675 //
4676 // `Some(value)` means the function ended by running off the end of its
4677 // instruction array, which is a normal return.
4678 let step = match self.run_fast() {
4679 Ok(Some(value)) => Ok(Step::Return(value)),
4680 Ok(None) => self.step(),
4681 Err(signal) => Err(signal),
4682 };
4683 match step {
4684 Ok(Step::Continue) => {}
4685 Ok(Step::Return(value)) => {
4686 self.pop_frame();
4687 // A frame that ended in a `tail_call` hands its value straight to
4688 // its caller: nothing after the call can run, so every frame above
4689 // the callee unwinds with the same value. See [`Frame::tail`] —
4690 // the reference does not reuse frames either, so recursion depth
4691 // and the stack-overflow limit behave the same way.
4692 while self.frames.len() > depth && self.frame().tail {
4693 self.pop_frame();
4694 }
4695 if self.frames.len() == depth {
4696 return Ok(value);
4697 }
4698 // The caller resumes with the value on its stack.
4699 self.frames
4700 .last_mut()
4701 .expect("a caller is live")
4702 .stack
4703 .push(value);
4704 }
4705 Err(Signal::Throw(value)) => {
4706 // The host's standing request becomes the active mode for this unwind,
4707 // and is consumed here so it does not leak into the next throw.
4708 if self.uncatchable_next {
4709 self.uncatchable_next = false;
4710 self.uncatchable = true;
4711 }
4712 // An uncatchable throw walks past every `catch` on the way out. The
4713 // frames are still popped, because the values they hold have to be
4714 // dropped — only the search for a handler is skipped.
4715 if self.uncatchable {
4716 while self.frames.len() > depth {
4717 self.frames.pop();
4718 }
4719 return Err(Signal::Throw(value));
4720 }
4721 // A handler lives on the stack of the frame that is throwing —
4722 // `catch` pushed it there — so this frame gets the first chance
4723 // to catch before it is popped.
4724 let mut value = value;
4725 loop {
4726 if self.frames.len() <= depth {
4727 return Err(Signal::Throw(value));
4728 }
4729 if self.catch_here(&mut value).is_some() {
4730 break;
4731 }
4732 self.frames.pop();
4733 }
4734 }
4735 // A `yield` in a frame that `execute` is running directly means a
4736 // generator body was entered as an ordinary call, which only happens if
4737 // the generator check in `call_or_push` was bypassed.
4738 Ok(Step::Suspend(_)) => {
4739 return Err(Signal::Throw(self.make_error(
4740 "InternalError",
4741 "a generator body ran as an ordinary call",
4742 )));
4743 }
4744 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4745 }
4746 }
4747 }
4748
4749 /// Install a handler for `value` if this frame has one, resuming at it.
4750 ///
4751 /// The scan is the reference's: walk the frame's stack downwards looking for the
4752 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset `0` is an
4753 /// enumerator marker rather than a handler — `for of` keeps one under its record so
4754 /// that `break` and `return` can find the iterator — and an exception reaching one
4755 /// **closes that iterator** before the unwinding continues.
4756 ///
4757 /// Skipping the marker instead leaked the iterator of every `for of` whose body threw:
4758 /// `for (const x of xs) { throw new Error }` never called `return`. It was also the
4759 /// whole of a nineteen-case `dstr` cluster, where `[ {}[thrower()] ] = iterable` has to
4760 /// close the iterator while the reference to store into is being worked out.
4761 ///
4762 /// `value` is `&mut` because closing the iterator may replace it: see
4763 /// [`Interp::close_iterator_on_throw`] for which of the two exceptions wins.
4764 fn catch_here(&mut self, value: &mut Value) -> Option<()> {
4765 loop {
4766 // Popped one at a time so no frame borrow is held across the close below.
4767 let top = self.frames.last_mut()?.stack.pop()?;
4768 let Value::CatchOffset(offset) = top else {
4769 continue;
4770 };
4771 if offset != 0 {
4772 let frame = self.frames.last_mut().expect("the frame was just read");
4773 frame.stack.push(value.clone());
4774 frame.pc = offset as usize;
4775 return Some(());
4776 }
4777 // The record's `iter` and `next` sit directly below the marker.
4778 let close = {
4779 let frame = self.frames.last_mut().expect("the frame was just read");
4780 let next = frame.stack.pop();
4781 let iterator = frame.stack.pop();
4782 match (iterator, next) {
4783 (Some(iterator), Some(_next)) => Some(iterator),
4784 // A malformed record cannot be closed, but unwinding still has to go
4785 // on: this is not a handler, so there is nothing to resume at.
4786 _ => None,
4787 }
4788 };
4789 if let Some(iterator) = close {
4790 self.close_iterator_on_throw(iterator);
4791 }
4792 }
4793 }
4794
4795 /// `IteratorClose` on the exception path — §7.4.6 reached with a *throw* completion.
4796 ///
4797 /// Two things differ from the ordinary close, both from the spec's step ordering:
4798 ///
4799 /// * the original exception **wins**. Step 4 (`If completion is a throw completion,
4800 /// return ? completion`) comes before step 5, so an exception raised by `return()`
4801 /// itself — or by reading it — is discarded;
4802 /// * a non-object result is **not** a `TypeError`, because step 6 is never reached.
4803 ///
4804 /// The reference does exactly this in `JS_IteratorClose(…, is_exception_pending=TRUE)`:
4805 /// it saves the pending exception, clears the slot, and re-throws the saved one from
4806 /// `done:` no matter what happened in between.
4807 fn close_iterator_on_throw(&mut self, iterator: Value) {
4808 if matches!(iterator, Value::Undefined) {
4809 return;
4810 }
4811 let Ok(method) = self.read_field(&iterator, "return") else {
4812 return;
4813 };
4814 if matches!(method, Value::Undefined | Value::Null) {
4815 return;
4816 }
4817 // A throw from `return()` replaces nothing: the exception already being unwound is
4818 // the one that propagates.
4819 let _ = self.call_value(method, iterator, Vec::new());
4820 }
4821
4822 fn push_frame(
4823 &mut self,
4824 code: Gc<CompiledCode>,
4825 env: Gc<ClosureEnv>,
4826 this: Value,
4827 mut args: Vec<Value>,
4828 callee: Value,
4829 ) -> JsResult<()> {
4830 // Two bounds, and the byte budget is the one that decides in practice. The
4831 // reference's message is `stack overflow` on an `InternalError`, not V8's
4832 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4833 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4834 let frame_cost = Self::frame_cost(&code);
4835 let stack_base = self.stack_used();
4836 if self.frames.len() >= self.max_frames
4837 || stack_base.saturating_add(frame_cost) > self.stack_limit
4838 {
4839 return Err(Signal::Throw(
4840 self.make_error("InternalError", "stack overflow"),
4841 ));
4842 }
4843 let arg_count = code.code.args.len();
4844 // How many were actually passed, which `arguments.length` reports and
4845 // `assert(x)` depends on: a call with one argument must not look like a call
4846 // with one argument and an explicit `undefined`.
4847 let passed = args.len();
4848 // Missing arguments are `undefined` in their slots; extra ones are dropped
4849 // from the slots but still reachable through `arguments`.
4850 //
4851 // A call that passes no more than the declared parameters needs **no** copy:
4852 // after the resize below, `args[..passed]` *is* the passed values. Only the
4853 // extra ones — which `truncate` is about to drop — have to be kept, and they are
4854 // the rare case. This used to copy every call: one `Value` clone per argument
4855 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4856 let passed_overflow = (passed > arg_count).then(|| {
4857 let mut values = self.take_values(passed, Value::Undefined);
4858 values[..passed].clone_from_slice(&args[..passed]);
4859 values
4860 });
4861 // Only when the counts differ, which for the overwhelmingly common call — as many
4862 // arguments as parameters — is never. `resize` followed by `truncate` on equal
4863 // lengths is two length compares and nothing else, but this is the hottest few
4864 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4865 if passed != arg_count {
4866 args.resize(arg_count, Value::Undefined);
4867 args.truncate(arg_count);
4868 }
4869 let cell_count = code.code.var_ref_count as usize;
4870 let mut cells = Vec::with_capacity(cell_count);
4871 for _ in 0..cell_count {
4872 cells.push(self.new_cell(Value::Undefined));
4873 }
4874 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4875 // A captured argument lives in its cell, not in the argument slot, so the
4876 // incoming value has to be moved there before the body runs.
4877 for (slot, cell) in code.arg_cell.iter().enumerate() {
4878 if *cell >= 0
4879 && let Some(value) = args.get(slot).cloned()
4880 {
4881 cells[*cell as usize].set(value);
4882 }
4883 }
4884 // Sloppy mode substitutes the global object for a missing receiver and boxes a
4885 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4886 // reports `object`. Strict mode passes the value through untouched.
4887 let this = if code.code.strict {
4888 this
4889 } else if this.is_nullish() {
4890 Value::Object(self.realm.global.clone())
4891 } else if matches!(this, Value::Object(_)) {
4892 this
4893 } else {
4894 match crate::builtins::this_object(self, &this) {
4895 Ok(boxed) => Value::Object(boxed),
4896 Err(_) => this,
4897 }
4898 };
4899 let stack_depth = code.code.stack_size as usize + 1;
4900 // Taken before the `push` borrows `self.frames`, because the operand stack comes
4901 // out of the same recycle pool the locals did.
4902 let stack = self.take_values(stack_depth, Value::Undefined);
4903 self.frames.push(Frame {
4904 code,
4905 env,
4906 this,
4907 args,
4908 passed_count: passed,
4909 passed_overflow: passed_overflow.map(Box::new),
4910 locals,
4911 cells,
4912 local_vars: None,
4913 // Exactly the depth the compiler computed, so the operand stack never
4914 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4915 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4916 // the buffer between calls, so "exactly" costs nothing after the first one.
4917 stack,
4918 pc: 0,
4919 at: 0,
4920 callee,
4921 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4922 cost: frame_cost,
4923 stack_base,
4924 tail: false,
4925 });
4926 Ok(())
4927 }
4928
4929 /// A value buffer of `len` slots, from the recycle pool when there is one.
4930 ///
4931 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4932 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4933 // A frame with no locals asks for nothing, and that is most frames: taking a
4934 // buffer out of the pool, clearing it and resizing it to zero is four operations
4935 // and a pool pop for an empty `Vec`, which is free to construct.
4936 if len == 0 {
4937 return Vec::new();
4938 }
4939 let mut buffer = self.free_values.pop().unwrap_or_default();
4940 buffer.clear();
4941 buffer.resize(len, fill);
4942 buffer
4943 }
4944
4945 /// Return a finished frame's value buffers for the next call to reuse.
4946 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4947 for mut buffer in [
4948 std::mem::take(&mut frame.locals),
4949 frame
4950 .passed_overflow
4951 .take()
4952 .map(|buffer| *buffer)
4953 .unwrap_or_default(),
4954 std::mem::take(&mut frame.stack),
4955 ] {
4956 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4957 // GC root: it kept every value the frame held reachable, which is invisible
4958 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4959 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4960 // exactly that within one run — the target `{}` of a finished IIFE was still
4961 // in its operand stack, in the pool.
4962 buffer.clear();
4963 // A buffer with no capacity is what `Vec::new` is; putting it back would just
4964 // fill the pool with nothing to offer.
4965 if free_values.len() < RECYCLE_SLOTS
4966 && buffer.capacity() > 0
4967 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4968 {
4969 free_values.push(buffer);
4970 }
4971 }
4972 }
4973
4974 /// Pop a finished frame and keep its buffers.
4975 ///
4976 /// Every place that drops a frame goes through here: a recycled buffer is also where
4977 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4978 /// nothing but the reuse.
4979 fn pop_frame(&mut self) -> Option<()> {
4980 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4981 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4982 let last = self.frames.len().checked_sub(1)?;
4983 Self::recycle(&mut self.free_values, &mut self.frames[last]);
4984 self.frames.truncate(last);
4985 Some(())
4986 }
4987
4988 /// Poll the host's interrupt handler, if one is installed.
4989 ///
4990 /// The counter is what keeps this off the hot path when nobody asked: the early return is
4991 /// one `Option` test, and with no handler installed the whole function is that test —
4992 /// `check_memory` next door already costs more, so this cannot be what shows up in a
4993 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4994 #[inline]
4995 fn check_interrupt(&mut self) -> JsResult<()> {
4996 if self.interrupt.is_none() {
4997 return Ok(());
4998 }
4999 if self.interrupt_counter > 0 {
5000 self.interrupt_counter -= 1;
5001 return Ok(());
5002 }
5003 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
5004 // The closure is taken out for the duration so that a handler which re-enters the
5005 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
5006 let mut handler = self.interrupt.take().expect("checked above");
5007 let abort = handler();
5008 self.interrupt = Some(handler);
5009 if abort {
5010 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
5011 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
5012 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
5013 // documentation says.
5014 self.uncatchable = true;
5015 return Err(Signal::Throw(
5016 self.make_error("InternalError", "interrupted"),
5017 ));
5018 }
5019 Ok(())
5020 }
5021
5022 /// A memory checkpoint: does the heap still fit under its limit?
5023 ///
5024 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
5025 /// a `Cell` read and a predictable branch, and the point of asking that often is that
5026 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
5027 /// only at calls would let it run until the machine died, which is the exact failure
5028 /// `--memory-limit` exists to prevent.
5029 ///
5030 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
5031 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
5032 /// script that catches it, drops the reference and carries on is legitimate: measured
5033 /// on `qjs --memory-limit 1M`, the engine recovers.
5034 fn check_memory(&mut self) -> JsResult<()> {
5035 // One `Cell` read and a predictable branch when no limit is set, and an integer
5036 // compare when one is. Containers report their own growth as it happens
5037 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
5038 // walking it here was the first version and it was O(live) per 256 instructions,
5039 // which turned a 100k-element push loop into a five-minute one.
5040 let Some(limit) = self.heap.memory_limit() else {
5041 return Ok(());
5042 };
5043 let used = self.heap.used_bytes();
5044 if used <= limit {
5045 // Back under the limit — a collection or a dropped reference did it. The next
5046 // time it goes over is a new failure, not a repeat of this one.
5047 self.oom_reported_at = 0;
5048 return Ok(());
5049 }
5050 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
5051 // block runs normally after `out of memory` — it allocates nothing, so nothing
5052 // fails. A check that re-fired on every instruction made the handler itself throw,
5053 // which is a dead end: the error became unobservable from script.
5054 //
5055 // Comparing against the total at the last report gives the same behaviour: the
5056 // handler runs while the total is unchanged, and the very next allocation over the
5057 // limit fails.
5058 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
5059 {
5060 return Ok(());
5061 }
5062 self.oom_reported_at = used;
5063 Err(Signal::Throw(
5064 self.make_error("InternalError", "out of memory"),
5065 ))
5066 }
5067
5068 /// Fail before allocating `payload` bytes, if they would not fit.
5069 ///
5070 /// For the allocations whose size comes from script data — `new Array(n)`,
5071 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
5072 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
5073 /// answering NULL for the one big request.
5074 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
5075 if self.heap.fits(payload) {
5076 return Ok(());
5077 }
5078 Err(Signal::Throw(
5079 self.make_error("InternalError", "out of memory"),
5080 ))
5081 }
5082
5083 /// Bytes of frame state the live call chain accounts for.
5084 pub fn stack_used(&self) -> usize {
5085 match self.frames.last() {
5086 Some(frame) => frame.stack_base + frame.cost,
5087 None => 0,
5088 }
5089 }
5090
5091 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
5092 ///
5093 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
5094 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
5095 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
5096 /// instead. That is the whole difference between the two models: it rations C stack, we
5097 /// ration frame state, and both quantities are dominated by the value slots — which is
5098 /// why the two depths come out comparable rather than merely proportional.
5099 fn frame_cost(code: &CompiledCode) -> usize {
5100 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
5101 std::mem::size_of::<Frame>()
5102 + std::mem::size_of::<Value>() * slots
5103 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
5104 }
5105
5106 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
5107 ///
5108 /// Only names the eval created are here: a name the frame already declared statically
5109 /// is written through to its own slot instead, so this cannot shadow a real local.
5110 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
5111 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
5112 let (local_vars, phase) = self.visible_local_vars()?;
5113 if !local_vars.contains(name) {
5114 return None;
5115 }
5116 local_vars.get(name, phase)
5117 }
5118
5119 /// The variables a direct `eval` declared, as the code currently running sees them.
5120 ///
5121 /// Inside an eval that is the *caller's* set — the eval's own variable environment
5122 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
5123 /// else it is the current frame's, falling back to the frame the closure was created
5124 /// in.
5125 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
5126 ///
5127 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
5128 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
5129 /// refcount operations (the clone out of the frame, the drop at the end of the match)
5130 /// just to be asked `is_none`.
5131 fn has_visible_local_vars(&self) -> bool {
5132 let index = match self.eval_caller.flatten() {
5133 Some(caller) => caller,
5134 None => match self.frames.len().checked_sub(1) {
5135 Some(top) => top,
5136 None => return false,
5137 },
5138 };
5139 match self.frames.get(index) {
5140 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
5141 None => false,
5142 }
5143 }
5144
5145 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
5146 // While an `eval` runs, its own frame is on top but its variable environment is
5147 // the *caller's* — so the caller is what the lookup has to start from.
5148 let (index, phase) = match self.eval_caller.flatten() {
5149 Some(caller) => (
5150 caller,
5151 if self.in_parameter_list_at(caller) {
5152 0
5153 } else {
5154 1
5155 },
5156 ),
5157 None => (
5158 self.frames.len().checked_sub(1)?,
5159 if self.in_parameter_list() { 0 } else { 1 },
5160 ),
5161 };
5162 let frame = self.frames.get(index)?;
5163 // The frame's own variables, or — for an arrow, which has no variable environment
5164 // of its own — the one it was created in, which `ClosureEnv` carries.
5165 if let Some(local_vars) = frame.local_vars.clone() {
5166 return Some((local_vars, phase));
5167 }
5168 frame
5169 .env
5170 .local_vars
5171 .clone()
5172 .map(|local_vars| (local_vars, frame.env.local_phase))
5173 }
5174
5175 /// Whether the innermost frame is still evaluating its parameter list.
5176 ///
5177 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
5178 /// and a closure created there may only see that much of [`LocalVars`].
5179 fn in_parameter_list(&self) -> bool {
5180 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
5181 }
5182
5183 /// [`Interp::in_parameter_list`] for a specific frame.
5184 fn in_parameter_list_at(&self, frame: usize) -> bool {
5185 let Some(frame) = self.frames.get(frame) else {
5186 return false;
5187 };
5188 let code = &frame.code.code;
5189 if !code.has_parameter_expressions {
5190 return false;
5191 }
5192 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
5193 // function as its body and let a direct `eval` act accordingly.
5194 if code.body_start == (0, 0) {
5195 return false;
5196 }
5197 match code.position_at(frame.at as u32) {
5198 Some(position) => position < code.body_start,
5199 None => false,
5200 }
5201 }
5202
5203 fn frame(&self) -> &Frame {
5204 self.frames.last().expect("a frame is live")
5205 }
5206
5207 fn frame_mut(&mut self) -> &mut Frame {
5208 self.frames.last_mut().expect("a frame is live")
5209 }
5210
5211 // -- slot access --------------------------------------------------------
5212
5213 /// Move a local's value out, leaving `undefined` in the slot.
5214 ///
5215 /// `None` for a captured slot: its value lives in a cell shared with every closure
5216 /// that closed over it, so it can never be exclusively ours and must not be taken.
5217 ///
5218 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
5219 /// for every read and fatal for this one — a clone is exactly the second handle that
5220 /// rules out growing the string in place.
5221 fn take_loc(&mut self, slot: usize) -> Option<Value> {
5222 let frame = self.frames.last_mut()?;
5223 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
5224 return None;
5225 }
5226 frame
5227 .locals
5228 .get_mut(slot)
5229 .map(|value| std::mem::replace(value, Value::Undefined))
5230 }
5231
5232 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
5233 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
5234 ///
5235 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
5236 /// it** — the value is put back before the general path runs — so a `valueOf` that
5237 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
5238 /// error as it would have without the fusion. This is why the in-place attempt is a
5239 /// `take` and not a `get`: an optimisation that changes what an exception observes is
5240 /// a wrong answer with a good excuse.
5241 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
5242 // The take is `matches!`-guarded on the *right* operand only, and the taken value
5243 // is put back on every path that does not append. An earlier version wrote the two
5244 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
5245 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
5246 // through with its value already taken and dropped: the general path below then
5247 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
5248 // A wrong answer, from an optimisation, with every test green.
5249 if matches!(right, Value::String(_))
5250 && let Some(taken) = self.take_loc(slot)
5251 {
5252 if let Value::String(mut left) = taken {
5253 let appended = match left.get_mut() {
5254 Some(string) => string.append_in_place(
5255 // The pattern is the one `matches!` just checked.
5256 match &right {
5257 Value::String(text) => text,
5258 _ => unreachable!("guarded above"),
5259 },
5260 ),
5261 None => None,
5262 };
5263 self.put_loc(slot, Value::String(left));
5264 if let Some(added) = appended {
5265 // The buffer grew where it stood, so the heap's running total has to
5266 // be told: `measure_used` would report the new length, and the two must
5267 // agree or the subtraction at free time leaves the counter wrong.
5268 self.heap.adjust_payload(added as isize);
5269 return Ok(());
5270 }
5271 } else {
5272 self.put_loc(slot, taken);
5273 }
5274 }
5275 // The two-number case, without an operand stack round trip. Everything below
5276 // this point is the *general* path: push both, call `binary_add`, pop the answer,
5277 // store it — five operations and two `Value` clones for what is one integer add.
5278 // `AddImmLoc` already answers this shape that way; the fusion above it was written
5279 // for string append and never got the numeric half, so `t += i` — a counting loop
5280 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
5281 let left = self.get_loc(slot);
5282 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
5283 self.put_loc(
5284 slot,
5285 match a.checked_add(*b) {
5286 Some(sum) => Value::Int(sum),
5287 None => Value::Float(*a as f64 + *b as f64),
5288 },
5289 );
5290 return Ok(());
5291 }
5292 self.push(left);
5293 self.push(right);
5294 self.binary_add()?;
5295 let value = self.pop();
5296 self.put_loc(slot, value);
5297 Ok(())
5298 }
5299
5300 fn get_arg(&self, slot: usize) -> Value {
5301 self.frame().read_arg(slot)
5302 }
5303
5304 fn put_arg(&mut self, slot: usize, value: Value) {
5305 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
5306 if cell == -1 {
5307 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
5308 *slot = value;
5309 }
5310 } else {
5311 self.frame().cells[cell as usize].set(value);
5312 }
5313 }
5314
5315 fn get_loc(&self, slot: usize) -> Value {
5316 // The cell mapping is `-1` for every slot that was not captured — which is all of
5317 // them in a function that creates no closure. `Frame::read_loc` tests that first,
5318 // so the common case is one array read and a clone: 20% of every loop iteration
5319 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
5320 // sample of `dispatch:arith`).
5321 self.frame().read_loc(slot)
5322 }
5323
5324 fn put_loc(&mut self, slot: usize, value: Value) {
5325 // One borrow instead of three, and the cell check on the frame we already hold.
5326 let frame = self.frames.last_mut().expect("a frame is live");
5327 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
5328 if cell < 0 {
5329 if let Some(slot) = frame.locals.get_mut(slot) {
5330 *slot = value;
5331 }
5332 } else if let Some(cell) = frame.cells.get(cell as usize) {
5333 cell.set(value);
5334 }
5335 }
5336
5337 // -- globals ------------------------------------------------------------
5338
5339 /// The name a global-slot operand refers to.
5340 fn global_name(&self, slot: usize) -> String {
5341 self.frame()
5342 .code
5343 .code
5344 .closure_vars
5345 .get(slot)
5346 .map(|c| c.name.clone())
5347 .unwrap_or_default()
5348 }
5349
5350 /// The facts about a global binding that decide where it lives.
5351 ///
5352 /// A script's globals split in two, and the split is observable: `var` and
5353 /// function declarations become properties of the global object (`globalThis.v`
5354 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
5355 /// declarations live in the global *lexical* environment and are invisible there
5356 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
5357 /// `is_lexical` flag means the answer is already in the bytecode.
5358 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
5359 let name = self.global_name(slot);
5360 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
5361 // while forwarding a reference through a nested function is built with the
5362 // flags cleared, so `const c` would look like an ordinary `var` from inside a
5363 // closure. Presence in the realm's lexical table is the same fact, recorded
5364 // once, and every slot sees it.
5365 let lexical = self.realm.globals.contains_key(&name);
5366 let is_const = self.realm.lexical_consts.contains(&name);
5367 (name, lexical, is_const)
5368 }
5369
5370 /// The value of `name` in the innermost active `with` object, if any.
5371 ///
5372 /// The active objects are the [`VarKind::With`] locals of every frame still running,
5373 /// innermost frame first and innermost block first within one. Walking frames rather
5374 /// than keeping a separate stack is what makes a closure called from inside a `with`
5375 /// see it, and what keeps the object alive only as long as the block is.
5376 /// The innermost active `with` object that has `name`, if any.
5377 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
5378 let objects = self.eval_with.clone().unwrap_or_default();
5379 for object in objects {
5380 let key = self.string(name.to_string());
5381 if self
5382 .has_property(&key, &Value::Object(object.clone()))
5383 .ok()?
5384 {
5385 return Some(object);
5386 }
5387 }
5388 None
5389 }
5390
5391 /// Every active `with` object, innermost first.
5392 fn with_objects(&self) -> Vec<Gc<JsObject>> {
5393 let mut objects = Vec::new();
5394 for frame in self.frames.iter().rev() {
5395 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
5396 if var.kind != js_compile::VarKind::With {
5397 continue;
5398 }
5399 // A captured binding lives in its cell and not in the slot list, so the
5400 // cell is consulted first — a closure created inside the block is exactly
5401 // what makes the object captured. Before the store runs the slot still
5402 // holds `undefined`, and a `with` object is always boxed, so a non-object
5403 // entry is simply not in scope yet.
5404 let value = frame
5405 .code
5406 .loc_cell
5407 .get(index)
5408 .copied()
5409 .filter(|cell| *cell >= 0)
5410 .and_then(|cell| frame.cells.get(cell as usize))
5411 .map(|cell| cell.get())
5412 .or_else(|| frame.locals.get(index).cloned());
5413 if let Some(Value::Object(object)) = value {
5414 objects.push(object);
5415 }
5416 }
5417 }
5418 objects
5419 }
5420
5421 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
5422 for object in self.eval_with.clone().unwrap_or_default() {
5423 let key = self.string(name.to_string());
5424 if self.has_property(&key, &Value::Object(object.clone()))? {
5425 return Ok(Some(self.read_field(&Value::Object(object), name)?));
5426 }
5427 }
5428 Ok(None)
5429 }
5430
5431 /// Whether every scope between here and the global object is an ordinary one.
5432 ///
5433 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
5434 /// bytecode resolved; when any is live the general path has to run in full order. When
5435 /// none is — every ordinary program — a global read is a property read and nothing
5436 /// else, and that is worth caching.
5437 fn scopes_are_plain(&self) -> bool {
5438 self.eval_caller.is_none()
5439 && self.eval_with.is_none()
5440 && self.eval_arguments.is_none()
5441 && self.eval_bindings.is_empty()
5442 && self.eval_scope.is_none()
5443 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
5444 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
5445 // its `ClosureEnv`, so the test has to be the same one the general path makes.
5446 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
5447 // upstream corpus caught and no unit test did.
5448 && !self.has_visible_local_vars()
5449 && self.frame().env.eval_scope.is_none()
5450 }
5451
5452 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
5453 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
5454 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
5455 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
5456 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
5457 // borrow outlive the `&mut self` the lookup needs.
5458 //
5459 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
5460 // forwarded through a nested function has its flags cleared, so the flag cannot
5461 // be believed.
5462 let code = self.frame().code.clone();
5463 let name = code
5464 .code
5465 .closure_vars
5466 .get(slot)
5467 .map(|c| c.name.as_str())
5468 .unwrap_or_default();
5469 let lexical = self.realm.globals.contains_key(name);
5470 // The common case, first: an ordinary global `var`, with a cache in front of the
5471 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
5472 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
5473 // cache hit and return without touching any of it.
5474 if !lexical && self.scopes_are_plain() {
5475 return self.get_plain_global(name, slot);
5476 }
5477 if name == "arguments"
5478 && let Some(arguments) = &self.eval_arguments
5479 {
5480 return Ok(arguments.clone());
5481 }
5482 // A `with` block around the *call site* is part of the scope an `eval` sees, so
5483 // the objects live when the eval started are consulted before anything else. The
5484 // snapshot is taken at entry rather than scanning the frames on every read: a
5485 // block that has already finished still leaves its object in the slot, and a
5486 // bytecode read outside the block must not see it.
5487 if let Some(value) = self.with_lookup(name)? {
5488 return Ok(value);
5489 }
5490 // A variable a direct `eval` declared shadows everything the compiler resolved,
5491 // including an enclosing function's binding: the eval put it in the caller's own
5492 // variable environment, which is nearer than any captured scope.
5493 if let Some((local_vars, phase)) = self.visible_local_vars()
5494 && let Some(cell) = local_vars.get(name, phase)
5495 {
5496 return Ok(cell.get());
5497 }
5498 // The frame that called `eval` is the innermost scope the eval'd code sees, so
5499 // its local `a` wins over a global `a`.
5500 if let Some(value) = self.eval_binding_value(name) {
5501 return Ok(value);
5502 }
5503 // A closure created by an `eval` resolves its free names against the bindings
5504 // that eval saw, even after the eval (and its frames) are gone.
5505 if let Some(cell) = self
5506 .frame()
5507 .env
5508 .eval_scope
5509 .as_ref()
5510 .and_then(|scope| scope.get(name))
5511 {
5512 let value = cell.get();
5513 if matches!(value, Value::Uninitialized) {
5514 return Err(self.throw_reference(name));
5515 }
5516 return Ok(value);
5517 }
5518 // A binding declared by the strict `eval` currently running shadows anything
5519 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5520 if let Some(scope) = &self.eval_scope
5521 && let Some(value) = scope.get(name)
5522 {
5523 return Ok(value.clone());
5524 }
5525 if lexical {
5526 // A lexical global is a binding in a side table, so the dead zone is
5527 // visible and it is nowhere on the global object.
5528 if let Some(cell) = self.realm.globals.get(name) {
5529 let value = cell.get();
5530 if matches!(value, Value::Uninitialized) {
5531 return Err(self.throw_reference(name));
5532 }
5533 return Ok(value);
5534 }
5535 return Err(self.throw_reference(name));
5536 }
5537 // A `var` global is an ordinary property, so the prototype chain and the
5538 // global object's own builtins are all reachable through it.
5539 match self.get_property(&self.realm.global.clone(), name)? {
5540 Some(value) => Ok(value),
5541 None => Err(self.throw_reference(name)),
5542 }
5543 }
5544
5545 /// Read a plain global `var`: a cached own data property, or the full lookup.
5546 ///
5547 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5548 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5549 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5550 let object = self.realm.global.clone();
5551 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5552 if let Some(cached) = &self.global_cache[site]
5553 && object.upgrades_to(&cached.object)
5554 && let Some(value) = object.data_property_at(cached.index, name)
5555 {
5556 return Ok(value);
5557 }
5558 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5559 // chain exactly as before, then remember the answer if it is worth remembering.
5560 let Some(value) = self.get_property(&object, name)? else {
5561 return Err(self.throw_reference(name));
5562 };
5563 if let Some(index) = object.own_data_index(name) {
5564 self.global_cache[site] = Some(GlobalCache {
5565 object: object.downgrade(),
5566 index,
5567 });
5568 }
5569 Ok(value)
5570 }
5571
5572 /// Store to a global binding.
5573 ///
5574 /// Returns a signal when the store is refused: a `const` global may only be
5575 /// written by its initialiser, and a non-configurable `var` global may not be
5576 /// deleted but is always writable.
5577 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5578 let (name, lexical, is_const) = self.global_binding(slot);
5579
5580 // An assignment inside a `with` writes through to the object that supplies the
5581 // name, which for an `eval` means consulting the same chain `get_global` does.
5582 if let Some(owner) = self.with_owner(&name) {
5583 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5584 return Ok(());
5585 }
5586 // A variable the running eval *declared* takes the write before any caller
5587 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5588 // environment even when an enclosing function has a `var c` of its own.
5589 if self.eval_caller.flatten().is_some()
5590 && let Some((local_vars, phase)) = self.visible_local_vars()
5591 && local_vars.contains(&name)
5592 && let Some(cell) = local_vars.get(&name, phase)
5593 {
5594 cell.set(value);
5595 return Ok(());
5596 }
5597 // A binding of the frame that called `eval` takes the write, which is what
5598 // makes `f("a = 3")` change the caller's `a`.
5599 if self.set_eval_binding(&name, &value)? {
5600 return Ok(());
5601 }
5602 // A closure that outlived its `eval` writes through to the same cell it reads.
5603 if let Some(cell) = self
5604 .frame()
5605 .env
5606 .eval_scope
5607 .as_ref()
5608 .and_then(|scope| scope.get(&name))
5609 .cloned()
5610 {
5611 cell.set(value);
5612 return Ok(());
5613 }
5614 // Inside a strict `eval`, a name it declared itself is stored there. An
5615 // *assignment* to a name nobody declared is not a declaration, so it falls
5616 // through: strict mode raises `ReferenceError` for it, which is what
5617 // `eval("1 + (@not_def = 1)")` has to do.
5618 if let Some(scope) = self.eval_scope.as_mut()
5619 && scope.contains_key(&name)
5620 {
5621 scope.insert(name, value);
5622 return Ok(());
5623 }
5624 if lexical {
5625 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5626 // A lexical global starts out `Uninitialized` and only `init_global` ends
5627 // that, so a store reaching here is either a plain assignment to a slot
5628 // still in its dead zone — `x = 1; let x` at the top level, a
5629 // `ReferenceError` — or a write to a `const` whose initialiser already ran.
5630 if matches!(cell.get(), Value::Uninitialized) {
5631 return Err(self.dead_zone_global(&name));
5632 }
5633 if is_const {
5634 return Err(self.read_only_global(&name));
5635 }
5636 cell.set(value);
5637 return Ok(());
5638 }
5639 // Writing an undeclared lexical global is a `ReferenceError` in strict
5640 // mode and a silent global creation otherwise; creating the cell here
5641 // keeps both paths from losing the value.
5642 let cell = self.new_cell(value);
5643 self.realm.globals.insert(name, cell);
5644 return Ok(());
5645 }
5646 // A variable a direct `eval` declared in this call shadows the global object, even
5647 // when the global already has a property of that name — `var c = "global"` at the
5648 // top level must not capture `eval("var c = 1")` inside a function.
5649 if let Some((local_vars, phase)) = self.visible_local_vars()
5650 && local_vars.contains(&name)
5651 && let Some(cell) = local_vars.get(&name, phase)
5652 {
5653 cell.set(value);
5654 return Ok(());
5655 }
5656 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5657 // remembered a global's slot index since M12b, but the *store* side never did: it
5658 // converted the name to a `PropertyKey` (two allocations) and then scanned the
5659 // global object's whole table — which holds every builtin — on every assignment to
5660 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5661 // full global lookup per iteration; measured with a counter, `s` as a global made
5662 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5663 //
5664 // Re-validated exactly like the read: same object, same index, still the name, and
5665 // — the one extra check a store needs — still writable. A global that is an
5666 // accessor, non-writable, or inherited fails here and falls through to the full
5667 // path below, which reports the failure the way it always did.
5668 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5669 let global = self.realm.global.clone();
5670 if let Some(cached) = &self.global_cache[site]
5671 && global.upgrades_to(&cached.object)
5672 && global.write_data_at(cached.index, &name, value.clone())
5673 {
5674 return Ok(());
5675 }
5676 match global.own_property(&name) {
5677 // A `var` global is writable, so the store goes straight through — but
5678 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5679 // store (a non-writable or accessor-without-setter global) is a silent
5680 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5681 // split every other assignment has.
5682 Some(_) => {
5683 let on_failure = if self.current_strict() {
5684 DeleteFailure::Throw
5685 } else {
5686 DeleteFailure::Ignore
5687 };
5688 let result = self.set_property_with(&global, &name, value, on_failure);
5689 // Teach the cache the slot for a plain writable own data property, which is
5690 // what a declared `var` is. Without this the fast path above could never
5691 // fire for a global that is only ever *written* — its entry would have to
5692 // be put there by a read of the same slot, and a write-only loop has none.
5693 if result.is_ok()
5694 && let Some(index) = global.own_data_index(&name)
5695 {
5696 self.global_cache[site] = Some(GlobalCache {
5697 object: global.downgrade(),
5698 index,
5699 });
5700 }
5701 result
5702 }
5703 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5704 // declaration creates a *configurable* property, which is what makes it
5705 // deletable and is the one way a global differs from a declared `var`.
5706 // In strict mode the same store is a `ReferenceError` instead: that is the
5707 // whole point of strict mode, and creating the global silently meant
5708 // `"use strict"; x = 1` looked like it worked.
5709 None => {
5710 if self.current_strict() {
5711 return Err(self.throw_reference(&name));
5712 }
5713 // A direct eval declares here rather than on the global object: its
5714 // `var`s belong to the caller's variable environment. `declare_eval_local`
5715 // also covers a plain assignment to a variable an earlier eval made.
5716 if let Some(cell) = self.declare_eval_local(&name) {
5717 cell.set(value);
5718 return Ok(());
5719 }
5720 global.define_data(&name, value);
5721 Ok(())
5722 }
5723 }
5724 }
5725
5726 /// The value of a binding of the frame that called `eval`, if there is one.
5727 fn eval_binding_value(&self, name: &str) -> Option<Value> {
5728 let binding = self
5729 .eval_bindings
5730 .iter()
5731 .find(|binding| binding.name == name)?;
5732 let owner = self.frames.get(binding.frame)?;
5733 let (slot, index) = (binding.slot, binding.index);
5734 Some(match slot {
5735 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5736 cell if cell >= 0 => owner
5737 .cells
5738 .get(cell as usize)
5739 .map(|cell| cell.get())
5740 .unwrap_or(Value::Undefined),
5741 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5742 },
5743 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5744 cell if cell >= 0 => owner
5745 .cells
5746 .get(cell as usize)
5747 .map(|cell| cell.get())
5748 .unwrap_or(Value::Undefined),
5749 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5750 },
5751 })
5752 }
5753
5754 /// Write to a binding of the frame that called `eval`.
5755 ///
5756 /// `Ok(false)` means no binding matched and the caller should keep looking. A
5757 /// matched binding can still refuse the store, which is why this is fallible: a
5758 /// `const` is read-only everywhere, and a named function expression's own name is
5759 /// read-only in strict mode.
5760 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5761 let Some(binding) = self
5762 .eval_bindings
5763 .iter()
5764 .find(|binding| binding.name == name)
5765 else {
5766 return Ok(false);
5767 };
5768 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5769 let strict = self.current_strict();
5770 let Some(owner) = self.frames.get_mut(frame) else {
5771 return Ok(false);
5772 };
5773 match slot {
5774 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5775 cell if cell >= 0 => {
5776 if let Some(cell) = owner.cells.get(cell as usize) {
5777 cell.set(value.clone());
5778 }
5779 }
5780 _ => {
5781 if let Some(slot) = owner.args.get_mut(index) {
5782 *slot = value.clone();
5783 }
5784 }
5785 },
5786 EvalSlot::Local => {
5787 let declared = owner.code.code.vars.get(index);
5788 // A `const` is read-only even through `eval`. The realm records this for
5789 // globals (see `lexical_consts`), but a local's `const`-ness is only in
5790 // the bytecode, so this is where it has to be enforced.
5791 if declared.is_some_and(|var| var.is_const) {
5792 return Err(self.read_only_local(name));
5793 }
5794 // The name of a named function expression is read-only too, but only
5795 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5796 // such a name is ignored, the same as a direct store would be.
5797 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5798 return if strict {
5799 Err(self.read_only_local(name))
5800 } else {
5801 Ok(true)
5802 };
5803 }
5804 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5805 cell if cell >= 0 => {
5806 if let Some(cell) = owner.cells.get(cell as usize) {
5807 cell.set(value.clone());
5808 }
5809 }
5810 _ => {
5811 if let Some(slot) = owner.locals.get_mut(index) {
5812 *slot = value.clone();
5813 }
5814 }
5815 }
5816 }
5817 }
5818 Ok(true)
5819 }
5820
5821 /// The `TypeError` an assignment to a read-only binding raises.
5822 fn read_only_local(&self, name: &str) -> Signal {
5823 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5824 }
5825
5826 /// Declare `name` as a variable of the frame that called the running `eval`.
5827 ///
5828 /// `None` when there is no direct eval in progress, or it was called from the top
5829 /// level — then the caller's variable environment *is* the global one and the
5830 /// existing path is right.
5831 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5832 let caller = self.eval_caller.flatten()?;
5833 // The bottom frame is the top-level script, whose variable environment *is* the
5834 // global one — so `eval("var x = 1")` at the top level still creates a global.
5835 if caller == 0 {
5836 return None;
5837 }
5838 // A name the eval's *own* variable environment already binds is not a new
5839 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5840 // `arguments`, and creating a second binding would leave the first — the one
5841 // closures read — untouched. A binding of an *outer* frame does not count: a
5842 // declaration shadows it rather than writing through.
5843 if self
5844 .eval_bindings
5845 .iter()
5846 .any(|binding| binding.name == name && binding.frame == caller)
5847 {
5848 return None;
5849 }
5850 let phase = if self.in_parameter_list_at(caller) {
5851 0
5852 } else {
5853 1
5854 };
5855 self.frame_local_vars(caller)?;
5856 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5857 if let Some(cell) = local_vars.get(name, 1) {
5858 return Some(cell);
5859 }
5860 let cell = self.new_cell(Value::Undefined);
5861 Some(local_vars.declare(name, phase, cell))
5862 }
5863
5864 /// Make sure `frame` has a `LocalVars`, creating it on demand.
5865 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5866 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5867 return Some(local_vars.clone());
5868 }
5869 let local_vars = Gc::new(self.heap, LocalVars::new());
5870 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5871 Some(local_vars)
5872 }
5873
5874 /// Whether the realm already has a binding for `name`, lexically or as an *own*
5875 /// property of the global object. Used to decide whether a store inside an
5876 /// `eval` writes through to the realm or declares a binding of its own.
5877 ///
5878 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5879 /// write to `Object.prototype.toString`, and must not shadow it either.
5880 fn global_knows(&mut self, name: &str) -> bool {
5881 if self.realm.globals.contains_key(name) {
5882 return true;
5883 }
5884 self.realm.global.own_property(name).is_some()
5885 }
5886
5887 /// Whether the code currently running is strict.
5888 ///
5889 /// Read off the frame's function, which is where the parser's answer ended up; a
5890 /// native function never runs strict-only checks, and there is no frame at all
5891 /// before the first script.
5892 pub fn current_strict(&self) -> bool {
5893 self.frames
5894 .last()
5895 .is_some_and(|frame| frame.code.code.strict)
5896 }
5897
5898 /// Initialise a declared global, which is what ends its dead zone.
5899 ///
5900 /// A `var` global becomes a property of the global object: writable, so a later
5901 /// assignment goes through, and non-configurable, so `delete` refuses.
5902 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5903 let (name, lexical, _) = self.global_binding(slot);
5904 // A `var` declared by the strict `eval` currently running belongs to the
5905 // eval's scope, not to the global object: `eval("var v = 1")` must not make
5906 // `typeof v` answer `"number"` afterwards. A name the realm already has is
5907 // initialised in place, which is what a re-declaration inside eval does.
5908 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5909 self.eval_scope
5910 .as_mut()
5911 .expect("checked above")
5912 .insert(name, value);
5913 return Ok(());
5914 }
5915 if let Some(scope) = self.eval_scope.as_mut()
5916 && scope.contains_key(&name)
5917 {
5918 scope.insert(name, value);
5919 return Ok(());
5920 }
5921 if lexical {
5922 // The cell exists (created at declaration time) holding the dead-zone
5923 // marker; storing the value is what makes the binding readable.
5924 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5925 cell.set(value);
5926 return Ok(());
5927 }
5928 let cell = self.new_cell(value);
5929 self.realm.globals.insert(name, cell);
5930 return Ok(());
5931 }
5932 let global = self.realm.global.clone();
5933 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5934 // to answer `false` and leave the binding in place. `with_attributes` ties
5935 // `configurable` to `writable`, so the property is built field by field.
5936 global.define(
5937 &name,
5938 Property {
5939 value: Some(value),
5940 writable: true,
5941 enumerable: true,
5942 configurable: false,
5943 ..Property::default()
5944 },
5945 );
5946 Ok(())
5947 }
5948
5949 /// The `TypeError` a store to a `const` global raises.
5950 fn read_only_global(&self, name: &str) -> Signal {
5951 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5952 }
5953
5954 /// The `ReferenceError` a store to a not-yet-initialised lexical global raises.
5955 fn dead_zone_global(&self, name: &str) -> Signal {
5956 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not initialized")))
5957 }
5958
5959 // -- properties ---------------------------------------------------------
5960
5961 /// Read `object[key]`, following the prototype chain.
5962 ///
5963 /// An inherited accessor runs with the *receiver* as `this`, which is why the
5964 /// lookup returns the owner rather than just the value.
5965 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5966 self.get_property_key(object, &PropertyKey::from(key))
5967 }
5968
5969 /// [`Interp::get_property`] with a key that may be a symbol.
5970 pub fn get_property_key(
5971 &mut self,
5972 object: &Gc<JsObject>,
5973 key: &PropertyKey,
5974 ) -> JsResult<Option<Value>> {
5975 self.get_property_key_for(object, None, key)
5976 }
5977
5978 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5979 ///
5980 /// The receiver matters when the property is found on a *prototype*: a getter has to
5981 /// see the object the read started from. For a primitive that is the primitive
5982 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5983 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5984 /// the owner.
5985 pub fn get_property_key_for(
5986 &mut self,
5987 object: &Gc<JsObject>,
5988 receiver: Option<&Value>,
5989 key: &PropertyKey,
5990 ) -> JsResult<Option<Value>> {
5991 // A proxy answers for itself, before any of the shortcuts below: `new
5992 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5993 // have.
5994 if object.proxy_state().is_some() {
5995 let receiver = receiver
5996 .cloned()
5997 .unwrap_or_else(|| Value::Object(object.clone()));
5998 return self.proxy_get(object, &receiver, key);
5999 }
6000 // A host class's `get_property` trap replaces the whole read, prototype walk
6001 // included — that is what makes a native accessor free rather than a JavaScript
6002 // getter call.
6003 if let Some(exotic) = object.exotic() {
6004 let receiver_value = receiver
6005 .cloned()
6006 .unwrap_or_else(|| Value::Object(object.clone()));
6007 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
6008 return Ok(Some(value));
6009 }
6010 // With no `get_property` trap, a `get_own_property` trap still answers for the
6011 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
6012 // and the hook lives exactly there. A key the trap reports as absent is still
6013 // looked for on the prototype, which is why the search resumes *above*.
6014 if let Some(property) = exotic.get_own_property(self, object, key)? {
6015 return match property {
6016 Some(property) => self.read_property(property, object, receiver),
6017 None => match lookup_key_above(object, key) {
6018 Some((_, property)) => self.read_property(property, object, receiver),
6019 None => Ok(None),
6020 },
6021 };
6022 }
6023 }
6024 // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
6025 // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
6026 // The `[[Get]]` short-circuit therefore belongs to this one arm.
6027 //
6028 // Constructibility is exactly the split the reference makes: `function f(){}` and
6029 // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
6030 // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
6031 // function" — it *is* the predicate, which is why no extra marker is needed.
6032 if let Some(text) = key.as_str()
6033 && (text == "caller" || text == "arguments")
6034 && object.is_constructor()
6035 && object.is_callable()
6036 && !object.is_bound_function()
6037 // …and only when the body is **sloppy**. A strict body reaches the
6038 // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
6039 // whole `Function/15.3.5.4_2-*gs` family is written against
6040 // (`onlyStrict`, so every function in them is strict).
6041 && !object.function_is_strict()
6042 && object.own_property(text).is_none()
6043 {
6044 return Ok(Some(Value::Undefined));
6045 }
6046 // The element-vector and `length` shortcuts are string-only: an array index
6047 // has no symbol spelling.
6048 if let Some(text) = key.as_str() {
6049 if let Some(value) = self.own_element(object, text) {
6050 return Ok(Some(value));
6051 }
6052 // `length` is not stored as a property: an array's length is its element
6053 // count, and keeping one copy of it is what makes `push`/`pop` and
6054 // `a.length = n` agree.
6055 if let Some(length) = object.array_length()
6056 && text == "length"
6057 {
6058 // Not `Value::Int(length as i32)`: see [`length_value`].
6059 return Ok(Some(crate::object::length_value(length)));
6060 }
6061 }
6062 // A proxy or a hooked exotic object anywhere above `object` makes the static
6063 // table walk below wrong: a proxy's own table is *empty by design* (the properties
6064 // live on its target), so the walk skipped that link entirely and everything behind
6065 // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
6066 // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
6067 // -target-is-proxy.js` are the four.
6068 if Self::chain_needs_dispatch(object) {
6069 return self.walk_get(object, receiver, key);
6070 }
6071 match lookup_key(object, key) {
6072 Some((_, property)) => self.read_property(property, object, receiver),
6073 None => Ok(None),
6074 }
6075 }
6076
6077 /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
6078 /// answer for itself.
6079 ///
6080 /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
6081 /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
6082 /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
6083 /// an inherited getter the object the read started from.
6084 fn walk_get(
6085 &mut self,
6086 start: &Gc<JsObject>,
6087 receiver: Option<&Value>,
6088 key: &PropertyKey,
6089 ) -> JsResult<Option<Value>> {
6090 let receiver = receiver
6091 .cloned()
6092 .unwrap_or_else(|| Value::Object(start.clone()));
6093 let mut current = Some(start.clone());
6094 while let Some(holder) = current {
6095 // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
6096 // has to ask it, not read its (empty) own-property table. `Object.create(new
6097 // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
6098 // instead found nothing.
6099 if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
6100 return Ok(Some(value));
6101 }
6102 // A host class's `get_property` trap replaces the whole read for that holder,
6103 // prototype walk included — the same rule `get_property_key_for` applies to the
6104 // first object.
6105 if let Some(exotic) = holder.exotic()
6106 && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
6107 {
6108 return Ok(Some(value));
6109 }
6110 if let Some(property) = self.object_get_own_property(&holder, key)? {
6111 return self.read_property(property, &holder, Some(&receiver));
6112 }
6113 current = self.object_prototype_of(&holder)?;
6114 }
6115 Ok(None)
6116 }
6117
6118 /// Whether `object` or anything above it has properties that cannot be read out of a
6119 /// property table — a proxy, or an exotic object with a `get_own_property` hook.
6120 ///
6121 /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
6122 /// is the hot path for every property read; this is the check that decides whether it
6123 /// is safe to take it.
6124 fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
6125 object
6126 .chain()
6127 .iter()
6128 .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
6129 }
6130
6131 /// The value a property read answers.
6132 ///
6133 /// One place rather than three, because an accessor has to run with the *receiver* as
6134 /// `this` whether the descriptor came from the property table, an exotic
6135 /// `get_own_property` trap, or a prototype above one.
6136 fn read_property(
6137 &mut self,
6138 property: Property,
6139 object: &Gc<JsObject>,
6140 receiver: Option<&Value>,
6141 ) -> JsResult<Option<Value>> {
6142 if property.is_accessor() {
6143 match &property.getter {
6144 Some(getter) if !matches!(getter, Value::Undefined) => {
6145 let receiver = receiver
6146 .cloned()
6147 .unwrap_or_else(|| Value::Object(object.clone()));
6148 self.call_value(getter.clone(), receiver, Vec::new())
6149 .map(Some)
6150 }
6151 // An accessor with no getter reads as `undefined`.
6152 _ => Ok(Some(Value::Undefined)),
6153 }
6154 } else {
6155 Ok(property.value)
6156 }
6157 }
6158
6159 /// `super.key` — start the search at `proto`, but report to `receiver`.
6160 ///
6161 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
6162 /// found on the prototype of a class has to see the *instance* as `this`, and a
6163 /// plain property read off `proto` would lose that.
6164 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
6165 let start = self.require_object(proto)?;
6166 let key = self.propkey(key)?;
6167 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
6168 if matches!(proto, Value::Null) {
6169 return Ok(Value::Undefined);
6170 }
6171 match lookup_key(&start, &key) {
6172 Some((_, property)) if property.is_accessor() => match &property.getter {
6173 Some(getter) if !matches!(getter, Value::Undefined) => {
6174 self.call_value(getter.clone(), receiver.clone(), Vec::new())
6175 }
6176 _ => Ok(Value::Undefined),
6177 },
6178 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
6179 None => Ok(Value::Undefined),
6180 }
6181 }
6182
6183 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
6184 ///
6185 /// A setter found on the prototype runs with `receiver` as `this`; a data property
6186 /// is shadowed by a new own property on the receiver, the same rule an ordinary
6187 /// assignment follows.
6188 fn super_write(
6189 &mut self,
6190 receiver: &Value,
6191 proto: &Value,
6192 key: &Value,
6193 value: Value,
6194 ) -> JsResult<()> {
6195 let target = self.require_object(receiver)?;
6196 let key = self.propkey(key)?;
6197 if !matches!(proto, Value::Null)
6198 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
6199 {
6200 if property.is_accessor() {
6201 if let Some(setter) = &property.setter
6202 && !matches!(setter, Value::Undefined)
6203 {
6204 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
6205 }
6206 return Ok(());
6207 }
6208 // A data property on the prototype is writable or not; reading `owner` at
6209 // all is only for the attribute check.
6210 if !property.writable {
6211 return Err(self.type_error(format!("'{key}' is read-only")));
6212 }
6213 let _ = owner;
6214 }
6215 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
6216 }
6217
6218 /// The object a `super` operation needs, or the `TypeError` the spec raises.
6219 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
6220 match value.as_object() {
6221 Some(object) => Ok(object.clone()),
6222 None => Err(Signal::Throw(
6223 self.make_error("TypeError", "value is not an object"),
6224 )),
6225 }
6226 }
6227
6228 /// Build the class object `define_class` produces.
6229 ///
6230 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
6231 /// whose prototype property is a fresh object inheriting from the parent's
6232 /// prototype, and whose own prototype is the parent constructor — which is what makes
6233 /// a static method inherited too.
6234 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
6235 let ctor = self.pop();
6236 let parent = self.pop();
6237 let Value::Object(function) = &ctor else {
6238 return Err(Signal::Throw(
6239 self.make_error("TypeError", "class constructor must be a function"),
6240 ));
6241 };
6242 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
6243 // but gives the instances no prototype at all.
6244 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
6245 match &parent {
6246 Value::Null => (Some(self.realm.function_proto.clone()), None),
6247 Value::Object(parent_class) => {
6248 // `IsConstructor`, not `IsCallable`: §15.7.14 ClassDefinitionEvaluation
6249 // step 9 rejects a heritage without `[[Construct]]` *before* reading
6250 // `superclass.prototype`, so an arrow function and a generator — both
6251 // callable, neither constructible — are a `TypeError` and their
6252 // `prototype` getter must never run
6253 // (`subclass/superclass-arrow-function`, `…-generator-function`).
6254 if !parent_class.is_constructor() {
6255 return Err(Signal::Throw(
6256 self.make_error("TypeError", "parent class must be constructor"),
6257 ));
6258 }
6259 let proto = self.get_property(parent_class, "prototype")?;
6260 match proto {
6261 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
6262 Some(Value::Null) => (Some(parent_class.clone()), None),
6263 _ => {
6264 return Err(Signal::Throw(self.make_error(
6265 "TypeError",
6266 "parent prototype must be an object or null",
6267 )));
6268 }
6269 }
6270 }
6271 _ => {
6272 return Err(Signal::Throw(
6273 self.make_error("TypeError", "parent class must be constructor"),
6274 ));
6275 }
6276 }
6277 } else {
6278 (
6279 Some(self.realm.function_proto.clone()),
6280 Some(self.realm.object_proto.clone()),
6281 )
6282 };
6283 let proto = self.new_object(parent_proto);
6284 function.set_proto(parent_ctor);
6285 // A class is not callable without `new`, and its `prototype` is not writable —
6286 // both follow from being a class and are what `class A {}; A()` throws on.
6287 function.set_class_constructor(true);
6288 function.set_home_object(None);
6289 self.set_function_name(&ctor, name);
6290 self.define_class_properties(function, &ctor, &proto)?;
6291 Ok((ctor, proto))
6292 }
6293
6294 /// Give the constructor its `prototype` and `length`, and the prototype its
6295 /// `constructor` back-pointer.
6296 fn define_class_properties(
6297 &mut self,
6298 function: &Gc<JsObject>,
6299 ctor: &Value,
6300 proto: &Gc<JsObject>,
6301 ) -> JsResult<()> {
6302 proto.define(
6303 "constructor",
6304 Property::with_attributes(ctor.clone(), true, false),
6305 );
6306 function.define(
6307 "prototype",
6308 Property::prototype_of(Value::Object(proto.clone()), false),
6309 );
6310 if let Some((code, _)) = bytecode_of(function) {
6311 let length = code.code.defined_args;
6312 function.define(
6313 "length",
6314 Property::name_or_length(Value::Int(length as i32)),
6315 );
6316 }
6317 Ok(())
6318 }
6319
6320 /// The own array element `key` names, if this object has one.
6321 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
6322 // A typed array's elements live in its buffer, not in a property list: reading one
6323 // goes through the view's element type so a bounds check and a detached buffer are
6324 // both handled there.
6325 //
6326 // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
6327 // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
6328 // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
6329 // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
6330 // consulted. Testing with `array_index` rejected all three, which let a throwing
6331 // getter installed on `TypedArray.prototype["-1"]` run.
6332 if object.typed_array_parts().is_some() {
6333 let property_key = PropertyKey::from(key);
6334 let numeric = canonical_numeric_index(&property_key)?;
6335 if typed_array_index_is_valid(object, numeric) {
6336 return object.typed_array_element(numeric as usize);
6337 }
6338 // Canonical, but not a valid index: `undefined`, and *final*.
6339 return Some(Value::Undefined);
6340 }
6341 let index = array_index(key)?;
6342 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
6343 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
6344 // search early, which is why `Array.prototype[1] = 9` could not be seen through
6345 // `[1,,3][1]`.
6346 match object.array_get(index as usize) {
6347 Some(Value::Hole) | None => None,
6348 other => other,
6349 }
6350 }
6351
6352 /// Store `object[key] = value`, honouring setters and inherited properties.
6353 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
6354 self.set_property_with(object, key, value, DeleteFailure::Throw)
6355 }
6356
6357 /// Store a property, choosing what to do when the object refuses.
6358 ///
6359 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
6360 /// mode, which is the one place assignment differs by mode. Native code (the array
6361 /// methods, `JSON`) always asks for the throw.
6362 pub fn set_property_with(
6363 &mut self,
6364 object: &Gc<JsObject>,
6365 key: &str,
6366 value: Value,
6367 on_failure: DeleteFailure,
6368 ) -> JsResult<()> {
6369 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
6370 }
6371
6372 /// [`Interp::set_property_with`] with a key that may be a symbol.
6373 pub fn set_property_with_key(
6374 &mut self,
6375 object: &Gc<JsObject>,
6376 key: &PropertyKey,
6377 value: Value,
6378 on_failure: DeleteFailure,
6379 ) -> JsResult<()> {
6380 self.set_property_with_key_receiver_aware(object, key, value, on_failure)
6381 }
6382
6383 /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
6384 ///
6385 /// The receiver split lives one level up, in
6386 /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
6387 /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
6388 /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
6389 /// stores into `object` itself, which is why the element branch below converts `V`
6390 /// before asking whether the index is valid: `V` may put it back in bounds
6391 /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
6392 fn set_property_with_key_receiver_aware(
6393 &mut self,
6394 object: &Gc<JsObject>,
6395 key: &PropertyKey,
6396 value: Value,
6397 on_failure: DeleteFailure,
6398 ) -> JsResult<()> {
6399 // §10.4.6.7: a module namespace's `[[Set]]` **always** returns false — for an
6400 // exported name, for a name that is not exported, and for `@@toStringTag` alike.
6401 // Nothing about the receiver or the value changes that, so the whole operation is
6402 // one answer.
6403 //
6404 // Not implementing it explicitly left the ordinary algorithm in charge, and that
6405 // says "true" for names the namespace does not own as soon as the value matches or
6406 // the key is writable, so `Reflect.set(ns, 'local1', …)` answered `true` and strict
6407 // assignment stopped throwing (`await-ns-set-strict`).
6408 if object.module_namespace_marker() {
6409 return match on_failure {
6410 DeleteFailure::Ignore => Ok(()),
6411 DeleteFailure::Throw => Err(self.type_error(format!(
6412 "cannot assign to property '{key}' of a module namespace object"
6413 ))),
6414 };
6415 }
6416 // A proxy's `set` trap decides, and its `false` means the same thing an
6417 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
6418 if object.proxy_state().is_some() {
6419 let receiver = Value::Object(object.clone());
6420 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
6421 return match (accepted, on_failure) {
6422 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6423 (false, DeleteFailure::Throw) => {
6424 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
6425 }
6426 };
6427 }
6428 }
6429 // A host class's `set_property` trap decides for itself. `Some(false)` is a
6430 // refusal and means exactly what a proxy's `false` means.
6431 if let Some(exotic) = object.exotic() {
6432 let receiver = Value::Object(object.clone());
6433 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
6434 return match (accepted, on_failure) {
6435 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
6436 (false, DeleteFailure::Throw) => {
6437 Err(self.type_error(format!("property '{key}' is read-only")))
6438 }
6439 };
6440 }
6441 }
6442 // The element and `length` shortcuts only exist for string keys: an array
6443 // index has no symbol spelling, and a symbol named `length` is an ordinary
6444 // property.
6445 let text = key.as_str();
6446 // A typed array's elements are a window onto its buffer: the store has to go
6447 // through the view's element type so the value is wrapped (or clamped) and so an
6448 // out-of-range or detached write is a silent no-op, as the spec says.
6449 //
6450 // The key test is `CanonicalNumericIndexString`, like every other index operation
6451 // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
6452 // does not exist, so they do nothing and leave no own property behind
6453 // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
6454 // path, which created a property named `"-0"`.
6455 //
6456 // The conversion comes **first**, before the index is checked at all, and that
6457 // order is observable twice over:
6458 //
6459 // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
6460 // has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
6461 // then store the converted value;
6462 // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
6463 // `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
6464 // run and its exception to escape.
6465 //
6466 // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
6467 // validity check, not a validity check that skips the conversion. The store itself
6468 // is a no-op when the index is invalid by then, which is why no extra guard is
6469 // needed around `typed_array_set`.
6470 if let Some(element) = object.typed_array_element_type()
6471 && let Some(numeric) = canonical_numeric_index(key)
6472 {
6473 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
6474 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
6475 // in `Interp`, because it is script-observable and the storage borrow inside
6476 // `typed_array_set` must not be held across it.
6477 let stored = self.element_value(element, value)?;
6478 if typed_array_index_is_valid(object, numeric)
6479 && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
6480 {
6481 return Err(self.type_error(reason));
6482 }
6483 return Ok(());
6484 }
6485 if let Some(text) = text
6486 && let Some(index) = array_index(text)
6487 && object.is_array()
6488 {
6489 // An accessor defined on an index lives in the property table while the
6490 // element slot is a hole, so the store has to go through the property first.
6491 // Writing the vector directly skipped the setter entirely.
6492 if let Some(existing) = object.own_property_key(key) {
6493 if existing.is_accessor() {
6494 return match existing.setter.clone() {
6495 Some(setter) if !matches!(setter, Value::Undefined) => {
6496 let receiver = Value::Object(object.clone());
6497 self.call_value(setter, receiver, vec![value]).map(|_| ())
6498 }
6499 _ => match on_failure {
6500 DeleteFailure::Throw => Err(self.type_error(format!(
6501 "cannot set property '{text}', it has only a getter"
6502 ))),
6503 DeleteFailure::Ignore => Ok(()),
6504 },
6505 };
6506 }
6507 if !existing.writable {
6508 return match on_failure {
6509 DeleteFailure::Throw => {
6510 Err(self.type_error(format!("'{text}' is read-only")))
6511 }
6512 DeleteFailure::Ignore => Ok(()),
6513 };
6514 }
6515 }
6516 {
6517 // Growing the array needs a writable `length`.
6518 if (index as usize) >= object.array_length().unwrap_or(0)
6519 && !object.length_writable()
6520 {
6521 return match on_failure {
6522 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6523 DeleteFailure::Ignore => Ok(()),
6524 };
6525 }
6526 // Adding an index past the end makes the array longer, which a
6527 // non-extensible array refuses.
6528 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6529 return match on_failure {
6530 DeleteFailure::Throw => Err(self.type_error(format!(
6531 "cannot add property '{key}', object is not extensible"
6532 ))),
6533 DeleteFailure::Ignore => Ok(()),
6534 };
6535 }
6536 if object.element_is_locked(index) {
6537 return match on_failure {
6538 DeleteFailure::Throw => {
6539 Err(self.type_error(format!("'{key}' is read-only")))
6540 }
6541 DeleteFailure::Ignore => Ok(()),
6542 };
6543 }
6544 // The element vector is only half of `[[Set]]` for an index: the
6545 // prototype chain is consulted first, and a setter there answers instead
6546 // of the element store. This branch used to write the element directly, so
6547 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6548 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6549 // the reference calls the setter and the array keeps no own index.
6550 //
6551 // An *exotic* prototype has no entry to find, because its indices live
6552 // outside the property table — `Object.setPrototypeOf([], typedArray)`
6553 // then looked like "nothing on the chain" and the store created the
6554 // element, where the view's `[[Set]]` answers `true` and does nothing for
6555 // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6556 // checks the array's `length` stays 0). So the dispatch comes first.
6557 if !object.has_own_key(key)
6558 && let Some(proto) = object.proto()
6559 && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6560 {
6561 let receiver = Value::Object(object.clone());
6562 let accepted =
6563 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6564 return if accepted {
6565 Ok(())
6566 } else {
6567 match on_failure {
6568 DeleteFailure::Throw => {
6569 Err(self.type_error(format!("'{key}' is read-only")))
6570 }
6571 DeleteFailure::Ignore => Ok(()),
6572 }
6573 };
6574 }
6575 if let Some((owner, property)) = lookup_key(object, key)
6576 && !owner.ptr_eq(object)
6577 {
6578 match &property {
6579 property if property.is_accessor() => {
6580 match &property.setter {
6581 Some(setter) if !matches!(setter, Value::Undefined) => {
6582 let receiver = Value::Object(object.clone());
6583 self.call_value(setter.clone(), receiver, vec![value])?;
6584 }
6585 _ => {
6586 return match on_failure {
6587 DeleteFailure::Throw => Err(self.type_error(format!(
6588 "cannot set property '{text}', it has only a getter"
6589 ))),
6590 DeleteFailure::Ignore => Ok(()),
6591 };
6592 }
6593 }
6594 return Ok(());
6595 }
6596 property if !property.writable => {
6597 return match on_failure {
6598 DeleteFailure::Throw => {
6599 Err(self.type_error(format!("'{text}' is read-only")))
6600 }
6601 DeleteFailure::Ignore => Ok(()),
6602 };
6603 }
6604 _ => {}
6605 }
6606 }
6607 if object.array_set(self.heap, index as usize, value.clone()) {
6608 return Ok(());
6609 }
6610 // Past the dense limit the slot is too far out to be worth one `Value`
6611 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6612 // constant time by keeping the index as an ordinary property. The store
6613 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6614 // to a legal program.
6615 object.define_key(key, Property::with_attributes(value, true, true));
6616 // Extend, never shorten: the index may be *inside* the current length (a
6617 // huge `length` with a sparse store), and shortening would delete the
6618 // sparse properties above it — including the one just stored.
6619 if index as usize + 1 > object.array_length().unwrap_or(0) {
6620 object.array_set_length(self.heap, index as usize + 1);
6621 }
6622 return Ok(());
6623 }
6624 }
6625 if text == Some("length") && object.is_array() {
6626 // §10.4.2.4 steps 3–5: **two** `ToNumber` conversions, then the writability
6627 // test. A `valueOf` that locks `length` on its second call therefore turns the
6628 // store into a refused write rather than a silent success
6629 // (`length/define-own-prop-length-coercion-order-set`).
6630 let rounded = self.coerce_array_length_twice(&value)?;
6631 if !object.length_writable() {
6632 return match on_failure {
6633 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6634 DeleteFailure::Ignore => Ok(()),
6635 };
6636 }
6637 // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6638 // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6639 // answered `NaN`, which left the assignment silently ignored
6640 // (`S15.4.5.2_A3_T2`).
6641 let _ = rounded;
6642 let length = self.to_js_number(&value)?;
6643 // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6644 // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6645 // `RangeError`s; the old code only tested "finite and non-negative" and then
6646 // truncated, so `[].length = 4294967297` quietly produced a length no array can
6647 // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6648 let valid = length.is_finite()
6649 && length >= 0.0
6650 && length.fract() == 0.0
6651 && length <= u32::MAX as f64;
6652 if !valid {
6653 return Err(self.range_error("invalid array length"));
6654 }
6655 {
6656 let length = length as usize;
6657 // `a.length = n` with `n` below a non-configurable element cannot
6658 // drop that element, so the whole assignment fails. The spec makes
6659 // this a `TypeError` rather than a silent no-op, in any mode.
6660 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6661 // Sloppy mode stops the truncation at the blocking element
6662 // instead of failing; strict mode raises.
6663 // Both modes stop at the blocking element; they differ in
6664 // whether that is reported. The reference truncates *then*
6665 // throws, so the array is left in the shortened state.
6666 object.array_truncate(self.heap, blocked + 1);
6667 return match on_failure {
6668 DeleteFailure::Throw => {
6669 Err(self.type_error(format!("cannot delete property '{blocked}'")))
6670 }
6671 DeleteFailure::Ignore => Ok(()),
6672 };
6673 }
6674 object.array_set_length(self.heap, length);
6675 return Ok(());
6676 }
6677 }
6678 // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6679 // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6680 // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6681 //
6682 // The prototype step is a dispatch, not a lookup. Walking the chain here and
6683 // applying whatever came back is the same thing for an ordinary prototype and
6684 // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6685 // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6686 // answers "not mine, the receiver is not me" without touching the buffer. This
6687 // code used to find nothing owned by `o`, find no property on the view either,
6688 // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6689 // object and never converted (`key-is-valid-index-prototype-chain-set`,
6690 // `key-is-canonical-invalid-index-prototype-chain-set`).
6691 //
6692 // The read-only and accessor rules of step 1 are what make
6693 // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6694 // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6695 let own = match self.lookup_for_write(object, key)? {
6696 Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6697 _ => None,
6698 };
6699 if let Some(property) = own {
6700 if property.is_accessor() {
6701 return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6702 Some(setter) => {
6703 let receiver = Value::Object(object.clone());
6704 self.call_value(setter, receiver, vec![value])?;
6705 Ok(())
6706 }
6707 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6708 // Sloppy code swallows that refusal, strict code raises — the same
6709 // rule the read-only *data* property below follows, and skipping it
6710 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6711 // return silently. The reference answers `TypeError: 'x' is
6712 // read-only`.
6713 None => match on_failure {
6714 DeleteFailure::Throw => {
6715 Err(self.type_error(format!("'{key}' is read-only")))
6716 }
6717 DeleteFailure::Ignore => Ok(()),
6718 },
6719 };
6720 }
6721 // An own non-writable data property stops here: nothing may change it.
6722 if !property.writable {
6723 return match on_failure {
6724 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6725 DeleteFailure::Ignore => Ok(()),
6726 };
6727 }
6728 // An existing writable own property keeps its attributes: only the value
6729 // moves. Redefining instead would reset them, which is how a
6730 // non-configurable global `var` used to become deletable.
6731 if object.write_value_key(key, value.clone()) {
6732 return Ok(());
6733 }
6734 }
6735 // Step 2: hand the store to the prototype, with `object` as the receiver.
6736 if let Some(proto) = object.proto() {
6737 let receiver = Value::Object(object.clone());
6738 let accepted =
6739 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6740 return if accepted {
6741 Ok(())
6742 } else {
6743 match on_failure {
6744 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6745 DeleteFailure::Ignore => Ok(()),
6746 }
6747 };
6748 }
6749 // Step 3: create one, and a non-extensible object cannot.
6750 if !object.is_extensible() {
6751 return match on_failure {
6752 DeleteFailure::Throw => Err(self.type_error(format!(
6753 "cannot add property {key}, object is not extensible"
6754 ))),
6755 DeleteFailure::Ignore => Ok(()),
6756 };
6757 }
6758 object.define_data_key(key, value);
6759 Ok(())
6760 }
6761
6762 /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6763 ///
6764 /// The distinction the fast path above does not need: it is called with the store's
6765 /// receiver already being the object it writes to. Here `object` is the one whose
6766 /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6767 /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6768 /// and not a write to `object`.
6769 ///
6770 /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6771 /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6772 /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6773 /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6774 /// descriptor on the prototype refuses instead, which is the same rule that keeps
6775 /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6776 ///
6777 /// Answers `false` where the spec says `false`; the caller turns that into the
6778 /// strict-mode `TypeError` or the sloppy-mode silence.
6779 fn ordinary_set_with_receiver(
6780 &mut self,
6781 object: &Gc<JsObject>,
6782 receiver: &Value,
6783 key: &PropertyKey,
6784 value: Value,
6785 on_failure: DeleteFailure,
6786 ) -> JsResult<bool> {
6787 // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6788 if object.proxy_state().is_some() {
6789 return Ok(self
6790 .proxy_set(object, key, value, receiver)?
6791 .unwrap_or(true));
6792 }
6793 // A host class decides for itself, with the receiver the caller named.
6794 if let Some(exotic) = object.exotic()
6795 && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6796 {
6797 return Ok(accepted);
6798 }
6799 // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6800 // rather than the receiver, but the receiver may still *be* the view:
6801 // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6802 // itself as receiver, and then the first half applies — convert `V` once, store
6803 // if the index is valid, answer `true` either way. The conversion is the observable
6804 // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6805 //
6806 // Only the second half, a view that is *not* the receiver, skips the conversion
6807 // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6808 // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6809 // below with the value still unconverted.
6810 if object.typed_array_element_type().is_some()
6811 && let Some(numeric) = canonical_numeric_index(key)
6812 {
6813 if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6814 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6815 return Ok(true);
6816 }
6817 if !typed_array_index_is_valid(object, numeric) {
6818 return Ok(true);
6819 }
6820 }
6821 let own = self.object_get_own_property(object, key)?;
6822 if let Some(own) = own {
6823 if own.is_accessor() {
6824 return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6825 Some(setter) => {
6826 self.call_value(setter, receiver.clone(), vec![value])?;
6827 Ok(true)
6828 }
6829 None => Ok(false),
6830 };
6831 }
6832 // A non-writable data descriptor refuses, own or inherited. Either way the
6833 // receiver must not gain a shadowing property.
6834 if !own.writable {
6835 return Ok(false);
6836 }
6837 // Step 1.d: the *receiver's* own descriptor decides whether it can be
6838 // created or written, and it is created as an ordinary data property.
6839 let Some(receiver_object) = receiver.as_object().cloned() else {
6840 return Ok(false);
6841 };
6842 return match self.object_get_own_property(&receiver_object, key)? {
6843 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6844 Some(existing) => self.object_define_own_property(
6845 &receiver_object,
6846 key,
6847 Property {
6848 value: Some(value),
6849 ..existing
6850 },
6851 ),
6852 None => {
6853 self.object_define_own_property(&receiver_object, key, Property::data(value))
6854 }
6855 };
6856 }
6857 // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6858 if let Some(proto) = object.proto() {
6859 return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6860 }
6861 // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6862 // *default* data descriptor here, so control falls into step 2 exactly as if the
6863 // target had owned a writable property — which means the **receiver's** own
6864 // descriptor is asked for before the write. Skipping that question went straight to
6865 // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6866 // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6867 // exactly those calls).
6868 let Some(receiver_object) = receiver.as_object().cloned() else {
6869 return Ok(false);
6870 };
6871 match self.object_get_own_property(&receiver_object, key)? {
6872 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6873 Some(existing) => self.object_define_own_property(
6874 &receiver_object,
6875 key,
6876 Property {
6877 value: Some(value),
6878 ..existing
6879 },
6880 ),
6881 None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6882 }
6883 }
6884
6885 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6886 ///
6887 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6888 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6889 /// a virtual accessor gets its setter run without implementing `set_property` at all.
6890 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6891 /// the prototype, so the walk resumes above the object.
6892 fn lookup_for_write(
6893 &mut self,
6894 object: &Gc<JsObject>,
6895 key: &PropertyKey,
6896 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6897 let Some(exotic) = object.exotic() else {
6898 return Ok(lookup_key(object, key));
6899 };
6900 Ok(match exotic.get_own_property(self, object, key)? {
6901 Some(Some(property)) => Some((object.clone(), property)),
6902 Some(None) => lookup_key_above(object, key),
6903 None => lookup_key(object, key),
6904 })
6905 }
6906
6907 /// Delete `object[key]`.
6908 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6909 self.delete_property_key(object, &PropertyKey::from(key))
6910 }
6911
6912 /// [`Interp::delete_property`] with a key that may be a symbol.
6913 pub fn delete_property_key(
6914 &mut self,
6915 object: &Gc<JsObject>,
6916 key: &PropertyKey,
6917 ) -> JsResult<bool> {
6918 // A proxy decides for itself, and may even throw; the invariant checks live in
6919 // `proxy_delete`.
6920 if let Some(answer) = self.proxy_delete(object, key)? {
6921 return Ok(answer);
6922 }
6923 // A host class's `delete_property` trap decides; `false` is a refusal, which the
6924 // caller reports as a failed delete.
6925 if let Some(exotic) = object.exotic()
6926 && let Some(answer) = exotic.delete_property(self, object, key)?
6927 {
6928 return Ok(answer);
6929 }
6930 // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6931 // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6932 // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6933 // one answers `false` because the elements are non-configurable. The prototype
6934 // chain is not consulted either, which is what makes a throwing getter on
6935 // `TypedArray.prototype["-1"]` stay unrun.
6936 if object.typed_array_parts().is_some()
6937 && object.proxy_state().is_none()
6938 && let Some(numeric) = canonical_numeric_index(key)
6939 {
6940 return Ok(!typed_array_index_is_valid(object, numeric));
6941 }
6942 let mapped_index = key.as_str().and_then(array_index);
6943 if let Some(index) = mapped_index
6944 && let Some(length) = object.array_length()
6945 && (index as usize) < length
6946 {
6947 // An accessor defined on an index lives in the property table rather than the
6948 // element vector, so both have to be cleared: `delete` after
6949 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6950 object.delete_key(key);
6951 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6952 // index stops answering `in`.
6953 if object.element_is_undeletable(index) {
6954 return Ok(false);
6955 }
6956 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6957 // so a later `defineProperty(arguments, "0", {value})` writes to the object
6958 // and no longer through to the parameter. A refused delete leaves the
6959 // mapping alone.
6960 object.drop_mapped_argument(index as usize);
6961 object.array_set(self.heap, index as usize, Value::Hole);
6962 return Ok(true);
6963 }
6964 // An array's `length` is a non-configurable own property that lives outside the
6965 // property table, so `delete_key` finds nothing and reports success — `Reflect
6966 // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6967 // §10.4.4.1 step 3 refuses it.
6968 if key.as_str() == Some("length") && object.array_length().is_some() {
6969 return Ok(false);
6970 }
6971 // The same for an object that is not an array: only a delete that actually
6972 // removed the property ends the alias.
6973 let deleted = object.delete_key(key);
6974 if deleted && let Some(index) = mapped_index {
6975 object.drop_mapped_argument(index as usize);
6976 }
6977 Ok(deleted)
6978 }
6979
6980 // -- proxy traps --------------------------------------------------------
6981 //
6982 // A proxy's internal methods all look the same: ask the handler for the trap, call it
6983 // with the target and the operation's own arguments, then check the answer against
6984 // the target. The checks are not decoration — they are what stops a proxy from
6985 // reporting a `non-configurable` property as missing, which would let a frozen object
6986 // be rewritten by standing in front of it.
6987
6988 /// The target and handler of `object`, or `None` when it is not a proxy.
6989 ///
6990 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6991 /// one has to fail: the slots the traps would have been read from are gone.
6992 pub(crate) fn proxy_parts(
6993 &mut self,
6994 object: &Gc<JsObject>,
6995 ) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6996 let Some(state) = object.proxy_state() else {
6997 return Ok(None);
6998 };
6999 let state = state.borrow();
7000 match (&state.target, &state.handler) {
7001 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
7002 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
7003 }
7004 }
7005
7006 /// Call `handler[name]`, or answer `None` when the trap is absent.
7007 ///
7008 /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
7009 /// and only a value that is neither is `IsCallable`-checked and refused. Treating
7010 /// `null` as "present but not callable" made every `{ get: null }` proxy throw
7011 /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
7012 /// one per trap plus the `target-is-proxy` variants.
7013 ///
7014 /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
7015 /// this cannot simply be "any non-callable means no trap".
7016 fn proxy_trap(
7017 &mut self,
7018 handler: &Value,
7019 name: &str,
7020 args: Vec<Value>,
7021 ) -> JsResult<Option<Value>> {
7022 let Value::Object(table) = handler else {
7023 return Err(self.type_error("proxy handler is not an object"));
7024 };
7025 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
7026 match trap {
7027 Value::Undefined | Value::Null => Ok(None),
7028 Value::Object(function) if function.is_callable() => {
7029 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
7030 Ok(Some(answer))
7031 }
7032 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
7033 }
7034 }
7035
7036 /// Whether the target's own property `key` is one it refuses to lose.
7037 ///
7038 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
7039 /// its value behind the target's back.
7040 ///
7041 /// A **method**, not a free function, because §10.5.1's invariants say
7042 /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
7043 /// property table directly finds nothing (a proxy's table is empty by design), so every
7044 /// invariant check silently passed for a proxy target. That is what
7045 /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
7046 /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
7047 /// where an array's elements and its `length` — both fixed, both outside the table —
7048 /// are covered.
7049 fn fixed_property(
7050 &mut self,
7051 target: &Gc<JsObject>,
7052 key: &PropertyKey,
7053 ) -> JsResult<Option<Property>> {
7054 Ok(self
7055 .object_get_own_property(target, key)?
7056 .filter(|property| !property.configurable))
7057 }
7058
7059 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
7060 fn proxy_get(
7061 &mut self,
7062 object: &Gc<JsObject>,
7063 receiver: &Value,
7064 key: &PropertyKey,
7065 ) -> JsResult<Option<Value>> {
7066 let Some((target, handler)) = self.proxy_parts(object)? else {
7067 return Ok(None);
7068 };
7069 let key_value = self.key_value(key);
7070 let Some(result) = self.proxy_trap(
7071 &handler,
7072 "get",
7073 vec![Value::Object(target.clone()), key_value, receiver.clone()],
7074 )?
7075 else {
7076 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
7077 // inherited getter still sees the proxy.
7078 return Ok(Some(
7079 self.get_property_key_for(&target, Some(receiver), key)?
7080 .unwrap_or(Value::Undefined),
7081 ));
7082 };
7083 if let Some(fixed) = self.fixed_property(&target, key)? {
7084 if fixed.is_accessor() {
7085 // A fixed accessor with no getter must read as `undefined`.
7086 let has_getter = fixed
7087 .getter
7088 .as_ref()
7089 .is_some_and(|getter| !matches!(getter, Value::Undefined));
7090 if !has_getter && !matches!(result, Value::Undefined) {
7091 return Err(self.type_error(format!(
7092 "proxy 'get' must report undefined for the non-configurable property '{key}'"
7093 )));
7094 }
7095 } else if !fixed.writable {
7096 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7097 if !fixed_value.same_value(&result) {
7098 return Err(self.type_error(format!(
7099 "proxy 'get' disagrees with the non-configurable property '{key}'"
7100 )));
7101 }
7102 }
7103 }
7104 Ok(Some(result))
7105 }
7106
7107 /// `[[Set]]` on a proxy.
7108 ///
7109 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
7110 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
7111 /// read-only store has.
7112 fn proxy_set(
7113 &mut self,
7114 object: &Gc<JsObject>,
7115 key: &PropertyKey,
7116 value: Value,
7117 receiver: &Value,
7118 ) -> JsResult<Option<bool>> {
7119 let Some((target, handler)) = self.proxy_parts(object)? else {
7120 return Ok(None);
7121 };
7122 let key_value = self.key_value(key);
7123 let Some(result) = self.proxy_trap(
7124 &handler,
7125 "set",
7126 vec![
7127 Value::Object(target.clone()),
7128 key_value,
7129 value.clone(),
7130 receiver.clone(),
7131 ],
7132 )?
7133 else {
7134 // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
7135 // given — not the target. `OrdinarySet` step 3 is
7136 // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
7137 // object whose prototype is a typed array has to reach the proxy's own
7138 // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
7139 // calls and expects exactly one. Storing on the target instead put the value
7140 // in the target and never consulted the trap.
7141 let accepted = self.ordinary_set_with_receiver(
7142 &target,
7143 receiver,
7144 key,
7145 value,
7146 DeleteFailure::Ignore,
7147 )?;
7148 return Ok(Some(accepted));
7149 };
7150 if !result.to_boolean() {
7151 return Ok(Some(false));
7152 }
7153 if let Some(fixed) = self.fixed_property(&target, key)? {
7154 if fixed.is_accessor() {
7155 let has_setter = fixed
7156 .setter
7157 .as_ref()
7158 .is_some_and(|setter| !matches!(setter, Value::Undefined));
7159 if !has_setter {
7160 return Err(self.type_error(format!(
7161 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
7162 )));
7163 }
7164 } else if !fixed.writable {
7165 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
7166 if !fixed_value.same_value(&value) {
7167 return Err(self.type_error(format!(
7168 "proxy 'set' changed the non-configurable property '{key}'"
7169 )));
7170 }
7171 }
7172 }
7173 // A new property cannot appear on a target that refuses new properties.
7174 if self.object_get_own_property(&target, key)?.is_none()
7175 && !self.object_is_extensible(&target)?
7176 {
7177 return Err(self.type_error(format!(
7178 "proxy 'set' added '{key}' to a non-extensible target"
7179 )));
7180 }
7181 Ok(Some(true))
7182 }
7183
7184 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
7185 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7186 let Some((target, handler)) = self.proxy_parts(object)? else {
7187 return Ok(None);
7188 };
7189 let key_value = self.key_value(key);
7190 let Some(result) = self.proxy_trap(
7191 &handler,
7192 "has",
7193 vec![Value::Object(target.clone()), key_value],
7194 )?
7195 else {
7196 return Ok(Some(self.has_own_or_inherited(&target, key)?));
7197 };
7198 if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7199 return Err(self.type_error(format!(
7200 "proxy 'has' denied the non-configurable property '{key}'"
7201 )));
7202 }
7203 // A non-extensible target cannot grow, so every own property it *has* is fixed.
7204 if !result.to_boolean()
7205 && !self.object_is_extensible(&target)?
7206 && self.object_get_own_property(&target, key)?.is_some()
7207 {
7208 return Err(self.type_error(format!(
7209 "proxy 'has' denied the own property '{key}' of a non-extensible target"
7210 )));
7211 }
7212 Ok(Some(result.to_boolean()))
7213 }
7214
7215 /// `[[Delete]]` on a proxy.
7216 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
7217 let Some((target, handler)) = self.proxy_parts(object)? else {
7218 return Ok(None);
7219 };
7220 let key_value = self.key_value(key);
7221 let Some(result) = self.proxy_trap(
7222 &handler,
7223 "deleteProperty",
7224 vec![Value::Object(target.clone()), key_value],
7225 )?
7226 else {
7227 return Ok(Some(self.delete_property_key(&target, key)?));
7228 };
7229 if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
7230 return Err(self.type_error(format!(
7231 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
7232 )));
7233 }
7234 if result.to_boolean()
7235 && !self.object_is_extensible(&target)?
7236 && self.object_get_own_property(&target, key)?.is_some()
7237 {
7238 return Err(self.type_error(format!(
7239 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
7240 )));
7241 }
7242 Ok(Some(result.to_boolean()))
7243 }
7244
7245 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
7246 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
7247 let Some((target, handler)) = self.proxy_parts(object)? else {
7248 return Ok(None);
7249 };
7250 let Some(result) =
7251 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
7252 else {
7253 // No trap: the target's own keys, already in the order an object reports.
7254 return Ok(Some(self.object_own_property_keys(&target)?));
7255 };
7256 // `CreateListFromArrayLike` with the string-or-symbol restriction.
7257 let list = self.list_from_array_like(&result, true)?;
7258 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
7259 for value in list {
7260 let key = self.propkey(&value)?;
7261 if keys.contains(&key) {
7262 return Err(self.type_error(format!(
7263 "proxy 'ownKeys' returned the duplicate key '{key}'"
7264 )));
7265 }
7266 keys.push(key);
7267 }
7268 // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
7269 // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
7270 // table is empty, which made every check below vacuous.
7271 let target_keys = self.object_own_property_keys(&target)?;
7272 let extensible = self.object_is_extensible(&target)?;
7273 for key in &target_keys {
7274 if keys.contains(key) {
7275 continue;
7276 }
7277 if self.fixed_property(&target, key)?.is_some() {
7278 return Err(self.type_error(format!(
7279 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
7280 )));
7281 }
7282 if !extensible {
7283 return Err(self.type_error(format!(
7284 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
7285 )));
7286 }
7287 }
7288 if !extensible {
7289 // §10.5.11 step 12: the lists must match one for one, in any order.
7290 if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
7291 {
7292 return Err(
7293 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
7294 );
7295 }
7296 }
7297 Ok(Some(keys))
7298 }
7299
7300 /// `[[GetOwnProperty]]` on a proxy.
7301 fn proxy_get_own_property(
7302 &mut self,
7303 object: &Gc<JsObject>,
7304 key: &PropertyKey,
7305 ) -> JsResult<Option<Option<Property>>> {
7306 let Some((target, handler)) = self.proxy_parts(object)? else {
7307 return Ok(None);
7308 };
7309 let key_value = self.key_value(key);
7310 let Some(result) = self.proxy_trap(
7311 &handler,
7312 "getOwnPropertyDescriptor",
7313 vec![Value::Object(target.clone()), key_value],
7314 )?
7315 else {
7316 // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
7317 // property table. Two things ride on that choice: a target that is itself a
7318 // proxy has to re-dispatch (its own table is empty, so reading it reported
7319 // `undefined` for every key, `Object.keys` then dropped them all), and an array's
7320 // indices and `length` live outside the table and need the ordinary synthesis.
7321 // `object_get_own_property` does both.
7322 return Ok(Some(self.object_get_own_property(&target, key)?));
7323 };
7324 // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
7325 // `ToPropertyDescriptor` runs, because that operation would box the primitive
7326 // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
7327 // empty descriptor instead of refusing.
7328 if !matches!(result, Value::Undefined | Value::Object(_)) {
7329 return Err(self.type_error(
7330 "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
7331 ));
7332 }
7333 let target_desc = self.object_get_own_property(&target, key)?;
7334 let extensible = self.object_is_extensible(&target)?;
7335 let Some(descriptor) = (match result {
7336 Value::Undefined => None,
7337 _ => Some(self.property_from_descriptor(&result)?),
7338 }) else {
7339 // Steps 12.a–12.d: reporting absent is allowed only when the target's own
7340 // descriptor is configurable *and* the target can still grow back.
7341 if let Some(target_desc) = &target_desc {
7342 if !target_desc.configurable {
7343 return Err(self.type_error(format!(
7344 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
7345 )));
7346 }
7347 if !extensible {
7348 return Err(self.type_error(format!(
7349 "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
7350 )));
7351 }
7352 }
7353 return Ok(Some(None));
7354 };
7355 // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
7356 // which is a stronger requirement than "the target is not contradicting it" — the
7357 // four branches below are each one test262 case.
7358 if !descriptor.configurable {
7359 let Some(target_desc) = &target_desc else {
7360 return Err(self.type_error(format!(
7361 "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
7362 )));
7363 };
7364 if target_desc.configurable {
7365 return Err(self.type_error(format!(
7366 "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
7367 )));
7368 }
7369 let target_is_data = !target_desc.is_accessor();
7370 let result_is_data = !descriptor.is_accessor();
7371 if result_is_data && !target_is_data {
7372 return Err(self.type_error(format!(
7373 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7374 )));
7375 }
7376 if target_is_data && !target_desc.writable {
7377 if !result_is_data {
7378 return Err(self.type_error(format!(
7379 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7380 )));
7381 }
7382 if descriptor.writable {
7383 return Err(self.type_error(format!(
7384 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7385 )));
7386 }
7387 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7388 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
7389 if !fixed_value.same_value(&reported) {
7390 return Err(self.type_error(format!(
7391 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
7392 )));
7393 }
7394 }
7395 // Step 16.d: a reported *read-only* data property needs a real read-only data
7396 // property behind it. Missing this let a trap bolt a frozen property onto a
7397 // writable target intent (`resultdesc-is-not-configurable-not-writable-
7398 // targetdesc-is-writable`).
7399 if result_is_data && !descriptor.writable {
7400 if !target_is_data {
7401 return Err(self.type_error(format!(
7402 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
7403 )));
7404 }
7405 if target_desc.writable {
7406 return Err(self.type_error(format!(
7407 "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
7408 )));
7409 }
7410 }
7411 if descriptor.is_accessor() {
7412 // Step 16.e: a getter the target does not have may not be invented, and
7413 // vice versa.
7414 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7415 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7416 (Some(a), Some(b)) => a.same_value(b),
7417 _ => false,
7418 };
7419 if !same(&target_desc.getter, &descriptor.getter)
7420 || !same(&target_desc.setter, &descriptor.setter)
7421 {
7422 return Err(self.type_error(format!(
7423 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7424 )));
7425 }
7426 }
7427 }
7428 // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
7429 // where the target's own is locked. Without it a handler could advertise
7430 // `{value: 1, configurable: true}` for a non-configurable property, and a caller
7431 // that believed it would try to redefine something it cannot.
7432 if descriptor.configurable
7433 && let Some(target_desc) = &target_desc
7434 && !target_desc.configurable
7435 {
7436 return Err(self.type_error(format!(
7437 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
7438 )));
7439 }
7440 // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
7441 // through the trap either, however well-formed the descriptor is. This is the
7442 // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
7443 // the frozen target does not own.
7444 if !extensible {
7445 let Some(target_desc) = &target_desc else {
7446 return Err(self.type_error(format!(
7447 "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
7448 )));
7449 };
7450 if target_desc.is_accessor() == descriptor.is_accessor() {
7451 let target_is_data = !target_desc.is_accessor();
7452 let result_is_data = !descriptor.is_accessor();
7453 if target_is_data && !target_desc.writable && descriptor.writable {
7454 return Err(self.type_error(format!(
7455 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7456 )));
7457 }
7458 if !result_is_data && !target_is_data {
7459 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7460 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7461 (Some(a), Some(b)) => a.same_value(b),
7462 _ => false,
7463 };
7464 if !same(&target_desc.getter, &descriptor.getter)
7465 || !same(&target_desc.setter, &descriptor.setter)
7466 {
7467 return Err(self.type_error(format!(
7468 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7469 )));
7470 }
7471 }
7472 }
7473 }
7474 Ok(Some(Some(descriptor)))
7475 }
7476
7477 /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
7478 ///
7479 /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
7480 /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
7481 /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
7482 /// for a data property. `Property` cannot express "this field is absent", so the whole
7483 /// property path is skipped and the descriptor is assembled here field by field.
7484 ///
7485 /// `current` is the property the trap reported, used only to tell a data property from
7486 /// an accessor.
7487 pub fn proxy_seal_property(
7488 &mut self,
7489 object: &Gc<JsObject>,
7490 key: &PropertyKey,
7491 frozen: bool,
7492 current: &Property,
7493 ) -> JsResult<bool> {
7494 let Some((_target, handler)) = self.proxy_parts(object)? else {
7495 return Err(self.type_error("not a proxy"));
7496 };
7497 let descriptor = self.new_object(None);
7498 descriptor.define_data("configurable", Value::Bool(false));
7499 if frozen && !current.is_accessor() {
7500 descriptor.define_data("writable", Value::Bool(false));
7501 }
7502 let key_value = self.key_value(key);
7503 let target = object
7504 .proxy_state()
7505 .and_then(|state| state.borrow().target.clone());
7506 let Some(target) = target else {
7507 return Err(self.type_error("cannot use a proxy that has been revoked"));
7508 };
7509 let Some(result) = self.proxy_trap(
7510 &handler,
7511 "defineProperty",
7512 vec![Value::Object(target), key_value, Value::Object(descriptor)],
7513 )?
7514 else {
7515 // No trap means the definition belongs to the target; `false` is its answer.
7516 return Ok(false);
7517 };
7518 Ok(result.to_boolean())
7519 }
7520
7521 /// `[[DefineOwnProperty]]` on a proxy.
7522 fn proxy_define_property(
7523 &mut self,
7524 object: &Gc<JsObject>,
7525 key: &PropertyKey,
7526 property: Property,
7527 ) -> JsResult<Option<bool>> {
7528 let Some((target, handler)) = self.proxy_parts(object)? else {
7529 return Ok(None);
7530 };
7531 let key_value = self.key_value(key);
7532 let descriptor = self.descriptor_from_property(&property);
7533 let Some(result) = self.proxy_trap(
7534 &handler,
7535 "defineProperty",
7536 vec![Value::Object(target.clone()), key_value, descriptor],
7537 )?
7538 else {
7539 // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7540 // going" answer and `object_define_own_property` turns it into exactly that
7541 // forwarding — see the note there. (Reading it as "not a proxy" would define
7542 // the property on the proxy object itself, whose table is empty and which no
7543 // read ever consults.)
7544 return Ok(None);
7545 };
7546 if !result.to_boolean() {
7547 return Ok(Some(false));
7548 }
7549 // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7550 // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7551 // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7552 // and treating them alike made four cases pass a descriptor the target contradicts.
7553 let target_desc = self.object_get_own_property(&target, key)?;
7554 let extensible = self.object_is_extensible(&target)?;
7555 let named = property
7556 .descriptor_fields
7557 .unwrap_or(crate::object::DescriptorFields {
7558 value: false,
7559 writable: false,
7560 enumerable: false,
7561 configurable: false,
7562 get: false,
7563 set: false,
7564 });
7565 if named.configurable && !property.configurable {
7566 let Some(target_desc) = &target_desc else {
7567 return Err(self.type_error(format!(
7568 "proxy 'defineProperty' invented the non-configurable '{key}'"
7569 )));
7570 };
7571 if target_desc.configurable {
7572 return Err(self.type_error(format!(
7573 "proxy 'defineProperty' made '{key}' non-configurable"
7574 )));
7575 }
7576 }
7577 // Step 11's other half: reporting that a property was made *configurable* needs a
7578 // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7579 // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7580 // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7581 // target`).
7582 if named.configurable
7583 && property.configurable
7584 && let Some(target_desc) = &target_desc
7585 && !target_desc.configurable
7586 {
7587 return Err(
7588 self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7589 );
7590 }
7591 // Step 12: a property cannot be reported *made writable* when the target's copy is
7592 // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7593 // the trap is allowed to claim a definition it did not perform, as long as the
7594 // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7595 // legal, and refusing it broke the commonest way to seed a proxy).
7596 if named.writable
7597 && property.writable
7598 && let Some(target_desc) = &target_desc
7599 && !target_desc.writable
7600 {
7601 return Err(self.type_error(format!(
7602 "proxy 'defineProperty' made the read-only '{key}' writable"
7603 )));
7604 }
7605 // Step 13: making a property read-only needs an existing read-only property.
7606 if named.writable
7607 && !property.writable
7608 && let Some(target_desc) = &target_desc
7609 && !target_desc.is_accessor()
7610 && target_desc.writable
7611 {
7612 return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7613 }
7614 // Step 14: a non-writable, non-configurable property's value is fixed.
7615 if named.value
7616 && let Some(target_desc) = &target_desc
7617 && !target_desc.is_accessor()
7618 && !target_desc.writable
7619 && !target_desc.configurable
7620 {
7621 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7622 let reported = property.value.clone().unwrap_or(Value::Undefined);
7623 if !fixed_value.same_value(&reported) {
7624 return Err(self.type_error(format!(
7625 "proxy 'defineProperty' changed the value of '{key}'"
7626 )));
7627 }
7628 }
7629 // Step 15: a non-extensible target cannot grow.
7630 if target_desc.is_none() && !extensible {
7631 return Err(self.type_error(format!(
7632 "proxy 'defineProperty' added '{key}' to a non-extensible target"
7633 )));
7634 }
7635 Ok(Some(true))
7636 }
7637
7638 /// `[[GetPrototypeOf]]` on a proxy.
7639 fn proxy_get_prototype_of(
7640 &mut self,
7641 object: &Gc<JsObject>,
7642 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7643 let Some((target, handler)) = self.proxy_parts(object)? else {
7644 return Ok(None);
7645 };
7646 let Some(result) = self.proxy_trap(
7647 &handler,
7648 "getPrototypeOf",
7649 vec![Value::Object(target.clone())],
7650 )?
7651 else {
7652 // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7653 // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7654 // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7655 // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7656 // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7657 return Ok(Some(self.object_prototype_of(&target)?));
7658 };
7659 let proto = match &result {
7660 Value::Null => None,
7661 Value::Object(proto) => Some(proto.clone()),
7662 _ => {
7663 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7664 }
7665 };
7666 if !self.object_is_extensible(&target)? {
7667 let actual = self.object_prototype_of(&target)?;
7668 if !same_proto(proto.as_ref(), actual.as_ref()) {
7669 return Err(self.type_error(
7670 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7671 ));
7672 }
7673 }
7674 Ok(Some(proto))
7675 }
7676
7677 /// `[[SetPrototypeOf]]` on a proxy.
7678 fn proxy_set_prototype_of(
7679 &mut self,
7680 object: &Gc<JsObject>,
7681 proto: Option<Gc<JsObject>>,
7682 ) -> JsResult<Option<bool>> {
7683 let Some((target, handler)) = self.proxy_parts(object)? else {
7684 return Ok(None);
7685 };
7686 let proto_value = match &proto {
7687 Some(proto) => Value::Object(proto.clone()),
7688 None => Value::Null,
7689 };
7690 let Some(result) = self.proxy_trap(
7691 &handler,
7692 "setPrototypeOf",
7693 vec![Value::Object(target.clone()), proto_value],
7694 )?
7695 else {
7696 // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7697 // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7698 // its stored prototype overwritten behind its back.
7699 return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7700 };
7701 if result.to_boolean()
7702 && !self.object_is_extensible(&target)?
7703 && !same_proto(
7704 Some(&proto).and_then(|p| p.clone()).as_ref(),
7705 self.object_prototype_of(&target)?.as_ref(),
7706 )
7707 {
7708 return Err(self.type_error(
7709 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7710 ));
7711 }
7712 Ok(Some(result.to_boolean()))
7713 }
7714
7715 /// `[[IsExtensible]]` on a proxy.
7716 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7717 let Some((target, handler)) = self.proxy_parts(object)? else {
7718 return Ok(None);
7719 };
7720 let Some(result) = self.proxy_trap(
7721 &handler,
7722 "isExtensible",
7723 vec![Value::Object(target.clone())],
7724 )?
7725 else {
7726 return Ok(Some(self.object_is_extensible(&target)?));
7727 };
7728 // The answer is not the proxy's to invent: it must agree with the target, or a
7729 // script could learn `false` while the target keeps accepting new properties.
7730 if result.to_boolean() != self.object_is_extensible(&target)? {
7731 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7732 }
7733 Ok(Some(result.to_boolean()))
7734 }
7735
7736 /// `[[PreventExtensions]]` on a proxy.
7737 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7738 let Some((target, handler)) = self.proxy_parts(object)? else {
7739 return Ok(None);
7740 };
7741 let Some(result) = self.proxy_trap(
7742 &handler,
7743 "preventExtensions",
7744 vec![Value::Object(target.clone())],
7745 )?
7746 else {
7747 // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7748 // its answer can be `false`.
7749 return Ok(Some(self.object_prevent_extensions(&target)?));
7750 };
7751 if result.to_boolean() && self.object_is_extensible(&target)? {
7752 return Err(self.type_error(
7753 "proxy 'preventExtensions' reported success but the target is still extensible",
7754 ));
7755 }
7756 Ok(Some(result.to_boolean()))
7757 }
7758
7759 /// `[[Call]]` on a proxy, through the `apply` trap.
7760 fn proxy_apply(
7761 &mut self,
7762 object: &Gc<JsObject>,
7763 this: Value,
7764 args: Vec<Value>,
7765 ) -> JsResult<Option<Value>> {
7766 let Some((target, handler)) = self.proxy_parts(object)? else {
7767 return Ok(None);
7768 };
7769 // The trap gets the arguments as one array, which is the shape the spec passes
7770 // and the shape `apply` traps are written against (`args[0]` is the first one).
7771 let arguments = self.new_array(args.clone());
7772 let this_for_trap = this.clone();
7773 let Some(result) = self.proxy_trap(
7774 &handler,
7775 "apply",
7776 vec![
7777 Value::Object(target.clone()),
7778 this_for_trap,
7779 Value::Object(arguments),
7780 ],
7781 )?
7782 else {
7783 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7784 };
7785 Ok(Some(result))
7786 }
7787
7788 /// `[[Construct]]` on a proxy, through the `construct` trap.
7789 fn proxy_construct(
7790 &mut self,
7791 object: &Gc<JsObject>,
7792 args: Vec<Value>,
7793 new_target: &Value,
7794 ) -> JsResult<Option<Value>> {
7795 let Some((target, handler)) = self.proxy_parts(object)? else {
7796 return Ok(None);
7797 };
7798 if !target.is_callable() {
7799 return Err(self.type_error("proxy target is not a constructor"));
7800 }
7801 let arguments = self.new_array(args.clone());
7802 let Some(result) = self.proxy_trap(
7803 &handler,
7804 "construct",
7805 vec![
7806 Value::Object(target.clone()),
7807 Value::Object(arguments),
7808 new_target.clone(),
7809 ],
7810 )?
7811 else {
7812 return Ok(Some(self.construct(
7813 Value::Object(target),
7814 new_target.clone(),
7815 args,
7816 )?));
7817 };
7818 if !matches!(result, Value::Object(_)) {
7819 return Err(self.type_error("proxy 'construct' must return an object"));
7820 }
7821 Ok(Some(result))
7822 }
7823
7824 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7825 pub(crate) fn has_own_or_inherited(
7826 &mut self,
7827 object: &Gc<JsObject>,
7828 key: &PropertyKey,
7829 ) -> JsResult<bool> {
7830 // The object itself first: it may be a proxy, and then the answer is its trap's.
7831 if let Some(answer) = self.proxy_has(object, key)? {
7832 return Ok(answer);
7833 }
7834 // An integer-indexed exotic object answers a canonical numeric index from
7835 // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7836 // prototype chain. That is observable twice: a view the buffer has been resized
7837 // away from has no indices, so `2 in view` is `false` even when
7838 // `Object.getPrototypeOf(view)[2]` exists (what
7839 // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7840 // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7841 // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7842 // goes through here, which is why the same rule is repeated in `has_property_key`
7843 // rather than living only there.
7844 if object.typed_array_parts().is_some()
7845 && let Some(numeric) = canonical_numeric_index(key)
7846 {
7847 return Ok(typed_array_index_is_valid(object, numeric));
7848 }
7849 // A host class answers `in` for its own keys, which may live nowhere in a property
7850 // table — `"x" in point` is true because the class says so, not because a property
7851 // exists.
7852 if let Some(exotic) = object.exotic()
7853 && let Some(answer) = exotic.has_property(self, object, key)?
7854 {
7855 return Ok(answer);
7856 }
7857 // `has_own` rather than `own_property_key`: an array's elements and its derived
7858 // `length` are invisible to the property table, and `Array.prototype` is an array.
7859 // A host class's `get_own_property` counts too, because the reference's
7860 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7861 // lives — a class with only `get_own_property` answers `in` through it.
7862 if self.exotic_has_own(object, key)? {
7863 return Ok(true);
7864 }
7865 // A hole is *not* the end of the search: the chain may still have the key, which
7866 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7867 for ancestor in object.chain() {
7868 // A proxy further up the chain answers for itself.
7869 if let Some(answer) = self.proxy_has(&ancestor, key)? {
7870 return Ok(answer);
7871 }
7872 // Same for a host class: a prototype may be one, and `in` reaches it.
7873 if let Some(exotic) = ancestor.exotic()
7874 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7875 {
7876 return Ok(answer);
7877 }
7878 if self.exotic_has_own(&ancestor, key)? {
7879 return Ok(true);
7880 }
7881 }
7882 Ok(false)
7883 }
7884
7885 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7886 /// trap included.
7887 ///
7888 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7889 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7890 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7891 if let Some(exotic) = object.exotic()
7892 && let Some(answer) = exotic.get_own_property(self, object, key)?
7893 {
7894 return Ok(answer.is_some());
7895 }
7896 Ok(has_own(object, key))
7897 }
7898
7899 /// `CreateListFromArrayLike`, optionally restricted to property keys.
7900 ///
7901 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7902 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7903 /// `TypeError` instead of a property named `"1.5"`.
7904 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7905 let object = self.object_from(value)?;
7906 let length = self
7907 .get_property(&object, "length")?
7908 .map(|value| value.to_number())
7909 .unwrap_or(0.0);
7910 if !length.is_finite() || length < 0.0 {
7911 return Err(self.type_error("invalid array-like length"));
7912 }
7913 let length = length as usize;
7914 let mut items = Vec::with_capacity(length.min(1024));
7915 for index in 0..length {
7916 let item = self
7917 .get_property(&object, &index.to_string())?
7918 .unwrap_or(Value::Undefined);
7919 if keys_only && matches!(&item, Value::Symbol(_)) {
7920 items.push(item);
7921 continue;
7922 }
7923 if keys_only && !matches!(&item, Value::String(_)) {
7924 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7925 }
7926 items.push(item);
7927 }
7928 Ok(items)
7929 }
7930
7931 /// A `Property` from the descriptor object a trap returned.
7932 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7933 let object = self.object_from(value)?;
7934 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7935 interp.get_property(&object, name)
7936 };
7937 let getter = field(self, "get")?;
7938 let setter = field(self, "set")?;
7939 let accessor = getter.is_some() || setter.is_some();
7940 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7941 Ok(interp
7942 .get_property(&object, name)?
7943 .is_some_and(|value| value.to_boolean()))
7944 };
7945 let enumerable = boolean(self, "enumerable")?;
7946 let configurable = boolean(self, "configurable")?;
7947 if accessor {
7948 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7949 return Err(
7950 self.type_error("a descriptor cannot be both a data property and an accessor")
7951 );
7952 }
7953 Ok(Property {
7954 getter: getter.or(Some(Value::Undefined)),
7955 setter: setter.or(Some(Value::Undefined)),
7956 enumerable,
7957 configurable,
7958 writable: false,
7959 value: None,
7960 descriptor_fields: None,
7961 })
7962 } else {
7963 Ok(Property {
7964 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7965 writable: boolean(self, "writable")?,
7966 enumerable,
7967 configurable,
7968 getter: None,
7969 setter: None,
7970 descriptor_fields: None,
7971 })
7972 }
7973 }
7974
7975 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7976 fn descriptor_from_property(&mut self, property: &Property) -> Value {
7977 let object = self.new_object(None);
7978 // A partial descriptor names only some fields, and the trap must see exactly those:
7979 // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7980 // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7981 // case, where every field is present.
7982 let fields = property.descriptor_fields;
7983 let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7984 fields.is_none_or(|fields| field(&fields))
7985 };
7986 if property.is_accessor() {
7987 let getter = property.getter.clone().unwrap_or(Value::Undefined);
7988 let setter = property.setter.clone().unwrap_or(Value::Undefined);
7989 object.define_data("get", getter);
7990 object.define_data("set", setter);
7991 } else {
7992 if names(|fields| fields.value) {
7993 let value = property.value.clone().unwrap_or(Value::Undefined);
7994 object.define_data("value", value);
7995 }
7996 if names(|fields| fields.writable) {
7997 object.define_data("writable", Value::Bool(property.writable));
7998 }
7999 }
8000 if names(|fields| fields.enumerable) {
8001 object.define_data("enumerable", Value::Bool(property.enumerable));
8002 }
8003 if names(|fields| fields.configurable) {
8004 object.define_data("configurable", Value::Bool(property.configurable));
8005 }
8006 Value::Object(object)
8007 }
8008
8009 // -- calling ------------------------------------------------------------
8010
8011 /// Call `callee` with `this` and `args`.
8012 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
8013 let Value::Object(function) = &callee else {
8014 // `typeof x === "function"` is not enough to make `x()` legal: only a
8015 // callable object is. `null` and `undefined` need no special wording
8016 // here — their `ToString` already reads the way the reference's does.
8017 let what = format!("{} is not a function", callee.to_js_string());
8018 return Err(Signal::Throw(self.make_error("TypeError", &what)));
8019 };
8020 // A proxy of a function is called through its `apply` trap. It has no
8021 // `ObjectKind::Function` of its own, so this has to come before the dispatch
8022 // below, and a proxy of a non-function has nothing to forward to.
8023 if function.proxy_state().is_some() {
8024 return match self.proxy_apply(function, this, args)? {
8025 Some(result) => Ok(result),
8026 None => Err(Signal::Throw(
8027 self.make_error("TypeError", "proxy target is not callable"),
8028 )),
8029 };
8030 }
8031 let callable = function.with(|data| match &data.kind {
8032 ObjectKind::Function(callable) => match callable {
8033 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
8034 // The `Rc` is cloned out so the borrow of this object's data is released
8035 // before the closure runs: the closure may touch the same object.
8036 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
8037 Callable::Bound {
8038 target,
8039 this,
8040 args: leading,
8041 } => Some(NativeCall::Bound {
8042 target: target.clone(),
8043 this: this.clone(),
8044 leading: leading.clone(),
8045 }),
8046 Callable::Bytecode { code, env } => {
8047 Some(NativeCall::Bytecode(code.clone(), env.clone()))
8048 }
8049 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
8050 Callable::PromiseResolve(promise) => {
8051 Some(NativeCall::PromiseResolve(promise.clone()))
8052 }
8053 Callable::PromiseReject(promise) => {
8054 Some(NativeCall::PromiseReject(promise.clone()))
8055 }
8056 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
8057 state: state.clone(),
8058 }),
8059 Callable::ThenShim {
8060 handler,
8061 resolve,
8062 reject,
8063 fulfilled,
8064 } => Some(NativeCall::ThenShim {
8065 handler: handler.clone(),
8066 resolve: resolve.clone(),
8067 reject: reject.clone(),
8068 fulfilled: *fulfilled,
8069 }),
8070 Callable::AwaitResume {
8071 coroutine,
8072 promise,
8073 kind,
8074 } => Some(NativeCall::AwaitResume {
8075 coroutine: coroutine.clone(),
8076 promise: promise.clone(),
8077 kind: *kind,
8078 }),
8079 Callable::CombinatorSettle {
8080 state,
8081 index,
8082 fulfilled,
8083 } => Some(NativeCall::CombinatorSettle {
8084 state: state.clone(),
8085 index: *index,
8086 fulfilled: *fulfilled,
8087 }),
8088 Callable::FinallyShim {
8089 callback,
8090 fulfilled,
8091 constructor,
8092 } => Some(NativeCall::FinallyShim {
8093 callback: callback.clone(),
8094 fulfilled: *fulfilled,
8095 constructor: constructor.clone(),
8096 }),
8097 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
8098 Callable::CompletedReturn {
8099 generator,
8100 promise,
8101 rejected,
8102 } => Some(NativeCall::CompletedReturn {
8103 generator: generator.clone(),
8104 promise: promise.clone(),
8105 rejected: *rejected,
8106 }),
8107 Callable::YieldResult {
8108 generator,
8109 promise,
8110 done,
8111 } => Some(NativeCall::YieldResult {
8112 generator: generator.clone(),
8113 promise: promise.clone(),
8114 done: *done,
8115 }),
8116 Callable::DisposeStep {
8117 remaining,
8118 promise,
8119 error,
8120 rejected,
8121 awaited,
8122 needs_await,
8123 } => Some(NativeCall::DisposeStep {
8124 remaining: remaining.clone(),
8125 promise: promise.clone(),
8126 error: error.clone(),
8127 rejected: *rejected,
8128 awaited: *awaited,
8129 needs_await: *needs_await,
8130 }),
8131 Callable::GeneratorResume {
8132 generator,
8133 promise,
8134 kind,
8135 } => Some(NativeCall::GeneratorResume {
8136 generator: generator.clone(),
8137 promise: promise.clone(),
8138 kind: *kind,
8139 }),
8140 Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
8141 Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
8142 Callable::SettlePromise {
8143 promise,
8144 value,
8145 rejected,
8146 } => Some(NativeCall::SettlePromise {
8147 promise: promise.clone(),
8148 value: value.clone(),
8149 rejected: *rejected,
8150 }),
8151 },
8152 _ => None,
8153 });
8154 match callable {
8155 Some(NativeCall::Host(func)) => {
8156 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
8157 // function by name rather than stopping at the caller.
8158 let frame_less = function
8159 .own_property("_frame_less")
8160 .and_then(|property| property.value)
8161 .is_some_and(|value| value.to_boolean());
8162 let outer = if frame_less {
8163 None
8164 } else {
8165 self.native_frames
8166 .push((function.clone(), self.frames.len()));
8167 Some(self.current_native.replace(function.clone()))
8168 };
8169 // Same frame bookkeeping as a `Native`, plus `new.target`: a host
8170 // constructor reads it through `current_new_target` because it is handed
8171 // `undefined` for `this`. Taking the parked value here is what stops a
8172 // *plain* call made from inside a constructor body from seeing the
8173 // enclosing `new.target`.
8174 let parked = self.pending_new_target.take();
8175 let result = {
8176 let outer_new_target = std::mem::replace(
8177 &mut self.active_new_target,
8178 parked.unwrap_or(Value::Undefined),
8179 );
8180 let result = {
8181 let mut body = func.borrow_mut();
8182 body(self, this, &args)
8183 };
8184 self.active_new_target = outer_new_target;
8185 result
8186 };
8187 if !frame_less {
8188 self.native_frames.pop();
8189 self.current_native = outer.flatten();
8190 }
8191 result
8192 }
8193 Some(NativeCall::Native(func)) => {
8194 // A function marked `_frame_less` is one the reference implements
8195 // without a call frame — `eval` is the only one so far.
8196 let frame_less = function
8197 .own_property("_frame_less")
8198 .and_then(|property| property.value)
8199 .is_some_and(|value| value.to_boolean());
8200 let outer = if frame_less {
8201 None
8202 } else {
8203 self.native_frames
8204 .push((function.clone(), self.frames.len()));
8205 Some(self.current_native.replace(function.clone()))
8206 };
8207 let parked = self.pending_new_target.take();
8208 let outer_new_target = std::mem::replace(
8209 &mut self.active_new_target,
8210 parked.unwrap_or(Value::Undefined),
8211 );
8212 let result = func(self, this, &args);
8213 self.active_new_target = outer_new_target;
8214 if !frame_less {
8215 self.native_frames.pop();
8216 self.current_native = outer.flatten();
8217 }
8218 result
8219 }
8220 Some(NativeCall::Revoker(slots)) => {
8221 // Idempotent: revoking twice answers `undefined` again rather than
8222 // complaining, which is what the spec says and what a `finally` block
8223 // relies on.
8224 let mut state = slots.borrow_mut();
8225 state.target = None;
8226 state.handler = None;
8227 Ok(Value::Undefined)
8228 }
8229 Some(NativeCall::PromiseResolve(promise)) => {
8230 // §27.2.1.3.2 step 4: `[[AlreadyResolved]]` is checked **before** anything
8231 // else, so a resolve after a reject does nothing *and* a resolve after a
8232 // resolve-with-thenable does nothing — the promise is still `Pending` then,
8233 // because the adoption is a queued job.
8234 let value = args.first().cloned().unwrap_or(Value::Undefined);
8235 if !self.claim_resolution(&promise) {
8236 return Ok(Value::Undefined);
8237 }
8238 // §27.2.1.3.2 steps 7–8: a self-resolution is **rejected, not thrown** —
8239 // the resolve function performs `RejectPromise` and returns `undefined`.
8240 // (`ResolvePromise` itself throws as well, so the engine's own callers see
8241 // it; only this wrapper swallows it.)
8242 let _ = self.resolve_promise_with(&promise, value);
8243 Ok(Value::Undefined)
8244 }
8245 Some(NativeCall::PromiseReject(promise)) => {
8246 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8247 // §27.2.1.3.1 step 3: same one-shot record as `resolve`.
8248 if !self.claim_resolution(&promise) {
8249 return Ok(Value::Undefined);
8250 }
8251 self.reject_promise(&promise, reason);
8252 Ok(Value::Undefined)
8253 }
8254 Some(NativeCall::ThenShim {
8255 handler,
8256 resolve,
8257 reject,
8258 fulfilled,
8259 }) => {
8260 // `PerformPromiseThen` with a capability: run the handler, then settle
8261 // through the capability's own pair. A throw from the handler is the
8262 // rejection, and a throw from the capability's `resolve` is not caught —
8263 // exactly the spec's `?`.
8264 let value = args.first().cloned().unwrap_or(Value::Undefined);
8265 match handler {
8266 Some(handler) => {
8267 match self.call_value(handler, Value::Undefined, vec![value]) {
8268 Ok(result) => {
8269 self.call_value(resolve, Value::Undefined, vec![result])?;
8270 }
8271 Err(Signal::Throw(reason)) => {
8272 self.call_value(reject, Value::Undefined, vec![reason])?;
8273 }
8274 Err(signal) => return Err(signal),
8275 }
8276 }
8277 None => {
8278 let handler = if fulfilled { resolve } else { reject };
8279 self.call_value(handler, Value::Undefined, vec![value])?;
8280 }
8281 }
8282 Ok(Value::Undefined)
8283 }
8284 Some(NativeCall::CapabilityExecutor { state }) => {
8285 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
8286 // slot holds a value yet. The test is on the *values*, not on a call count —
8287 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
8288 // called-twice`'s first case does exactly that), while a second call after a
8289 // real pair is the `TypeError`.
8290 let defined = |name: &str| {
8291 state
8292 .own_property(name)
8293 .and_then(|property| property.value)
8294 .is_some_and(|value| !matches!(value, Value::Undefined))
8295 };
8296 if defined("resolve") || defined("reject") {
8297 return Err(self.type_error("promise capability executor called twice"));
8298 }
8299 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
8300 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
8301 state.define_data("resolve", resolve);
8302 state.define_data("reject", reject);
8303 Ok(Value::Undefined)
8304 }
8305 Some(NativeCall::CombinatorSettle {
8306 state,
8307 index,
8308 fulfilled,
8309 }) => {
8310 let value = args.first().cloned().unwrap_or(Value::Undefined);
8311 self.settle_combinator(&state, index, fulfilled, value)?;
8312 Ok(Value::Undefined)
8313 }
8314 Some(NativeCall::AwaitResume {
8315 coroutine,
8316 promise,
8317 kind,
8318 }) => {
8319 // Resume *inline*, in the reaction that delivered the value. Deferring it
8320 // by another job inserts a tick between every `await` and its
8321 // continuation, which reorders `await` against unrelated `then` chains —
8322 // `f().then(g)` then runs before `f`'s own next statement.
8323 self.drive_async(
8324 &coroutine,
8325 &promise,
8326 kind,
8327 args.first().cloned().unwrap_or(Value::Undefined),
8328 )
8329 .map(|()| Value::Undefined)
8330 }
8331 Some(NativeCall::ReturnValue(value)) => Ok(value),
8332 Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
8333 Some(NativeCall::FinallyShim {
8334 callback,
8335 fulfilled,
8336 constructor,
8337 }) => {
8338 // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
8339 // own value is discarded; what the caller sees is the *original* outcome,
8340 // delayed until `PromiseResolve(C, result)` has settled.
8341 //
8342 // Two details are observable and both have a test:
8343 //
8344 // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
8345 // `PerformPromiseThen`. A callback that returns a thenable with its own
8346 // `then` must have that `then` called
8347 // (`resolved-observable-then-calls` counts it);
8348 // * only the **fulfil** handler is supplied. A returned promise that
8349 // *rejects* rejects the whole `finally`, rather than having its failure
8350 // swallowed and the original value passed through.
8351 let original = args.first().cloned().unwrap_or(Value::Undefined);
8352 let result = match &callback {
8353 Some(callback) => {
8354 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
8355 }
8356 None => Value::Undefined,
8357 };
8358 // `PromiseResolve(C, result)`: a `result` that is already a promise of this
8359 // constructor is reused rather than rewrapped, which is what keeps
8360 // `mp1.finally(() => mp2)` from gaining a layer.
8361 let resolved = self.promise_resolve_for(&constructor, result)?;
8362 let thunk = if fulfilled {
8363 Callable::ReturnValue(original)
8364 } else {
8365 Callable::ThrowValue(original)
8366 };
8367 // `length: 0` and `name: ""`, and **not** a constructor — the three things
8368 // `resolved-observable-then-calls-argument` reads off the thunk while it has
8369 // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
8370 // function with no `length` at all.
8371 let thunk = self.builtin_function("", 0, thunk);
8372 let then = self.read_field(&resolved, "then")?;
8373 if !matches!(&then, Value::Object(object) if object.is_callable()) {
8374 return Err(self.type_error("then is not a function"));
8375 }
8376 self.call_value(then, resolved, vec![Value::Object(thunk)])
8377 }
8378 Some(NativeCall::DisposeStep {
8379 remaining,
8380 promise,
8381 error,
8382 rejected,
8383 awaited,
8384 needs_await,
8385 }) => {
8386 let error = if rejected {
8387 let reason = args.first().cloned().unwrap_or(Value::Undefined);
8388 self.merge_dispose_error(reason, error)
8389 } else {
8390 error
8391 };
8392 self.dispose_step(&remaining, &promise, error, awaited, needs_await)?;
8393 Ok(Value::Undefined)
8394 }
8395 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
8396 Some(NativeCall::CompletedReturn {
8397 generator,
8398 promise,
8399 rejected,
8400 }) => {
8401 let value = args.first().cloned().unwrap_or(Value::Undefined);
8402 let outcome = if rejected {
8403 AsyncOutcome::Error(value)
8404 } else {
8405 AsyncOutcome::Value(self.iterator_result(value, true)?)
8406 };
8407 self.settle_async_request(&generator, &promise, outcome)?;
8408 Ok(Value::Undefined)
8409 }
8410 Some(NativeCall::YieldResult {
8411 generator,
8412 promise,
8413 done,
8414 }) => {
8415 let value = args.first().cloned().unwrap_or(Value::Undefined);
8416 let result = self.iterator_result(value, done)?;
8417 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
8418 Ok(Value::Undefined)
8419 }
8420 Some(NativeCall::GeneratorResume {
8421 generator,
8422 promise,
8423 kind,
8424 }) => {
8425 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
8426 // tick and reorders the generator against other chains.
8427 self.step_async_generator(
8428 &generator,
8429 &promise,
8430 kind,
8431 args.first().cloned().unwrap_or(Value::Undefined),
8432 )
8433 .map(|()| Value::Undefined)
8434 }
8435 Some(NativeCall::SettlePromise {
8436 promise,
8437 value,
8438 rejected,
8439 }) => {
8440 if rejected {
8441 self.reject_promise(&promise, value);
8442 } else {
8443 self.fulfill_promise(&promise, value);
8444 }
8445 Ok(Value::Undefined)
8446 }
8447 Some(NativeCall::Bound {
8448 target,
8449 this: bound_this,
8450 leading,
8451 }) => {
8452 let mut all = leading;
8453 all.extend(args);
8454 self.call_value(target, bound_this, all)
8455 }
8456 Some(NativeCall::Bytecode(code, env)) => {
8457 if code.code.kind.is_generator() {
8458 return self.new_generator(callee, this, args);
8459 }
8460 if code.code.kind.is_async() {
8461 // Same coroutine machinery as a generator; the difference is only in
8462 // what the completion does — see `new_async_function`.
8463 return self.new_async_function(callee, this, args);
8464 }
8465 self.execute(code, env, this, args, callee)
8466 }
8467 None => Err(Signal::Throw(
8468 self.make_error("TypeError", "not a function"),
8469 )),
8470 }
8471 }
8472
8473 /// Give a freshly built function its own `prototype` object.
8474 ///
8475 /// Every function that can be used with `new` carries one, and its
8476 /// `constructor` points back at the function — a reference cycle, which is
8477 /// exactly what the collector's cycle pass exists to reclaim.
8478 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
8479 self.install_function_prototype_with(function, None);
8480 }
8481
8482 /// [`Interp::install_function_prototype`] with an explicit parent for the new
8483 /// `prototype` object.
8484 ///
8485 /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
8486 /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
8487 /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
8488 /// `None` means `%Object.prototype%`.
8489 fn install_function_prototype_with(
8490 &mut self,
8491 function: &Gc<JsObject>,
8492 parent: Option<Gc<JsObject>>,
8493 ) {
8494 let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
8495 let prototype = self.new_object(Some(parent));
8496 let constructor = Value::Object(function.clone());
8497 prototype.define(
8498 "constructor",
8499 Property::with_attributes(constructor, true, false),
8500 );
8501 let value = Value::Object(prototype);
8502 function.define("prototype", Property::prototype_of(value, true));
8503 }
8504
8505 /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
8506 /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
8507 /// [`Interp::install_function_prototype`] — **no `constructor` property**.
8508 ///
8509 /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
8510 /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
8511 /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
8512 /// is `[]` there.
8513 fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
8514 let prototype = self.new_object(Some(parent));
8515 let value = Value::Object(prototype);
8516 function.define("prototype", Property::prototype_of(value, true));
8517 }
8518
8519 /// The `[[Prototype]]` a newly created generator object gets:
8520 /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
8521 ///
8522 /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
8523 /// function's `prototype` is writable, so a script can replace it with anything, and
8524 /// only an *object* is consulted.
8525 fn generator_instance_proto(
8526 &mut self,
8527 function: &Gc<JsObject>,
8528 default: Gc<JsObject>,
8529 ) -> JsResult<Gc<JsObject>> {
8530 match self.get_property(function, "prototype")? {
8531 Some(Value::Object(prototype)) => Ok(prototype),
8532 _ => Ok(default),
8533 }
8534 }
8535
8536 /// A getter or setter that reads or writes the reference cell behind a mapped
8537 /// `arguments` index.
8538 ///
8539 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
8540 /// count — which is what the collector treats as "a reference from outside the
8541 /// heap". The closure therefore keeps the cell alive for exactly as long as the
8542 /// accessor is reachable, which is the same lifetime the arguments object has.
8543 ///
8544 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8545 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8546 /// parameter value and the arguments object reaches the closure, never the other
8547 /// way round. Nothing the collector has to see is hidden.
8548 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8549 let name = if is_setter { "set" } else { "get" };
8550 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8551 if is_setter {
8552 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8553 Ok(Value::Undefined)
8554 } else {
8555 Ok(cell.get())
8556 }
8557 };
8558 self.new_host_function(name, 1, Box::new(func))
8559 }
8560
8561 /// The object `special_object` builds.
8562 ///
8563 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8564 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8565 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8566 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8567 /// write through `arguments` does not reach the parameter.
8568 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8569 match magic {
8570 0 | 1 => {
8571 let args = self.frame().passed().to_vec();
8572 let proto = self.realm.object_proto.clone();
8573 let object = self.new_object(Some(proto));
8574 // The marker `Object.prototype.toString` needs: an arguments object is an
8575 // ordinary object apart from reporting `[object Arguments]`, and that has
8576 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8577 // show up ahead of them in a key listing anyway — it is non-enumerable.
8578 self.internal_set(&object, "_class", self.string("Arguments"));
8579 // `length` is writable and configurable but neither enumerable nor a
8580 // plain data property: `Object.keys(arguments)` lists the indices only,
8581 // which is how `{...arguments}` copies them without the length.
8582 object.define(
8583 "length",
8584 Property::with_attributes(Value::Int(args.len() as i32), true, false),
8585 );
8586 // `magic == 1` is sloppy mode, where each index is *mapped* to the
8587 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8588 // change `a`, and assigning `a` has to change `arguments[0]`.
8589 //
8590 // The shared storage is the parameter's reference cell. The compiler
8591 // gives every parameter of such a function one (see
8592 // `provide_body_arguments`), and the cell outlives the frame, so this
8593 // keeps working after the arguments object escapes.
8594 //
8595 // The index becomes an accessor rather than a data property. A mapped
8596 // index reports as a plain writable/enumerable data property through
8597 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8598 // the getter/setter pair is only the plumbing underneath.
8599 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8600 let frame = self.frame();
8601 frame
8602 .code
8603 .arg_cell
8604 .iter()
8605 .map(|cell| {
8606 (*cell >= 0)
8607 .then(|| frame.cells.get(*cell as usize).cloned())
8608 .flatten()
8609 })
8610 .collect()
8611 } else {
8612 Vec::new()
8613 };
8614 // Tell the object which indices are mapped, so
8615 // `Object.getOwnPropertyDescriptor` can report them as the data
8616 // properties the spec describes instead of the accessors that
8617 // implement the aliasing.
8618 if magic == 1 {
8619 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8620 for cell in &mapped_cells {
8621 table.push(cell.clone());
8622 }
8623 object.set_mapped_arguments(table);
8624 }
8625 for (index, value) in args.into_iter().enumerate() {
8626 match mapped_cells.get(index).cloned().flatten() {
8627 Some(cell) => {
8628 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8629 let setter = self.new_mapped_arguments_accessor(cell, true);
8630 object.define(
8631 &index.to_string(),
8632 Property::accessor_with(
8633 Some(Value::Object(getter)),
8634 Some(Value::Object(setter)),
8635 true,
8636 ),
8637 );
8638 }
8639 None => object.define_data(&index.to_string(), value),
8640 }
8641 }
8642 // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8643 // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8644 // non-enumerable and non-configurable. It is not a nicety — it is the only
8645 // documented way to reach `%ThrowTypeError%`:
8646 //
8647 // Object.getOwnPropertyDescriptor(function(){"use strict";
8648 // return arguments;}(), "callee").get
8649 //
8650 // and the whole `ThrowTypeError/` directory is written against that
8651 // expression. Without it 13 cases failed with `cannot read property 'get'
8652 // of undefined`, which reads like a test harness bug rather than a missing
8653 // accessor.
8654 //
8655 // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8656 // writable data property holding the function being called, and
8657 // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8658 // `hasOwnProperty("callee")` hold there.
8659 if magic == 1 {
8660 let callee = self.frame().callee.clone();
8661 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8662 object.define("callee", Property::with_attributes(callee, true, false));
8663 } else if let Some(thrower) = self.realm.throw_type_error.clone()
8664 && object.own_property("callee").is_none()
8665 {
8666 object.define(
8667 "callee",
8668 Property {
8669 getter: Some(Value::Object(thrower.clone())),
8670 setter: Some(Value::Object(thrower)),
8671 enumerable: false,
8672 configurable: false,
8673 ..Property::default()
8674 },
8675 );
8676 }
8677 // An arguments object is iterable: `[...arguments]` and
8678 // `for (const a of arguments)` both work, through the *array* iterator
8679 // because the object is array-like. Without this the whole spread form
8680 // reported "not iterable".
8681 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8682 let values = self
8683 .realm
8684 .array_proto
8685 .own_property("values")
8686 .and_then(|property| property.value);
8687 if let Some(values) = values {
8688 object.define_key(
8689 &iterator_key,
8690 Property::with_attributes(values, true, false),
8691 );
8692 }
8693 Ok(Value::Object(object))
8694 }
8695 // `this.active_func`: the constructor `super()` resolves against.
8696 //
8697 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8698 // own, so it inherits this from the function it was written in along with `this`
8699 // — and that is a lexical relationship, not a stack one: an arrow that escaped
8700 // the constructor and is called back later (`iter.return = () => super()`) has
8701 // the constructor nowhere on the stack. The compiler therefore reads it out of
8702 // a closure variable of the enclosing function, exactly as the reference does
8703 // with its `this_active_func` local.
8704 2 => Ok(self
8705 .current_callee()
8706 .map_or(Value::Undefined, Value::Object)),
8707 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8708 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8709 // its own either, so the lookup walks out to the nearest non-arrow frame for
8710 // the same reason as `this.active_func` above — without that, `super()` inside
8711 // an arrow passed `undefined` as the new target and the parent constructor was
8712 // then rejected for being invoked without `new`.
8713 3 => Ok(self
8714 .eval_new_target
8715 .clone()
8716 .unwrap_or_else(|| self.frame().new_target.clone())),
8717 // `[[HomeObject]]` of the function being run: what `super` is relative to.
8718 // An arrow has none of its own, so the lookup walks out to the enclosing
8719 // method — which is why `super` works inside an arrow inside a method.
8720 4 => Ok(self
8721 .frames
8722 .iter()
8723 .rev()
8724 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8725 .map_or(Value::Undefined, Value::Object)),
8726 // `import.meta`: the innermost module body's meta object. Outside a module
8727 // the compiler never emits this, so an empty fallback is unreachable rather
8728 // than permissive.
8729 6 => {
8730 let name = self.module_stack.last().cloned();
8731 let meta = name
8732 .and_then(|name| self.modules.get(&name).cloned())
8733 .and_then(|module| module.with(|r| r.import_meta.clone()));
8734 Ok(meta.map_or(Value::Undefined, Value::Object))
8735 }
8736 other => Err(Signal::Throw(self.make_error(
8737 "InternalError",
8738 &format!("special_object {other} is not implemented yet"),
8739 ))),
8740 }
8741 }
8742
8743 /// `[[HomeObject]]` of the innermost function that has one, if any.
8744 ///
8745 /// An arrow has none, so the search walks out to the enclosing method — the same
8746 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8747 /// inside a method.
8748 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8749 self.frames
8750 .iter()
8751 .rev()
8752 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8753 }
8754
8755 /// The dispose method a `using` declaration should snapshot, or an error.
8756 ///
8757 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8758 /// is what makes a resource that only knows the synchronous protocol usable in both
8759 /// forms.
8760 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8761 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8762 if value.is_nullish() {
8763 return Ok(Value::Undefined);
8764 }
8765 let Some(object) = value.as_object() else {
8766 return Err(self.type_error("not an object"));
8767 };
8768 let mut method = if await_form {
8769 let found = self.get_property_key(
8770 object,
8771 &self.realm.well_known_key(WellKnown::AsyncDisposable),
8772 )?;
8773 match found {
8774 Some(found) if !found.is_nullish() => Some(found),
8775 _ => self
8776 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8777 }
8778 } else {
8779 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8780 };
8781 let Some(found) = method.take() else {
8782 return Err(self.type_error("value is not disposable"));
8783 };
8784 if found.is_nullish() {
8785 return Err(self.type_error("value is not disposable"));
8786 }
8787 let callable = found.as_object().is_some_and(|object| object.is_callable());
8788 if !callable {
8789 return Err(self.type_error("dispose method is not a function"));
8790 }
8791 Ok(found)
8792 }
8793
8794 /// Call one resource's disposer, folding a failure into `error_state`.
8795 ///
8796 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8797 /// because a captured `using` binding lives in its reference cell and the local slot is
8798 /// stale — a closure over the resource is legal and must not change what is disposed.
8799 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8800 let value = self.get_loc(slot);
8801 let method = self.get_loc(slot + 1);
8802 // A resource that was never initialised — its declaration threw — or that is
8803 // `null`/`undefined` has nothing to dispose.
8804 if value.is_nullish() || matches!(value, Value::Uninitialized) {
8805 return Ok(error_state);
8806 }
8807 if matches!(method, Value::Undefined | Value::Uninitialized) {
8808 return Ok(error_state);
8809 }
8810 match self.call_value(method, value, Vec::new()) {
8811 Ok(_) => Ok(error_state),
8812 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8813 Err(other) => Err(other),
8814 }
8815 }
8816
8817 /// Combine a disposal failure with whatever was already going wrong.
8818 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8819 if matches!(error_state, Value::Uninitialized) {
8820 return new_error;
8821 }
8822 self.new_suppressed_error(new_error, error_state)
8823 }
8824
8825 /// A `SuppressedError` instance built straight from its prototype.
8826 ///
8827 /// Not through the constructor: a script that rewrites
8828 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8829 /// error wrapping.
8830 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8831 let proto = self
8832 .realm
8833 .suppressed_error_proto
8834 .clone()
8835 .unwrap_or_else(|| self.realm.error_proto.clone());
8836 let object = self.new_object(Some(proto));
8837 object.define("error", Property::with_attributes(error, true, true));
8838 object.define(
8839 "suppressed",
8840 Property::with_attributes(suppressed, true, true),
8841 );
8842 object.define(
8843 "message",
8844 Property::with_attributes(self.string("SuppressedError"), true, true),
8845 );
8846 self.internal_set(&object, "_class", self.string("Error"));
8847 self.add_stack(&object);
8848 Value::Object(object)
8849 }
8850
8851 /// Call `callee`, or push its frame and let the main loop run it.
8852 ///
8853 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8854 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8855 /// continues, so `function f(){ return f() }` costs heap and stops at
8856 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8857 /// is entered directly, and natives do not re-enter JavaScript in this
8858 /// milestone.
8859 ///
8860 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8861 /// because the returning frame will.
8862 /// The elements of an array-like value, as a call argument list.
8863 ///
8864 /// `apply` accepts any array-like, not only a real array: the reference reads
8865 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8866 /// `ToIndex(value)`: `ToIntegerOrInfinity` and then the `2^53 - 1` bound.
8867 ///
8868 /// Used by the paths that take a *length* from script data — the typed-array
8869 /// constructor's array-like argument, `Array.from`. `ToIntegerOrInfinity` runs
8870 /// `ToNumber`, so a Symbol is a `TypeError`; a value past `2^53 - 1` is a
8871 /// `RangeError` rather than a silently clamped count.
8872 pub fn to_index(&mut self, value: &Value) -> JsResult<usize> {
8873 let number = self.to_js_number(value)?;
8874 if number.is_nan() {
8875 return Ok(0);
8876 }
8877 let number = number.trunc();
8878 if number < 0.0 || number > 9_007_199_254_740_991.0 {
8879 return Err(self.range_error("invalid length"));
8880 }
8881 Ok(number as usize)
8882 }
8883
8884 /// `CreateListFromArrayLike(value)`: the elements of an array-like, for `apply` and the
8885 /// other callers that take an argument list from script data.
8886 ///
8887 /// The length is `ToLength`, which *clamps* rather than refusing — the typed-array
8888 /// constructor and `Array.from` need `ToIndex` instead (see
8889 /// [`Interp::to_index`]), which is why they do not go through here.
8890 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8891 let Some(object) = value.as_object().cloned() else {
8892 if value.is_nullish() {
8893 // `f.apply(this, null)` passes no arguments at all.
8894 return Ok(Vec::new());
8895 }
8896 return Err(self.type_error("createListFromArrayLike called on non-object"));
8897 };
8898 let length = match self.get_property(&object, "length")? {
8899 Some(length) => length.to_number(),
8900 None => 0.0,
8901 };
8902 if !length.is_finite() || length <= 0.0 {
8903 return Ok(Vec::new());
8904 }
8905 let length = (length as usize).min(1_000_000);
8906 let mut args = Vec::with_capacity(length);
8907 for index in 0..length {
8908 let element = self.get_property(&object, &index.to_string())?;
8909 args.push(element.unwrap_or(Value::Undefined));
8910 }
8911 Ok(args)
8912 }
8913
8914 /// Turn a call to a generator function into a generator object.
8915 ///
8916 /// The frame is built exactly as an ordinary call would build it, then detached and
8917 /// stored in the generator before any body instruction runs — which is what makes
8918 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8919 /// is `initial_yield`, the first instruction of every suspending body.
8920 pub fn new_generator(
8921 &mut self,
8922 function: Value,
8923 this: Value,
8924 args: Vec<Value>,
8925 ) -> JsResult<Value> {
8926 let Some(object) = function.as_object().cloned() else {
8927 return Err(self.type_error("not a generator function"));
8928 };
8929 let Some((code, env)) = bytecode_of(&object) else {
8930 return Err(self.type_error("not a generator function"));
8931 };
8932 let is_async = code.code.kind.is_async();
8933 self.push_frame(code, env, this, args, function)?;
8934 let frame = self.frames.pop().expect("push_frame just pushed it");
8935 // A fresh generator is *suspended at start*: the body has not run, so a
8936 // `return`/`throw` on it finishes without executing anything.
8937 let mut state = GeneratorState {
8938 frame: Some(frame),
8939 phase: GeneratorPhase::SuspendedStart,
8940 parked_on_await: false,
8941 parked_on_yield_star: false,
8942 requests: std::collections::VecDeque::new(),
8943 async_busy: false,
8944 is_async,
8945 };
8946 // Run to the first suspension. For a generator that is `initial_yield`, so no
8947 // body code runs; for a malformed body it would be the first `yield`.
8948 // An `async function*` answers an async generator: same coroutine, but its
8949 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8950 let default_proto = if is_async {
8951 self.realm
8952 .async_generator_proto
8953 .clone()
8954 .unwrap_or_else(|| self.realm.generator_proto.clone())
8955 } else {
8956 self.realm.generator_proto.clone()
8957 };
8958 // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
8959 // `prototype` object when it is one, the intrinsic otherwise. Every generator having
8960 // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
8961 // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
8962 let proto = self.generator_instance_proto(&object, default_proto)?;
8963 let generator = self.new_object(Some(proto));
8964 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8965 Ok(_) => {}
8966 Err(error) => return Err(error),
8967 }
8968 generator.with_mut(|data| {
8969 data.kind = ObjectKind::Generator(Box::new(state));
8970 });
8971 Ok(Value::Object(generator))
8972 }
8973
8974 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8975 ///
8976 /// Returns the `{value, done}` object itself rather than the pair, because a
8977 /// `yield*` suspension already has one — the inner iterator's own result — and the
8978 /// protocol says to hand that straight through rather than nest it.
8979 /// Advance a generator and report *why* it parked.
8980 ///
8981 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
8982 /// "hand this value to the caller" — but an async generator does: an `await` has to
8983 /// settle before it can answer, while a `yield` is the answer.
8984 fn resume_generator_detailed(
8985 &mut self,
8986 generator: &Gc<JsObject>,
8987 kind: ResumeKind,
8988 value: Value,
8989 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8990 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
8991 ObjectKind::Generator(state) => {
8992 let is_async = state.is_async;
8993 Some(std::mem::replace(
8994 state.as_mut(),
8995 GeneratorState {
8996 frame: None,
8997 phase: GeneratorPhase::Executing,
8998 parked_on_await: false,
8999 parked_on_yield_star: false,
9000 requests: std::collections::VecDeque::new(),
9001 // **Busy while the body runs**, so a `next()` called *from inside*
9002 // the body queues instead of being served. §27.6.3.7
9003 // `AsyncGeneratorResumeNext` returns immediately for the state
9004 // "executing", and the request is served once the body suspends;
9005 // with `false` here the re-entrant call found an empty frame and
9006 // rejected (`request-queue-order-state-executing`).
9007 async_busy: is_async,
9008 is_async,
9009 },
9010 ))
9011 }
9012 _ => None,
9013 }) else {
9014 return Err(self.type_error("not a generator"));
9015 };
9016 let result = self.step_generator(&mut state, kind, value);
9017 // Requests queued *while* the body ran live on the placeholder, because the real
9018 // state is out of the object for the duration. They have to be folded back in
9019 // before the placeholder is overwritten, or the promise they carry never settles.
9020 let queued = generator.with_mut(|data| match &mut data.kind {
9021 ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
9022 _ => std::collections::VecDeque::new(),
9023 });
9024 state.requests.extend(queued);
9025 generator.with_mut(|data| {
9026 data.kind = ObjectKind::Generator(Box::new(state));
9027 });
9028 result
9029 }
9030
9031 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
9032 ///
9033 /// Returns the `{value, done}` object itself rather than the pair, because a
9034 /// `yield*` suspension already has one — the inner iterator's own result — and the
9035 /// protocol says to hand that straight through rather than nest it.
9036 pub fn resume_generator(
9037 &mut self,
9038 generator: &Gc<JsObject>,
9039 kind: ResumeKind,
9040 value: Value,
9041 ) -> JsResult<Value> {
9042 let (value, done, ready, _reason) =
9043 self.resume_generator_detailed(generator, kind, value)?;
9044 if ready {
9045 return Ok(value);
9046 }
9047 self.iterator_result(value, done)
9048 }
9049
9050 /// `next`/`return`/`throw` on an async generator, which answer a promise.
9051 ///
9052 /// The body is the same coroutine a sync generator runs; what changes is that an
9053 /// `await` inside it has to settle before the method can answer, so the step is
9054 /// driven off the job queue rather than returning inline.
9055 pub fn resume_async_generator(
9056 &mut self,
9057 generator: &Gc<JsObject>,
9058 kind: ResumeKind,
9059 value: Value,
9060 ) -> JsResult<Value> {
9061 let promise = self.new_promise();
9062 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
9063 // that order, and the second value must reach the *second* `yield`.
9064 let idle = generator.with_mut(|data| match &mut data.kind {
9065 ObjectKind::Generator(state) => {
9066 state.requests.push_back(AsyncRequest {
9067 kind,
9068 value,
9069 promise: promise.clone(),
9070 });
9071 !state.async_busy
9072 }
9073 _ => false,
9074 });
9075 if idle {
9076 self.next_async_request(generator)?;
9077 }
9078 Ok(Value::Object(promise))
9079 }
9080
9081 /// Serve the front queued request, if the generator is free to run one.
9082 ///
9083 /// A finished generator answers from the queue without running anything:
9084 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
9085 /// first, and `throw(e)` rejects.
9086 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
9087 enum Front {
9088 Idle,
9089 Run(ResumeKind, Value, Gc<JsObject>),
9090 Finished(ResumeKind, Value, Gc<JsObject>),
9091 }
9092 let front = generator.with_mut(|data| match &mut data.kind {
9093 ObjectKind::Generator(state) => {
9094 let Some(request) = state.requests.front() else {
9095 return Front::Idle;
9096 };
9097 // Busy means a request is still in flight — awaiting inside the body, not
9098 // finished. Serving another now would interleave two requests.
9099 if state.async_busy && state.phase != GeneratorPhase::Completed {
9100 return Front::Idle;
9101 }
9102 let kind = request.kind;
9103 let value = request.value.clone();
9104 let promise = request.promise.clone();
9105 state.async_busy = true;
9106 if state.phase == GeneratorPhase::Completed {
9107 Front::Finished(kind, value, promise)
9108 } else {
9109 Front::Run(kind, value, promise)
9110 }
9111 }
9112 _ => Front::Idle,
9113 });
9114 match front {
9115 Front::Idle => Ok(()),
9116 Front::Run(kind, value, promise) => {
9117 self.step_async_generator(generator, &promise, kind, value)
9118 }
9119 Front::Finished(kind, value, promise) => match kind {
9120 ResumeKind::Throw => {
9121 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
9122 }
9123 ResumeKind::Next | ResumeKind::Start => {
9124 let result = self.iterator_result(Value::Undefined, true)?;
9125 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
9126 }
9127 ResumeKind::Return => {
9128 // `js_async_generator_completed_return`: the value is awaited before it
9129 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
9130 // finished generator answers `1`, not a promise.
9131 let resolved = match self.promise_resolve_intrinsic(value) {
9132 Ok(resolved) => resolved,
9133 Err(Signal::Throw(reason)) => {
9134 return self.settle_async_request(
9135 generator,
9136 &promise,
9137 AsyncOutcome::Error(reason),
9138 );
9139 }
9140 Err(other) => return Err(other),
9141 };
9142 let done = JsObject::function(
9143 self.heap,
9144 Some(self.realm.function_proto.clone()),
9145 Callable::CompletedReturn {
9146 generator: generator.clone(),
9147 promise: promise.clone(),
9148 rejected: false,
9149 },
9150 );
9151 let failed = JsObject::function(
9152 self.heap,
9153 Some(self.realm.function_proto.clone()),
9154 Callable::CompletedReturn {
9155 generator: generator.clone(),
9156 promise: promise.clone(),
9157 rejected: true,
9158 },
9159 );
9160 let Value::Object(resolved) = resolved else {
9161 return self.settle_async_request(
9162 generator,
9163 &promise,
9164 AsyncOutcome::Error(Value::Undefined),
9165 );
9166 };
9167 self.perform_then(
9168 &resolved,
9169 Some(Value::Object(done)),
9170 Some(Value::Object(failed)),
9171 )?;
9172 Ok(())
9173 }
9174 },
9175 }
9176 }
9177
9178 /// Settle the front request and start the next one.
9179 ///
9180 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
9181 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
9182 /// generator would strand every later request.
9183 fn settle_async_request(
9184 &mut self,
9185 generator: &Gc<JsObject>,
9186 promise: &Gc<JsObject>,
9187 outcome: AsyncOutcome,
9188 ) -> JsResult<()> {
9189 let settled = generator.with_mut(|data| match &mut data.kind {
9190 ObjectKind::Generator(state) => {
9191 let front = state.requests.front();
9192 debug_assert!(
9193 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
9194 "a request settled outside its turn"
9195 );
9196 state.requests.pop_front();
9197 state.async_busy = false;
9198 true
9199 }
9200 _ => false,
9201 });
9202 if settled {
9203 match outcome {
9204 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
9205 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
9206 }
9207 }
9208 self.next_async_request(generator)
9209 }
9210
9211 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
9212 ///
9213 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
9214 /// disposer runs **synchronously** — the reference starts it before returning, which
9215 /// a test can observe by logging after the call — and the rest follow once their
9216 /// predecessor settles.
9217 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
9218 let promise = self.new_promise();
9219 // §24.4.3.6 `DisposeResources` step 1: `needsAwait` is true as soon as the stack holds
9220 // any resource at all, because every `await using` resource has the async-dispose
9221 // hint — including the null/undefined ones that have nothing to call. If none of them
9222 // turned out to be awaitable, step 4 still performs one `Await(undefined)`, which is
9223 // why `stack.use(null); stack.disposeAsync()` settles one microtask later rather than
9224 // in the tick it was called from (`disposeAsync/explicit-await-for-null`).
9225 let needs_await = !resources.is_empty();
9226 let mut pairs = Vec::with_capacity(resources.len());
9227 for (value, method) in resources {
9228 let pair = self.new_array(vec![value, method]);
9229 pairs.push(Value::Object(pair));
9230 }
9231 let remaining = self.new_array(pairs);
9232 self.dispose_step(
9233 &remaining,
9234 &promise,
9235 Value::Uninitialized,
9236 false,
9237 needs_await,
9238 )?;
9239 Ok(Value::Object(promise))
9240 }
9241
9242 /// One link of the `disposeAsync` chain.
9243 ///
9244 /// Loops while the disposers finish synchronously, and parks on the first thenable it
9245 /// meets — pushing itself back in as the continuation, with the accumulated error
9246 /// carried along so a later failure can still be folded into the `SuppressedError`.
9247 fn dispose_step(
9248 &mut self,
9249 remaining: &Gc<JsObject>,
9250 promise: &Gc<JsObject>,
9251 mut error: Value,
9252 awaited: bool,
9253 needs_await: bool,
9254 ) -> JsResult<()> {
9255 loop {
9256 let length = remaining.array_length().unwrap_or(0);
9257 if length == 0 {
9258 // Step 4: `needsAwait` true and `hasAwaited` false means one `Await(undefined)`
9259 // still has to happen. Re-entering this same step past an already-fulfilled
9260 // promise is exactly one tick, and it keeps the folding of `error` in one place.
9261 if needs_await && !awaited {
9262 let finished = self.new_array(Vec::new());
9263 let thunk = JsObject::function(
9264 self.heap,
9265 Some(self.realm.function_proto.clone()),
9266 Callable::DisposeStep {
9267 remaining: finished.clone(),
9268 promise: promise.clone(),
9269 error,
9270 rejected: false,
9271 awaited: true,
9272 needs_await: false,
9273 },
9274 );
9275 let tick = self.promise_resolve_value(Value::Undefined)?;
9276 if let Value::Object(tick) = tick {
9277 self.perform_then(
9278 &tick,
9279 Some(Value::Object(thunk.clone())),
9280 Some(Value::Object(thunk)),
9281 )?;
9282 }
9283 return Ok(());
9284 }
9285 if matches!(error, Value::Uninitialized) {
9286 self.fulfill_promise(promise, Value::Undefined);
9287 } else {
9288 self.reject_promise(promise, error);
9289 }
9290 return Ok(());
9291 }
9292 let Some(Value::Object(pair)) = remaining
9293 .array_get(length - 1)
9294 .filter(|v| !matches!(v, Value::Hole))
9295 else {
9296 remaining.array_truncate(self.heap, length - 1);
9297 continue;
9298 };
9299 remaining.array_truncate(self.heap, length - 1);
9300 let value = pair.array_get(0).unwrap_or(Value::Undefined);
9301 let Some(Value::Object(method)) = pair.array_get(1) else {
9302 continue;
9303 };
9304 if !method.is_callable() {
9305 continue;
9306 }
9307 match self.call_value(Value::Object(method), value, Vec::new()) {
9308 Ok(result) => {
9309 if !self.is_thenable(&result)? {
9310 // Finished synchronously; the next disposer is the next iteration.
9311 continue;
9312 }
9313 let awaited = match self.promise_resolve_value(result) {
9314 Ok(awaited) => awaited,
9315 Err(Signal::Throw(reason)) => {
9316 self.reject_promise(promise, reason);
9317 return Ok(());
9318 }
9319 Err(other) => return Err(other),
9320 };
9321 let Value::Object(awaited) = awaited else {
9322 continue;
9323 };
9324 let ok = JsObject::function(
9325 self.heap,
9326 Some(self.realm.function_proto.clone()),
9327 Callable::DisposeStep {
9328 remaining: remaining.clone(),
9329 promise: promise.clone(),
9330 error: error.clone(),
9331 rejected: false,
9332 awaited: true,
9333 needs_await,
9334 },
9335 );
9336 let failed = JsObject::function(
9337 self.heap,
9338 Some(self.realm.function_proto.clone()),
9339 Callable::DisposeStep {
9340 remaining: remaining.clone(),
9341 promise: promise.clone(),
9342 error,
9343 rejected: true,
9344 awaited: true,
9345 needs_await,
9346 },
9347 );
9348 self.perform_then(
9349 &awaited,
9350 Some(Value::Object(ok)),
9351 Some(Value::Object(failed)),
9352 )?;
9353 return Ok(());
9354 }
9355 Err(Signal::Throw(thrown)) => {
9356 error = self.merge_dispose_error(thrown, error);
9357 }
9358 Err(other) => return Err(other),
9359 }
9360 }
9361 }
9362
9363 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
9364 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
9365 let Value::Object(object) = value else {
9366 return Ok(false);
9367 };
9368 Ok(matches!(
9369 self.get_property(object, "then")?,
9370 Some(Value::Object(then)) if then.is_callable()
9371 ))
9372 }
9373
9374 /// One step of an async generator, settling `promise` with an `{value, done}` result.
9375 fn step_async_generator(
9376 &mut self,
9377 generator: &Gc<JsObject>,
9378 promise: &Gc<JsObject>,
9379 kind: ResumeKind,
9380 value: Value,
9381 ) -> JsResult<()> {
9382 // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
9383 // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
9384 // is abrupt — a `constructor` getter that throws — the generator is resumed with a
9385 // *throw* completion instead, so the body's own `try { yield } catch` sees it:
9386 // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
9387 // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
9388 // out of the same read, one as a rejection and one as a rethrow.
9389 //
9390 // Narrow on purpose: only a value that is *already a promise* is inspected, so
9391 // nothing changes for `return 1` and the extra read is a plain data-property
9392 // lookup on the intrinsic case.
9393 if kind == ResumeKind::Return
9394 && let Value::Object(object) = &value
9395 && self.promise_state(object).is_some()
9396 && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
9397 {
9398 return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
9399 }
9400 let stepped = self.resume_generator_detailed(generator, kind, value);
9401 let (value, done, ready, reason) = match stepped {
9402 Ok(stepped) => stepped,
9403 Err(Signal::Throw(reason)) => {
9404 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
9405 }
9406 Err(other) => return Err(other),
9407 };
9408 // Only an `await` has to wait before the method can answer.
9409 if !done && reason == Some(SuspendKind::Await) {
9410 let awaited = match self.promise_resolve_value(value) {
9411 Ok(awaited) => awaited,
9412 Err(Signal::Throw(reason)) => {
9413 return self.settle_async_request(
9414 generator,
9415 promise,
9416 AsyncOutcome::Error(reason),
9417 );
9418 }
9419 Err(other) => return Err(other),
9420 };
9421 let Value::Object(awaited) = awaited else {
9422 return Ok(());
9423 };
9424 let resumed = JsObject::function(
9425 self.heap,
9426 Some(self.realm.function_proto.clone()),
9427 Callable::GeneratorResume {
9428 generator: generator.clone(),
9429 promise: promise.clone(),
9430 kind: ResumeKind::Next,
9431 },
9432 );
9433 let raised = JsObject::function(
9434 self.heap,
9435 Some(self.realm.function_proto.clone()),
9436 Callable::GeneratorResume {
9437 generator: generator.clone(),
9438 promise: promise.clone(),
9439 kind: ResumeKind::Throw,
9440 },
9441 );
9442 self.perform_then(
9443 &awaited,
9444 Some(Value::Object(resumed)),
9445 Some(Value::Object(raised)),
9446 )?;
9447 return Ok(());
9448 }
9449 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
9450 // completes it — both arrive as the settled value rather than as the promise
9451 // object. A plain value skips the round trip, which is also what keeps `yield 1`
9452 // from costing an extra tick.
9453 let awaits_value = self.is_thenable(&value)?;
9454 if awaits_value {
9455 // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
9456 // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
9457 // value that merely gets `yield`ed is awaited by the body's own `Await`, where
9458 // no `PromiseResolve` appears, so that path keeps the shortcut.
9459 let awaited = match if done {
9460 self.promise_resolve_intrinsic(value)
9461 } else {
9462 self.promise_resolve_value(value)
9463 } {
9464 Ok(awaited) => awaited,
9465 Err(Signal::Throw(reason)) => {
9466 return self.settle_async_request(
9467 generator,
9468 promise,
9469 AsyncOutcome::Error(reason),
9470 );
9471 }
9472 Err(other) => return Err(other),
9473 };
9474 let Value::Object(awaited) = awaited else {
9475 return Ok(());
9476 };
9477 // A rejected yield throws *at the yield* inside the body, so the rejection
9478 // resumes the generator rather than the method's promise.
9479 let answer = JsObject::function(
9480 self.heap,
9481 Some(self.realm.function_proto.clone()),
9482 Callable::YieldResult {
9483 generator: generator.clone(),
9484 promise: promise.clone(),
9485 done,
9486 },
9487 );
9488 let raise = JsObject::function(
9489 self.heap,
9490 Some(self.realm.function_proto.clone()),
9491 Callable::GeneratorResume {
9492 generator: generator.clone(),
9493 promise: promise.clone(),
9494 kind: ResumeKind::Throw,
9495 },
9496 );
9497 self.perform_then(
9498 &awaited,
9499 Some(Value::Object(answer)),
9500 Some(Value::Object(raise)),
9501 )?;
9502 return Ok(());
9503 }
9504 let result = if ready {
9505 // `yield*` handed back the inner iterator's own result object.
9506 value
9507 } else {
9508 self.iterator_result(value, done)?
9509 };
9510 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
9511 }
9512
9513 /// The `{value, done}` object an iterator method answers with.
9514 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
9515 let result = self.new_object(Some(self.realm.object_proto.clone()));
9516 result.define_data("value", value);
9517 result.define_data("done", Value::Bool(done));
9518 Ok(Value::Object(result))
9519 }
9520
9521 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
9522 fn step_generator(
9523 &mut self,
9524 state: &mut GeneratorState,
9525 kind: ResumeKind,
9526 value: Value,
9527 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9528 match state.phase {
9529 GeneratorPhase::Executing => {
9530 return Err(self.type_error("cannot invoke a running generator"));
9531 }
9532 GeneratorPhase::Completed => {
9533 // A finished generator answers every resumption without running.
9534 return Ok(match kind {
9535 ResumeKind::Throw => return Err(Signal::Throw(value)),
9536 ResumeKind::Return => (value, true, false, None),
9537 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
9538 });
9539 }
9540 GeneratorPhase::SuspendedStart => {
9541 if kind != ResumeKind::Next && kind != ResumeKind::Start {
9542 // The body never started, so there is nothing to unwind or return
9543 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
9544 state.frame = None;
9545 state.phase = GeneratorPhase::Completed;
9546 return Ok(match kind {
9547 ResumeKind::Throw => return Err(Signal::Throw(value)),
9548 _ => (value, true, false, None),
9549 });
9550 }
9551 }
9552 GeneratorPhase::SuspendedYield => {}
9553 }
9554
9555 let Some(mut frame) = state.frame.take() else {
9556 return Ok((Value::Undefined, true, false, None));
9557 };
9558 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
9559 // number that says which method resumed it; the emitted `if_false` branches on
9560 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
9561 let mut raised = None;
9562 match kind {
9563 ResumeKind::Next | ResumeKind::Start => {
9564 if state.phase == GeneratorPhase::SuspendedYield {
9565 frame.stack.push(value);
9566 // An `await` resumes with its value alone; only a `yield` gets the
9567 // magic number that says which of `next`/`return` resumed it.
9568 if !state.parked_on_await {
9569 frame.stack.push(Value::Int(RESUME_NEXT));
9570 }
9571 }
9572 }
9573 ResumeKind::Return => {
9574 // A `return` on a not-yet-started generator is handled above, so this is
9575 // always a real resumption.
9576 frame.stack.push(value);
9577 frame.stack.push(Value::Int(RESUME_RETURN));
9578 }
9579 ResumeKind::Throw => {
9580 // At a `yield*` the exception is *data* for the delegation: the compiled
9581 // code resumes with the value and magic `2` and calls the inner iterator's
9582 // `throw`. Everywhere else it is raised at the suspension point, so the
9583 // body's own handler sees it.
9584 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
9585 frame.stack.push(value);
9586 frame.stack.push(Value::Int(RESUME_THROW));
9587 } else {
9588 raised = Some(value);
9589 }
9590 }
9591 }
9592 state.phase = GeneratorPhase::Executing;
9593
9594 let depth = self.frames.len();
9595 self.frames.push(frame);
9596 // A `throw` unwinds from where the frame parked, exactly as if the exception had
9597 // happened at the `yield`.
9598 if let Some(mut exception) = raised {
9599 if self.catch_here(&mut exception).is_none() {
9600 self.pop_frame();
9601 state.phase = GeneratorPhase::Completed;
9602 return Err(Signal::Throw(exception));
9603 }
9604 }
9605
9606 // Only the generator's *own* frame ends the generator. The body may call ordinary
9607 // functions, and those push frames of their own: a `Step::Return` from one of them
9608 // is a nested call finishing, not the generator completing. Miscounting that is
9609 // silent — the generator reports the callee's value as its own result and marks
9610 // itself done — so the depth comparison is load-bearing, not defensive.
9611 let own_frame = depth + 1;
9612 loop {
9613 match self.step() {
9614 Ok(Step::Continue) => {}
9615 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9616 let mut frame = self.frames.pop().expect("a frame is live");
9617 // `yield` left the value on the stack; `initial_yield` left nothing.
9618 let yielded = if reason == SuspendKind::Initial {
9619 Value::Undefined
9620 } else {
9621 frame.stack.pop().unwrap_or(Value::Undefined)
9622 };
9623 state.frame = Some(frame);
9624 state.parked_on_await = reason == SuspendKind::Await;
9625 state.parked_on_yield_star =
9626 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9627 state.phase = if reason == SuspendKind::Initial {
9628 GeneratorPhase::SuspendedStart
9629 } else {
9630 GeneratorPhase::SuspendedYield
9631 };
9632 // `yield*` hands the inner iterator's own result object straight
9633 // back, so the caller sees one `{value, done}` rather than a nested
9634 // one — which is why the third field says "already a result".
9635 return Ok((
9636 yielded,
9637 false,
9638 reason == SuspendKind::YieldStar,
9639 Some(reason),
9640 ));
9641 }
9642 Ok(Step::Suspend(_)) => {
9643 // A `yield` in a frame other than the generator's would mean a
9644 // generator body entered as an ordinary call, which
9645 // `call_or_push` prevents.
9646 self.unwind_to(depth);
9647 state.phase = GeneratorPhase::Completed;
9648 return Err(Signal::Throw(self.make_error(
9649 "InternalError",
9650 "a generator body ran as an ordinary call",
9651 )));
9652 }
9653 Ok(Step::Return(value)) => {
9654 self.pop_frame();
9655 if self.frames.len() > depth {
9656 // A nested call finished: hand the value back to its caller and
9657 // keep running the generator body.
9658 self.frames
9659 .last_mut()
9660 .expect("a caller is live")
9661 .stack
9662 .push(value);
9663 continue;
9664 }
9665 state.phase = GeneratorPhase::Completed;
9666 // The reference closes the generator's closure variables here; ours
9667 // live in cells the frame owned, which the drop below releases.
9668 return Ok((value, true, false, None));
9669 }
9670 Err(Signal::Throw(exception)) => {
9671 // The frame that threw gets the first chance to catch, exactly as in
9672 // the ordinary call loop; a frame above the generator's is popped and
9673 // the exception carries on down.
9674 let mut exception = exception;
9675 loop {
9676 if self.frames.len() <= depth {
9677 // The generator's own frame is gone, so nothing here caught it.
9678 state.phase = GeneratorPhase::Completed;
9679 return Err(Signal::Throw(exception));
9680 }
9681 if self.catch_here(&mut exception).is_some() {
9682 break;
9683 }
9684 self.pop_frame();
9685 }
9686 }
9687 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9688 }
9689 }
9690 }
9691
9692 /// Pop frames until `depth` are left, keeping their buffers.
9693 fn unwind_to(&mut self, depth: usize) {
9694 while self.frames.len() > depth {
9695 self.pop_frame();
9696 }
9697 }
9698 fn call_or_push(
9699 &mut self,
9700 callee: Value,
9701 this: Value,
9702 args: Vec<Value>,
9703 ) -> JsResult<Option<Value>> {
9704 if let Value::Object(function) = &callee
9705 && let Some((code, env)) = bytecode_of(function)
9706 {
9707 // Calling a generator function does not run anything: it captures the
9708 // arguments in a frame and hands back the generator object.
9709 if code.code.kind.is_generator() {
9710 return self.new_generator(callee, this, args).map(Some);
9711 }
9712 // An async function answers a promise and runs its body as a coroutine, so it
9713 // takes the same path as a plain call into it.
9714 if code.code.kind.is_async() {
9715 return self.new_async_function(callee, this, args).map(Some);
9716 }
9717 self.push_frame(code, env, this, args, callee)?;
9718 return Ok(None);
9719 }
9720 self.call_value(callee, this, args).map(Some)
9721 }
9722
9723 /// `new callee(args)`.
9724 ///
9725 /// A constructor differs from a plain call in three ways: it gets a fresh object
9726 /// as `this` whose prototype is the constructor's `prototype` property, its
9727 /// return value is *replaced* by that object unless it returns an object itself,
9728 /// and a native constructor is expected to initialise the object it is given
9729 /// rather than build one.
9730 pub fn construct(
9731 &mut self,
9732 callee: Value,
9733 new_target: Value,
9734 args: Vec<Value>,
9735 ) -> JsResult<Value> {
9736 // `new` on a bound function constructs its *target*, prepending the arguments
9737 // the bind fixed and ignoring the bound `this` — a bound function is a
9738 // constructor only when its target is one, and `new` always makes a fresh
9739 // object of the target's prototype rather than reusing the bound receiver.
9740 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9741 // ran the body with `this === null` and threw on `this.x = a`.
9742 let mut callee = callee;
9743 let mut new_target = new_target;
9744 let mut args = args;
9745 loop {
9746 let Some(object) = callee.as_object().cloned() else {
9747 return Err(Signal::Throw(
9748 self.make_error("TypeError", "not a constructor"),
9749 ));
9750 };
9751 // A proxy of a function constructs through its `construct` trap, and the
9752 // trap's answer is the result directly — no fresh object is made here.
9753 if object.proxy_state().is_some() {
9754 return match self.proxy_construct(&object, args, &new_target)? {
9755 Some(result) => Ok(result),
9756 None => Err(Signal::Throw(
9757 self.make_error("TypeError", "proxy target is not a constructor"),
9758 )),
9759 };
9760 }
9761 // A generator function has no `[[Construct]]`, and the reference names it in
9762 // the message: `new (function* G(){})()` reports "G is not a constructor".
9763 if object.with(|data| match &data.kind {
9764 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9765 code.code.kind.is_generator()
9766 }
9767 _ => false,
9768 }) {
9769 let name = object
9770 .own_property("name")
9771 .and_then(|property| property.value)
9772 .map(|value| value.to_js_string())
9773 .unwrap_or_default();
9774 return Err(Signal::Throw(
9775 self.make_error("TypeError", &format!("{name} is not a constructor")),
9776 ));
9777 }
9778 let bound = object.with(|data| match &data.kind {
9779 ObjectKind::Function(Callable::Bound {
9780 target,
9781 args: leading,
9782 ..
9783 }) => Some((target.clone(), leading.clone())),
9784 _ => None,
9785 });
9786 let Some((target, leading)) = bound else {
9787 // Not a bound function, so this object is the callee. §7.2.4
9788 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9789 // refusals above cover only the built-ins the reference also refuses by
9790 // name. Everything else — a method, an arrow, an async function — has no
9791 // `[[Construct]]` either, and answering "yes" here made
9792 // `new (Array.prototype.map)` build an object instead of throwing.
9793 if !object.is_constructor() {
9794 let name = object
9795 .own_property("name")
9796 .and_then(|property| property.value)
9797 .map(|value| value.to_js_string())
9798 .unwrap_or_default();
9799 return Err(Signal::Throw(
9800 self.make_error("TypeError", &format!("{name} is not a constructor")),
9801 ));
9802 }
9803 break;
9804 };
9805 let mut all = leading;
9806 all.extend(args);
9807 args = all;
9808 // A bound function that is its own `new.target` stands in for its target:
9809 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9810 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9811 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9812 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9813 _ => false,
9814 };
9815 if same_wrapper {
9816 new_target = target.clone();
9817 }
9818 callee = target;
9819 }
9820 let Value::Object(function) = &callee else {
9821 unreachable!("the loop above only breaks on an object");
9822 };
9823 // The fresh object's prototype comes from `new.target`, not from the callee: a
9824 // derived constructor reaches here through `super()`, and the instance must be a
9825 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9826 // an object inheriting `D.prototype` rather than `C.prototype`.
9827 let prototype_source = match new_target.as_object() {
9828 Some(target) => target.clone(),
9829 None => function.clone(),
9830 };
9831 // A native constructor builds its own instance, through `new_ctor_instance`, once it
9832 // has validated its arguments. Pre-building one here would read
9833 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9834 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9835 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9836 let is_native = function.native_creates_own_instance();
9837 let this = if is_native {
9838 Value::Undefined
9839 } else {
9840 let prototype = self.get_property(&prototype_source, "prototype")?;
9841 let prototype = match prototype {
9842 Some(Value::Object(proto)) => Some(proto),
9843 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
9844 // object, the answer is the realm's *intrinsic* prototype for this
9845 // constructor, not `%Object.prototype%`.
9846 _ => {
9847 // `GetPrototypeFromConstructor` step 4 is `GetFunctionRealm(constructor)`,
9848 // and that is a `TypeError` for a revoked proxy. Without it, `new
9849 // revokedProxy()` quietly produced an `%Object.prototype%` instance —
9850 // `base-ctor-revoked-proxy` revokes the proxy from inside its own `get`
9851 // trap, so it is already revoked when this fallback runs.
9852 if prototype_source.proxy_state().is_some() {
9853 self.proxy_parts(&prototype_source)?;
9854 }
9855 let fallback = self.get_property(function, "prototype")?;
9856 match fallback {
9857 Some(Value::Object(proto)) => Some(proto),
9858 _ => Some(self.realm.object_proto.clone()),
9859 }
9860 }
9861 };
9862 Value::Object(self.new_object(prototype))
9863 };
9864 // `new.target` inside the body is the constructor that was written, so a bound
9865 // function's target sees itself rather than the bound wrapper.
9866 //
9867 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
9868 // `?`, so assigning `None` after the call would be skipped and the failed
9869 // `new.target` would stay visible to every later native call. The symptom was a
9870 // native constructor refusing a plain call — `var s = Symbol(); new
9871 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
9872 // "FinalizationRegistry is not a constructor".
9873 let outer_new_target = self.pending_new_target.replace(new_target);
9874 let callee = callee.clone();
9875 let result = self.call_value(callee, this.clone(), args);
9876 self.pending_new_target = outer_new_target;
9877 let result = result?;
9878 // A constructor that returns an object overrides `this`; any other return value
9879 // (including `undefined`) is ignored — **except** in a derived constructor, where
9880 // §15.7.1 step 12 makes a non-object return a `TypeError`
9881 // (`Function/internals/Construct/derived-return-val`).
9882 let derived = function.with(|data| match &data.kind {
9883 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9884 code.code.is_derived_constructor
9885 }
9886 _ => false,
9887 });
9888 Ok(match result {
9889 Value::Object(_) => result,
9890 // A bare `return;` answers `undefined`, which is **legal** even in a derived
9891 // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
9892 Value::Undefined => this,
9893 _ if derived => {
9894 return Err(Signal::Throw(self.make_error(
9895 "TypeError",
9896 "derived constructor may only return an object or undefined",
9897 )));
9898 }
9899 _ => this,
9900 })
9901 }
9902
9903 /// `new.target` for the call currently being made.
9904 ///
9905 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9906 /// it as `this`), but a *host* constructor that builds its own instance is handed
9907 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9908 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9909 /// it here.
9910 ///
9911 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9912 /// receives for a plain call.
9913 pub fn current_new_target(&self) -> Value {
9914 self.active_new_target.clone()
9915 }
9916
9917 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9918 ///
9919 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9920 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9921 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9922 let constructor = self.realm.errors.get("AggregateError").cloned();
9923 let Some(constructor) = constructor else {
9924 return self.make_error("AggregateError", message);
9925 };
9926 let list = self.new_array(errors);
9927 match self.construct(
9928 Value::Object(constructor.clone()),
9929 Value::Object(constructor),
9930 vec![Value::Object(list), self.string(message)],
9931 ) {
9932 Ok(value) => value,
9933 // A user could have replaced `AggregateError` with something that throws; the
9934 // engine still owes the caller a rejection, so it falls back rather than
9935 // turning `Promise.any`'s rejection into a throw.
9936 Err(_) => self.make_error("AggregateError", message),
9937 }
9938 }
9939
9940 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9941 ///
9942 /// The error classes themselves arrive with the builtins milestone; what
9943 /// matters here is that the thrown value stringifies the way a script printing
9944 /// the caught value expects.
9945 ///
9946 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9947 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9948 /// rely on when they print a caught value.
9949 pub fn make_error(&self, name: &str, message: &str) -> Value {
9950 let proto = self
9951 .realm
9952 .errors
9953 .get(name)
9954 .map(|constructor| self.prototype_of(constructor))
9955 .unwrap_or_else(|| self.realm.error_proto.clone());
9956 let error = self.new_object(Some(proto));
9957 // `name` and `message` are own properties of the instance, which is what
9958 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9959 // `Error`.
9960 error.define(
9961 "name",
9962 Property::with_attributes(self.string(name), true, false),
9963 );
9964 error.define(
9965 "message",
9966 Property::with_attributes(self.string(message), true, false),
9967 );
9968 // The internal class, which is what tells a printer this is an error rather than a
9969 // plain object with `name` and `message` properties. The constructor path sets it
9970 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9971 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
9972 // literally `"Error"` in both places — the *name* is read from `name`, which is why
9973 // a `RangeError` still prints as `RangeError`.
9974 self.internal_set(&error, "_class", self.string("Error"));
9975 // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
9976 // answered `false` from `Error.isError` while a constructed one answered `true`,
9977 // because only the constructor set the slot. The reference answers `true` for both
9978 // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
9979 // accessor gated on this slot the omission stopped being cosmetic: `print_error`
9980 // tests `typeof stack === "string"` to decide on a trailing newline, so every
9981 // engine-thrown error lost its blank line.
9982 self.internal_set(&error, "_error_data", Value::Bool(true));
9983 // The trace is captured where the error is *made*, which is where the reference
9984 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
9985 // way out, so a caught engine error already has its stack even if the handler
9986 // never rethrows it.
9987 self.add_stack(&error);
9988 Value::Object(error)
9989 }
9990
9991 /// Give an error object its `stack` property, from the current frame stack.
9992 ///
9993 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
9994 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
9995 /// `stack` a script set, is not rewritten.
9996 pub fn add_stack(&self, object: &Gc<JsObject>) {
9997 self.add_stack_skipping(object, 0);
9998 }
9999
10000 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
10001 ///
10002 /// An `Error` constructor passes 1: the reference builds those traces with
10003 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
10004 /// constructor itself, while a `RangeError` raised inside `toISOString` does
10005 /// report `at toISOString (native)`.
10006 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
10007 if object.has_own("stack") {
10008 return;
10009 }
10010 // The trace is *captured* here but not installed as a property: `stack` is an
10011 // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
10012 // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
10013 // is kept in a hidden slot and the getter materialises it on first read.
10014 //
10015 // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
10016 // shows it — this is the same discipline `_error_data` and `_class` follow.
10017 let trace = self.stack_trace_skipping(skip);
10018 let text = self.string(trace);
10019 self.internal_set(object, "_stack_trace", text);
10020 }
10021
10022 /// The function object currently being called, if any.
10023 ///
10024 /// A native function is a bare `fn` pointer, so it cannot capture which class
10025 /// it belongs to; it reads that from the callee instead. This is also what a
10026 /// stack trace would use.
10027 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
10028 match &self.frames.last()?.callee {
10029 Value::Object(object) => Some(object.clone()),
10030 _ => None,
10031 }
10032 }
10033
10034 /// The `prototype` property of a constructor, falling back to
10035 /// `Object.prototype` for anything that is not shaped like one.
10036 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
10037 constructor
10038 .own_property("prototype")
10039 .and_then(|property| property.value)
10040 .and_then(|value| value.as_object().cloned())
10041 .unwrap_or_else(|| self.realm.object_proto.clone())
10042 }
10043
10044 /// Throw a `TypeError` carrying `message`.
10045 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
10046 Signal::Throw(self.make_error("TypeError", message.as_ref()))
10047 }
10048
10049 /// Throw a `RangeError` carrying `message`.
10050 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
10051 Signal::Throw(self.make_error("RangeError", message.as_ref()))
10052 }
10053
10054 /// A `ReferenceError`, as the value to throw.
10055 ///
10056 /// `throw` uses it for "called on a disposed stack": `DisposableStack.prototype.defer`
10057 /// and its siblings report a `ReferenceError` there, which is what
10058 /// `adopt|defer|move/throws-if-disposed` assert.
10059 pub fn reference_error(&self, message: impl AsRef<str>) -> Signal {
10060 Signal::Throw(self.make_error("ReferenceError", message.as_ref()))
10061 }
10062
10063 /// The `ReferenceError` a read of an uninitialised binding raises.
10064 /// The name of the binding `slot` refers to, for an error message.
10065 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
10066 match kind {
10067 VarSlot::Loc => self
10068 .frame()
10069 .code
10070 .code
10071 .vars
10072 .get(slot)
10073 .map(|v| v.name.clone()),
10074 VarSlot::Closure => self
10075 .frame()
10076 .code
10077 .code
10078 .closure_vars
10079 .get(slot)
10080 .map(|c| c.name.clone()),
10081 }
10082 .unwrap_or_default()
10083 }
10084
10085 /// Whether `slot` names a `const` binding, which rejects every store after its
10086 /// initialiser.
10087 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
10088 match kind {
10089 VarSlot::Loc => self
10090 .frame()
10091 .code
10092 .code
10093 .vars
10094 .get(slot)
10095 .is_some_and(|v| v.is_const),
10096 VarSlot::Closure => self
10097 .frame()
10098 .code
10099 .code
10100 .closure_vars
10101 .get(slot)
10102 .is_some_and(|c| c.is_const),
10103 }
10104 }
10105
10106 /// The `TypeError` a store to a `const` binding raises.
10107 ///
10108 /// `const` is enforced here rather than at compile time because the binding can be
10109 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
10110 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
10111 /// both halves of what "checked store" means: the dead zone is over, and the
10112 /// binding is writable.
10113 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
10114 let name = self.binding_name(slot, kind);
10115 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
10116 }
10117
10118 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
10119 let name = match kind {
10120 VarSlot::Loc => self
10121 .frame()
10122 .code
10123 .code
10124 .vars
10125 .get(slot)
10126 .map(|v| v.name.clone()),
10127 VarSlot::Closure => self
10128 .frame()
10129 .code
10130 .code
10131 .closure_vars
10132 .get(slot)
10133 .map(|c| c.name.clone()),
10134 }
10135 .unwrap_or_default();
10136 Signal::Throw(self.make_error(
10137 "ReferenceError",
10138 &format!("cannot access '{name}' before initialization"),
10139 ))
10140 }
10141
10142 fn throw_reference(&self, name: &str) -> Signal {
10143 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
10144 }
10145
10146 // -- the instruction loop -----------------------------------------------
10147
10148 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
10149 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
10150 // measured at 16% of a tight arithmetic loop's total time.
10151 #[inline(always)]
10152 fn step(&mut self) -> JsResult<Step> {
10153 // The instruction is already decoded (see [`crate::insn`]), so this is an index
10154 // and a `Copy` read rather than a table lookup plus a width switch. Only the
10155 // borrow lives across the boundary; nothing is cloned.
10156 // **One** borrow of the frame: fetch the record, then advance in the same scope.
10157 // The obvious version borrowed it three times (`last` to read, `last_mut` to
10158 // write, and once more inside the handler), and each is a bounds check plus an
10159 // `Option` unwrap — on the one path every instruction takes.
10160 let Some((insn, next)) = ({
10161 let frame = self
10162 .frames
10163 .last_mut()
10164 .expect("step() is only called with a live frame");
10165 // Past the last instruction is a normal return: the compiler ends a function
10166 // with `return`, and a jump to the end of a block lands here.
10167 let insn = frame.insns().get(frame.pc).copied();
10168 match insn {
10169 None => None,
10170 Some(insn) => {
10171 // A fused record stands for the next few instructions, so the next
10172 // `pc` is its width ahead — the instructions it replaces are never
10173 // dispatched. `at` is the byte offset a stack trace reports; it stays
10174 // an offset because the line table is keyed by bytes.
10175 frame.at = insn.offset as usize;
10176 frame.pc += insn.width();
10177 Some((insn, frame.pc))
10178 }
10179 }
10180 }) else {
10181 return Ok(Step::Return(Value::Undefined));
10182 };
10183 self.check_memory()?;
10184 self.check_interrupt()?;
10185 if insn.fused == crate::insn::Fused::None {
10186 self.execute_instruction(insn.op, insn.a, insn.b, next)
10187 } else {
10188 self.execute_fused(insn)
10189 }
10190 }
10191
10192 /// Run a fused instruction: several bytecode instructions in one dispatch.
10193 ///
10194 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
10195 /// it cannot throw and cannot allocate — and anything else falls back to the real
10196 /// instructions, in their real order, so an exception leaves the operand stack
10197 /// exactly as it would have been.
10198 #[inline]
10199 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
10200 use crate::insn::Fused;
10201 let slot = insn.a as usize;
10202 match insn.fused {
10203 // `x = k`: `push k; put_loc x`.
10204 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
10205 // `x += k`: `get_loc x; push k; add; put_loc x`.
10206 Fused::AddImmLoc => {
10207 let delta = insn.b as i32;
10208 match self.get_loc(slot) {
10209 Value::Int(left) => {
10210 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
10211 // that built two `Value`s, called a function, and matched on them
10212 // again to reach this same `checked_add`. It is the innermost
10213 // operation of every accumulator in every program.
10214 let answer = match left.checked_add(delta) {
10215 Some(sum) => Value::Int(sum),
10216 None => Value::Float(left as f64 + delta as f64),
10217 };
10218 self.put_loc(slot, answer);
10219 }
10220 other => {
10221 self.push(other);
10222 self.push(Value::Int(delta));
10223 self.binary_add()?;
10224 let value = self.pop();
10225 self.put_loc(slot, value);
10226 }
10227 }
10228 }
10229 // `x += "literal"` and `x += y`: the two shapes that can append in place.
10230 Fused::AddAtomLoc => {
10231 let text = self.atom_wtf8(insn.b as usize);
10232 let right = self.string_wtf8(text);
10233 self.add_into_loc(slot, right)?;
10234 }
10235 Fused::AddLocLoc => {
10236 let source = (insn.a & 0xFFFF) as usize;
10237 let target = (insn.a >> 16) as usize;
10238 let right = self.get_loc(source);
10239 self.add_into_loc(target, right)?;
10240 }
10241 Fused::AddArgLoc => {
10242 let source = (insn.a & 0xFFFF) as usize;
10243 let target = (insn.a >> 16) as usize;
10244 let right = self.get_arg(source);
10245 self.add_into_loc(target, right)?;
10246 }
10247 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
10248 Fused::PostIncLoc => match self.get_loc(slot) {
10249 Value::Int(left) => {
10250 let answer = match left.checked_add(1) {
10251 Some(sum) => Value::Int(sum),
10252 None => Value::Float(left as f64 + 1.0),
10253 };
10254 self.put_loc(slot, answer);
10255 }
10256 other => {
10257 self.push(other);
10258 let raw = self.pop();
10259 let (old, updated) = self.advance_numeric(raw, true)?;
10260 self.push(old);
10261 self.push(updated);
10262 let value = self.pop();
10263 self.put_loc(slot, value);
10264 self.pop();
10265 }
10266 },
10267 // `if (!(x < arg)) goto target`: a loop header.
10268 //
10269 // The comparison is computed rather than replayed on the operand stack. That
10270 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
10271 // that throws: the effects happen in the same order, and a handler truncates
10272 // the stack down to its marker, so the intermediate values are unobservable.
10273 Fused::LtLocArgJump => {
10274 let loc = (insn.a >> 16) as usize;
10275 let arg = (insn.a & 0xFFFF) as usize;
10276 let left = self.get_loc(loc);
10277 let right = self.get_arg(arg);
10278 let taken = match (&left, &right) {
10279 (Value::Int(left), Value::Int(right)) => !(left < right),
10280 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10281 };
10282 if taken {
10283 self.frame_mut().pc = insn.b as usize;
10284 }
10285 }
10286 // `i < k` in a loop header, where `k` is an integer literal.
10287 Fused::LtLocImmJump => {
10288 let left = self.get_loc(insn.a as usize);
10289 let right = Value::Int(insn.imm as i32);
10290 let taken = match &left {
10291 Value::Int(left) => !(*left < insn.imm as i32),
10292 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
10293 };
10294 if taken {
10295 self.frame_mut().pc = insn.b as usize;
10296 }
10297 }
10298 Fused::None => unreachable!("only called for a fused record"),
10299 }
10300 Ok(Step::Continue)
10301 }
10302
10303 /// Run records that cannot call script, cannot throw and cannot change frames.
10304 ///
10305 /// Returns `Some(value)` when the function ran off the end of its instructions (a
10306 /// normal return), and `None` when it stopped in front of an instruction the slow path
10307 /// has to handle — `pc` is written back either way, so `step` resumes at the right
10308 /// place.
10309 ///
10310 /// **The invariant is the whole point.** Every arm here is restricted to work that
10311 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
10312 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
10313 /// that the memory limit has to see. An opcode whose operands turn out to need any of
10314 /// that **stops the loop** instead of trying, so the slow path gets the instruction
10315 /// untouched and with its operands still on the stack. That is why the fallback is a
10316 /// `break` and not a duplicated slow arm: a second implementation of the same
10317 /// semantics is how a wrong answer gets in with no test noticing.
10318 ///
10319 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
10320 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
10321 fn run_fast(&mut self) -> JsResult<Option<Value>> {
10322 use crate::insn::Fused;
10323 // The outer loop exists only so a `Call` can come back through here: once a
10324 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
10325 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
10326 // frame. Re-entering re-reads both from whichever frame is now on top. Every
10327 // other exit from the inner loop returns, so this costs one loop per call.
10328 'outer: loop {
10329 // One reference-count bump per *slow* instruction (a call, an allocation, a
10330 // property access), never one per instruction — that distinction is worth
10331 // two orders of magnitude and was measured as such.
10332 let (code, mut pc) = {
10333 let frame = self.frame();
10334 (frame.code.clone(), frame.pc)
10335 };
10336 let insns = &code.insns;
10337 loop {
10338 let Some(insn) = insns.get(pc).copied() else {
10339 self.frame_mut().pc = pc;
10340 return Ok(Some(Value::Undefined));
10341 };
10342 match insn.fused {
10343 // `x = k`
10344 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
10345 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
10346 // object — stops the loop so `binary_add` can decide.
10347 Fused::AddImmLoc => {
10348 let slot = insn.a as usize;
10349 let delta = insn.b as i32;
10350 let Value::Int(left) = self.get_loc(slot) else {
10351 return Ok(self.stop(pc));
10352 };
10353 let sum = match left.checked_add(delta) {
10354 Some(sum) => Value::Int(sum),
10355 None => Value::Float(left as f64 + delta as f64),
10356 };
10357 self.put_loc(slot, sum);
10358 }
10359 // `x += "literal"` / `x += y`: the operand is a string, so the append
10360 // either allocates one or grows one. Both are the slow path's business;
10361 // the fusion's job is only to make the *slot* the sole owner, which is what
10362 // `execute_fused` needs and what `get_loc` alone destroys.
10363 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
10364 return Ok(self.stop(pc));
10365 }
10366 // `x++` on an integer, old value dropped.
10367 Fused::PostIncLoc => {
10368 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
10369 // value is read in place and overwritten in place, so the reference
10370 // count it held is released by the same assignment that stores the
10371 // new one. `get_loc` plus `put_loc` did two borrows, two table
10372 // lookups and a clone, and this arm is the whole body of a counting
10373 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
10374 let slot = insn.a as usize;
10375 let frame = self.frames.last_mut().expect("a frame is live");
10376 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
10377 let target = if cell < 0 {
10378 frame.locals.get_mut(slot)
10379 } else {
10380 None
10381 };
10382 let Some(target) = target else {
10383 return Ok(self.stop(pc));
10384 };
10385 let Value::Int(left) = *target else {
10386 return Ok(self.stop(pc));
10387 };
10388 *target = match left.checked_add(1) {
10389 Some(sum) => Value::Int(sum),
10390 None => Value::Float(left as f64 + 1.0),
10391 };
10392 }
10393 // A loop header, `if (!(x < arg)) goto target`, with both sides already
10394 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
10395 // bound stayed small integers.
10396 Fused::LtLocArgJump => {
10397 let loc = (insn.a >> 16) as usize;
10398 let arg = (insn.a & 0xFFFF) as usize;
10399 // One borrow for both slots: this arm *is* the whole loop of a
10400 // `for (i = 0; i < n; i++)` with an argument bound, so a second
10401 // `frames.last()` here is paid on every iteration. Measured 7.5% on
10402 // `dispatch:empty-loop`.
10403 let (left, right) = {
10404 let frame = self.frame();
10405 (frame.read_loc(loc), frame.read_arg(arg))
10406 };
10407 // Heavily measured: the bound is very often a `Float` even when the
10408 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
10409 // `JSON.parse` or a division is one — so requiring both sides to be
10410 // `Int` sent every iteration of those loops down the slow path. The
10411 // comparison below is the same one `relational` makes for two numbers.
10412 if !is_number(&left) || !is_number(&right) {
10413 return Ok(self.stop(pc));
10414 }
10415 // `if_false` branches on the comparison being false, which is **not**
10416 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
10417 // `>=` is also false and would keep it running forever. Clippy wants the
10418 // negation folded; that would be a wrong answer.
10419 let ordered = left.to_number() < right.to_number();
10420 let take_branch = !ordered;
10421 if take_branch {
10422 pc = insn.b as usize;
10423 continue;
10424 }
10425 }
10426 // The same header with a literal bound: `if (!(x < k)) goto target`.
10427 // The bound is an immediate, so only the counter needs a type test.
10428 #[allow(clippy::neg_cmp_op_on_partial_ord)]
10429 Fused::LtLocImmJump => {
10430 let left = self.get_loc(insn.a as usize);
10431 if !is_number(&left) {
10432 return Ok(self.stop(pc));
10433 }
10434 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
10435 if take_branch {
10436 pc = insn.b as usize;
10437 continue;
10438 }
10439 }
10440 Fused::None => match insn.op {
10441 // -- branches ---------------------------------------------------
10442 // A jump is an assignment now, because the target is an instruction
10443 // index. No arithmetic, no resolution table.
10444 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10445 let target = insn.a as usize;
10446 // A **back-edge** is a loop, and it is the only place an
10447 // instruction-level checkpoint can stop one: `for(;;){}` compiles
10448 // to a jump to itself and never leaves this loop, so the
10449 // per-instruction checks in `step` never run. That is exactly the
10450 // hole this arm closes — a host's `JS_SetInterruptHandler` did
10451 // nothing to a `for(;;){}` until it did, which is what
10452 // `tests/c/embed.c` is for.
10453 //
10454 // Polling here rather than on every instruction in this loop is
10455 // also the reference's choice (`OP_goto` calls
10456 // `js_poll_interrupts`), and it costs one compare per branch
10457 // instead of one decrement per instruction.
10458 if target <= pc {
10459 self.frame_mut().pc = target;
10460 self.check_memory()?;
10461 self.check_interrupt()?;
10462 }
10463 pc = target;
10464 continue;
10465 }
10466 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
10467 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
10468 let taken = self.pop().to_boolean();
10469 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
10470 if taken == want {
10471 pc = insn.a as usize;
10472 continue;
10473 }
10474 }
10475 // -- slot access -------------------------------------------------
10476 // A load's slot is already an operand (see `insn::implicit_operand`);
10477 // a captured one goes through its cell, which runs no script.
10478 Opcode::GetLoc
10479 | Opcode::GetLoc8
10480 | Opcode::GetLoc0
10481 | Opcode::GetLoc1
10482 | Opcode::GetLoc2
10483 | Opcode::GetLoc3 => {
10484 let value = self.get_loc(insn.a as usize);
10485 self.push(value);
10486 }
10487 Opcode::PutLoc
10488 | Opcode::PutLoc8
10489 | Opcode::PutLoc0
10490 | Opcode::PutLoc1
10491 | Opcode::PutLoc2
10492 | Opcode::PutLoc3 => {
10493 let value = self.pop();
10494 self.put_loc(insn.a as usize, value);
10495 }
10496 Opcode::GetArg
10497 | Opcode::GetArg0
10498 | Opcode::GetArg1
10499 | Opcode::GetArg2
10500 | Opcode::GetArg3 => {
10501 let value = self.get_arg(insn.a as usize);
10502 self.push(value);
10503 }
10504 Opcode::PutArg
10505 | Opcode::PutArg0
10506 | Opcode::PutArg1
10507 | Opcode::PutArg2
10508 | Opcode::PutArg3 => {
10509 let value = self.pop();
10510 self.put_arg(insn.a as usize, value);
10511 }
10512 // `a[i]` with an integer index on a dense array: see `fast_array_get`
10513 // for why a non-hole own element is exactly the slow path's answer.
10514 // The two operands are *peeked*, so a miss leaves the stack as the
10515 // slow path expects to find it.
10516 Opcode::GetArrayEl => {
10517 // One lookup, not two. The guard used `if …is_some()` and the arm
10518 // then called it again to get the value — two `peek`s, two
10519 // `array_get`s and two `Value` clones for one element.
10520 // `fast_array_get` was 13.1% of `array:indexed`, and the same
10521 // double call was the first version of the `get_field` fast path.
10522 let Some(value) = self.fast_array_get() else {
10523 return Ok(self.stop(pc));
10524 };
10525 // `a[i]` consumes both operands and leaves the element in their
10526 // place: one `truncate` and one write, no `pop`/`push` pair.
10527 let frame = self.frame_mut();
10528 frame.stack.truncate(frame.stack.len() - 2);
10529 frame.stack.push(value);
10530 }
10531 // `a[i] = v` on a dense array with an integer index: see
10532 // `fast_array_set` for why the whole store is one step.
10533 Opcode::PutArrayEl if self.fast_array_set() => {}
10534 // `o.x` resolved from the inline cache without leaving the loop.
10535 //
10536 // The cache is keyed by `(receiver identity, atom, site)` and a
10537 // monomorphic read re-validates the same chain every iteration, so
10538 // each one used to cost a `stop(pc)` — a write of `pc` into the
10539 // frame, a return out of this loop, a re-dispatch through `step` and
10540 // a re-entry. `property:monomorphic` spent 18% in
10541 // `read_field_cached` and 21% in `push`, both across that boundary.
10542 //
10543 // The site is `pc + width`, which is exactly the `next` the slow arm
10544 // passes — the two must agree or every fast lookup misses and
10545 // re-records the same entry forever.
10546 //
10547 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
10548 // slow arm finds the receiver where it expects it.
10549 // `name` resolved from the global-variable cache inside the loop.
10550 //
10551 // Same shape as `get_field` above and for the same reason: `get_var`
10552 // was not in the fast loop, so reading a global — which `fib` does
10553 // once per recursive call, for its own name — cost a `stop(pc)`, a
10554 // return out of the loop, a `step` re-dispatch and a re-entry, before
10555 // `get_global` even started its `scopes_are_plain` checks.
10556 //
10557 // Everything here is exactly `get_global`'s first branch: not lexical,
10558 // no `eval` scope, cache hit. Anything else leaves the stack untouched
10559 // and lets the slow arm decide.
10560 Opcode::GetVar => {
10561 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
10562 return Ok(self.stop(pc));
10563 };
10564 self.push(value);
10565 }
10566 Opcode::GetField | Opcode::GetField2 => {
10567 let Some(value) =
10568 self.fast_field_get(insn.a as usize, pc + insn.width())
10569 else {
10570 return Ok(self.stop(pc));
10571 };
10572 if insn.op == Opcode::GetField2 {
10573 // `get_field2` keeps the receiver for the `call_method` that
10574 // follows.
10575 self.push(value);
10576 } else {
10577 // `get_field` replaces the receiver, so this is one store over
10578 // the top slot rather than a `pop` and a `push`: the length
10579 // never changes, so neither `Vec` arm has a capacity check or a
10580 // drop to run beyond the one the overwrite itself does.
10581 let frame = self.frame_mut();
10582 match frame.stack.last_mut() {
10583 Some(slot) => *slot = value,
10584 None => return Ok(self.stop(pc)),
10585 }
10586 }
10587 }
10588 // -- constants ---------------------------------------------------
10589 Opcode::PushMinus1
10590 | Opcode::Push0
10591 | Opcode::Push1
10592 | Opcode::Push2
10593 | Opcode::Push3
10594 | Opcode::Push4
10595 | Opcode::Push5
10596 | Opcode::Push6
10597 | Opcode::Push7
10598 | Opcode::PushI8
10599 | Opcode::PushI16
10600 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
10601 // -- stack shuffling ---------------------------------------------
10602 Opcode::Drop => {
10603 self.pop();
10604 }
10605 // -- arithmetic on two integers ----------------------------------
10606 //
10607 // The operands are *looked at* before they are popped, so a non-integer
10608 // pair leaves the stack exactly as the slow path expects to find it.
10609 Opcode::Add if self.numeric_pair() => {
10610 let right = self.pop();
10611 let left = self.pop();
10612 // Exactly [`add_numbers`], which is what the slow arm reaches.
10613 let answer = match (&left, &right) {
10614 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10615 Some(sum) => Value::Int(sum),
10616 None => Value::Float(*a as f64 + *b as f64),
10617 },
10618 _ => Value::Float(left.to_number() + right.to_number()),
10619 };
10620 self.push(answer);
10621 }
10622 Opcode::Sub
10623 | Opcode::And
10624 | Opcode::Or
10625 | Opcode::Xor
10626 | Opcode::Shl
10627 | Opcode::Sar
10628 | Opcode::Shr
10629 if self.numeric_pair() =>
10630 {
10631 let right = self.pop();
10632 let left = self.pop();
10633 let answer =
10634 arithmetic(insn.op, left, right).expect("numbers cannot throw");
10635 self.push(answer);
10636 }
10637 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10638 if self.numeric_pair() =>
10639 {
10640 let right = self.pop();
10641 let left = self.pop();
10642 let answer = self
10643 .relational(insn.op, left, right)
10644 .expect("numbers cannot throw");
10645 self.push(answer);
10646 }
10647 // -- calls -------------------------------------------------------
10648 //
10649 // A plain call: `callee(arg0, …, argN) -> result`.
10650 //
10651 // This arm exists because of one measurement. `call:recursion` had
10652 // **20.4% of its profile in `execute_instruction`** — the *slow*
10653 // executor — and `fib`'s recursive call is the only thing in that
10654 // function which is not a fast arm. Every call therefore left this
10655 // loop via `stop()`, went through `step()`'s dispatch and
10656 // `execute_instruction`'s match over every opcode, and came back here
10657 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
10658 //
10659 // Two things make it safe to do here rather than only in the slow path:
10660 //
10661 // * the caller's `pc` is stored *before* the call, which is what
10662 // `step` does too — so when the callee returns, the caller resumes
10663 // after the call and not at it;
10664 // * `check_memory` runs, because `step` calls it once per instruction
10665 // and a call allocates a frame, its locals and its cells. Skipping
10666 // the checkpoint here would let a `--memory-limit` script overshoot
10667 // by one call per instruction.
10668 Opcode::Call
10669 | Opcode::Call0
10670 | Opcode::Call1
10671 | Opcode::Call2
10672 | Opcode::Call3 => {
10673 let argc = self.argc_operand(insn.op, insn.a);
10674 let next = pc + insn.width();
10675 {
10676 let frame = self
10677 .frames
10678 .last_mut()
10679 .expect("run_fast() is only called with a live frame");
10680 // `at` is what a stack trace reports for this frame, so a throw
10681 // inside the callee has to see the call site and not whatever
10682 // the last `stop()` left there.
10683 frame.at = insn.offset as usize;
10684 frame.pc = next;
10685 }
10686 self.check_memory()?;
10687 self.check_interrupt()?;
10688 let args = self.pop_n(argc);
10689 let callee = self.pop();
10690 // A plain call has no receiver; the callee decides what to do with
10691 // `undefined` (a sloppy function substitutes the global object).
10692 if let Some(result) =
10693 self.call_or_push(callee, Value::Undefined, args)?
10694 {
10695 // Native, host, generator, async, bound — no frame was pushed,
10696 // so this loop is still describing the right function. `pc`
10697 // is advanced by the loop tail like every other arm; only the
10698 // frame's copy had to be written here, and it already was.
10699 self.push(result);
10700 } else {
10701 // A bytecode callee: its frame is on top now, and `insns` and
10702 // `pc` both belong to the caller. Start over on the new frame.
10703 continue 'outer;
10704 }
10705 }
10706 // -- return ------------------------------------------------------
10707 Opcode::Return => {
10708 let value = self.pop();
10709 self.frame_mut().pc = pc + insn.width();
10710 return Ok(Some(value));
10711 }
10712 Opcode::ReturnUndef => {
10713 self.frame_mut().pc = pc + insn.width();
10714 return Ok(Some(Value::Undefined));
10715 }
10716 // Everything else needs the slow path.
10717 _ => return Ok(self.stop(pc)),
10718 },
10719 }
10720 pc += insn.width();
10721 }
10722 }
10723 }
10724
10725 /// Whether the top two operand-stack values are both numbers.
10726 ///
10727 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
10728 /// cannot run script, so the arm may not throw and may not change frames.
10729 fn numeric_pair(&self) -> bool {
10730 is_number(&self.peek(0)) && is_number(&self.peek(1))
10731 }
10732
10733 /// `a[i]` for a dense array and an integer index, without the string round trip.
10734 ///
10735 /// The slow path answers this by turning `i` into a string (`propkey` →
10736 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
10737 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
10738 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
10739 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
10740 /// without even the cheap `Int` formatting.
10741 ///
10742 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
10743 /// unambiguously the one the slow path would give:
10744 ///
10745 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
10746 /// `2^32-1` is the length, not an index),
10747 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
10748 /// typed array or an ordinary object, all of which have their own rules),
10749 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
10750 /// starts walking the prototype chain, and `a[i]` on a hole must find
10751 /// `Array.prototype[i]` if it exists rather than `undefined`.
10752 ///
10753 /// The last condition is the one that makes this safe rather than merely fast: an own
10754 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
10755 /// `get_var` answered from the global-variable cache, or `None`.
10756 ///
10757 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10758 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10759 /// records nothing — the slow arm is about to walk the chain and record it.
10760 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10761 let frame = self.frame();
10762 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10763 // "Lexical" is presence in the realm's table, not the closure var's flag: a
10764 // `GlobalRef` forwarded through a nested function has its flags cleared.
10765 if self.realm.globals.contains_key(name) {
10766 return None;
10767 }
10768 if !self.scopes_are_plain() {
10769 return None;
10770 }
10771 let object = &self.realm.global;
10772 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10773 let cached = self.global_cache[site].as_ref()?;
10774 if !object.upgrades_to(&cached.object) {
10775 return None;
10776 }
10777 object.data_property_at(cached.index, name)
10778 }
10779
10780 /// `o.x` answered entirely from the inline cache, or `None`.
10781 ///
10782 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
10783 /// about to do exactly that and recording it twice would rebuild the chain for every
10784 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
10785 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
10786 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
10787 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
10788 // an object receiver is a reference-count bump that the answer never needs.
10789 let frame = self.frame();
10790 let object = frame.stack.last()?;
10791 let Value::Object(target) = object else {
10792 return None;
10793 };
10794 // A proxy traps the lookup, so no cache entry ever describes it.
10795 if target.proxy_state().is_some() {
10796 return None;
10797 }
10798 let key = frame.code.atom_keys.get(atom)?;
10799 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
10800 if cached.key != *key {
10801 return None;
10802 }
10803 Self::cached_hit(target, cached)
10804 }
10805
10806 fn fast_array_get(&self) -> Option<Value> {
10807 let Value::Int(index) = self.peek(0) else {
10808 return None;
10809 };
10810 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
10811 // set for an `i32`.
10812 if index < 0 {
10813 return None;
10814 }
10815 let Value::Object(object) = self.peek(1) else {
10816 return None;
10817 };
10818 match object.array_get(index as usize) {
10819 Some(value) if !matches!(value, Value::Hole) => Some(value),
10820 _ => None,
10821 }
10822 }
10823
10824 /// `a[i] = v` on a dense array with an integer index, as one store.
10825 ///
10826 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
10827 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
10828 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
10829 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
10830 /// reference at the time it was measured (14.7x).
10831 ///
10832 /// Every condition here is one the slow path would also have to satisfy before
10833 /// storing into the element vector:
10834 ///
10835 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
10836 /// accepts as an index;
10837 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
10838 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
10839 /// one inside a recorded descriptor, reports `false` and the caller stops.
10840 ///
10841 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
10842 /// writes the own element too once `array_set` says it did.
10843 fn fast_array_set(&mut self) -> bool {
10844 // Every test runs *before* anything is popped: a refusal has to leave the stack
10845 // exactly as the slow path expects to find it. Popping first and reporting the
10846 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
10847 // then ran the slow path with nothing to write.
10848 let Value::Int(index) = self.peek(1) else {
10849 return false;
10850 };
10851 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
10852 if index < 0 {
10853 return false;
10854 }
10855 // Only a real array: a typed array's elements live in its buffer, a string-like
10856 // object has no element vector, and `array_set` on either does nothing.
10857 let Value::Object(object) = self.peek(2) else {
10858 return false;
10859 };
10860 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
10861 return false;
10862 }
10863 // A non-extensible array reports `false` here, but the *slow* path has to decide
10864 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
10865 // that with the key and the stack still intact.
10866 if !object.is_extensible() {
10867 return false;
10868 }
10869 // Inside the logical length, so the store cannot change `length`. Combined with
10870 // extensibility above, the only growth left for `array_set` is filling a hole in
10871 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
10872 // shape this fast path exists for. A store past the length would grow the array,
10873 // and whether that is allowed is the slow path's question.
10874 if index as usize >= object.array_length().unwrap_or(0) {
10875 return false;
10876 }
10877 // Only an *own element* can take the inline store. A hole is not an own property,
10878 // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
10879 // trap or a setter decides, and where `new Array(1)` with a proxy above it must
10880 // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
10881 // the one case this path used to swallow.
10882 //
10883 // The cost is small: `array:indexed` only reads after a 64-element fill, and
10884 // `array:push` appends past the length, which this path already refused.
10885 if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
10886 {
10887 return false;
10888 }
10889 // The bound `array_set` refuses past. Checking it here keeps that arm from having
10890 // to report a failure after the operands are gone.
10891 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
10892 return false;
10893 }
10894 let value = self.pop();
10895 self.pop();
10896 self.pop();
10897 object.array_store(self.heap, index as usize, value)
10898 }
10899
10900 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
10901 fn stop(&mut self, pc: usize) -> Option<Value> {
10902 self.frame_mut().pc = pc;
10903 None
10904 }
10905
10906 fn push(&mut self, value: Value) {
10907 self.frame_mut().stack.push(value);
10908 }
10909
10910 fn pop(&mut self) -> Value {
10911 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10912 }
10913
10914 fn pop_n(&mut self, count: usize) -> Vec<Value> {
10915 let frame = self.frame_mut();
10916 let start = frame.stack.len().saturating_sub(count);
10917 frame.stack.split_off(start)
10918 }
10919
10920 fn peek(&self, back: usize) -> Value {
10921 let frame = self.frame();
10922 frame
10923 .stack
10924 .get(frame.stack.len().wrapping_sub(1 + back))
10925 .cloned()
10926 .unwrap_or(Value::Undefined)
10927 }
10928
10929 #[allow(clippy::too_many_lines)]
10930 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10931 use Opcode::*;
10932 match op {
10933 // -- constants and stack shuffling -----------------------------
10934 Nop => {}
10935 PushMinus1 => self.push(Value::Int(-1)),
10936 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10937 let value = match op {
10938 Push0 => 0,
10939 Push1 => 1,
10940 Push2 => 2,
10941 Push3 => 3,
10942 Push4 => 4,
10943 Push5 => 5,
10944 Push6 => 6,
10945 _ => 7,
10946 };
10947 self.push(Value::Int(value));
10948 }
10949 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
10950 PushBigintI32 => {
10951 // The immediate form of a `BigInt` literal; the reference has the same
10952 // split between this and a constant-pool entry.
10953 let value = crate::bigint::BigInt::from_i64(a as i64);
10954 self.push(self.bigint(value));
10955 }
10956 PushTrue => self.push(Value::Bool(true)),
10957 PushFalse => self.push(Value::Bool(false)),
10958 PushEmptyString => self.push(self.string("")),
10959 Undefined => self.push(Value::Undefined),
10960 Null => self.push(Value::Null),
10961 Object => {
10962 let proto = self.realm.object_proto.clone();
10963 self.push(Value::Object(self.new_object(Some(proto))));
10964 }
10965 PushThis => {
10966 let this = self.frame().this.clone();
10967 self.push(this);
10968 }
10969 PushConst | PushConst8 => {
10970 let value = self.constant(a as usize)?;
10971 self.push(value);
10972 }
10973 PushAtomValue => {
10974 let text = self.atom_wtf8(a as usize);
10975 self.push(self.string_wtf8(text));
10976 }
10977 Dup => {
10978 let value = self.peek(0);
10979 self.push(value);
10980 }
10981 Dup2 => {
10982 // `a b -> a b a b`
10983 let b = self.peek(0);
10984 let a = self.peek(1);
10985 self.push(a);
10986 self.push(b);
10987 }
10988 Dup3 => {
10989 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
10990 // prototype and key while reading the current value through them.
10991 let c = self.peek(0);
10992 let b = self.peek(1);
10993 let a = self.peek(2);
10994 self.push(a);
10995 self.push(b);
10996 self.push(c);
10997 }
10998 Swap => {
10999 // `a b -> b a`
11000 let bottom = self.pop();
11001 let top = self.pop();
11002 self.push(bottom);
11003 self.push(top);
11004 }
11005 Perm3 => {
11006 // `a b c -> b a c`, the reference's reordering for a spread method
11007 // call: `obj func array` becomes the `func this array` that `apply`
11008 // takes.
11009 let c = self.pop();
11010 let b = self.pop();
11011 let a = self.pop();
11012 self.push(b);
11013 self.push(a);
11014 self.push(c);
11015 }
11016 Dup1 => {
11017 let value = self.peek(1);
11018 self.push(value);
11019 }
11020 Drop => {
11021 self.pop();
11022 }
11023 Nip => {
11024 // `a b -> b`
11025 let top = self.pop();
11026 self.pop();
11027 self.push(top);
11028 }
11029 Perm4 => {
11030 // `obj prop a b -> a obj prop b`, the reference's reordering for a
11031 // postfix update of a computed element: it puts the *old* value
11032 // underneath the receiver and key so `put_array_el` can consume them
11033 // and leave the old value as the expression's result.
11034 let d = self.pop();
11035 let c = self.pop();
11036 let b = self.pop();
11037 let a = self.pop();
11038 self.push(c);
11039 self.push(a);
11040 self.push(b);
11041 self.push(d);
11042 }
11043 Insert2 => {
11044 // `obj a -> a obj a`
11045 let value = self.pop();
11046 let object = self.pop();
11047 self.push(value.clone());
11048 self.push(object);
11049 self.push(value);
11050 }
11051 Insert3 => {
11052 // `obj prop a -> a obj prop a`
11053 let value = self.pop();
11054 let key = self.pop();
11055 let object = self.pop();
11056 self.push(value.clone());
11057 self.push(object);
11058 self.push(key);
11059 self.push(value);
11060 }
11061 Insert4 => {
11062 // `this obj prop a -> a this obj prop a`
11063 //
11064 // `put_super_value` consumes all four and yields nothing, so the copy
11065 // underneath is what leaves the assignment an expression value.
11066 let value = self.pop();
11067 let key = self.pop();
11068 let object = self.pop();
11069 let receiver = self.pop();
11070 self.push(value.clone());
11071 self.push(receiver);
11072 self.push(object);
11073 self.push(key);
11074 self.push(value);
11075 }
11076 Swap2 => {
11077 // `a b c d -> c d a b`
11078 let d = self.pop();
11079 let c = self.pop();
11080 let b = self.pop();
11081 let a = self.pop();
11082 self.push(c);
11083 self.push(d);
11084 self.push(a);
11085 self.push(b);
11086 }
11087 Rot3l => {
11088 // `x a b -> a b x`
11089 let b = self.pop();
11090 let a = self.pop();
11091 let x = self.pop();
11092 self.push(a);
11093 self.push(b);
11094 self.push(x);
11095 }
11096 Rot3r => {
11097 // `a b c -> c a b`
11098 let c = self.pop();
11099 let b = self.pop();
11100 let a_value = self.pop();
11101 self.push(c);
11102 self.push(a_value);
11103 self.push(b);
11104 }
11105
11106 Rest => {
11107 // `...rest` in a parameter list: the arguments from index `a` on, as a
11108 // real array. It takes nothing off the stack — the arguments are in the
11109 // frame, not on it.
11110 let frame = self.frame();
11111 let from = a as usize;
11112 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
11113 let array = self.new_array(collected);
11114 self.push(Value::Object(array));
11115 }
11116
11117 // -- slots ------------------------------------------------------
11118 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
11119 let slot = self.slot_operand(op, a);
11120 let value = self.get_loc(slot);
11121 self.push(value);
11122 }
11123 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
11124 let slot = self.slot_operand(op, a);
11125 let value = self.pop();
11126 self.put_loc(slot, value);
11127 }
11128 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
11129 let slot = self.slot_operand(op, a);
11130 let value = self.pop();
11131 self.put_loc(slot, value.clone());
11132 self.push(value);
11133 }
11134 // The `_check` forms are the temporal dead zone: they throw when the
11135 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
11136 // *reads*, so only the two writes may pop — mishandling that quietly
11137 // consumes the value the caller pushed just before.
11138 GetLocCheck => {
11139 let slot = self.slot_operand(op, a);
11140 let value = self.get_loc(slot);
11141 if matches!(value, Value::Uninitialized) {
11142 return Err(self.dead_zone(slot, VarSlot::Loc));
11143 }
11144 self.push(value);
11145 }
11146 PutLocCheck | SetLocCheck => {
11147 let slot = self.slot_operand(op, a);
11148 let value = self.pop();
11149 // The dead zone is a property of the **slot**, not of the value being
11150 // stored: `x = 1; let x` is a `ReferenceError` because `x` has not been
11151 // initialised yet. Testing the value instead — which is never
11152 // `Uninitialized` in practice — let every such store through, so the check
11153 // only ever fired for an explicit `x = undefined`-shaped accident. Reads
11154 // (`get_loc_check`) were already asking the slot, which is why
11155 // `print(x); let x` threw while `x = 1; let x` did not.
11156 if matches!(self.get_loc(slot), Value::Uninitialized) {
11157 return Err(self.dead_zone(slot, VarSlot::Loc));
11158 }
11159 // The initialiser goes through `put_loc`, not this, so any store that
11160 // reaches here is a later assignment — which a `const` refuses.
11161 if self.is_read_only(slot, VarSlot::Loc) {
11162 return Err(self.read_only(slot, VarSlot::Loc));
11163 }
11164 if op == SetLocCheck {
11165 self.put_loc(slot, value.clone());
11166 self.push(value);
11167 } else {
11168 self.put_loc(slot, value);
11169 }
11170 }
11171 PutLocCheckInit => {
11172 // The one store that *initialises* a lexical slot: `this` in a derived
11173 // constructor, which only exists after `super()` has run. A second
11174 // initialisation is the error the reference reports as
11175 // "'this' can be initialized only once".
11176 let slot = self.slot_operand(op, a);
11177 let value = self.pop();
11178 if !matches!(self.get_loc(slot), Value::Uninitialized) {
11179 return Err(Signal::Throw(self.make_error(
11180 "ReferenceError",
11181 "'this' can be initialized only once",
11182 )));
11183 }
11184 self.put_loc(slot, value);
11185 }
11186 CheckCtor => {
11187 // A class constructor may only run under `new`, which is what makes
11188 // `class A {}; A()` a TypeError.
11189 if matches!(self.frame().new_target, Value::Undefined) {
11190 return Err(Signal::Throw(self.make_error(
11191 "TypeError",
11192 "class constructors must be invoked with 'new'",
11193 )));
11194 }
11195 }
11196 InitCtor => {
11197 // The body a derived class gets when it declares no constructor:
11198 // forward every argument to the parent constructor, keeping `new.target`.
11199 if matches!(self.frame().new_target, Value::Undefined) {
11200 return Err(Signal::Throw(self.make_error(
11201 "TypeError",
11202 "class constructors must be invoked with 'new'",
11203 )));
11204 }
11205 let Some(callee) = self.current_callee() else {
11206 return Err(Signal::Throw(
11207 self.make_error("TypeError", "no constructor to inherit from"),
11208 ));
11209 };
11210 let parent = callee.proto().map_or(Value::Null, Value::Object);
11211 let new_target = self.frame().new_target.clone();
11212 let args = self.frame().passed().to_vec();
11213 let result = self.construct(parent, new_target, args)?;
11214 self.push(result);
11215 }
11216 SetLocUninitialized => {
11217 let slot = self.slot_operand(op, a);
11218 self.put_loc(slot, Value::Uninitialized);
11219 }
11220 CloseLoc => {
11221 // "Close" a binding: give it a *fresh* cell holding the current
11222 // value. Closures created before this point keep the old cell and the
11223 // ones created after see the new one, which is what makes every
11224 // iteration of `for (let i ...)` capture its own `i`, and what freezes
11225 // a block-scoped binding when the block ends.
11226 //
11227 // Clearing the slot instead (which this used to do) broke both: a
11228 // closure over a captured block variable read `undefined`, and a loop
11229 // terminated after one iteration.
11230 let slot = self.slot_operand(op, a);
11231 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
11232 if index >= 0 {
11233 let current = self.frame().cells[index as usize].get();
11234 let fresh = self.new_cell(current);
11235 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
11236 *cell = fresh;
11237 }
11238 }
11239 }
11240 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
11241 let slot = self.slot_operand(op, a);
11242 let value = self.get_arg(slot);
11243 self.push(value);
11244 }
11245 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
11246 let slot = self.slot_operand(op, a);
11247 let value = self.pop();
11248 self.put_arg(slot, value);
11249 }
11250 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
11251 let slot = self.slot_operand(op, a);
11252 let value = self.pop();
11253 self.put_arg(slot, value.clone());
11254 self.push(value);
11255 }
11256
11257 // -- closure variables ------------------------------------------
11258 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
11259 let slot = self.slot_operand(op, a);
11260 // A name a direct `eval` created shadows the binding the compiler chose.
11261 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
11262 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
11263 // and only a runtime lookup can know that.
11264 if let Some(cell) = self.eval_created_local(slot) {
11265 self.push(cell.get());
11266 return self.step();
11267 }
11268 let value = self.cell_value(slot)?;
11269 self.push(value);
11270 }
11271 GetVarRefCheck => {
11272 let slot = self.slot_operand(op, a);
11273 let value = self.cell_value(slot)?;
11274 if matches!(value, Value::Uninitialized) {
11275 return Err(self.dead_zone(slot, VarSlot::Closure));
11276 }
11277 self.push(value);
11278 }
11279 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
11280 let slot = self.slot_operand(op, a);
11281 let value = self.pop();
11282 if let Some(cell) = self.eval_created_local(slot) {
11283 cell.set(value);
11284 return self.step();
11285 }
11286 // Same two rules as `PutLocCheck`: a checked store to a captured binding
11287 // asks the cell about the dead zone, then refuses a `const` whose
11288 // initialiser has already run.
11289 if op == PutVarRefCheck {
11290 let current = self.cell_value(slot)?;
11291 if matches!(current, Value::Uninitialized) {
11292 return Err(self.dead_zone(slot, VarSlot::Closure));
11293 }
11294 if self.is_read_only(slot, VarSlot::Closure) {
11295 return Err(self.read_only(slot, VarSlot::Closure));
11296 }
11297 }
11298 self.set_cell(slot, value)?;
11299 }
11300 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
11301 let slot = self.slot_operand(op, a);
11302 let value = self.pop();
11303 if let Some(cell) = self.eval_created_local(slot) {
11304 cell.set(value.clone());
11305 self.push(value);
11306 return self.step();
11307 }
11308 self.set_cell(slot, value.clone())?;
11309 self.push(value);
11310 }
11311
11312 // -- globals ----------------------------------------------------
11313 GetVar => {
11314 let value = self.get_global(a as usize)?;
11315 self.push(value);
11316 }
11317 GetVarUndef => {
11318 let slot = a as usize;
11319 // `typeof undeclared` answers `"undefined"`; `typeof x` where `x` is in its
11320 // **dead zone** still throws (§13.5.3 evaluates the operand as a Reference
11321 // and `GetValue`s it, and only the unresolvable case is forgiven).
11322 //
11323 // The distinction is made by asking whether a binding exists at all: a name
11324 // in the realm's lexical table is declared, so a `ReferenceError` from
11325 // reading it is the dead zone talking. Swallowing every error made
11326 // `eval("typeof x; let x;")` print `"undefined"`.
11327 let declared = self.realm.globals.contains_key(&self.global_name(slot));
11328 let value = if declared {
11329 self.get_global(slot)?
11330 } else {
11331 match self.get_global(slot) {
11332 Ok(value) => value,
11333 Err(Signal::Throw(_)) => Value::Undefined,
11334 Err(other) => return Err(other),
11335 }
11336 };
11337 self.push(value);
11338 }
11339 DeleteVar => {
11340 // `delete name` for a name that is not a declared binding. A lexical
11341 // global lives in the reference table and cannot be deleted; anything
11342 // reachable only as a property of the global object is *implicit* —
11343 // `x = 1` with no declaration — and goes away if it is configurable,
11344 // which is what `delete` on an implicit global answers.
11345 let name = self.atom_text(a as usize);
11346 let global = self.realm.global.clone();
11347 let deleted = if self.realm.globals.contains_key(&name) {
11348 false
11349 } else if global.own_property(&name).is_some() {
11350 self.delete_property(&global, &name)?
11351 } else {
11352 true
11353 };
11354 self.push(Value::Bool(deleted));
11355 }
11356 PutVar => {
11357 let value = self.pop();
11358 self.put_global(a as usize, value)?;
11359 }
11360 PutVarInit => {
11361 let slot = a as usize;
11362 let value = self.pop();
11363 self.init_global(slot, value)?;
11364 }
11365
11366 // -- arithmetic -------------------------------------------------
11367 Add => self.binary_add()?,
11368 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
11369 let raw_right = self.pop();
11370 let raw_left = self.pop();
11371 // BigInt arithmetic is a separate path, and not only for the type of the
11372 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
11373 // rather than a silent conversion.
11374 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
11375 let left = self.primitive_of(raw_left)?;
11376 let right = self.primitive_of(raw_right)?;
11377 let value = self.bigint_arithmetic(op, left, right)?;
11378 self.push(value);
11379 } else {
11380 let right = self.numeric(raw_right)?;
11381 let left = self.numeric(raw_left)?;
11382 self.push(arithmetic(op, left, right)?);
11383 }
11384 }
11385 Neg => {
11386 let raw = self.pop();
11387 match raw {
11388 // A bigint negates exactly, however wide it is.
11389 Value::BigInt(big) => {
11390 let negated = big.negate();
11391 self.push(self.bigint(negated));
11392 }
11393 other => {
11394 let value = self.numeric(other)?;
11395 self.push(negate(value));
11396 }
11397 }
11398 }
11399 Plus => {
11400 let value = self.pop();
11401 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
11402 // unary plus is defined to produce a *number*, which a bigint cannot
11403 // become without loss. It used to fall through to `NaN`.
11404 if matches!(value, Value::BigInt(_)) {
11405 return Err(self.type_error("cannot convert bigint to number"));
11406 }
11407 let numeric = self.numeric_of(value)?;
11408 self.push(numeric);
11409 }
11410 Inc => {
11411 let raw = self.pop();
11412 let (_, updated) = self.advance_numeric(raw, true)?;
11413 self.push(updated);
11414 }
11415 Dec => {
11416 let raw = self.pop();
11417 let (_, updated) = self.advance_numeric(raw, false)?;
11418 self.push(updated);
11419 }
11420 PostInc | PostDec => {
11421 // `x -> x x+1`: the *new* value ends up on top, so the store the
11422 // compiler emits right after (`put_var`) writes the incremented
11423 // one, while the old value stays underneath for the expression's
11424 // own result. Getting this backwards makes `i++` a no-op, which
11425 // turns `while (i < 3)` into an infinite loop.
11426 let raw = self.pop();
11427 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
11428 self.push(old);
11429 self.push(updated);
11430 }
11431 Not => {
11432 let raw = self.pop();
11433 match raw {
11434 // `~x` on a bigint is `-x - 1`, exact at any width.
11435 Value::BigInt(big) => {
11436 let inverted = big.bitnot();
11437 self.push(self.bigint(inverted));
11438 }
11439 other => {
11440 let value = self.numeric(other)?;
11441 self.push(Value::Int(!value.to_int32()));
11442 }
11443 }
11444 }
11445 Lnot => {
11446 let value = self.pop();
11447 self.push(Value::Bool(!value.to_boolean()));
11448 }
11449
11450 // -- comparison -------------------------------------------------
11451 Lt | Lte | Gt | Gte => {
11452 let right = self.pop();
11453 let left = self.pop();
11454 let answer = self.relational(op, left, right)?;
11455 self.push(answer);
11456 }
11457 Eq | Neq => {
11458 let right = self.pop();
11459 let left = self.pop();
11460 let equal = self.abstract_equals(left, right)?;
11461 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
11462 }
11463 StrictEq => {
11464 let right = self.pop();
11465 let left = self.pop();
11466 self.push(Value::Bool(left.strict_equals(&right)));
11467 }
11468 StrictNeq => {
11469 let right = self.pop();
11470 let left = self.pop();
11471 self.push(Value::Bool(!left.strict_equals(&right)));
11472 }
11473 IsUndefined => {
11474 // `=== undefined`, which is what a destructuring default tests. It is
11475 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
11476 let value = self.pop();
11477 self.push(Value::Bool(matches!(value, Value::Undefined)));
11478 }
11479 IsUndefinedOrNull => {
11480 let value = self.pop();
11481 self.push(Value::Bool(value.is_nullish()));
11482 }
11483 Typeof => {
11484 let value = self.pop();
11485 self.push(self.string(value.type_of()));
11486 }
11487 ToObject => {
11488 // A destructuring *object* pattern starts here, which is why
11489 // `var {} = null` throws. Only `undefined` and `null` are refused; a
11490 // primitive is boxed.
11491 let value = self.pop();
11492 let object = self.object_from(&value)?;
11493 self.push(Value::Object(object));
11494 }
11495 Instanceof => {
11496 let constructor = self.pop();
11497 let object = self.pop();
11498 let answer = self.instance_of(&object, &constructor)?;
11499 self.push(Value::Bool(answer));
11500 }
11501 In => {
11502 let object = self.pop();
11503 let key = self.pop();
11504 let answer = self.has_property(&key, &object)?;
11505 self.push(Value::Bool(answer));
11506 }
11507 WithHasVar => {
11508 // `obj -> bool`: does this `with` object bind the name?
11509 //
11510 // §9.1.1.2.1 `HasBinding` for an Object Environment Record is **not**
11511 // `HasProperty`: step 2 skips the property entirely when the object's
11512 // `Symbol.unscopables` lists it. So `globalThis[Symbol.unscopables] = {v:
11513 // true}` makes `with (globalThis) { v }` read the *outer* `v`, which is what
11514 // the thirty-odd `unscopables-with` cases assert.
11515 //
11516 // One instruction rather than a hand-expanded sequence of `in`, a
11517 // `Symbol.unscopables` lookup and a second `in`: the same question is asked
11518 // by both the read/write guard and `delete`, and a compiler-side expansion
11519 // would be about ten instructions per name per `with` object.
11520 let object = self.pop();
11521 let name = self.atom_text(a as usize);
11522 let bound = self.with_has_binding(&object, &name)?;
11523 self.push(Value::Bool(bound));
11524 }
11525 WithGetVar => {
11526 // `obj -> value`: the second half of `GetBindingValue`.
11527 let object = self.pop();
11528 let name = self.atom_text(a as usize);
11529 let value = self.with_get_binding(&object, &name)?;
11530 self.push(value);
11531 }
11532 WithPutVar => {
11533 // `obj value ->`: the second half of `SetMutableBinding`. The operand order
11534 // is `put_field`'s (value on top), not the reference's, so that the
11535 // read-modify-write shapes (`perm3`/`insert2`) can be shared with the
11536 // member-expression forms.
11537 let value = self.pop();
11538 let object = self.pop();
11539 let name = self.atom_text(a as usize);
11540 self.with_put_binding(&object, &name, value)?;
11541 }
11542
11543 // -- control flow -----------------------------------------------
11544 Goto | Goto8 | Goto16 => {
11545 self.frame_mut().pc = a as usize;
11546 }
11547 IfTrue | IfTrue8 => {
11548 let value = self.pop();
11549 if value.to_boolean() {
11550 self.frame_mut().pc = a as usize;
11551 }
11552 }
11553 IfFalse | IfFalse8 => {
11554 let value = self.pop();
11555 if !value.to_boolean() {
11556 self.frame_mut().pc = a as usize;
11557 }
11558 }
11559 Catch => {
11560 // Pushes the handler target onto the value stack; `unwind` finds it.
11561 self.push(Value::CatchOffset(a));
11562 }
11563 Gosub => {
11564 self.push(Value::ReturnAddress(next as u32));
11565 self.frame_mut().pc = a as usize;
11566 }
11567 Ret => {
11568 let value = self.pop();
11569 match value {
11570 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
11571 _ => {
11572 return Err(Signal::Throw(
11573 self.make_error("InternalError", "invalid return address"),
11574 ));
11575 }
11576 }
11577 }
11578 NipCatch => {
11579 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
11580 // including the marker, keeping the top value.
11581 let top = self.pop();
11582 loop {
11583 match self.pop() {
11584 Value::CatchOffset(_) | Value::Undefined => break,
11585 _ => {}
11586 }
11587 if self.frame().stack.is_empty() {
11588 break;
11589 }
11590 }
11591 self.push(top);
11592 }
11593 Throw => {
11594 let value = self.pop();
11595 return Err(Signal::Throw(value));
11596 }
11597 ThrowError => {
11598 let name = self.atom_text(a as usize);
11599 let (class, message) = match b {
11600 0 => ("TypeError", format!("'{name}' is read-only")),
11601 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
11602 2 => ("ReferenceError", format!("'{name}' is not initialized")),
11603 // `delete super.x` is a syntax-level mistake the reference reports
11604 // with this wording, not a property-access failure.
11605 3 => (
11606 "ReferenceError",
11607 "unsupported reference to 'super'".to_string(),
11608 ),
11609 4 => (
11610 "TypeError",
11611 "iterator does not have a throw method".to_string(),
11612 ),
11613 5 => (
11614 "ReferenceError",
11615 "invalid assignment left-hand side".to_string(),
11616 ),
11617 _ => ("TypeError", format!("invalid operation on '{name}'")),
11618 };
11619 return Err(Signal::Throw(self.make_error(class, &message)));
11620 }
11621 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
11622 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
11623 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
11624 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
11625 Await => return Ok(Step::Suspend(SuspendKind::Await)),
11626 ReturnAsync => {
11627 // The reference's `return_async` returns `undefined` and lets the resume
11628 // machinery pick the real value off `sp[-1]`, which is how it tells a
11629 // completion from a suspension. Carrying the value explicitly says the
11630 // same thing without the implicit stack slot.
11631 let value = self.pop();
11632 return Ok(Step::Return(value));
11633 }
11634 Return => {
11635 let value = self.pop();
11636 return Ok(Step::Return(value));
11637 }
11638 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
11639
11640 // -- calls ------------------------------------------------------
11641 Call | Call0 | Call1 | Call2 | Call3 => {
11642 let argc = self.argc_operand(op, a);
11643 let args = self.pop_n(argc);
11644 let callee = self.pop();
11645 // A plain call has no receiver; the callee decides what to do with
11646 // `undefined` (a sloppy function substitutes the global object).
11647 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
11648 self.push(result);
11649 }
11650 }
11651 CallConstructor => {
11652 // `constructor this_obj args… -> object`. The duplicated
11653 // constructor is `new.target`; this milestone does not expose it,
11654 // so the extra copy is simply consumed here.
11655 let argc = a as usize;
11656 let args = self.pop_n(argc);
11657 let new_target = self.pop();
11658 let callee = self.pop();
11659 let result = self.construct(callee, new_target, args)?;
11660 self.push(result);
11661 }
11662 CallMethod => {
11663 let argc = a as usize;
11664 let args = self.pop_n(argc);
11665 let callee = self.pop();
11666 let this = self.pop();
11667 if let Some(result) = self.call_or_push(callee, this, args)? {
11668 self.push(result);
11669 }
11670 }
11671 Apply => {
11672 // `func this array -> result`, the spread-call form: the compiler
11673 // builds one array of arguments, and all that is left here is to
11674 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
11675 let array = self.pop();
11676 let this = self.pop();
11677 let callee = self.pop();
11678 let args = self.array_like_to_args(&array)?;
11679 if a & 1 != 0 {
11680 let result = self.construct(callee, this, args)?;
11681 self.push(result);
11682 } else if let Some(result) = self.call_or_push(callee, this, args)? {
11683 self.push(result);
11684 }
11685 }
11686 TailCall | TailCallMethod => {
11687 // `tail_call` is `call` whose result is returned immediately — the
11688 // reference jumps straight to `done` instead of storing the value and
11689 // running on. The callee still gets its own frame, so deep tail
11690 // recursion hits the stack limit exactly like plain recursion does;
11691 // marking this frame lets the return path unwind without needing
11692 // instructions after the call.
11693 let argc = if op == TailCallMethod {
11694 a as usize
11695 } else {
11696 self.argc_operand(op, a)
11697 };
11698 let args = self.pop_n(argc);
11699 let callee = self.pop();
11700 let this = if op == TailCallMethod {
11701 self.pop()
11702 } else {
11703 Value::Undefined
11704 };
11705 if let Value::Object(function) = &callee
11706 && let Some((code, env)) = bytecode_of(function)
11707 {
11708 // A generator or async body is not run here at all: calling it only
11709 // *creates* the generator/coroutine, so it must not inherit this
11710 // frame. Doing so made `function f(){ return g() }` push `g`'s body
11711 // onto `f`'s frame, and the first `yield`/`await` then reported
11712 // "a generator body ran as an ordinary call".
11713 if code.code.kind.is_generator() || code.code.kind.is_async() {
11714 let value = self.call_value(callee, this, args)?;
11715 return Ok(Step::Return(value));
11716 }
11717 self.frame_mut().tail = true;
11718 self.push_frame(code, env, this, args, callee)?;
11719 return Ok(Step::Continue);
11720 }
11721 // A native callee has no frame to reuse, so its value is simply
11722 // returned.
11723 let value = self.call_value(callee, this, args)?;
11724 return Ok(Step::Return(value));
11725 }
11726
11727 // -- objects ----------------------------------------------------
11728 SpecialObject => {
11729 let value = self.special_object(a)?;
11730 self.push(value);
11731 }
11732 PrivateSymbol => {
11733 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
11734 // symbol each time it is evaluated, which is why the compiler evaluates it
11735 // once (at class definition) and stores it in a class-scope binding.
11736 let name = self.atom_text(a as usize);
11737 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
11738 self.push(Value::Symbol(symbol));
11739 }
11740 GetPrivateField => {
11741 // `obj symbol -> value`. A missing private field is a TypeError, which is what
11742 // makes `#x` inaccessible on any object not built by this class.
11743 let symbol = self.pop();
11744 let object = self.pop();
11745 let value = self.read_private_field(&object, &symbol)?;
11746 self.push(value);
11747 }
11748 PutPrivateField => {
11749 // `obj value symbol ->`, and the store is a plain assignment to a property the
11750 // class already created, so there is no setter to consult.
11751 let symbol = self.pop();
11752 let value = self.pop();
11753 let object = self.pop();
11754 self.write_private_field(&object, &symbol, value)?;
11755 }
11756 DefinePrivateField => {
11757 // `obj symbol value -> obj`: a field initialiser creates the property, and
11758 // redefining one is a TypeError ("already exists").
11759 let value = self.pop();
11760 let symbol = self.pop();
11761 let object = self.pop();
11762 self.define_private_field(&object, &symbol, value)?;
11763 self.push(object);
11764 }
11765 PrivateIn => {
11766 // `obj key -> bool`: `#x in o`. The second operand decides which question is
11767 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
11768 // is a field, so this is an own-property test; a *function* is a method or
11769 // accessor, so this is a brand check.
11770 let key = self.pop();
11771 let object = self.pop();
11772 let Some(target) = object.as_object() else {
11773 return Err(Signal::Throw(
11774 self.make_error("TypeError", "invalid 'in' operand"),
11775 ));
11776 };
11777 let present = match &key {
11778 Value::Object(_) => self.check_brand(target, &key)?,
11779 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
11780 };
11781 self.push(Value::Bool(present));
11782 }
11783 AddBrand => {
11784 // `obj home ->`: create the class brand on `home` if it has none, then give
11785 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
11786 // class definition: only the prototype's copy of the symbol is wanted.
11787 let home = self.pop();
11788 let object = self.pop();
11789 self.add_brand(&object, &home)?;
11790 }
11791 CheckBrand => {
11792 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
11793 // Both stay, because the caller needs them — `nip` halves a read into its
11794 // value and `call_method` uses the pair as receiver and callee.
11795 let function = self.peek(0);
11796 let object = self.peek(1);
11797 let Some(target) = object.as_object() else {
11798 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11799 };
11800 if !self.check_brand(target, &function)? {
11801 return Err(Signal::Throw(
11802 self.make_error("TypeError", "invalid brand on object"),
11803 ));
11804 }
11805 }
11806 GetLength => {
11807 // `get_length` is the `.length` read; an array and a string answer
11808 // from their own length, anything else from the property.
11809 let target = self.pop();
11810 let value = match &target {
11811 Value::Object(object) => match object.array_length() {
11812 Some(length) => crate::object::length_value(length),
11813 None => self.read_field(&target, "length")?,
11814 },
11815 Value::String(text) => Value::Int(text.utf16_len() as i32),
11816 _ => self.read_field(&target, "length")?,
11817 };
11818 self.push(value);
11819 }
11820 GetField | GetField2 => {
11821 let object = self.pop();
11822 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
11823 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
11824 // just below is what lets the borrow outlive the `&mut self` the lookup
11825 // needs — one refcount bump instead of a key clone plus its drop, on the
11826 // hottest property path there is: every `o.x` and every `o.m()` receiver.
11827 let code = self.frame().code.clone();
11828 let key = &code.atom_keys[a as usize];
11829 let value = self.read_field_cached(&object, key, next)?;
11830 if op == GetField2 {
11831 self.push(object);
11832 }
11833 self.push(value);
11834 }
11835 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
11836 let key = self.pop();
11837 let object = self.pop();
11838 // §7.1.1 `GetValue` step 3 orders these two conversions: `ToObject(V.[[Base]])`
11839 // first, then `ToPropertyKey(V.[[ReferencedName]])`. So a nullish base is a
11840 // `TypeError` and the key is **never coerced** — `null[{toString(){throw}}]`
11841 // throws the TypeError, not the key's exception
11842 // (`S11.3.1_A6_T1`). A write has the opposite order, which is why
11843 // `PutArrayEl` deliberately does not do this.
11844 //
11845 // Only nullish is checked here, and the full boxing is still left to
11846 // `read_field_key`: a string base has an index fast path that turning it
11847 // into a `String` object up front would throw away.
11848 if object.is_nullish() {
11849 return Err(Signal::Throw(self.make_error(
11850 "TypeError",
11851 &format!("cannot read property of {}", object.to_js_string()),
11852 )));
11853 }
11854 let key = self.propkey(&key)?;
11855 let value = self.read_field_key(&object, &key)?;
11856 if matches!(op, GetArrayEl2 | GetArrayEl3) {
11857 self.push(object);
11858 }
11859 if op == GetArrayEl3 {
11860 // The key goes back in its *value* form, which the compiler stores
11861 // into the target of a destructuring assignment.
11862 self.push(match &key {
11863 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11864 PropertyKey::String(text) => self.string_wtf8(text.clone()),
11865 });
11866 }
11867 self.push(value);
11868 }
11869 PutField => {
11870 let value = self.pop();
11871 let object = self.pop();
11872 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
11873 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
11874 // only reads. `this.value = …` is the write half of the hottest loop in
11875 // `property:method-call`, and `own_property_key` was 4.8% of the case.
11876 let code = self.frame().code.clone();
11877 let key = &code.atom_keys[a as usize];
11878 self.write_field_key(&object, key, value)?;
11879 }
11880 PutArrayEl => {
11881 let value = self.pop();
11882 let key = self.pop();
11883 let object = self.pop();
11884 let key = self.propkey(&key)?;
11885 self.write_field_key(&object, &key, value)?;
11886 }
11887 DefineField => {
11888 let value = self.pop();
11889 let object = self.pop();
11890 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
11891 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
11892 // three U+FFFD — a property under a different name from the one
11893 // `o["\uD800"]` reads.
11894 let code = self.frame().code.clone();
11895 let key = code.atom_keys[a as usize].clone();
11896 // No naming here. `{m: function(){}}` is named by the *compiler*, which
11897 // emits `set_name` — and only where `NamedEvaluation` applies, so
11898 // `{m: (0, function(){})}` stays anonymous. Naming every function that
11899 // reaches a property definition got that case wrong, and the compiler is
11900 // the only place that can tell the two apart.
11901 if let Some(target) = object.as_object() {
11902 // Only an *array* stores into the element vector. A numeric key
11903 // on an ordinary object is an ordinary property, which is what
11904 // makes `{1: 'a'}` iterate as a key rather than disappear.
11905 let stored = target.is_array()
11906 && key.as_str().and_then(array_index).is_some_and(|index| {
11907 target.array_set(self.heap, index as usize, value.clone())
11908 });
11909 if !stored {
11910 // `CreateDataPropertyOrThrow`, not a raw table insert: a class
11911 // field is defined with `[[DefineOwnProperty]]`, so a frozen
11912 // receiver throws (`class Test { f = Object.freeze(this); g = 1 }`
11913 // must fail on `g`) and a **proxy** receiver runs its
11914 // `defineProperty` trap (`class-field-is-observable-by-proxy`
11915 // counts the trap's calls). `define_data_key` writes straight into
11916 // the table, which did neither.
11917 // `?` and not `unwrap_or(false)`: a proxy's `defineProperty` trap
11918 // may *throw*, and that exception is the answer
11919 // (`public-class-field-initialization-is-visible-to-proxy` throws
11920 // a `Test262Error` from the trap and expects it, not a `TypeError`).
11921 let defined =
11922 self.object_define_own_property(target, &key, Property::data(value))?;
11923 if !defined {
11924 let target = Value::Object(target.clone());
11925 return Err(Signal::Throw(self.make_error(
11926 "TypeError",
11927 &format!(
11928 "cannot define property '{key}' of {}",
11929 target.to_js_string()
11930 ),
11931 )));
11932 }
11933 }
11934 }
11935 self.push(object);
11936 }
11937 DefineArrayEl => {
11938 // `obj key value -> obj key`. The *value* form of the key is what goes
11939 // back on the stack — the compiler stores it into the pattern's binding —
11940 // so the symbol is not stringified on the way through.
11941 let value = self.pop();
11942 let key_value = self.pop();
11943 let object = self.peek(0);
11944 let key = self.propkey(&key_value)?;
11945 self.write_field_key(&object, &key, value)?;
11946 self.push(key_value);
11947 }
11948 SetHomeObject => {
11949 // `obj func -> obj func`: records the object a method was defined on so
11950 // `super` inside it resolves against that object's prototype.
11951 let function = self.peek(0);
11952 let home = self.peek(1);
11953 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
11954 function.set_home_object(Some(home.clone()));
11955 }
11956 }
11957 Regexp => {
11958 // `pattern flags -> regexp`. A literal compiles here rather than through the
11959 // constructor, which is both what the reference's dedicated opcode is for
11960 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
11961 let flags = self.pop();
11962 let pattern = self.pop();
11963 let pattern = self.to_js_string(&pattern)?;
11964 let flags = self.to_js_string(&flags)?;
11965 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
11966 self.push(Value::Object(object));
11967 }
11968 UsingDisposeInit => {
11969 // The error state a disposal accumulates into. Uninitialised means "no
11970 // failure yet"; anything else is the exception being propagated.
11971 self.push(Value::Uninitialized);
11972 }
11973 UsingCheck => {
11974 // `value -> value, method`: validate and snapshot the disposer now, so a
11975 // later change to `Symbol.dispose` cannot change what gets called, and so a
11976 // value that is not disposable fails before the body runs.
11977 let value = self.pop();
11978 let method = self.using_method_for(&value, a as u8 == 1)?;
11979 self.push(value);
11980 self.push(method);
11981 }
11982 UsingDispose => {
11983 // `error_state -> error_state'`: dispose the variable at `slot` — its value
11984 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
11985 // the pending error.
11986 let slot = self.slot_operand(op, a);
11987 let error_state = self.pop();
11988 let merged = self.using_dispose_once(slot, error_state)?;
11989 self.push(merged);
11990 }
11991 UsingDisposeMerge => {
11992 let new_error = self.pop();
11993 let error_state = self.pop();
11994 let merged = self.merge_dispose_error(new_error, error_state);
11995 self.push(merged);
11996 }
11997 UsingDisposeEnd => {
11998 // A disposal that failed replaces the block's normal completion, so the
11999 // error state becomes a real throw here rather than at the call site.
12000 let error_state = self.pop();
12001 if !matches!(error_state, Value::Uninitialized) {
12002 return Err(Signal::Throw(error_state));
12003 }
12004 }
12005 UsingDisposeAsync => {
12006 // `await using` needs a promise to await and this runtime has no
12007 // `Promise` builtin, so the disposer is called synchronously and its result
12008 // discarded. That is correct for a disposer that returns nothing and is
12009 // reported as a gap rather than silently skipped.
12010 let slot = self.slot_operand(op, a);
12011 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
12012 self.push(error_state);
12013 }
12014 GetSuper => {
12015 // `obj -> obj's prototype`: the starting point of a `super` lookup.
12016 let object = self.pop();
12017 let proto = match &object {
12018 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
12019 _ => Value::Null,
12020 };
12021 self.push(proto);
12022 }
12023 GetSuperValue => {
12024 // `receiver proto key -> value`, searching from `proto` but reporting to
12025 // `receiver`, which is what `super.g` must do for a getter to see `this`.
12026 //
12027 // Three values in, one out: the receiver is *consumed*, not left under the
12028 // result. Leaving it there was invisible for `super.x` in `return` or
12029 // statement position (the result is what gets popped) and corrupted the
12030 // frame everywhere else — `print(super.x)` left the class where the call
12031 // opcode looks for the receiver and called the class itself.
12032 let key = self.pop();
12033 let proto = self.pop();
12034 let receiver = self.pop();
12035 let value = self.super_read(&receiver, &proto, &key)?;
12036 self.push(value);
12037 }
12038 PutSuperValue => {
12039 // `receiver proto key value ->`: a store that starts at `proto` but
12040 // assigns to `receiver`.
12041 let value = self.pop();
12042 let key = self.pop();
12043 let proto = self.pop();
12044 let receiver = self.pop();
12045 self.super_write(&receiver, &proto, &key, value)?;
12046 }
12047 DefineClass => {
12048 // `parent ctor -> ctor proto`: the constructor becomes the class and a
12049 // fresh prototype object lands on top for the methods to go on.
12050 let name = self.atom_text(a as usize);
12051 let (ctor, proto) = self.define_class(&name, b)?;
12052 self.push(ctor);
12053 self.push(Value::Object(proto));
12054 }
12055 DefineClassComputed => {
12056 // `parent ctor key -> ctor proto key`: the computed name stays put so
12057 // `define_field`-style consumers can still read it.
12058 let key = self.pop();
12059 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
12060 let (ctor, proto) = self.define_class(&name, b)?;
12061 self.push(ctor);
12062 self.push(Value::Object(proto));
12063 self.push(key);
12064 }
12065 DefineMethod => {
12066 let function = self.pop();
12067 let object = self.pop();
12068 // The exact key, like `define_field`: a quoted method key may hold an
12069 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
12070 // that `o["\uD800"]` finds.
12071 let code = self.frame().code.clone();
12072 let key = code.atom_keys[a as usize].clone();
12073 // A method's `[[HomeObject]]` is the object it was defined on, which is
12074 // what `super` inside it resolves against.
12075 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12076 function.set_home_object(Some(object.clone()));
12077 }
12078 let name = match key.as_wtf8() {
12079 Some(text) => text.clone(),
12080 // A symbol atom — one of the well-known symbols, which the lexer keeps
12081 // as an atom rather than a runtime value. Its name is the bracketed
12082 // description, like any other symbol key.
12083 None => symbol_key_name(&key),
12084 };
12085 self.set_function_name_wtf8(&function, &accessor_prefixed(&name, b));
12086 if let Some(array) = object.as_object() {
12087 define_function_property(array, &key, function, b);
12088 }
12089 self.push(object);
12090 }
12091 DefineMethodComputed => {
12092 let function = self.pop();
12093 let key = self.pop();
12094 let object = self.pop();
12095 let key = self.propkey(&key)?;
12096 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
12097 // the name: `super` inside a computed method resolves through it. Without
12098 // this, `class B extends A { [k]() { return super.m() } }` read the
12099 // home object as null and threw.
12100 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
12101 function.set_home_object(Some(object.clone()));
12102 }
12103 // A symbol key names the method `[description]`, or `""` without one —
12104 // §7.3.24, the same rule [`Interp::function_name_from_key`] applies to
12105 // `set_name_computed`. Falling back to `to_string` here named every
12106 // `{ [sym](){} }` method `Symbol()` instead.
12107 match &key {
12108 PropertyKey::Symbol(_) => {
12109 // The accessor prefix still applies: `get [Symbol.iterator](){}`
12110 // is named `"get [Symbol.iterator]"`.
12111 let name = accessor_prefixed(&symbol_key_name(&key), a);
12112 self.set_function_name_wtf8(&function, &name);
12113 }
12114 PropertyKey::String(text) => {
12115 let name = accessor_prefixed(text, a);
12116 self.set_function_name_wtf8(&function, &name);
12117 }
12118 }
12119 if let Some(array) = object.as_object() {
12120 define_function_property(array, &key, function, a);
12121 }
12122 self.push(object);
12123 }
12124 SetProto => {
12125 let proto = self.pop();
12126 let object = self.pop();
12127 if let Some(target) = object.as_object() {
12128 target.set_proto(proto.as_object().cloned());
12129 }
12130 self.push(object);
12131 }
12132 CopyDataProperties => {
12133 let exclusion = self.pop();
12134 let source = self.pop();
12135 let target = self.peek(0);
12136 self.copy_properties(&target, &source, &exclusion)?;
12137 self.push(source);
12138 self.push(exclusion);
12139 }
12140 ToPropkey => {
12141 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
12142 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
12143 // ordinary `"Symbol(b)"` property.
12144 let value = self.pop();
12145 let key = match self.propkey(&value)? {
12146 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
12147 PropertyKey::String(text) => self.string_wtf8(text),
12148 };
12149 self.push(key);
12150 }
12151 SetName => {
12152 let function = self.peek(0);
12153 let name = self.atom_wtf8(a as usize);
12154 self.set_function_name_wtf8(&function, &name);
12155 }
12156 SetNameComputed => {
12157 let key = self.peek(1);
12158 let function = self.peek(0);
12159 let name = self.function_name_from_key(&key)?;
12160 self.set_function_name_wtf8(&function, &name);
12161 }
12162
12163 // -- arrays -----------------------------------------------------
12164 ArrayFrom => {
12165 let count = a as usize;
12166 let elements = self.pop_n(count);
12167 let array = self.new_array(elements);
12168 self.push(Value::Object(array));
12169 }
12170 Append => {
12171 // `array index iterable -> array new_index`
12172 let iterable = self.pop();
12173 self.pop();
12174 let array = self.peek(0);
12175 let added = self.append_enumerate(&array, &iterable)?;
12176 self.push(Value::Int(added));
12177 }
12178
12179 // -- iteration --------------------------------------------------
12180 ForInStart => {
12181 let value = self.pop();
12182 let record = self.for_in_record(&value)?;
12183 self.push(Value::Object(record));
12184 }
12185 ForInNext => {
12186 // `record -> record key done`. The flag is *done*, not "found":
12187 // the compiler tests it with `if_false` to jump back into the body,
12188 // so reporting `true` while keys remain would end the loop at once.
12189 let record = self.peek(0);
12190 match self.for_in_advance(&record)? {
12191 Some(key) => {
12192 let text = self.string(key);
12193 self.push(text);
12194 self.push(Value::Bool(false));
12195 }
12196 None => {
12197 self.push(Value::Undefined);
12198 self.push(Value::Bool(true));
12199 }
12200 }
12201 }
12202 ForOfStart => {
12203 let value = self.pop();
12204 let iterator = self.get_iterator(&value)?;
12205 self.push(iterator.object);
12206 self.push(iterator.next);
12207 self.push(Value::CatchOffset(0));
12208 }
12209 ForOfNext => {
12210 // `iter next catch_offset -> iter next catch_offset value done`.
12211 //
12212 // The operand is how many values sit *above* the iterator triple: a
12213 // destructuring rest element keeps its target array and running index
12214 // there while draining the iterator, so the triple is not at the top.
12215 let extra = a as usize;
12216 let iterator_slot = 2 + extra;
12217 // An exhausted iterator is replaced by `undefined` (see below), so a
12218 // second step must not call `next` again — `Array.from` and a
12219 // destructuring pattern both keep stepping past the end.
12220 let stepped = if matches!(self.peek(iterator_slot), Value::Undefined) {
12221 Ok((Value::Undefined, true))
12222 } else {
12223 let iterator = Iterator {
12224 object: self.peek(iterator_slot),
12225 next: self.peek(1 + extra),
12226 };
12227 self.iterator_step(&iterator)
12228 };
12229 let (value, done) = match stepped {
12230 Ok(stepped) => stepped,
12231 Err(signal) => {
12232 // An exception from `next()` is not an abrupt completion of the
12233 // *body*, so §7.4.6 does not apply and the iterator must not be
12234 // closed: `[ , ] = iterable` with a throwing `next` expects
12235 // `returnCount === 0`. Clearing the slot is how the reference says
12236 // so (`js_for_of_next`: `sp[offset] = JS_UNDEFINED` before it
12237 // returns -1), and it is also what makes the destructor below — the
12238 // exception path's `catch_offset 0` close — a no-op here.
12239 self.clear_iterator_slot(iterator_slot);
12240 return Err(signal);
12241 }
12242 };
12243 if done {
12244 // The result's `value` is meaningless once the iterator is done:
12245 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
12246 // rather than binding the generator's return value.
12247 let top = self.frame().stack.len() - 1 - iterator_slot;
12248 self.frame_mut().stack[top] = Value::Undefined;
12249 self.push(Value::Undefined);
12250 self.push(Value::Bool(true));
12251 } else {
12252 self.push(value);
12253 self.push(Value::Bool(false));
12254 }
12255 }
12256 IteratorNext => {
12257 // `iter next catch val -> iter next catch val'`: replace the argument with
12258 // the result of `next(val)`. The triple below stays put, which is why the
12259 // three instructions of the `yield*` loop all address the stack the same way.
12260 let value = self.pop();
12261 let object = self.peek(2);
12262 let next = self.peek(1);
12263 let result = self.call_value(next, object, vec![value])?;
12264 self.push(result);
12265 }
12266 IteratorCall => {
12267 // `iter next catch val -> iter next catch val' flag`.
12268 //
12269 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
12270 // The flag is `true` when the method was missing, which is how the
12271 // caller learns that the inner iterator cannot take part in the
12272 // unwinding.
12273 let value = self.pop();
12274 let object = self.peek(2);
12275 let key = if a & 1 != 0 { "throw" } else { "return" };
12276 let method = self.read_field(&object, key)?;
12277 if matches!(method, Value::Undefined | Value::Null) {
12278 self.push(value);
12279 self.push(Value::Bool(true));
12280 } else {
12281 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
12282 let result = self.call_value(method, object, argument)?;
12283 self.push(result);
12284 self.push(Value::Bool(false));
12285 }
12286 }
12287 IteratorCheckObject => {
12288 if !matches!(self.peek(0), Value::Object(_)) {
12289 return Err(Signal::Throw(
12290 self.make_error("TypeError", "iterator must return an object"),
12291 ));
12292 }
12293 }
12294 IteratorClose => {
12295 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
12296 // calling the iterator's `return` so it can release whatever it holds.
12297 //
12298 // The catch offset goes first, so an exception from `return` is not caught
12299 // by the loop being abandoned. This used to pop the three operands and call
12300 // nothing at all, which made `break` out of a `for of` invisible to an
12301 // iterator with a `return` method.
12302 self.pop();
12303 self.pop();
12304 let iterator = self.pop();
12305 if !matches!(iterator, Value::Undefined) {
12306 let method = self.read_field(&iterator, "return")?;
12307 if !matches!(method, Value::Undefined | Value::Null) {
12308 let result = self.call_value(method, iterator.clone(), Vec::new())?;
12309 // §7.4.6: a `return` that answers a non-object is a TypeError.
12310 if !matches!(result, Value::Object(_)) {
12311 return Err(Signal::Throw(
12312 self.make_error("TypeError", "iterator must return an object"),
12313 ));
12314 }
12315 }
12316 }
12317 }
12318 Import => {
12319 // `import(specifier, options)`: the options slot is on top. Both are
12320 // `GetValue`-ed by the compiler, which is why this pops values rather than
12321 // references — and why the validation of `options` (§13.3.10.1 step 10)
12322 // happens inside `dynamic_import`, where its failures can be turned into a
12323 // rejection instead of a throw.
12324 let options = self.pop();
12325 let specifier = self.pop();
12326 let promise = self.dynamic_import(specifier, options)?;
12327 self.push(promise);
12328 }
12329 ForAwaitOfStart => {
12330 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
12331 // `Symbol.iterator` fallback.
12332 let value = self.pop();
12333 let iterator = self.get_async_iterator(&value)?;
12334 self.push(iterator.object);
12335 self.push(iterator.next);
12336 self.push(Value::CatchOffset(0));
12337 }
12338 ForAwaitOfNext => {
12339 // `for await` steps the iterator and leaves the *result* wrapped in a
12340 // promise, so the `await` the compiler emits right after this can suspend
12341 // on it. Unwrapping happens in `iterator_get_value_done`.
12342 let extra = a as usize;
12343 let iterator_slot = 2 + extra;
12344 // The enumerator marker is **disabled for the step**, and
12345 // `iterator_get_value_done` puts it back once the result has survived the
12346 // awaiting. Both halves are load-bearing for the async case:
12347 //
12348 // * a rejection is not "the body threw", so the loop must not close the
12349 // iterator *again* — the wrapper already did;
12350 // * but until the result arrives the record is live, so a later failure
12351 // still has to close it.
12352 //
12353 // The reference says the same in one line each
12354 // (`js_for_await_of_next`: `sp[-1] = JS_UNDEFINED; /* disable the catch
12355 // offset so that exceptions do not close the iterator */`).
12356 self.clear_iterator_slot(extra);
12357 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
12358 Value::Undefined
12359 } else {
12360 let iterator = Iterator {
12361 object: self.peek(iterator_slot),
12362 next: self.peek(1 + extra),
12363 };
12364 let next = iterator.next.clone();
12365 self.call_value(next, iterator.object, Vec::new())?
12366 };
12367 let promise = self.promise_resolve_value(result)?;
12368 self.push(promise);
12369 }
12370 IteratorGetValueDone => {
12371 // `result -> value done`. A missing result object means the iterator was
12372 // already exhausted, which the loop treats as `done`.
12373 let result = self.pop();
12374 // Re-arm the marker `for_await_of_next` disabled; the step got this far, so
12375 // from here on the record is closeable again.
12376 {
12377 let depth = self.frame().stack.len();
12378 if depth >= 2 {
12379 self.frame_mut().stack[depth - 1] = Value::CatchOffset(0);
12380 }
12381 }
12382 let done = match &result {
12383 Value::Object(object) => self
12384 .get_property(object, "done")?
12385 .is_some_and(|value| value.to_boolean()),
12386 _ => true,
12387 };
12388 if done {
12389 // Clear the iterator object so the `iterator_close` the loop emits on
12390 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
12391 // on normal completion, and this is where a normal completion is
12392 // recognised — the same trick `for_of_next` uses, which also replaces
12393 // the slot with `undefined`.
12394 //
12395 // The layout is fixed because only `for await` emits this opcode:
12396 // `iter next catch [result]`, so the iterator is three below the top.
12397 let depth = self.frame().stack.len();
12398 if depth >= 3 {
12399 self.frame_mut().stack[depth - 3] = Value::Undefined;
12400 }
12401 self.push(Value::Undefined);
12402 self.push(Value::Bool(true));
12403 } else {
12404 let Value::Object(object) = &result else {
12405 self.push(Value::Undefined);
12406 self.push(Value::Bool(true));
12407 return Ok(Step::Continue);
12408 };
12409 let value = self
12410 .get_property(object, "value")?
12411 .unwrap_or(Value::Undefined);
12412 self.push(value);
12413 self.push(Value::Bool(false));
12414 }
12415 }
12416
12417 Delete => {
12418 // `delete obj[key]`, where the key was just pushed. Deleting an array
12419 // index leaves a *hole* rather than closing the gap, and a
12420 // non-configurable property answers `false` and stays.
12421 let key = self.pop();
12422 let target = self.pop();
12423 let key = self.propkey(&key)?;
12424 let text_label = key.as_str().unwrap_or("").to_string();
12425 let deleted = match &target {
12426 Value::Object(object) => {
12427 let object = object.clone();
12428 self.delete_property_key(&object, &key)?
12429 }
12430 // A string's `length` and its index properties are
12431 // non-configurable, so deleting one answers `false`.
12432 Value::String(text) => {
12433 !(text_label == "length"
12434 || array_index(&text_label)
12435 .is_some_and(|index| (index as usize) < text.utf16_len()))
12436 }
12437 // "delete null.a" is a TypeError, not a no-op: the operator needs an
12438 // object to delete from, and only a *boxable* primitive has one.
12439 Value::Undefined | Value::Null => {
12440 return Err(Signal::Throw(
12441 self.make_error("TypeError", "cannot convert to object"),
12442 ));
12443 }
12444 // Any other primitive has no own properties; deleting nothing
12445 // succeeds.
12446 _ => true,
12447 };
12448 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
12449 // `TypeError` rather than a `false` result. Sloppy mode silently reports
12450 // the refusal, which is why the same statement throws here but not there.
12451 if !deleted && self.current_strict() {
12452 return Err(Signal::Throw(
12453 self.make_error("TypeError", "cannot delete property"),
12454 ));
12455 }
12456 self.push(Value::Bool(deleted));
12457 }
12458
12459 // -- exceptions and bookkeeping ---------------------------------
12460 Fclosure | Fclosure8 => {
12461 let value = self.closure(a as usize)?;
12462 self.push(value);
12463 }
12464
12465 other => {
12466 let name = other.info().name;
12467 return Err(Signal::Throw(self.make_error(
12468 "InternalError",
12469 &format!("{name} is not implemented yet"),
12470 )));
12471 }
12472 }
12473 Ok(Step::Continue)
12474 }
12475
12476 // -- operand helpers ----------------------------------------------------
12477
12478 /// The slot index an operand names, taking short forms into account.
12479 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
12480 use Opcode::*;
12481 match op {
12482 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
12483 | SetVarRef0 => 0,
12484 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
12485 | SetVarRef1 => 1,
12486 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
12487 | SetVarRef2 => 2,
12488 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
12489 | SetVarRef3 => 3,
12490 _ => a as usize,
12491 }
12492 }
12493
12494 /// The argument count of a call, taking `call0`…`call3` into account.
12495 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
12496 use Opcode::*;
12497 match op {
12498 Call0 => 0,
12499 Call1 => 1,
12500 Call2 => 2,
12501 Call3 => 3,
12502 _ => a as usize,
12503 }
12504 }
12505
12506 /// The atom's name as a property key.
12507 ///
12508 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
12509 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
12510 /// `String::clone` was a heap allocation and a copy — per property access.
12511 /// The atom at `index`, as a property key.
12512 ///
12513 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
12514 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
12515 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
12516 /// 5.3% of `property:monomorphic`.
12517 /// The atom's text, exactly — including an unpaired surrogate.
12518 ///
12519 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
12520 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
12521 /// `atom_text` below is for the other kind of use, where the atom is a key in the
12522 /// engine's own tables.
12523 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
12524 self.frame()
12525 .code
12526 .code
12527 .atoms
12528 .get(index)
12529 .map(|atom| match atom {
12530 Atom::Str(text) => text.clone(),
12531 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
12532 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
12533 Atom::Null => crate::value::Wtf8::new(String::new()),
12534 })
12535 .unwrap_or_default()
12536 }
12537
12538 fn atom_text(&self, index: usize) -> String {
12539 self.frame()
12540 .code
12541 .code
12542 .atoms
12543 .get(index)
12544 .map(|atom| match atom {
12545 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
12546 // compare it to an identifier, and a surrogate-bearing name is reachable
12547 // through `atom_wtf8` where it matters.
12548 Atom::Str(text) => text.to_string_lossy().into_owned(),
12549 Atom::Index(value) => value.to_string(),
12550 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
12551 // `throw_error`, `delete super.x`) never read it.
12552 Atom::Null => String::new(),
12553 })
12554 .unwrap_or_default()
12555 }
12556
12557 fn constant(&mut self, index: usize) -> JsResult<Value> {
12558 let constant = self.frame().code.code.cpool.get(index).cloned();
12559 Ok(match &constant {
12560 Some(Constant::Number(number)) => Value::Float(*number),
12561 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
12562 Some(Constant::BigInt { digits, radix }) => {
12563 match crate::bigint::BigInt::from_radix(digits, *radix) {
12564 Some(big) => self.bigint(big),
12565 // A literal the parser accepted is always parseable; a failure here
12566 // would be a compiler bug, so it reads as an `InternalError`.
12567 None => {
12568 return Err(Signal::Throw(
12569 self.make_error("InternalError", "unparseable bigint literal"),
12570 ));
12571 }
12572 }
12573 }
12574 Some(Constant::Function(_)) => {
12575 return Err(Signal::Throw(
12576 self.make_error("InternalError", "a bare function constant"),
12577 ));
12578 }
12579 // A tagged template's call site: a frozen array of the cooked chunks with a
12580 // frozen `raw` array beside it, which is what `String.raw` reads back.
12581 Some(Constant::Template { cooked, raw }) => {
12582 let cooked_values: Vec<Value> = cooked
12583 .iter()
12584 .map(|chunk| match chunk {
12585 Some(text) => self.string_wtf8(text.clone()),
12586 None => Value::Undefined,
12587 })
12588 .collect();
12589 let raw_values: Vec<Value> =
12590 raw.iter().map(|text| self.string(text.clone())).collect();
12591 let raw_array = self.new_array(raw_values);
12592 raw_array.set_extensible(false);
12593 let template = self.new_array(cooked_values);
12594 template.define(
12595 "raw",
12596 Property::with_attributes(Value::Object(raw_array), false, false),
12597 );
12598 template.set_extensible(false);
12599 Value::Object(template)
12600 }
12601 _ => Value::Undefined,
12602 })
12603 }
12604
12605 /// The reference cell a closure-variable slot names.
12606 ///
12607 /// Two kinds of binding share this addressing: a genuine closure variable
12608 /// (captured from an enclosing function) lives in this frame's environment,
12609 /// while a *declared global* lives in the realm so that a script, a function
12610 /// declaration and their uses all see one binding. A plain `Global` — an
12611 /// undeclared name that may be satisfied by the global object — has no cell at
12612 /// all, which is how `typeof x` still works for a name that does not exist.
12613 /// The reference cell a closure-variable slot names.
12614 ///
12615 /// The environment is resolved once, when the closure is built, and this is
12616 /// just the lookup afterwards. A *declared global* is in there too, pointing at
12617 /// the realm's cell, so a script, a hoisted function declaration and their uses
12618 /// all share one binding. A plain `Global` — a name the script never declared —
12619 /// is read and written through `get_var`/`put_var` by name instead, which is
12620 /// what lets the global object satisfy it.
12621 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
12622 self.frame().env.cells.get(slot).cloned()
12623 }
12624
12625 /// Whether `slot` refers to a global binding through the reference table.
12626 ///
12627 /// A global's cell in the closure environment only exists so the slot has
12628 /// something to point at; the binding itself lives on the global object (a `var`)
12629 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
12630 /// be routed, not performed on the placeholder.
12631 fn is_global_slot(&self, slot: usize) -> bool {
12632 self.frame()
12633 .code
12634 .code
12635 .closure_vars
12636 .get(slot)
12637 .is_some_and(|c| {
12638 // A module's declarations and imports are *not* globals: their cells are
12639 // the module environment's, filled by the host, so the placeholder routing
12640 // must not apply to them.
12641 matches!(
12642 c.closure_type,
12643 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
12644 )
12645 })
12646 }
12647
12648 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
12649 if self.is_global_slot(slot) {
12650 return self.get_global(slot);
12651 }
12652 Ok(self
12653 .var_ref_cell(slot)
12654 .map(|cell| cell.get())
12655 .unwrap_or(Value::Undefined))
12656 }
12657
12658 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
12659 // A function declaration is hoisted by storing into a global reference before
12660 // the body runs, so this path is also what puts it on the global object.
12661 if self.is_global_slot(slot) {
12662 return self.put_global(slot, value);
12663 }
12664 if let Some(cell) = self.var_ref_cell(slot) {
12665 cell.set(value);
12666 }
12667 Ok(())
12668 }
12669
12670 // -- closures -----------------------------------------------------------
12671
12672 /// Build the closure for the function constant `index`.
12673 ///
12674 /// Every entry in the child's closure table names where its binding lives in
12675 /// *this* frame: a local or argument slot that was marked captured, or a cell
12676 /// this frame is itself holding. That is how a variable three functions deep
12677 /// stays one binding.
12678 fn closure(&mut self, index: usize) -> JsResult<Value> {
12679 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
12680 else {
12681 return Err(Signal::Throw(
12682 self.make_error("InternalError", "fclosure of a non-function"),
12683 ));
12684 };
12685 let mut cells = Vec::with_capacity(function.closure_vars.len());
12686 for closure_var in &function.closure_vars {
12687 let cell = match closure_var.closure_type {
12688 ClosureType::Arg => {
12689 let slot = closure_var.var_idx as usize;
12690 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
12691 }
12692 ClosureType::Local => {
12693 let slot = closure_var.var_idx as usize;
12694 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
12695 }
12696 ClosureType::Ref | ClosureType::GlobalRef => {
12697 // A `Ref` names a cell in this frame's own closure table; a
12698 // `GlobalRef` also starts there, then resolves by name below.
12699 let slot = closure_var.var_idx as usize;
12700 if let Some(cell) = self.frame().env.cells.get(slot) {
12701 cells.push(cell.clone());
12702 continue;
12703 }
12704 -1
12705 }
12706 _ => -1,
12707 };
12708 if cell >= 0 {
12709 let cell = self.frame().cells[cell as usize].clone();
12710 cells.push(cell);
12711 continue;
12712 }
12713 // A global: the cell is created on demand and shared through the realm,
12714 // so every function sees one binding.
12715 let name = closure_var.name.clone();
12716 let cell = match self.realm.globals.get(&name) {
12717 Some(cell) => cell.clone(),
12718 None => {
12719 let cell = self.new_cell(Value::Undefined);
12720 self.realm.globals.insert(name.clone(), cell.clone());
12721 cell
12722 }
12723 };
12724 cells.push(cell);
12725 }
12726 let name = function.name.clone();
12727 // `.length` is the arity before any default or rest parameter, not the number
12728 // of slots a pattern parameter needs.
12729 let length = function.defined_args;
12730 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
12731 // function and an arrow function do not. A *method* also does not, but that is not
12732 // known here — the method is marked when the `[[HomeObject]]` is attached (see
12733 // `set_home_object`), which is the moment it becomes a method.
12734 let function_kind = function.kind;
12735 let constructible =
12736 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
12737 let code = Gc::new(self.heap, CompiledCode::new(*function));
12738 // A closure built inside an `eval` inherits the eval's view of the enclosing
12739 // bindings, so it can still read them once the eval has returned.
12740 let eval_scope = self
12741 .active_eval_scope
12742 .clone()
12743 .or_else(|| self.frame().env.eval_scope.clone());
12744 // A closure sees the variables a direct `eval` declared in the frame it was
12745 // created in — the ones declared before *and after* it, so the same object is
12746 // shared; only the phase bounds which of them are visible.
12747 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
12748 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
12749 let env = Gc::new(
12750 self.heap,
12751 ClosureEnv {
12752 cells,
12753 eval_scope,
12754 local_vars,
12755 local_phase,
12756 },
12757 );
12758 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
12759 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
12760 // the only thing that carries `Symbol.toStringTag`, so without it
12761 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
12762 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
12763 let proto = match function_kind {
12764 js_compile::bytecode::FunctionKind::AsyncGenerator => self
12765 .realm
12766 .async_generator_function_proto
12767 .clone()
12768 .or_else(|| self.realm.function_proto.clone().into()),
12769 js_compile::bytecode::FunctionKind::Generator => self
12770 .realm
12771 .generator_function_proto
12772 .clone()
12773 .or_else(|| self.realm.function_proto.clone().into()),
12774 js_compile::bytecode::FunctionKind::Async => self
12775 .realm
12776 .async_function_proto
12777 .clone()
12778 .or_else(|| self.realm.function_proto.clone().into()),
12779 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
12780 };
12781 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
12782 object.set_constructible(constructible);
12783 object.define(
12784 "length",
12785 Property::name_or_length(Value::Int(length as i32)),
12786 );
12787 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
12788 // that checks the own-property descriptor fails if the property is missing.
12789 object.define("name", Property::name_or_length(self.string(name)));
12790 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
12791 // when `[[Construct]]` is created, so an async function and an arrow function have
12792 // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
12793 // function) an own `prototype` property, which `builtin.js` checks for absence.
12794 //
12795 // A **generator** function is the exception that is not constructible: it still
12796 // gets a `prototype` field, because that object is what a generator *instance*
12797 // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
12798 // made `function* g(){}; g.prototype` `undefined` and every generator share
12799 // `%GeneratorPrototype%` as its direct prototype.
12800 if constructible {
12801 self.install_function_prototype(&object);
12802 } else if matches!(
12803 function_kind,
12804 js_compile::bytecode::FunctionKind::Generator
12805 | js_compile::bytecode::FunctionKind::AsyncGenerator
12806 ) {
12807 let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
12808 self.realm.generator_proto.clone()
12809 } else {
12810 self.realm
12811 .async_generator_proto
12812 .clone()
12813 .unwrap_or_else(|| self.realm.generator_proto.clone())
12814 };
12815 self.install_generator_prototype(&object, parent);
12816 }
12817 Ok(Value::Object(object))
12818 }
12819
12820 // -- conversions used by the operators ----------------------------------
12821
12822 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
12823 // `+x` is `ToNumber`, which for a string parses it and for an object runs
12824 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
12825 // string, which then behaves differently in every later comparison.
12826 match value {
12827 Value::Int(_) | Value::Float(_) => Ok(value),
12828 other => Ok(Value::Float(self.to_js_number(&other)?)),
12829 }
12830 }
12831
12832 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
12833 ///
12834 /// Returns the *converted* old value and the new one, because the two callers need
12835 /// different halves: `++x` yields the new value, while `x++` yields the old one and
12836 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
12837 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
12838 /// boolean.
12839 ///
12840 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
12841 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
12842 /// a bigint algorithm then ran exactly once.
12843 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
12844 if let Value::BigInt(big) = &value {
12845 let one = crate::bigint::BigInt::from_i64(1);
12846 let next = if up { big.add(&one) } else { big.sub(&one) };
12847 return Ok((value, self.bigint(next)));
12848 }
12849 let old = self.numeric(value)?;
12850 let new = if up {
12851 increment(old.clone())
12852 } else {
12853 decrement(old.clone())
12854 };
12855 Ok((old, new))
12856 }
12857
12858 fn numeric(&mut self, value: Value) -> JsResult<Value> {
12859 // `ToNumber` on an object runs `ToPrimitive` first, which is how
12860 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
12861 // heard at all. Reading the object's own tag instead (`other.to_number()`)
12862 // turned the whole operand into `NaN` and swallowed the exception.
12863 match value {
12864 Value::Int(_) | Value::Float(_) => Ok(value),
12865 other => Ok(Value::Float(self.to_js_number(&other)?)),
12866 }
12867 }
12868
12869 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
12870 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
12871 match value {
12872 Value::BigInt(big) => Ok((**big).clone()),
12873 // The reference words this the same way for every operator, so a failing
12874 // script reads identically; the operator itself adds nothing a caller can use.
12875 _ => Err(Signal::Throw(
12876 self.make_error("TypeError", "cannot convert bigint to number"),
12877 )),
12878 }
12879 }
12880
12881 /// Arithmetic where at least one operand is a `BigInt`.
12882 ///
12883 /// The two numeric types never mix, so a bigint paired with anything else is an error
12884 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
12885 /// that the relational operators handle it separately.
12886 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12887 use Opcode::*;
12888 let a = self.bigint_operand(&left)?;
12889 let b = self.bigint_operand(&right)?;
12890 let result = match op {
12891 Add => a.add(&b),
12892 Sub => a.sub(&b),
12893 Mul => a.mul(&b),
12894 Div | Mod => {
12895 let Some((quotient, remainder)) = a.div_rem(&b) else {
12896 return Err(Signal::Throw(
12897 self.make_error("RangeError", "division by zero"),
12898 ));
12899 };
12900 if op == Div { quotient } else { remainder }
12901 }
12902 Pow => {
12903 let Some(value) = a.pow(&b) else {
12904 return Err(Signal::Throw(self.make_error(
12905 "RangeError",
12906 "BigInt exponent must be non-negative and not absurdly large",
12907 )));
12908 };
12909 value
12910 }
12911 And => a.bitand(&b),
12912 Or => a.bitor(&b),
12913 Xor => a.bitxor(&b),
12914 Shl | Sar => {
12915 // A shift count is a `BigInt` here, and both directions are exact; a
12916 // negative count would be the other direction, which the spec forbids.
12917 let Some(count) = b.to_i64() else {
12918 return Err(Signal::Throw(
12919 self.make_error("RangeError", "BigInt shift count is too large"),
12920 ));
12921 };
12922 if count < 0 {
12923 return Err(Signal::Throw(self.make_error(
12924 "RangeError",
12925 "BigInt shift count must be non-negative",
12926 )));
12927 }
12928 if op == Shl {
12929 a.shl(count as u64)
12930 } else {
12931 a.shr(count as u64)
12932 }
12933 }
12934 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
12935 _ => {
12936 return Err(Signal::Throw(self.make_error(
12937 "TypeError",
12938 "BigInts have no unsigned right shift, use >> instead",
12939 )));
12940 }
12941 };
12942 Ok(self.bigint(result))
12943 }
12944
12945 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
12946 ///
12947 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
12948 /// is on the mathematical values, and nothing is rounded first.
12949 /// `<`, `<=`, `>`, `>=`.
12950 ///
12951 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
12952 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
12953 /// It is a `?`-returning function for exactly that reason: an object operand can run
12954 /// script, and script can throw. The old version compared `to_number` of the raw
12955 /// values, which answered `false` for every object instead of calling `valueOf` —
12956 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
12957 /// never ran.
12958 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12959 // The hot arm first: `i < n` with both sides already integers. No conversion, no
12960 // call, nothing that can throw.
12961 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12962 let ordering = Some(left.cmp(right));
12963 return Ok(ordering_answer(op, ordering));
12964 }
12965 // Anything that can run script has to be converted first, in this order.
12966 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
12967 {
12968 (
12969 self.to_primitive(left, Hint::Number)?,
12970 self.to_primitive(right, Hint::Number)?,
12971 )
12972 } else {
12973 (left, right)
12974 };
12975 let ordering = match (&left, &right) {
12976 // The loop condition `i < n` is integer against integer, and it runs once
12977 // per iteration of every loop in every program. Without this arm it took the
12978 // `to_number` path twice, which is a `match` plus a conversion each.
12979 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
12980 (Value::String(a), Value::String(b)) => {
12981 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
12982 }
12983 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
12984 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
12985 // is true even though `2.5` has no bigint form.
12986 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
12987 let b = other.to_number();
12988 if b.is_nan() {
12989 None
12990 } else {
12991 compare_bigint_and_f64(a, b)
12992 }
12993 }
12994 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
12995 let a = other.to_number();
12996 if a.is_nan() {
12997 None
12998 } else {
12999 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
13000 }
13001 }
13002 // `ToNumeric` on the pair, which refuses a Symbol rather than answering `NaN`:
13003 // `Object(Symbol()) <= ""` is a `TypeError`, and the total `to_number` made it
13004 // `false` (`Symbol/prototype/Symbol.toPrimitive/…-ordinary-toprimitive`).
13005 _ => self
13006 .to_js_number(&left)?
13007 .partial_cmp(&self.to_js_number(&right)?),
13008 };
13009 Ok(ordering_answer(op, ordering))
13010 }
13011
13012 fn binary_add(&mut self) -> JsResult<()> {
13013 let right = self.pop();
13014 let left = self.pop();
13015 // Two integers add without any of the machinery below: no `ToPrimitive` (an
13016 // `Int` is already primitive), no string check, no bigint check, no allocation.
13017 // `x += 1` in a loop is the single most common instruction sequence in real
13018 // script, and it used to walk every one of those checks before reaching the
13019 // same `checked_add`.
13020 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
13021 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
13022 return Ok(());
13023 }
13024 let left = self.primitive_of(left)?;
13025 let right = self.primitive_of(right)?;
13026 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
13027 // that check comes before the bigint one: `"" + 1n` is a string, not a
13028 // mixed-type error.
13029 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
13030 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
13031 // `TypeError`, the one place a symbol and a string do not mix.
13032 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
13033 // between a copy and a rope from their lengths, and a rope is what turns
13034 // `text += "abc"` in a loop from quadratic into linear.
13035 if let (Value::String(left), Value::String(right)) = (&left, &right) {
13036 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
13037 // reports as `InternalError: string too long`.
13038 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
13039 return Err(Signal::Throw(
13040 self.make_error("InternalError", "string too long"),
13041 ));
13042 };
13043 self.push(Value::String(Gc::new(self.heap, joined)));
13044 return Ok(());
13045 }
13046 // At least one operand was not a string, so `ToString` it. This rejects a
13047 // symbol, which is the one place a symbol and a string do not mix.
13048 let left = self.checked_to_wtf8(&left)?;
13049 let right = self.checked_to_wtf8(&right)?;
13050 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
13051 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
13052 let text = left.concat(&right);
13053 self.push(self.string_wtf8(text));
13054 return Ok(());
13055 }
13056 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
13057 // not a conversion.
13058 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
13059 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
13060 self.push(value);
13061 return Ok(());
13062 }
13063 let left = self.numeric(left)?;
13064 let right = self.numeric(right)?;
13065 self.push(add_numbers(left, right));
13066 Ok(())
13067 }
13068
13069 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
13070 self.to_primitive(value, Hint::Default)
13071 }
13072
13073 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
13074 ///
13075 /// The order depends on the hint: the "number" order tries `valueOf` first and
13076 /// `toString` second, the "string" order the other way round, and the default
13077 /// hint uses the number order. A result that is still an object is a `TypeError`,
13078 /// because no built-in `valueOf`/`toString` returns one.
13079 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
13080 let Value::Object(object) = &value else {
13081 return Ok(value);
13082 };
13083 // A Date overrides the default hint to mean "string", which is what
13084 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
13085 // this, `"" + new Date()` would print the milliseconds, not the date.
13086 let hint = if hint == Hint::Default && is_date_object(self, object) {
13087 Hint::String
13088 } else {
13089 hint
13090 };
13091 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
13092 // handed the hint as a string. This is the hook a Date uses for its default hint
13093 // and a script uses to take over conversion entirely.
13094 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
13095 // `GetMethod`, not "is it a callable object": the property has to be read and then
13096 // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
13097 // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
13098 // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
13099 // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
13100 // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
13101 // callable.
13102 match self.get_property_key(object, &key)? {
13103 None | Some(Value::Undefined) | Some(Value::Null) => {}
13104 Some(Value::Object(function)) if function.is_callable() => {
13105 let hint = match hint {
13106 Hint::String => "string",
13107 Hint::Number => "number",
13108 Hint::Default => "default",
13109 };
13110 let hint = self.string(hint);
13111 let result = self.call_value(
13112 Value::Object(function),
13113 Value::Object(object.clone()),
13114 vec![hint],
13115 )?;
13116 if !matches!(result, Value::Object(_)) {
13117 return Ok(result);
13118 }
13119 return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
13120 }
13121 Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
13122 }
13123 let order: [&str; 2] = match hint {
13124 Hint::String => ["toString", "valueOf"],
13125 Hint::Number | Hint::Default => ["valueOf", "toString"],
13126 };
13127 let receiver = object.clone();
13128 for method in order {
13129 if let Some(function) = self.get_property(&receiver, method)?
13130 && matches!(&function, Value::Object(object) if object.is_callable())
13131 {
13132 let result =
13133 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
13134 if !matches!(result, Value::Object(_)) {
13135 return Ok(result);
13136 }
13137 }
13138 }
13139 Err(self.type_error("cannot convert object to primitive value"))
13140 }
13141
13142 /// `ToString` with the object case going through `ToPrimitive`.
13143 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
13144 if matches!(value, Value::Object(_)) {
13145 let primitive = self.to_primitive(value.clone(), Hint::String)?;
13146 return Ok(primitive.to_js_string());
13147 }
13148 // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
13149 // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
13150 // callers that want that strictness call [`Interp::to_string_strict`] — putting the
13151 // check here broke `String(Symbol())` and 45 cases that print a symbol.
13152 Ok(value.to_js_string())
13153 }
13154
13155 /// `ToString(value)`, with §7.1.19's symbol refusal.
13156 ///
13157 /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
13158 /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
13159 /// operations and conflating them cost 45 cases in one direction and 6 in the other.
13160 pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
13161 if matches!(value, Value::Symbol(_)) {
13162 return Err(self.type_error("cannot convert a Symbol to a string"));
13163 }
13164 if matches!(value, Value::Object(_)) {
13165 let primitive = self.to_primitive(value.clone(), Hint::String)?;
13166 if matches!(primitive, Value::Symbol(_)) {
13167 return Err(self.type_error("cannot convert a Symbol to a string"));
13168 }
13169 return Ok(primitive.to_js_string());
13170 }
13171 Ok(value.to_js_string())
13172 }
13173
13174 /// `ToString` that keeps the string's code units instead of flattening them.
13175 ///
13176 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
13177 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
13178 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13179 if matches!(value, Value::Symbol(_)) {
13180 return Err(Signal::Throw(
13181 self.make_error("TypeError", "cannot convert symbol to string"),
13182 ));
13183 }
13184 // An object runs `ToPrimitive` first, which may itself produce a symbol.
13185 let value = self.to_primitive(value.clone(), Hint::String)?;
13186 match value {
13187 Value::Symbol(_) => Err(Signal::Throw(
13188 self.make_error("TypeError", "cannot convert symbol to string"),
13189 )),
13190 Value::String(text) => Ok(text.wtf8().clone()),
13191 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
13192 }
13193 }
13194
13195 /// `ToNumber` with the object case going through `ToPrimitive`.
13196 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
13197 let value = if matches!(value, Value::Object(_)) {
13198 self.to_primitive(value.clone(), Hint::Number)?
13199 } else {
13200 value.clone()
13201 };
13202 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
13203 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
13204 // `NaN` to stay total, and the operators check for the bigint themselves — but
13205 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
13206 // refuse, and answering `NaN` made them silently wrong instead.
13207 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
13208 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
13209 match value {
13210 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
13211 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
13212 other => Ok(other.to_number()),
13213 }
13214 }
13215
13216 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
13217 /// [`ElementType::write`].
13218 ///
13219 /// This is separated from the write because both conversions are observable script —
13220 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
13221 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
13222 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
13223 /// setters, and a plain `a[i] = v`.
13224 pub(crate) fn element_value(
13225 &mut self,
13226 element: crate::builtins::typedarray::ElementType,
13227 value: Value,
13228 ) -> JsResult<Value> {
13229 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
13230 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
13231 let primitive = match &value {
13232 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
13233 _ => value,
13234 };
13235 if element.is_bigint() {
13236 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
13237 Ok(Value::BigInt(Gc::new(self.heap, big)))
13238 } else {
13239 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
13240 Ok(Value::Float(self.to_js_number(&primitive)?))
13241 }
13242 }
13243
13244 /// `ToPropertyKey`: what a computed member access uses as its key.
13245 ///
13246 /// A symbol is returned as itself, never stringified — that is what keeps
13247 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
13248 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
13249 match value {
13250 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
13251 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
13252 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
13253 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
13254 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13255 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
13256 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
13257 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
13258 other.to_js_string(),
13259 ))),
13260 },
13261 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
13262 }
13263 }
13264
13265 /// `ToPropertyKey` for the callers that can only use a string key.
13266 ///
13267 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
13268 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
13269 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
13270 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
13271 /// program continues with a value nobody asked for.
13272 /// `SetFunctionName`'s name for a computed key, which is not `ToPropertyKey`.
13273 ///
13274 /// §7.3.24 step 1: when the key is a **Symbol**, the name is `"[" + description + "]"`
13275 /// — or the empty string when the symbol has no description. Going through
13276 /// `ToPropertyKey` instead gave `Symbol(test262)` and `Symbol()`, so every
13277 /// `{ [sym](){} }` method had the wrong `name` (`fn-name-fn` and its generated
13278 /// relatives, in both `expressions/object` and `statements/class`).
13279 ///
13280 /// Everything else is an ordinary `ToPropertyKey` — a string key keeps its code units,
13281 /// which is what makes `{ "\uD800": function () {} }.name` the lone surrogate.
13282 fn function_name_from_key(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13283 if let Value::Symbol(symbol) = value {
13284 return Ok(match symbol.description() {
13285 Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
13286 None => crate::value::Wtf8::default(),
13287 });
13288 }
13289 self.propkey_of(value)
13290 }
13291
13292 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
13293 use crate::value::Wtf8;
13294 Ok(match value {
13295 // A string key keeps its code units. Going through a lossy `String` would make
13296 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
13297 Value::String(text) => text.wtf8().clone(),
13298 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
13299 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
13300 // falling back to its `ToString` would print `[object Object]`.
13301 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
13302 Value::String(text) => text.wtf8().clone(),
13303 other => Wtf8::new(other.to_js_string()),
13304 },
13305 other => Wtf8::new(other.to_js_string()),
13306 })
13307 }
13308
13309 // -- object operations used by instructions -----------------------------
13310
13311 /// Read `object[key]`, returning `undefined` when the property is missing.
13312 ///
13313 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
13314 /// primitive (looking through its prototype) as well as an object — which is what
13315 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
13316 /// argument needs too.
13317 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
13318 self.read_field_key(object, &PropertyKey::from(key))
13319 }
13320
13321 /// [`Interp::read_field`] with a key that may be a symbol.
13322 ///
13323 /// A symbol key never reaches the string shortcuts: a string's `length` and its
13324 /// indices are string properties, and a symbol named `length` is a different
13325 /// property that a string primitive cannot have.
13326 /// [`Interp::read_field_key`], with an inline cache in front of it.
13327 ///
13328 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
13329 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
13330 /// without this the engine walked the chain and compared ~40 property names on each
13331 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
13332 ///
13333 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
13334 /// missing property. Those answers depend on running code or on state the guard below
13335 /// does not cover, and a wrong answer here is far more expensive than a lookup.
13336 ///
13337 /// A hit is re-validated against the *whole* walked chain, not just the level that
13338 /// answered: the receiver and every prototype down to that level must still be the same
13339 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
13340 /// property-table *lengths* — which is what catches a property appearing on an
13341 /// intermediate prototype and shadowing the cached one.
13342 pub fn read_field_cached(
13343 &mut self,
13344 object: &Value,
13345 key: &PropertyKey,
13346 slot: usize,
13347 ) -> JsResult<Value> {
13348 let index = Self::field_cache_slot(object, key, slot);
13349 let Value::Object(target) = object else {
13350 return self.read_field_key(object, key);
13351 };
13352 if target.proxy_state().is_some() {
13353 return self.read_field_key(object, key);
13354 }
13355 if let Some(cached) = &self.field_cache[index]
13356 && cached.key == *key
13357 && let Some(value) = Self::cached_hit(target, cached)
13358 {
13359 return Ok(value);
13360 }
13361 let value = self.read_field_key(object, key)?;
13362 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
13363 Ok(value)
13364 }
13365
13366 /// Whether a cache entry still describes this lookup, and if so the value.
13367 ///
13368 /// The guard is the whole point of the entry: identity plus property-table length for
13369 /// every level walked. Re-checked per level rather than once at the receiving end,
13370 /// because a shadowing property can appear anywhere along the chain.
13371 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
13372 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
13373 // starts with: a clone is a reference-count bump and a drop, and for
13374 // `property:monomorphic` every single hit takes only this arm.
13375 let (weak, len) = cached.chain[0].as_ref()?;
13376 if !target.upgrades_to(weak) {
13377 return None;
13378 }
13379 if cached.level == 0 {
13380 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
13381 return target.cached_property_at(cached.index, &cached.key, *len);
13382 }
13383 if target.props_len() != *len {
13384 return None;
13385 }
13386 let mut level = 1;
13387 let mut current = target.proto()?;
13388 loop {
13389 let (weak, len) = cached.chain[level].as_ref()?;
13390 if !current.upgrades_to(weak) || current.props_len() != *len {
13391 return None;
13392 }
13393 if level == cached.level as usize {
13394 // The level that answered: the value is only reusable while the key is
13395 // still there and still a plain data property.
13396 return current.cached_data_property(cached.index, &cached.key);
13397 }
13398 current = current.proto()?;
13399 level += 1;
13400 }
13401 }
13402
13403 /// Build a cache entry for a lookup that just went through the slow path.
13404 ///
13405 /// Records the chain only when the answer came from a plain data property at a level
13406 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
13407 /// costs the next lookup the walk it would have cost anyway.
13408 fn record_field_lookup(
13409 target: &Gc<JsObject>,
13410 key: &PropertyKey,
13411 _value: Value,
13412 ) -> Option<FieldCache> {
13413 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
13414 [None, None, None];
13415 let mut current = target.clone();
13416 for level in 0..MAX_CACHED_CHAIN {
13417 chain[level] = Some((current.downgrade(), current.props_len()));
13418 if let Some((found, _)) = current.own_property_index(key) {
13419 // `own_property_index` declines an accessor and a hole, which is exactly
13420 // the set that must not be cached.
13421 return Some(FieldCache {
13422 key: key.clone(),
13423 index: found,
13424 level: level as u8,
13425 chain,
13426 });
13427 }
13428 current = current.proto()?;
13429 }
13430 None
13431 }
13432
13433 /// Which cache slot a lookup uses.
13434 ///
13435 /// Mixes the object's address, the name and the site, so that two properties of one
13436 /// object, and one property of two objects, land in different slots — which is what lets
13437 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
13438 /// other iteration.
13439 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
13440 let mut hash = match object {
13441 Value::Object(object) => object.address(),
13442 _ => 0,
13443 };
13444 hash = hash
13445 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
13446 .rotate_left(17)
13447 .wrapping_add(key.hash_code());
13448 hash = hash.wrapping_add(site.wrapping_mul(31));
13449 // The table is a power of two, so the low bits are the slot.
13450 hash & (FIELD_CACHE_SLOTS - 1)
13451 }
13452
13453 /// Read `key` from `object`, without the inline cache.
13454 ///
13455 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
13456 /// prototype chain, while the cached form answers an own data property from memory.
13457 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
13458 let text = key.as_str().unwrap_or("");
13459 let Value::Object(object) = object else {
13460 // Reading a property of `undefined`/`null` is the classic TypeError.
13461 if object.is_nullish() {
13462 return Err(Signal::Throw(self.make_error(
13463 "TypeError",
13464 &format!("cannot read property '{key}' of {}", object.to_js_string()),
13465 )));
13466 }
13467 // A string has `length` and index access without being boxed.
13468 if let Value::String(value) = object {
13469 if text == "length" {
13470 return Ok(Value::Int(value.utf16_len() as i32));
13471 }
13472 if let Some(index) = array_index(text) {
13473 return Ok(match value.wtf8().unit_at(index as usize) {
13474 Some(unit) => self.string_wtf8(unit),
13475 None => Value::Undefined,
13476 });
13477 }
13478 }
13479 // A property of a primitive is looked up on its prototype: this is what
13480 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
13481 let prototype = match object {
13482 Value::String(_) => self.realm.string_proto.clone(),
13483 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13484 Value::Bool(_) => self.realm.boolean_proto.clone(),
13485 // A symbol's methods live on `Symbol.prototype`, reached the same way —
13486 // `sym.description` reads through the prototype, not off the symbol.
13487 Value::Symbol(_) => self.realm.symbol_proto.clone(),
13488 // …and a bigint's on `BigInt.prototype`, which is how
13489 // `(255n).toString(16)` reaches its method.
13490 Value::BigInt(_) => self.realm.bigint_proto.clone(),
13491 _ => None,
13492 };
13493 if let Some(prototype) = prototype
13494 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
13495 {
13496 return Ok(value);
13497 }
13498 return Ok(Value::Undefined);
13499 };
13500 Ok(self
13501 .get_property_key(object, key)?
13502 .unwrap_or(Value::Undefined))
13503 }
13504
13505 /// The `#name` a private symbol stands for, for error messages.
13506 ///
13507 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
13508 /// was made from.
13509 fn private_name(symbol: &Value) -> Option<String> {
13510 match symbol {
13511 Value::Symbol(symbol) if symbol.is_private() => Some(
13512 symbol
13513 .description()
13514 .map(|text| text.to_string())
13515 .unwrap_or_default(),
13516 ),
13517 _ => None,
13518 }
13519 }
13520
13521 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
13522 ///
13523 /// Every private-field opcode takes the symbol the class stored in its own scope; a
13524 /// non-symbol here would be a compiler bug, and the reference guards it with
13525 /// `JS_ThrowTypeErrorNotASymbol`.
13526 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
13527 match symbol {
13528 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
13529 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
13530 }
13531 }
13532
13533 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
13534 ///
13535 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
13536 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
13537 /// would hit if the parser did not reject it first.
13538 fn define_private_field(
13539 &mut self,
13540 object: &Value,
13541 symbol: &Value,
13542 value: Value,
13543 ) -> JsResult<()> {
13544 let key = self.private_key(symbol)?;
13545 let Some(target) = object.as_object() else {
13546 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13547 };
13548 if !target.is_extensible() {
13549 return Err(Signal::Throw(
13550 self.make_error("TypeError", "object is not extensible"),
13551 ));
13552 }
13553 if target.own_property_key(&key).is_some() {
13554 let name = Self::private_name(symbol).unwrap_or_default();
13555 return Err(Signal::Throw(self.make_error(
13556 "TypeError",
13557 &format!("private class field '{name}' already exists"),
13558 )));
13559 }
13560 target.define_data_key(&key, value);
13561 Ok(())
13562 }
13563
13564 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
13565 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
13566 let key = self.private_key(symbol)?;
13567 let Some(target) = object.as_object() else {
13568 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13569 };
13570 match target.own_property_key(&key) {
13571 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
13572 None => {
13573 let name = Self::private_name(symbol).unwrap_or_default();
13574 Err(Signal::Throw(self.make_error(
13575 "TypeError",
13576 &format!("private class field '{name}' does not exist"),
13577 )))
13578 }
13579 }
13580 }
13581
13582 /// `JS_SetPrivateField`: the store half of the same rule.
13583 fn write_private_field(
13584 &mut self,
13585 object: &Value,
13586 symbol: &Value,
13587 value: Value,
13588 ) -> JsResult<()> {
13589 let key = self.private_key(symbol)?;
13590 let Some(target) = object.as_object() else {
13591 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13592 };
13593 if target.write_value_key(&key, value) {
13594 return Ok(());
13595 }
13596 let name = Self::private_name(symbol).unwrap_or_default();
13597 Err(Signal::Throw(self.make_error(
13598 "TypeError",
13599 &format!("private class field '{name}' does not exist"),
13600 )))
13601 }
13602
13603 /// The `in` half: does `object` have this private field?
13604 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
13605 ///
13606 /// The symbol is created once per class — the first `add_brand` on a given home object
13607 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
13608 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
13609 /// emit for the *instance* brand passes null because all it wants is the symbol.
13610 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
13611 let Some(home_object) = home.as_object() else {
13612 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13613 };
13614 let symbol = match home_object.private_brand() {
13615 Some(symbol) => symbol,
13616 None => {
13617 let symbol = Gc::new(
13618 self.heap,
13619 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
13620 );
13621 home_object.set_private_brand(symbol.clone());
13622 symbol
13623 }
13624 };
13625 let Some(target) = object.as_object() else {
13626 // Not an object: nothing to brand. The reference does the same, and `undefined`
13627 // here would otherwise turn a field initialiser into a TypeError.
13628 return Ok(());
13629 };
13630 if !target.is_extensible() {
13631 return Err(Signal::Throw(
13632 self.make_error("TypeError", "object is not extensible"),
13633 ));
13634 }
13635 if target.carries_brand(&symbol) {
13636 return Err(Signal::Throw(
13637 self.make_error("TypeError", "private method is already present"),
13638 ));
13639 }
13640 target.add_brand(symbol);
13641 Ok(())
13642 }
13643
13644 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
13645 ///
13646 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
13647 /// decides whether to throw.
13648 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
13649 let Some(function) = function.as_object() else {
13650 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13651 };
13652 let Some(home) = function.home_object() else {
13653 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13654 };
13655 let Some(brand) = home.private_brand() else {
13656 return Err(Signal::Throw(
13657 self.make_error("TypeError", "expecting <brand> private field"),
13658 ));
13659 };
13660 Ok(object.carries_brand(&brand))
13661 }
13662
13663 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
13664 let Value::Object(object) = object else {
13665 // `PutValue` on a property of a primitive is a silent no-op in sloppy mode and a
13666 // `TypeError` in strict mode: `sym.a = 1` on a Symbol must leave `sym.a`
13667 // `undefined` rather than throwing (`Symbol/auto-boxing-non-strict`). `null` and
13668 // `undefined` still throw, with their own message.
13669 if !self.current_strict() && !matches!(object, Value::Null | Value::Undefined) {
13670 return Ok(());
13671 }
13672 return Err(Signal::Throw(self.make_error(
13673 "TypeError",
13674 &format!("cannot set property '{key}' of {}", object.to_js_string()),
13675 )));
13676 };
13677 // The write half of the property inline cache, in effect: an own, writable,
13678 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
13679 // decide — no prototype walk (an own property shadows the chain before a setter
13680 // there could matter), no extensibility check (the object already has the key),
13681 // and no `[[DefineOwnProperty]]`.
13682 //
13683 // `this.value = …` inside a method is the whole write side of
13684 // `property:method-call`, and it was reaching `set_property_with_key` with its
13685 // proxy test, its typed-array test, its array-index test and finally a linear
13686 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
13687 //
13688 // Every disqualifier is checked here: a proxy traps the set, an array index and
13689 // `length` live outside the property table, and a typed array's element is stored
13690 // through its view's element type.
13691 if object.proxy_state().is_none()
13692 && !object.is_array()
13693 && object.typed_array_element_type().is_none()
13694 && object.write_value_key(key, value.clone())
13695 {
13696 return Ok(());
13697 }
13698 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
13699 let on_failure = if self.frame().code.code.strict {
13700 DeleteFailure::Throw
13701 } else {
13702 DeleteFailure::Ignore
13703 };
13704 self.set_property_with_key(object, key, value, on_failure)
13705 }
13706
13707 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
13708 ///
13709 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
13710 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
13711 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
13712 /// `Number.parseInt(sym)` — so those callers use this instead.
13713 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
13714 if matches!(value, Value::Symbol(_)) {
13715 return Err(Signal::Throw(
13716 self.make_error("TypeError", "cannot convert symbol to string"),
13717 ));
13718 }
13719 // An object runs `ToPrimitive` first, which may itself produce a symbol —
13720 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
13721 let value = self.to_primitive(value.clone(), Hint::String)?;
13722 if matches!(value, Value::Symbol(_)) {
13723 return Err(Signal::Throw(
13724 self.make_error("TypeError", "cannot convert symbol to string"),
13725 ));
13726 }
13727 Ok(value.to_js_string())
13728 }
13729
13730 /// `ToPropertyKey` for a builtin that takes a key argument.
13731 ///
13732 /// Fallible: a key whose `toString` throws has to propagate that error, both for
13733 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
13734 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
13735 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
13736 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
13737 self.propkey(value)
13738 }
13739
13740 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
13741 ///
13742 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
13743 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
13744 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
13745 /// `RangeError` — and why this cannot be a plain `ToNumber`.
13746 /// `ToNumber(value)` for `ArraySetLength`, which the spec performs **twice**.
13747 ///
13748 /// §10.4.2.4 steps 3–5 are `ToUint32(Desc.[[Value]])`, then `ToNumber(Desc.[[Value]])`,
13749 /// then a `RangeError` when they disagree. Two conversions rather than one is
13750 /// observable: a `valueOf` that runs the first time can make `length` non-writable
13751 /// before the second, which turns the store into a refused write
13752 /// (`length/define-own-prop-length-coercion-order`, `…-set`).
13753 pub fn coerce_array_length_twice(&mut self, value: &Value) -> JsResult<u32> {
13754 let first = self.array_length_of(value)?;
13755 let second = self.array_length_of(value)?;
13756 debug_assert_eq!(first, second);
13757 Ok(first)
13758 }
13759
13760 /// `ArraySetLength`'s `ToNumber(value)`, then the `ToUint32` round-trip check.
13761 ///
13762 /// Separate from [`Interp::coerce_array_length_twice`] so the callers that need one
13763 /// conversion can say so; a caller that needs the spec's two uses that instead.
13764 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
13765 let number = match value {
13766 Value::Int(number) => *number as f64,
13767 Value::Float(number) => *number,
13768 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
13769 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
13770 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
13771 // reference answers 0.
13772 Value::Null | Value::Bool(_) | Value::Undefined => value.to_number(),
13773 // A string goes through the full numeric-literal grammar: `"0x00B"` is 11 and
13774 // `" 5 "` is 5, which is exactly what `string_to_number` implements.
13775 Value::String(text) => crate::value::string_to_number(&text.to_string_lossy()),
13776 _ => {
13777 // The primitive comes back through this same conversion, so a wrapper of a
13778 // boolean (`new Boolean(false)`) is `0` rather than the `NaN` that
13779 // `ToNumber("false")` would give — `S15.4.5.1_A1.3_T1` walks every wrapper.
13780 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
13781 return self.array_length_of(&primitive);
13782 }
13783 };
13784 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
13785 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
13786 // is a `RangeError`, not `0`.
13787 if !number.is_finite()
13788 || number.fract() != 0.0
13789 || !(0.0..=u32::MAX as f64).contains(&number)
13790 {
13791 return Err(self.range_error("invalid array length"));
13792 }
13793 Ok(number as u32)
13794 }
13795
13796 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
13797 /// `Object.getOwnPropertySymbols` put in their result array.
13798 pub fn key_value(&self, key: &PropertyKey) -> Value {
13799 match key {
13800 PropertyKey::String(text) => self.string_wtf8(text.clone()),
13801 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
13802 }
13803 }
13804
13805 /// Fill in a String exotic object: `_value`, `length` and the index properties.
13806 ///
13807 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
13808 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
13809 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
13810 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
13811 /// the two paths had drifted; this is the one both now use.
13812 ///
13813 /// The indices are *code units*, so an astral character occupies two of them — the
13814 /// same rule `s.length` and `s[i]` follow.
13815 /// Give an already-created object the internal slot that makes it a wrapper of
13816 /// `value`, so the primitive's prototype methods work on it.
13817 ///
13818 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
13819 /// which are wrappers of their own type holding the empty value.
13820 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
13821 self.internal_set(object, "_value", value);
13822 }
13823
13824 pub(crate) fn init_string_wrapper(
13825 &mut self,
13826 object: &Gc<JsObject>,
13827 text: &Gc<crate::value::JsString>,
13828 ) {
13829 object.define(
13830 "length",
13831 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
13832 );
13833 for index in 0..text.utf16_len() {
13834 if let Some(unit) = text.wtf8().unit_at(index) {
13835 object.define(
13836 &index.to_string(),
13837 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
13838 Property::with_attributes(self.string_wtf8(unit), false, true),
13839 );
13840 }
13841 }
13842 object.define_key(
13843 &self.internal_slot("_value"),
13844 Property::with_attributes(Value::String(text.clone()), false, false),
13845 );
13846 }
13847
13848 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
13849 ///
13850 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
13851 /// throws. The wrapper carries its primitive in `_value` — the same slot
13852 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
13853 /// on a boxed value no constructor ever built.
13854 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13855 let (prototype, primitive) = match value {
13856 Value::Object(object) => return Ok(object.clone()),
13857 Value::String(text) => {
13858 let object = self.new_object(self.realm.string_proto.clone());
13859 self.init_string_wrapper(&object, text);
13860 return Ok(object);
13861 }
13862 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
13863 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
13864 // A symbol and a bigint box into wrappers whose methods live on
13865 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
13866 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
13867 // branch below instead produced an object with *no* prototype, so those
13868 // methods were unreachable on a box.
13869 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
13870 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
13871 Value::Undefined | Value::Null => {
13872 return Err(Signal::Throw(self.make_error(
13873 "TypeError",
13874 &format!("cannot convert {} to object", value.to_js_string()),
13875 )));
13876 }
13877 _ => (None, value.clone()),
13878 };
13879 let object = self.new_object(prototype);
13880 self.internal_set(&object, "_value", primitive);
13881 Ok(object)
13882 }
13883
13884 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
13885 ///
13886 /// Split out for a reader that has to create the object *before* it knows what it wraps:
13887 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
13888 /// written before its primitive, so the placeholder has to exist first and be filled in
13889 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
13890 /// than a second in the deserialiser.
13891 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
13892 let prototype = match value {
13893 Value::String(_) => self.realm.string_proto.clone(),
13894 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13895 Value::Bool(_) => self.realm.boolean_proto.clone(),
13896 Value::Symbol(_) => self.realm.symbol_proto.clone(),
13897 Value::BigInt(_) => self.realm.bigint_proto.clone(),
13898 _ => {
13899 return Err(Signal::Throw(self.make_error(
13900 "TypeError",
13901 &format!("cannot box {}", value.to_js_string()),
13902 )));
13903 }
13904 };
13905 object.set_proto(prototype);
13906 if let Value::String(text) = value {
13907 self.init_string_wrapper(object, text);
13908 return Ok(());
13909 }
13910 self.internal_set(object, "_value", value.clone());
13911 Ok(())
13912 }
13913
13914 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
13915 ///
13916 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
13917 /// through the `Symbol` function object, so the registry is reachable as a method rather
13918 /// than only from `builtins::symbol`.
13919 pub fn symbol_for(&mut self, key: &str) -> Value {
13920 if let Some(existing) = self.realm.symbol_registry.get(key) {
13921 return existing.clone();
13922 }
13923 let symbol = crate::builtins::symbol::symbol_value(
13924 self,
13925 crate::value::JsSymbol::registered(key.to_string()),
13926 );
13927 self.realm
13928 .symbol_registry
13929 .insert(key.to_string(), symbol.clone());
13930 symbol
13931 }
13932
13933 /// `a == b`, the coercing comparison.
13934 ///
13935 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
13936 /// which is what makes `[] == ""` true: `[]` becomes `""` via
13937 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
13938 /// because the conversion is allowed to call script code, so the two primitive
13939 /// operands are handed back to it.
13940 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
13941 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
13942 return Ok(left.loose_equals(&right));
13943 }
13944 // `null == undefined` holds even though neither is an object.
13945 if matches!(left, Value::Undefined | Value::Null)
13946 && matches!(right, Value::Undefined | Value::Null)
13947 {
13948 return Ok(true);
13949 }
13950 if matches!(left, Value::Undefined | Value::Null)
13951 || matches!(right, Value::Undefined | Value::Null)
13952 {
13953 return Ok(false);
13954 }
13955 // Two objects compare by identity. Only an object *against a primitive* is
13956 // converted, which is why `{} == {}` is false while `[] == ""` is true.
13957 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
13958 return Ok(a.ptr_eq(b));
13959 }
13960 let left = self.to_primitive(left, Hint::Default)?;
13961 let right = self.to_primitive(right, Hint::Default)?;
13962 Ok(left.loose_equals(&right))
13963 }
13964
13965 /// `HasBinding(N)` for an Object Environment Record whose binding object is `object`.
13966 ///
13967 /// §9.1.1.2.1: `HasProperty` **and then** not listed in the object's
13968 /// `Symbol.unscopables`. The `unscopables` object is read with a plain `Get`, so a
13969 /// getter on it runs exactly once per lookup — `with/with-get-unscopables-once` counts
13970 /// the calls.
13971 fn with_has_binding(&mut self, object: &Value, name: &str) -> JsResult<bool> {
13972 let key = PropertyKey::from(name);
13973 if !self.has_property_value(object, &key)? {
13974 return Ok(false);
13975 }
13976 let unscopables_key = self.realm.well_known_key(WellKnown::Unscopables);
13977 let unscopables = self.read_field_key(object, &unscopables_key)?;
13978 let Value::Object(_) = unscopables else {
13979 // `undefined` (the usual case) or a primitive: nothing is excluded.
13980 return Ok(true);
13981 };
13982 let excluded = self.read_field_key(&unscopables, &key)?;
13983 Ok(!excluded.to_boolean())
13984 }
13985
13986 /// `GetBindingValue(N, S)` for an Object Environment Record: §9.1.1.2.4.
13987 ///
13988 /// `HasProperty` is asked a **second** time — the guard already asked it — because the
13989 /// object may have changed in between: `GetBindingValue` step 2 is a fresh lookup, and
13990 /// a proxy sees two `has` traps plus the `get`. The `unscopables` step is *not*
13991 /// repeated: that belongs to `HasBinding`, not to `GetBindingValue`.
13992 ///
13993 /// When the property has gone, strict code throws and sloppy code reads `undefined`
13994 /// from the environment (step 2's `S` is the strictness of the *running* code, not of
13995 /// the declaration).
13996 fn with_get_binding(&mut self, object: &Value, name: &str) -> JsResult<Value> {
13997 let key = PropertyKey::from(name);
13998 if !self.has_property_value(object, &key)? {
13999 if self.frame().code.code.strict {
14000 return Err(self.throw_reference(name));
14001 }
14002 return Ok(Value::Undefined);
14003 }
14004 self.read_field_key(object, &key)
14005 }
14006
14007 /// `SetMutableBinding(N, V, S)` for an Object Environment Record: §9.1.1.2.5.
14008 ///
14009 /// Same second `HasProperty`, and the same strict-mode `ReferenceError` when the
14010 /// property is gone — before the store, which is what makes
14011 /// `set-mutable-binding-binding-deleted-with-typed-array-in-proto-chain-strict-mode`
14012 /// a `ReferenceError` rather than whatever the failed store would have thrown.
14013 fn with_put_binding(&mut self, object: &Value, name: &str, value: Value) -> JsResult<()> {
14014 let key = PropertyKey::from(name);
14015 if !self.has_property_value(object, &key)? && self.frame().code.code.strict {
14016 return Err(self.throw_reference(name));
14017 }
14018 self.write_field_key(object, &key, value)
14019 }
14020
14021 /// `HasProperty(O, P)` on a `Value`, without the `in`-operator error for a primitive.
14022 fn has_property_value(&mut self, object: &Value, key: &PropertyKey) -> JsResult<bool> {
14023 match object {
14024 Value::Object(target) => self.has_property_key(target, key),
14025 // `with` boxes its object when the statement is entered (`to_object`), so a
14026 // primitive cannot arrive here; `false` is the honest answer rather than a
14027 // panic if it ever does.
14028 _ => Ok(false),
14029 }
14030 }
14031
14032 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
14033 let Value::Object(object) = object else {
14034 return Err(Signal::Throw(
14035 self.make_error("TypeError", "cannot use 'in' on a non-object"),
14036 ));
14037 };
14038 let key = self.propkey(key)?;
14039 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
14040 // trap. One implementation, so an array's derived `length` and its inherited holes
14041 // cannot be right in one caller and wrong in another.
14042 self.has_own_or_inherited(object, &key)
14043 }
14044
14045 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
14046 ///
14047 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
14048 /// whole reason the operator is a hook rather than a prototype walk.
14049 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14050 if let Value::Object(function) = constructor {
14051 let key = self.realm.well_known_key(WellKnown::HasInstance);
14052 let method = self.get_property_key(function, &key)?;
14053 if let Some(method) = method
14054 && !matches!(method, Value::Undefined)
14055 {
14056 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
14057 return Ok(answer.to_boolean());
14058 }
14059 }
14060 self.instance_of(object, constructor)
14061 }
14062
14063 /// `OrdinaryHasInstance`: the prototype walk on its own.
14064 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14065 self.instance_of(object, constructor)
14066 }
14067
14068 /// `IsArray`: an array, or a proxy whose target is one.
14069 ///
14070 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
14071 /// makes `Array.isArray(new Proxy([], {}))` true.
14072 pub fn is_array_value(&self, value: &Value) -> bool {
14073 match value {
14074 Value::Object(object) => {
14075 if let Some(state) = object.proxy_state() {
14076 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
14077 }
14078 object.is_array()
14079 }
14080 _ => false,
14081 }
14082 }
14083
14084 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
14085 ///
14086 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
14087 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
14088 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
14089 /// see [`Interp::enqueue_job_function`].
14090 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
14091 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
14092 // the handler is reported rather than lost — the same reason a `then` reaction needs a
14093 // promise to settle.
14094 let promise = self.new_promise();
14095 self.fulfill_promise(&promise, Value::Undefined);
14096 self.jobs.push_back(Job::Reaction {
14097 handler: Some(function),
14098 argument: Value::Undefined,
14099 rejected: false,
14100 promise,
14101 });
14102 Ok(())
14103 }
14104
14105 /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
14106 ///
14107 /// Four of its steps were missing or wrong, and each one is a test262 case in
14108 /// `Function/prototype/Symbol.hasInstance/`:
14109 ///
14110 /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
14111 /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
14112 /// `[[BoundThis]]` standing in for the object when that is an object), which is why
14113 /// `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
14114 /// `prototype` of its own, so without this step the walk below gives `false`;
14115 /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
14116 /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
14117 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
14118 let Value::Object(function) = constructor else {
14119 return Ok(false);
14120 };
14121 if !function.is_callable() {
14122 return Ok(false);
14123 }
14124 // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
14125 // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
14126 // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
14127 if let Some((target, this)) = function.bound_target_and_this() {
14128 let object = if this.as_object().is_some() {
14129 this
14130 } else {
14131 object.clone()
14132 };
14133 return self.instance_of(&object, &target);
14134 }
14135 let Value::Object(target) = object else {
14136 return Ok(false);
14137 };
14138 let prototype = self.get_property(function, "prototype")?;
14139 let Some(Value::Object(prototype)) = prototype else {
14140 return Err(Signal::Throw(self.make_error(
14141 "TypeError",
14142 "function has non-object prototype in instanceof check",
14143 )));
14144 };
14145 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
14146 // which is also what makes `proxyOfInstance instanceof C` work.
14147 let mut current = Some(target.clone());
14148 while let Some(object) = current {
14149 if object.ptr_eq(&prototype) {
14150 return Ok(true);
14151 }
14152 current = self.object_prototype_of(&object)?;
14153 }
14154 Ok(false)
14155 }
14156
14157 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
14158 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
14159 if let Some(proto) = self.proxy_get_prototype_of(object)? {
14160 return Ok(proto);
14161 }
14162 if let Some(exotic) = object.exotic()
14163 && let Some(proto) = exotic.get_prototype(self, object)?
14164 {
14165 return Ok(proto);
14166 }
14167 Ok(object.proto())
14168 }
14169
14170 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
14171 pub fn object_set_prototype_of(
14172 &mut self,
14173 object: &Gc<JsObject>,
14174 proto: Option<Gc<JsObject>>,
14175 ) -> JsResult<bool> {
14176 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
14177 return Ok(answer);
14178 }
14179 if let Some(exotic) = object.exotic()
14180 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
14181 {
14182 return Ok(answer);
14183 }
14184 // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
14185 // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
14186 // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
14187 // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
14188 if self
14189 .internal_get(object, "_immutable_proto")
14190 .is_some_and(|flag| flag.to_boolean())
14191 && !same_proto(object.proto().as_ref(), proto.as_ref())
14192 {
14193 return Ok(false);
14194 }
14195 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
14196 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
14197 // inheriting from itself, which every later prototype walk then had to defend
14198 // against — and `Reflect.setPrototypeOf` reported success for an operation the
14199 // language says is impossible.
14200 if let Some(proto) = &proto {
14201 let mut current = Some(proto.clone());
14202 let mut guard = 0;
14203 while let Some(node) = current {
14204 if node.ptr_eq(object) {
14205 // §10.1.2.1 step 5.a: a cycle is `return false`, not a throw —
14206 // `Object.setPrototypeOf` turns that `false` into the `TypeError`,
14207 // while `Reflect.setPrototypeOf` reports it
14208 // (`setPrototypeOf/return-false-if-target-is-prototype-of-proto`).
14209 return Ok(false);
14210 }
14211 guard += 1;
14212 if guard > 1000 {
14213 break;
14214 }
14215 current = node.proto();
14216 }
14217 }
14218 // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
14219 // re-setting it to the *same* one is a no-op `true`. Missing this made
14220 // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
14221 // actually reparent the object — and it is what
14222 // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
14223 // forwarding path has nothing else left to refuse it.
14224 if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
14225 return Ok(false);
14226 }
14227 object.set_proto(proto);
14228 Ok(true)
14229 }
14230
14231 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
14232 ///
14233 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
14234 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
14235 /// already one.
14236 /// `HasProperty(O, P)`.
14237 ///
14238 /// One implementation, shared with the `in` operator. It used to be a second copy that
14239 /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
14240 /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
14241 /// proxy ran the wrong hook and could even disagree with `in`. The
14242 /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
14243 /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
14244 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
14245 self.has_own_or_inherited(object, key)
14246 }
14247
14248 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
14249 ///
14250 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
14251 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
14252 /// boolean as well, and it needs the receiver to be the one the caller named.
14253 pub fn set_property_with_key_receiver(
14254 &mut self,
14255 object: &Gc<JsObject>,
14256 key: &PropertyKey,
14257 value: Value,
14258 receiver: Option<&Value>,
14259 on_failure: DeleteFailure,
14260 ) -> JsResult<bool> {
14261 let receiver = receiver
14262 .cloned()
14263 .unwrap_or_else(|| Value::Object(object.clone()));
14264 if object.proxy_state().is_some() {
14265 return match self.proxy_set(object, key, value, &receiver)? {
14266 Some(accepted) => Ok(accepted),
14267 None => Ok(true),
14268 };
14269 }
14270 // §10.4.6.7: a module namespace's `[[Set]]` always answers false, whatever the
14271 // receiver. This has to be answered here as well as in the storing path below,
14272 // because `Reflect.set` reports the refusal as a `bool` instead of raising.
14273 if object.module_namespace_marker() {
14274 return Ok(false);
14275 }
14276 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
14277 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
14278 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
14279 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
14280 //
14281 // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
14282 //
14283 // * `SameValue(O, Receiver)` stores into the buffer, converting first;
14284 // * an *invalid* index with a different receiver answers `true` and does nothing,
14285 // not even converting `V` (`valueOfCalls` stays 0);
14286 // * a valid index with a different receiver falls through to
14287 // `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
14288 // value lands on the **receiver**, unconverted, and can be refused by a
14289 // non-extensible receiver, an accessor, or a read-only index there.
14290 //
14291 // The last one used to write into the view itself, which left `target[0]` changed
14292 // and `receiver[0]` untouched — backwards.
14293 if object.typed_array_element_type().is_some()
14294 && let Some(numeric) = canonical_numeric_index(key)
14295 {
14296 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14297 if same {
14298 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14299 return Ok(true);
14300 }
14301 if !typed_array_index_is_valid(object, numeric) {
14302 return Ok(true);
14303 }
14304 let Some(receiver) = receiver.as_object().cloned() else {
14305 return Ok(false);
14306 };
14307 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
14308 if existing.is_accessor() || !existing.writable {
14309 return Ok(false);
14310 }
14311 let property = Property {
14312 value: Some(value),
14313 ..existing
14314 };
14315 return self.object_define_own_property(&receiver, key, property);
14316 }
14317 return self.object_define_own_property(&receiver, key, Property::data(value));
14318 }
14319 // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
14320 // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
14321 // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
14322 // `Reflect.set` to *report* the refusal instead of raising.
14323 //
14324 // A receiver that is not the object turns the whole operation into
14325 // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
14326 // `[[Set]]` rather than a lookup — that is what makes
14327 // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
14328 // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
14329 // writes to `object`, so it cannot express that and is only used when the two are
14330 // the same.
14331 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
14332 if !same {
14333 return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
14334 }
14335 // Same receiver: the plain path below writes into `object`, which is right, but it
14336 // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
14337 // boolean, so the two step-1 refusals have to be read off the own descriptor here.
14338 if let Some(existing) = self.object_get_own_property(object, key)? {
14339 if existing.is_accessor() {
14340 return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
14341 Some(setter) => {
14342 self.call_value(setter, receiver, vec![value])?;
14343 Ok(true)
14344 }
14345 None => Ok(false),
14346 };
14347 }
14348 if !existing.writable {
14349 return Ok(false);
14350 }
14351 }
14352 // Otherwise it is an ordinary create-or-write into `object` itself.
14353 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
14354 Ok(true)
14355 }
14356
14357 /// `[[IsExtensible]]`, with the proxy trap when there is one.
14358 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14359 if let Some(answer) = self.proxy_is_extensible(object)? {
14360 return Ok(answer);
14361 }
14362 if let Some(exotic) = object.exotic()
14363 && let Some(answer) = exotic.is_extensible(self, object)?
14364 {
14365 return Ok(answer);
14366 }
14367 Ok(object.is_extensible())
14368 }
14369
14370 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
14371 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
14372 if let Some(answer) = self.proxy_prevent_extensions(object)? {
14373 return Ok(answer);
14374 }
14375 // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
14376 //
14377 // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
14378 //
14379 // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
14380 // created with an explicit length, because the buffer can still move it. That is
14381 // what makes `Object.freeze` refuse every such view, including a zero-length one
14382 // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
14383 // plain buffer is allowed.
14384 if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
14385 && buffer
14386 .array_buffer_storage()
14387 .is_some_and(|storage| storage.borrow().is_resizable())
14388 {
14389 return Err(
14390 self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
14391 );
14392 }
14393 if let Some(exotic) = object.exotic()
14394 && let Some(answer) = exotic.prevent_extensions(self, object)?
14395 {
14396 return Ok(answer);
14397 }
14398 object.set_extensible(false);
14399 Ok(true)
14400 }
14401
14402 fn copy_properties(
14403 &mut self,
14404 target: &Value,
14405 source: &Value,
14406 exclusion: &Value,
14407 ) -> JsResult<()> {
14408 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
14409 // does contribute: its index properties are own, enumerable and writable, which
14410 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
14411 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
14412 // is a no-op.
14413 let Some(target) = target.as_object() else {
14414 return Ok(());
14415 };
14416 let source_object = match source {
14417 Value::Object(object) => object.clone(),
14418 Value::String(text) => {
14419 // Untaken keys are the string's indices, which are code units.
14420 for index in 0..text.utf16_len() {
14421 if let Some(unit) = text.wtf8().unit_at(index) {
14422 target.define_data(&index.to_string(), self.string_wtf8(unit));
14423 }
14424 }
14425 return Ok(());
14426 }
14427 _ => return Ok(()),
14428 };
14429 // An object *rest* element passes the keys already taken by the literal part as
14430 // an array of **key values**; a spread passes `null`, which excludes nothing. The
14431 // array is read by its elements rather than by its own property names, and the
14432 // values stay `PropertyKey`s: a computed key can be a symbol, and
14433 // `{[sym]: a, ...rest}` has to leave `sym` out of `rest`
14434 // (`object-rest-proxy-gopd-not-called-on-excluded-keys`). Flattening them to
14435 // strings made a symbol exclusion a no-op.
14436 let mut excluded: Vec<PropertyKey> = Vec::new();
14437 if let Value::Object(list) = exclusion
14438 && let Some(length) = list.array_length()
14439 {
14440 for index in 0..length {
14441 if let Some(value) = list.array_get(index) {
14442 excluded.push(self.propkey(&value)?);
14443 }
14444 }
14445 }
14446 let source = &source_object;
14447 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
14448 // Reading the property table directly made every spread of a proxy empty.
14449 let keys = self.object_own_property_keys(source)?;
14450 for as_key in keys {
14451 // §7.3.25 step 4 walks `[[OwnPropertyKeys]]`, so **symbol**-keyed properties
14452 // are copied as well — `{...{[Symbol("s")]: 1}}` has one own symbol key.
14453 // Skipping them silently lost every symbol on every spread and every object
14454 // rest element (`obj-rest-order`).
14455 //
14456 if excluded.contains(&as_key) {
14457 continue;
14458 }
14459 let enumerable = self
14460 .object_get_own_property(source, &as_key)?
14461 .is_some_and(|property| property.enumerable);
14462 if !enumerable {
14463 continue;
14464 }
14465 let value = self
14466 .get_property_key(source, &as_key)?
14467 .unwrap_or(Value::Undefined);
14468 target.define_data_key(&as_key, value);
14469 }
14470 Ok(())
14471 }
14472
14473 // -- iteration ---------------------------------------------------------
14474
14475 /// One object's own keys in enumeration order: array indices ascending, then the
14476 /// rest in insertion order.
14477 ///
14478 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
14479 /// whether the key is enumerable, which the caller resolves per key because an
14480 /// array's elements are not in the same store as its named properties.
14481 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
14482 // An index can arrive twice, once from the array's element store and once from
14483 // its property map, so the numeric keys go through a map that keeps the
14484 // enumerable answer if either source gave one.
14485 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
14486 for (key, enumerable) in &own {
14487 if let Some(index) = key.as_str().and_then(array_index) {
14488 let entry = numeric.entry(index).or_insert(false);
14489 *entry = *entry || *enumerable;
14490 }
14491 }
14492 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
14493 .into_iter()
14494 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
14495 .collect();
14496 ordered.extend(
14497 own.into_iter()
14498 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
14499 );
14500 ordered
14501 }
14502
14503 /// Build the key list a `for-in` loop walks.
14504 ///
14505 /// The order is the specification's: own properties before inherited ones, and
14506 /// within one object the integer-like keys in ascending numeric order ahead of the
14507 /// string keys in insertion order. A shadowed key only appears once, and a key that
14508 /// is a non-enumerable own property anywhere nearer is skipped entirely.
14509 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
14510 let record = self.new_object(None);
14511 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
14512 // A proxy supplies its own key list, and — the reason this is not just another
14513 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
14514 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
14515 // descriptor there.
14516 if let Value::Object(object) = value
14517 && object.proxy_state().is_some()
14518 {
14519 let own = self
14520 .proxy_own_keys(object)?
14521 .unwrap_or_else(|| object.own_property_keys());
14522 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
14523 let mut numeric: Vec<u32> = Vec::new();
14524 let mut rest: Vec<PropertyKey> = Vec::new();
14525 for key in own {
14526 match key.as_str().and_then(array_index) {
14527 Some(index) => numeric.push(index),
14528 None => rest.push(key),
14529 }
14530 }
14531 numeric.sort_unstable();
14532 ordered.extend(
14533 numeric
14534 .into_iter()
14535 .map(|index| PropertyKey::from(index.to_string())),
14536 );
14537 ordered.extend(rest);
14538 for (index, key) in ordered.into_iter().enumerate() {
14539 record.define_data(&index.to_string(), self.key_value(&key));
14540 }
14541 record.define_data("__index", Value::Int(0));
14542 // The mark that makes `for_in_advance` re-ask the proxy per key.
14543 record.define_data("__proxy", Value::Object(object.clone()));
14544 return Ok(record);
14545 }
14546 if let Value::Object(object) = value {
14547 let mut chain = vec![object.clone()];
14548 chain.extend(object.chain());
14549 // Every own string key the walk has seen, enumerable or not. A
14550 // non-enumerable own property still hides a same-named enumerable one
14551 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
14552 // keeps `x` out of the loop even when the prototype has one.
14553 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
14554 for object in chain {
14555 let mut own: Vec<(crate::value::Wtf8, bool)> = object
14556 .own_property_keys()
14557 .iter()
14558 .filter_map(|key| key.as_wtf8().cloned())
14559 .map(|key| {
14560 let enumerable = object
14561 .own_property(&key.to_string_lossy())
14562 .map(|property| property.enumerable)
14563 .unwrap_or(false);
14564 (key, enumerable)
14565 })
14566 .collect();
14567 if let Some(length) = object.array_length() {
14568 own.retain(|(key, _)| key.as_str() != Some("length"));
14569 for index in 0..length {
14570 // A dense element is enumerable; a **hole** is not there at all —
14571 // and a hole is also what an index with a recorded descriptor
14572 // leaves behind, in which case the table entry above already
14573 // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
14574 // defines index 0 non-enumerable and `for…in` must skip it).
14575 if let Some(value) = object.array_get(index)
14576 && !matches!(value, Value::Hole)
14577 {
14578 own.push((crate::value::Wtf8::new(index.to_string()), true));
14579 }
14580 }
14581 }
14582 // Integer-like keys come first in ascending order, then the rest in
14583 // insertion order — and the ordering is *per object*, not for the chain
14584 // as a whole: one pass over every collected key lifted a prototype's
14585 // `"4"` above the target's own `x`/`y`, which is not the order
14586 // `for…in` reports.
14587 for (key, enumerable) in Self::order_own_keys(own) {
14588 if visited.contains(&key) {
14589 continue;
14590 }
14591 visited.push(key.clone());
14592 if enumerable {
14593 keys.push(key);
14594 }
14595 }
14596 }
14597 }
14598 for (index, key) in keys.into_iter().enumerate() {
14599 record.define_data(&index.to_string(), self.string_wtf8(key));
14600 }
14601 record.define_data("__index", Value::Int(0));
14602 Ok(record)
14603 }
14604
14605 /// The next key of a `for…in` record, `None` when the loop is done.
14606 ///
14607 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
14608 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
14609 /// the loop reaches it, so a handler that stops reporting a key partway through drops
14610 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
14611 /// key the handler had already withdrawn.
14612 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
14613 let Value::Object(record) = record else {
14614 return Ok(None);
14615 };
14616 let proxy = record
14617 .own_property("__proxy")
14618 .and_then(|property| property.value);
14619 loop {
14620 let index = record
14621 .own_property("__index")
14622 .and_then(|property| property.value)
14623 .map(|value| value.to_int32())
14624 .unwrap_or(0);
14625 let Some(candidate) = record
14626 .own_property(&index.to_string())
14627 .and_then(|property| property.value)
14628 else {
14629 return Ok(None);
14630 };
14631 record.define_data("__index", Value::Int(index + 1));
14632 let text = candidate.to_js_string();
14633 let Some(Value::Object(proxy)) = &proxy else {
14634 return Ok(Some(text));
14635 };
14636 // The candidate is already a key string here, so the lookup does not need a
14637 // second `ToPropertyKey` conversion.
14638 let key = PropertyKey::from(text.as_str());
14639 let live = match self.proxy_get_own_property(proxy, &key)? {
14640 Some(descriptor) => descriptor,
14641 // Not a proxy after all, or it lost its state: fall back to the target.
14642 None => proxy.own_property_key(&key),
14643 };
14644 if live.is_some_and(|property| property.enumerable) {
14645 return Ok(Some(text));
14646 }
14647 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
14648 // next one.
14649 }
14650 }
14651
14652 /// The iterator for `for-of`: the object and its `next` method.
14653 ///
14654 /// An object that already carries a `next` method is used as it is — that is what
14655 /// `arr.values()` returns — and only arrays and strings get the built-in
14656 /// sequence iterator.
14657 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
14658 ///
14659 /// Callers that must choose between the iterable and the array-like protocol — the
14660 /// typed-array constructor is the main one — need to ask *before* committing to one.
14661 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
14662 let key = self.realm.well_known_key(WellKnown::Iterator);
14663 let method = self.read_field_key(value, &key)?;
14664 if matches!(method, Value::Undefined | Value::Null) {
14665 return Ok(false);
14666 }
14667 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14668 return Err(Signal::Throw(
14669 self.make_error("TypeError", "Symbol.iterator is not callable"),
14670 ));
14671 }
14672 Ok(true)
14673 }
14674
14675 /// Collect everything an iterable yields.
14676 ///
14677 /// The cap is a guard against a generator that never ends: an unbounded collect would
14678 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
14679 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
14680 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
14681 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
14682 const MAX_ITEMS: usize = 1 << 24;
14683 let iterator = self.get_iterator(value)?;
14684 let mut out = Vec::new();
14685 loop {
14686 let (element, done) = self.iterator_step(&iterator)?;
14687 if done {
14688 return Ok(out);
14689 }
14690 out.push(element);
14691 if out.len() > MAX_ITEMS {
14692 // Close before refusing: the walk is being abandoned, so the iterator's
14693 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
14694 // unrun and a locked resource unreleased.
14695 self.close_iterator_after_throw(&iterator)?;
14696 return Err(self.range_error("iterable is too long to collect"));
14697 }
14698 }
14699 }
14700
14701 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
14702 ///
14703 /// A native constructor calls this once it has validated its arguments, which is the
14704 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
14705 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
14706 /// never reached. The prototype comes from `new.target` when it is an object, and from
14707 /// `default_proto` otherwise.
14708 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14709 let proto = self.ctor_prototype(default_proto)?;
14710 Ok(self.new_object(Some(proto)))
14711 }
14712
14713 /// An **array** whose prototype comes from `new.target`.
14714 ///
14715 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
14716 /// instance from `new.target.prototype`, and building a plain array instead made every
14717 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
14718 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
14719 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
14720 Ok(JsObject::array(self.heap, Some(proto), 0))
14721 }
14722
14723 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
14724 ///
14725 /// The `Option` form is for the constructors that build their instance in a helper which
14726 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
14727 /// from `await`'s internal promise, and only the first has a `new.target`.
14728 fn ctor_prototype_opt(
14729 &mut self,
14730 default_proto: Option<Gc<JsObject>>,
14731 ) -> JsResult<Option<Gc<JsObject>>> {
14732 // `active_new_target`: by the time a native constructor runs, `call_value` has
14733 // already consumed the parked value.
14734 let Some(target) = self
14735 .active_new_target
14736 .as_object()
14737 .cloned()
14738 .map(Value::Object)
14739 else {
14740 return Ok(default_proto);
14741 };
14742 let Some(target) = target.as_object().cloned() else {
14743 return Ok(default_proto);
14744 };
14745 match self.get_property(&target, "prototype")? {
14746 Some(Value::Object(proto)) => Ok(Some(proto)),
14747 _ => Ok(default_proto),
14748 }
14749 }
14750
14751 /// `new.target.prototype`, or `default_proto` when this is a plain call.
14752 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14753 let Some(target) = self.active_new_target.as_object().cloned() else {
14754 return Ok(default_proto);
14755 };
14756 match self.get_property(&target, "prototype")? {
14757 Some(Value::Object(proto)) => Ok(proto),
14758 _ => Ok(default_proto),
14759 }
14760 }
14761
14762 /// `CreateDataPropertyOrThrow(O, key, value)`.
14763 ///
14764 /// A *definition*, not an assignment. The difference is visible the moment the target
14765 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
14766 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
14767 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
14768 /// refused (`configurable: false`).
14769 ///
14770 /// The fast path exists because this is called once per element by `map`, `filter`,
14771 /// `slice` and friends: a plain array with no custom element descriptors and a writable
14772 /// `length` can store straight into its element vector.
14773 pub fn create_data_property_or_throw(
14774 &mut self,
14775 object: &Gc<JsObject>,
14776 index: usize,
14777 value: Value,
14778 ) -> JsResult<()> {
14779 // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
14780 // an array (that is what `Array.isArray` must say), so the element fast path would
14781 // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
14782 // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
14783 // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
14784 // records the exact trap sequence.
14785 if object.proxy_state().is_none()
14786 && object.is_array()
14787 && object.elements_writable()
14788 && !object.has_element_descriptors()
14789 && object.is_extensible()
14790 && object.array_set(self.heap, index, value.clone())
14791 {
14792 return Ok(());
14793 }
14794 let key = PropertyKey::from(index.to_string());
14795 let property = Property {
14796 value: Some(value),
14797 writable: true,
14798 enumerable: true,
14799 configurable: true,
14800 ..Property::default()
14801 };
14802 // `CreateDataProperty` always asks for the default attributes, so it can only ever
14803 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
14804 // the rest. Checking here rather than inside `object_define_own_property` is
14805 // deliberate: that function receives a fully-populated `Property` and cannot tell
14806 // an omitted attribute from an explicit `false`, so the generic check it would need
14807 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
14808 // writable property (that cost eight `Object/defineProperty` tests).
14809 if object.proxy_state().is_none()
14810 && let Some(existing) = self.object_get_own_property(object, &key)?
14811 && !existing.configurable
14812 {
14813 return Err(self.type_error("cannot create the property"));
14814 }
14815 if self.object_define_own_property(object, &key, property)? {
14816 return Ok(());
14817 }
14818 Err(self.type_error("cannot create the property"))
14819 }
14820
14821 /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
14822 ///
14823 /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
14824 /// its callers have; this is the same operation for the named properties a built-in
14825 /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
14826 /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
14827 /// `Array.prototype` cannot see it — while `Set` would run that accessor.
14828 pub fn create_named_data_property_or_throw(
14829 &mut self,
14830 object: &Gc<JsObject>,
14831 key: &str,
14832 value: Value,
14833 ) -> JsResult<()> {
14834 let key = PropertyKey::from(key);
14835 let property = Property {
14836 value: Some(value),
14837 writable: true,
14838 enumerable: true,
14839 configurable: true,
14840 ..Property::default()
14841 };
14842 if object.proxy_state().is_none()
14843 && let Some(existing) = self.object_get_own_property(object, &key)?
14844 && !existing.configurable
14845 {
14846 return Err(self.type_error("cannot create the property"));
14847 }
14848 if self.object_define_own_property(object, &key, property)? {
14849 return Ok(());
14850 }
14851 Err(self.type_error("cannot create the property"))
14852 }
14853
14854 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
14855 ///
14856 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
14857 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
14858 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
14859 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
14860 /// run user code and both can throw.
14861 pub fn species_constructor(
14862 &mut self,
14863 object: &Gc<JsObject>,
14864 default: Value,
14865 ) -> JsResult<Value> {
14866 let Some(constructor) = self.get_property(object, "constructor")? else {
14867 return Ok(default);
14868 };
14869 let constructor = match constructor {
14870 Value::Undefined => return Ok(default),
14871 Value::Object(constructor) => constructor,
14872 _ => return Err(self.type_error("constructor is not an object")),
14873 };
14874 let key = self.realm.well_known_key(WellKnown::Species);
14875 let species = self.get_property_key(&constructor, &key)?;
14876 match species {
14877 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
14878 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
14879 Some(_) => Err(self.type_error("species is not a constructor")),
14880 }
14881 }
14882
14883 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
14884 ///
14885 /// The result is an array of `length` holes whose prototype comes from
14886 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
14887 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
14888 /// is why the `IsArray` check is the first step and not an optimisation.
14889 pub fn array_species_create(
14890 &mut self,
14891 original: &Value,
14892 length: usize,
14893 ) -> JsResult<Gc<JsObject>> {
14894 // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
14895 // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
14896 // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
14897 // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
14898 // `new_array_of_length` (`slice/create-non-array-invalid-len`).
14899 // `ArrayCreate(length)` is only reached when the result is a **plain array of this
14900 // realm** — the species may be a user function that ignores the length entirely, and
14901 // then `2**53 - 1` is not its problem
14902 // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
14903 // a short proxy and expects the copy loop to run).
14904 let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
14905 if length > ARRAY_CREATE_LIMIT {
14906 return Err(interp.range_error("invalid array length"));
14907 }
14908 Ok(interp.new_array_of_length(length))
14909 };
14910 let Some(object) = original.as_object().cloned() else {
14911 return default(self);
14912 };
14913 if !object.is_array() {
14914 return default(self);
14915 }
14916 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
14917 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
14918 let Some(constructor) = self.get_property(&object, "constructor")? else {
14919 return default(self);
14920 };
14921 let species = match constructor {
14922 Value::Undefined => return Ok(self.new_array_of_length(length)),
14923 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
14924 return default(self);
14925 }
14926 Value::Object(constructor) => {
14927 let key = self.realm.well_known_key(WellKnown::Species);
14928 match self.get_property_key(&constructor, &key)? {
14929 None | Some(Value::Undefined) | Some(Value::Null) => {
14930 return default(self);
14931 }
14932 Some(species) => species,
14933 }
14934 }
14935 // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
14936 // is a `TypeError`, not "the default". Treating it as the default made
14937 // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
14938 // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
14939 // `concat/create-ctor-non-object` are the same rule three times.
14940 _ => return Err(self.type_error("constructor is not an object")),
14941 };
14942 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
14943 // that is merely callable is the `create-species-non-ctor` case.
14944 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
14945 return Err(self.type_error("species is not a constructor"));
14946 }
14947 // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
14948 // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
14949 // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
14950 let created = self.construct(
14951 species.clone(),
14952 species,
14953 vec![crate::object::length_value(length)],
14954 )?;
14955 let Some(created) = created.as_object().cloned() else {
14956 return Err(self.type_error("species constructor did not answer an object"));
14957 };
14958 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
14959 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
14960 // object, and `create-species-with-non-writable-property` asserts exactly that.
14961 // The length is set for the array case; the generic case is the caller's
14962 // `Set(A, "length", …)`.
14963 if created.is_array() {
14964 created.array_set_length(self.heap, length);
14965 }
14966 Ok(created)
14967 }
14968
14969 /// Whether `object` is this realm's `%Array%`.
14970 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
14971 self.realm
14972 .array_constructor
14973 .as_ref()
14974 .is_some_and(|array| array.ptr_eq(object))
14975 }
14976
14977 /// A fresh `length`-hole array with the intrinsic prototype.
14978 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
14979 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
14980 array.array_set_length(self.heap, length);
14981 array
14982 }
14983
14984 /// Whether this call is a construction, i.e. `new.target` is defined.
14985 ///
14986 /// A native constructor receives `this = undefined` (it builds its own instance), so it
14987 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
14988 /// The native function currently executing, if any.
14989 pub fn current_native(&self) -> Option<Gc<JsObject>> {
14990 self.current_native.clone()
14991 }
14992
14993 /// Whether this call is a construction, i.e. `new.target` is defined.
14994 pub fn is_constructing(&self) -> bool {
14995 // `active_new_target`, not `pending_new_target`: the parked value is consumed by
14996 // `call_value` before a native runs, so by the time a constructor body asks, the
14997 // answer is only in the active slot.
14998 matches!(self.active_new_target, Value::Object(_))
14999 }
15000
15001 /// The `TypeError` a constructor too primitive to have a wrapper raises.
15002 ///
15003 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
15004 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
15005 /// happens inside the native function, which is why the trace carries an
15006 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
15007 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
15008 /// constructor`, and an unnamed one reports the leading space of `" is not a
15009 /// constructor"` because the reference formats the empty name as it is.
15010 ///
15011 /// It is also the answer for a `new.target` that cannot be named at all — not a
15012 /// function, or a throwing `name` getter — where the reference falls back to the bare
15013 /// `not a constructor`.
15014 pub fn not_a_constructor_error(&mut self) -> Signal {
15015 let target = self.active_new_target.clone();
15016 self.not_a_constructor_error_for(target)
15017 }
15018
15019 /// The same `TypeError` for an explicit target, for the callers that check
15020 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
15021 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
15022 let target = match target {
15023 Value::Object(target) if target.is_callable() => target,
15024 _ => return self.type_error("not a constructor"),
15025 };
15026 let name = match self.get_property(&target, "name") {
15027 Ok(Some(value)) => value.to_js_string(),
15028 _ => return self.type_error("not a constructor"),
15029 };
15030 self.type_error(format!("{name} is not a constructor"))
15031 }
15032
15033 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
15034 ///
15035 /// True whenever `new.target` is not the callee itself, or when it has no usable
15036 /// `prototype` — the cases where reading the property is observable at all.
15037 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
15038 match &self.active_new_target {
15039 Value::Object(target) => !target.ptr_eq(callee),
15040 Value::Undefined => false,
15041 _ => true,
15042 }
15043 }
15044
15045 /// The symbol key for one of the engine's own hidden slots.
15046 ///
15047 /// Cached on the realm, so every object of a kind shares one key and a slot can be
15048 /// read back by name.
15049 /// Whether any object on `object`'s **prototype chain** owns an array index.
15050 ///
15051 /// The one question the array methods' dense fast paths have to ask before touching the
15052 /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
15053 /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
15054 /// vector an unreliable answer. Walking the chain once per call is cheap because a
15055 /// prototype almost never holds an index.
15056 pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
15057 let mut current = object.proto();
15058 // Bounded, like every other prototype walk here: a proxy can answer a cycle.
15059 for _ in 0..10_000 {
15060 let Some(proto) = current else {
15061 return false;
15062 };
15063 if proto.has_indexed_own_property() {
15064 return true;
15065 }
15066 current = proto.proto();
15067 }
15068 false
15069 }
15070
15071 /// The hidden symbol a named internal slot is keyed by, created on first use.
15072 ///
15073 /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
15074 /// either keeping a table of its own.
15075 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
15076 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
15077 return PropertyKey::Symbol(symbol.clone());
15078 }
15079 let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
15080 self.realm
15081 .internal_slots
15082 .borrow_mut()
15083 .insert(name, Value::Symbol(symbol.clone()));
15084 PropertyKey::Symbol(symbol)
15085 }
15086
15087 /// Read a hidden slot, or `None` when the object has none of that name.
15088 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
15089 let slots = self.realm.internal_slots.borrow();
15090 let Value::Symbol(symbol) = slots.get(name)? else {
15091 return None;
15092 };
15093 object
15094 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
15095 .and_then(|property| property.value)
15096 }
15097
15098 /// Define a hidden slot.
15099 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
15100 let key = self.internal_slot(name);
15101 object.define_key(&key, Property::with_attributes(value, false, false));
15102 }
15103
15104 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
15105 ///
15106 /// The method is looked up on the value (through its prototype), called with no
15107 /// arguments, and its result becomes the iterator. A generator gets here through
15108 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
15109 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
15110 ///
15111 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
15112 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
15113 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
15114 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
15115 /// does, and a user-defined iterable works without a special case.
15116 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
15117 /// `Symbol.iterator`.
15118 ///
15119 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
15120 /// iterable is legal there, and each value it produces is simply already settled by
15121 /// the time the `await` around it runs.
15122 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15123 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
15124 let method = self.read_field_key(value, &async_key)?;
15125 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
15126 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
15127 // is *present but not callable* is a TypeError — it does not mean "try the other
15128 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
15129 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
15130 // guard is there to catch.
15131 let absent = matches!(method, Value::Undefined | Value::Null);
15132 if !absent {
15133 let Value::Object(object) = &method else {
15134 return Err(Signal::Throw(
15135 self.make_error("TypeError", "value is not iterable"),
15136 ));
15137 };
15138 if !object.is_callable() {
15139 return Err(Signal::Throw(
15140 self.make_error("TypeError", "value is not iterable"),
15141 ));
15142 }
15143 }
15144 if absent {
15145 // §7.4.2 step 5: the synchronous iterator is **wrapped**. `for await` and an async
15146 // generator's `yield*` both reach here, and the wrapper is what puts
15147 // `PromiseResolve(%Promise%, value)` between the sync iterator's `value` and the
15148 // caller — a poisoned `constructor` on that value rejects instead of being
15149 // yielded, and a rejection closes the synchronous iterator first.
15150 let sync = self.get_iterator(value)?;
15151 return self.async_from_sync_iterator(sync);
15152 }
15153 let iterator = self.call_value(method, value.clone(), Vec::new())?;
15154 if !matches!(iterator, Value::Object(_)) {
15155 return Err(Signal::Throw(
15156 self.make_error("TypeError", "iterator is not an object"),
15157 ));
15158 }
15159 let next = self.read_field(&iterator, "next")?;
15160 Ok(Iterator {
15161 object: iterator,
15162 next,
15163 })
15164 }
15165
15166 /// `CreateAsyncFromSyncIterator(syncIteratorRecord)` (§27.1.4.1).
15167 ///
15168 /// The wrapper itself is script (see [`crate::builtins::async_from_sync`]); this only
15169 /// hands it the record and reads back its `next`. Both are properties of the wrapper, so
15170 /// the returned [`Iterator`] steps through `%AsyncFromSyncIteratorPrototype%.next`.
15171 fn async_from_sync_iterator(&mut self, sync: Iterator) -> JsResult<Iterator> {
15172 let Some(factory) = self.realm.async_from_sync.clone() else {
15173 // No wrapper installed (a realm whose heap refused to hold it): fall back to the
15174 // raw synchronous iterator rather than refusing to iterate at all.
15175 return Ok(sync);
15176 };
15177 let wrapper = self.call_value(factory, Value::Undefined, vec![sync.object, sync.next])?;
15178 let next = self.read_field(&wrapper, "next")?;
15179 Ok(Iterator {
15180 object: wrapper,
15181 next,
15182 })
15183 }
15184
15185 /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
15186 /// read — `@@iterator` is **not** consulted.
15187 ///
15188 /// The distinction is observable and test262 exercises it: a set-like object's `keys`
15189 /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
15190 /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
15191 /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
15192 /// refused it with "[object Object] is not iterable".
15193 pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
15194 if !matches!(value, Value::Object(_)) {
15195 return Err(self.type_error("iterator is not an object"));
15196 }
15197 let next = self.read_field(&value, "next")?;
15198 Ok(Iterator {
15199 object: value,
15200 next,
15201 })
15202 }
15203
15204 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
15205 let key = self.realm.well_known_key(WellKnown::Iterator);
15206 let method = self.read_field_key(value, &key)?;
15207 let Value::Object(function) = &method else {
15208 return Err(Signal::Throw(self.make_error(
15209 "TypeError",
15210 &format!("{} is not iterable", value.to_js_string()),
15211 )));
15212 };
15213 if !function.is_callable() {
15214 return Err(Signal::Throw(self.make_error(
15215 "TypeError",
15216 &format!("{} is not iterable", value.to_js_string()),
15217 )));
15218 }
15219 let iterator = self.call_value(method, value.clone(), Vec::new())?;
15220 // The spec requires an object here; a primitive iterator has no `next` to call
15221 // and would fail one step later with a confusing message.
15222 if !matches!(iterator, Value::Object(_)) {
15223 return Err(Signal::Throw(
15224 self.make_error("TypeError", "iterator is not an object"),
15225 ));
15226 }
15227 let next = self.read_field(&iterator, "next")?;
15228 Ok(Iterator {
15229 object: iterator,
15230 next,
15231 })
15232 }
15233
15234 /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
15235 /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
15236 /// exception from `return` propagates normally instead of being swallowed. That is the
15237 /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
15238 /// because confusing them is exactly the bug both exist to avoid.
15239 pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
15240 let method = self.read_field(&iterator.object, "return")?;
15241 if matches!(method, Value::Undefined | Value::Null) {
15242 return Ok(());
15243 }
15244 if !matches!(&method, Value::Object(object) if object.is_callable()) {
15245 return Err(self.type_error("iterator return is not a function"));
15246 }
15247 self.call_value(method, iterator.object.clone(), Vec::new())?;
15248 Ok(())
15249 }
15250
15251 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
15252 /// cannot replace it.
15253 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
15254 let method = self.read_field(&iterator.object, "return")?;
15255 if matches!(method, Value::Undefined | Value::Null) {
15256 return Ok(());
15257 }
15258 if !matches!(&method, Value::Object(object) if object.is_callable()) {
15259 return Err(self.type_error("iterator return is not a function"));
15260 }
15261 self.call_value(method, iterator.object.clone(), Vec::new())?;
15262 Ok(())
15263 }
15264
15265 /// One step of an internal iterator: the value and whether it is exhausted.
15266 /// Replace the iterator slot of an iteration record with `undefined`.
15267 ///
15268 /// `slot` counts values above it, the same convention `for_of_next`'s operand uses. An
15269 /// `undefined` record is what every close path already treats as "nothing to close", so
15270 /// one store both records "this iterator must not be closed" and keeps
15271 /// [`Interp::catch_here`] from calling `return` on an iterator whose `next` threw.
15272 fn clear_iterator_slot(&mut self, slot: usize) {
15273 let frame = self.frame_mut();
15274 let depth = frame.stack.len();
15275 if depth > slot {
15276 frame.stack[depth - 1 - slot] = Value::Undefined;
15277 }
15278 }
15279
15280 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
15281 // §7.4.4 `IteratorNext`: `Call(iteratorRecord.[[NextMethod]], …)` is where a
15282 // non-callable `next` is rejected — **not** `GetIteratorDirect`, which only reads
15283 // the property. The difference is observable: `[ …{}[yield] ] = it` suspends
15284 // before the first step, so an iterator with no `next` still gets its `return`
15285 // called by `it.return()` instead of failing up front
15286 // (`array-rest-iter-rtrn-close-err`).
15287 if let Value::Object(object) = &iterator.next
15288 && object.is_callable()
15289 {
15290 let result =
15291 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
15292 let Some(result) = result.as_object().cloned() else {
15293 return Err(self.type_error("iterator result is not an object"));
15294 };
15295 let done = self
15296 .get_property(&result, "done")?
15297 .is_some_and(|value| value.to_boolean());
15298 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
15299 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
15300 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
15301 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
15302 // made an unrelated `value` getter observable after the loop was over.
15303 if done {
15304 return Ok((Value::Undefined, true));
15305 }
15306 let value = self
15307 .get_property(&result, "value")?
15308 .unwrap_or(Value::Undefined);
15309 return Ok((value, false));
15310 }
15311 // §7.4.4: `next` was read by `GetIteratorDirect` but its callability is only
15312 // tested at the call. Treating a non-callable `next` as "exhausted" instead made
15313 // `Object.fromEntries({[Symbol.iterator]: () => ({next: null})})` succeed with an
15314 // empty object, where §21.1.2.2's `? IteratorStepValue` must throw a `TypeError`.
15315 Err(Signal::Throw(self.make_error(
15316 "TypeError",
15317 "iterator's next method is not callable",
15318 )))
15319 }
15320
15321 /// `[...iterable]`: append everything the iterator yields, and answer the next
15322 /// index.
15323 ///
15324 /// This goes through the same iterator machinery `for-of` uses rather than copying
15325 /// an array's elements, because a spread source is any iterable: a string spreads
15326 /// into its characters and an array iterator spreads into its results. Handling
15327 /// only arrays made `[..."ab"]` come out empty with no error at all.
15328 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
15329 let Some(target) = array.as_object().cloned() else {
15330 return Ok(0);
15331 };
15332 let start = target.array_length().unwrap_or(0);
15333 let mut added = 0;
15334 let iterator = self.get_iterator(iterable)?;
15335 loop {
15336 let (value, done) = self.iterator_step(&iterator)?;
15337 if done {
15338 break;
15339 }
15340 target.array_set(self.heap, start + added, value);
15341 added += 1;
15342 }
15343 Ok((start + added) as i32)
15344 }
15345
15346 /// How an uncaught exception is reported.
15347 ///
15348 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
15349 /// with `ToString` — `js_std_dump_error` is three lines that end in
15350 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
15351 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
15352 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
15353 ///
15354 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
15355 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
15356 /// `toString`"; it does call it, but only for objects of a class it does not know how
15357 /// to walk, and never for errors, arrays or plain objects.
15358 ///
15359 /// A printer that fails must not take the reporter down with it, so that case falls
15360 /// back to the `ToString` rendering.
15361 pub fn describe_exception(&mut self, value: &Value) -> String {
15362 match crate::print::sprint(self, value) {
15363 Ok(text) => text,
15364 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
15365 }
15366 }
15367
15368 /// The file name of whatever is running, innermost frame first.
15369 ///
15370 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
15371 /// innermost frame's file name, without distinguishing a module body from a plain
15372 /// script. `import()` uses it as the base for a relative specifier, which is why
15373 /// `import('./x.js')` inside a script resolves next to the script and not next to the
15374 /// process's working directory.
15375 pub fn script_or_module_name(&self) -> Option<String> {
15376 self.script_or_module_name_at(0)
15377 }
15378
15379 /// [`Interp::script_or_module_name`] `level` frames further out.
15380 ///
15381 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
15382 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
15383 /// frame without a file name is skipped rather than counted, because a native call
15384 /// pushes no frame of its own and so cannot be a level.
15385 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
15386 self.frames
15387 .iter()
15388 .rev()
15389 .filter_map(|frame| frame.code.code.filename.clone())
15390 .nth(level)
15391 }
15392
15393 /// The innermost frame name that could be a *file*, skipping `<eval>`-style pseudo-names.
15394 ///
15395 /// `eval` and `std.evalScript` compile their bodies under `<input>` / `<evalScript>`
15396 /// because that is what a stack trace should print, but §19.2.1.1's
15397 /// `GetActiveScriptOrModule` makes an eval'd body belong to the script that called it —
15398 /// never to something called `<input>`. Resolving `import('./x.js')` against a pseudo-name
15399 /// produced the bare specifier `x.js`, which the loader then looked for in the working
15400 /// directory instead of beside the file that called `eval`.
15401 pub fn script_or_module_file_name(&self) -> Option<String> {
15402 self.frames.iter().rev().find_map(|frame| {
15403 let name = frame.code.code.filename.as_deref()?;
15404 (!name.starts_with('<')).then(|| name.to_string())
15405 })
15406 }
15407
15408 /// The current call stack, formatted the way `qjs` prints `error.stack`.
15409 ///
15410 /// One ` at name (file:line:col)` line per active frame, innermost first. The
15411 /// position is the one recorded for the instruction each frame is stopped on, which
15412 /// is why the compiler builds a pc-to-position table per function: without it a
15413 /// trace could only name the function, not the line inside it.
15414 ///
15415 /// A frame whose code has no positions prints just `(file)`, matching the
15416 /// reference's output for stripped bytecode.
15417 pub fn stack_trace(&self) -> String {
15418 self.stack_trace_skipping(0)
15419 }
15420
15421 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
15422 fn stack_trace_skipping(&self, skip: usize) -> String {
15423 // One ordered list, innermost first, so `skip` counts the same thing whether the
15424 // frames it leaves out are native or bytecode. Indices rather than references: a
15425 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
15426 let depth = self.frames.len();
15427 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
15428 // A native entered while `at` bytecode frames were live was called *from* the
15429 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
15430 // entered at the current depth are therefore innermost of all.
15431 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
15432 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
15433 if *at == wanted {
15434 order.push((true, index));
15435 }
15436 }
15437 };
15438 push_natives(&mut order, depth);
15439 for index in (0..depth).rev() {
15440 order.push((false, index));
15441 push_natives(&mut order, index);
15442 }
15443 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
15444 // barrier. Natives entered at exactly the barrier depth are the eval entry point
15445 // itself (`evalScript (native)`), and the reference leaves those out too.
15446 if let Some(barrier) = self.trace_barriers.last().copied() {
15447 order.retain(|(is_native, index)| match is_native {
15448 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
15449 false => *index >= barrier,
15450 });
15451 }
15452
15453 let mut out = String::new();
15454 for (is_native, index) in order.into_iter().skip(skip) {
15455 match is_native {
15456 true => {
15457 out.push_str(" at ");
15458 let (native, _) = &self.native_frames[index];
15459 let name = native
15460 .own_property("name")
15461 .and_then(|property| property.value)
15462 .map(|value| value.to_js_string())
15463 .unwrap_or_default();
15464 out.push_str(&name);
15465 out.push_str(" (native)\n");
15466 }
15467 false => {
15468 let frame = &self.frames[index];
15469 let code = &frame.code.code;
15470 let file = code.filename.as_deref().unwrap_or("<input>");
15471 // The name comes from the function *object*, not from the compiled code:
15472 // an anonymous function expression is named by the property it is stored
15473 // in (`{valueOf: function(){}}`), which only the object knows.
15474 let bound_name = match &frame.callee {
15475 Value::Object(object) => {
15476 object
15477 .own_property("name")
15478 .and_then(|property| match property.value {
15479 Some(Value::String(text)) if !text.wtf8().is_empty() => {
15480 Some(text.to_string_lossy().into_owned())
15481 }
15482 _ => None,
15483 })
15484 }
15485 _ => None,
15486 };
15487 // No callee object means the body was entered by the host, so the
15488 // name has to come from the compiled code. Two cases differ:
15489 //
15490 // * an *unnamed* function of any kind — the reference reads the
15491 // `name` property, finds it empty, and prints `<anonymous>`;
15492 // * a *module* body, which has no `name` property at all: the
15493 // reference builds that function object with `js_closure2` and
15494 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
15495 // so a trace reaching it also prints `<anonymous>` — while a
15496 // *script* body prints `<eval>`, its `name`.
15497 let unnamed = code.name.is_empty() || code.module.is_some();
15498 out.push_str(" at ");
15499 match bound_name.as_deref() {
15500 Some(name) => out.push_str(name),
15501 None if unnamed => out.push_str("<anonymous>"),
15502 None => out.push_str(&code.name),
15503 }
15504 match code.position_at(frame.at as u32) {
15505 Some((line, column)) => {
15506 out.push_str(&format!(" ({file}:{line}:{column})\n"));
15507 }
15508 None => out.push_str(&format!(" ({file})\n")),
15509 }
15510 }
15511 }
15512 }
15513 out
15514 }
15515
15516 /// Give an anonymous function the name of the property it is stored in.
15517 ///
15518 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
15519 /// enumerable and not configurable, and a function that already has a real name
15520 /// keeps it.
15521 ///
15522 /// "Already named" means a *non-empty* name: every function object is created with
15523 /// a `name` of `""` so the property exists on all of them, and treating that empty
15524 /// string as a name left every anonymous function nameless — which is how a stack
15525 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
15526 /// `SetFunctionName`, for a name that came from source text.
15527 fn set_function_name(&mut self, function: &Value, name: &str) {
15528 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
15529 }
15530
15531 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
15532 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
15533 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
15534 let Value::Object(object) = function else {
15535 return;
15536 };
15537 // `SetFunctionName` applies to *functions* and classes only, and only when they are
15538 // anonymous. Without the callability guard, `{value: someObject}` renamed
15539 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
15540 // on the right-hand side of a property. That is how a `zipKeyed` result object
15541 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
15542 // has no `NamedEvaluation` at all.
15543 if !object.is_callable() {
15544 return;
15545 }
15546 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
15547 && !existing.wtf8().is_empty()
15548 {
15549 return;
15550 }
15551 let text = self.string_wtf8(name.clone());
15552 object.define("name", Property::name_or_length(text));
15553 }
15554
15555 // -- global declarations -----------------------------------------------
15556
15557 /// Declare a global binding, creating its reference cell.
15558 /// Declare a `var` or function global, whose home is the global object.
15559 ///
15560 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
15561 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
15562 /// such as `print`, or a redeclaration — is left alone.
15563 pub fn declare_var_global(&mut self, name: &str) {
15564 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
15565 // global object is exactly the leak `typeof my_var === "undefined"` after
15566 // `eval("var my_var=2")` rules out.
15567 if let Some(scope) = self.eval_scope.as_mut() {
15568 scope.entry(name.to_string()).or_insert(Value::Undefined);
15569 return;
15570 }
15571 // A sloppy direct eval declares into its *caller's* variable environment. Doing
15572 // this on the global object instead made `eval("var c = 1")` inside a parameter
15573 // list overwrite a global `c`, and made two calls to the same function share one
15574 // binding.
15575 if let Some(cell) = self.declare_eval_local(name) {
15576 cell.set(Value::Undefined);
15577 return;
15578 }
15579 let global = self.realm.global.clone();
15580 if global.own_property(name).is_some() {
15581 return;
15582 }
15583 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
15584 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
15585 // whole point of that trick and what lets `Object.defineProperty` reshape it
15586 // afterwards. `eval_scope` is `Some` while an eval is running.
15587 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
15588 global.define(
15589 name,
15590 Property {
15591 value: Some(Value::Undefined),
15592 writable: true,
15593 enumerable: true,
15594 configurable: from_eval,
15595 ..Property::default()
15596 },
15597 );
15598 }
15599
15600 /// Declare a *lexical* global binding, which starts in its dead zone.
15601 ///
15602 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
15603 /// global object and is created when its initialiser runs.
15604 pub fn declare_global(&mut self, name: &str, is_const: bool) {
15605 if is_const {
15606 self.realm.lexical_consts.insert(name.to_string());
15607 }
15608 if !self.realm.globals.contains_key(name) {
15609 // `Uninitialized` rather than `Undefined`: the binding exists but is not
15610 // readable until its initialiser runs, and that is what `let x` before
15611 // `x = 1` has to observe.
15612 let cell = self.new_cell(Value::Uninitialized);
15613 self.realm.globals.insert(name.to_string(), cell);
15614 self.realm.declared.push(name.to_string());
15615 }
15616 }
15617}
15618
15619/// The bytecode and environment of a function object, if it is a bytecode function.
15620///
15621/// Extracted before a call so no borrow of the object is held across it.
15622fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
15623 function.with(|data| match &data.kind {
15624 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
15625 _ => None,
15626 })
15627}
15628
15629/// A native call target, extracted before the call so no borrow is held.
15630enum NativeCall {
15631 Native(NativeFn),
15632 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
15633 /// not hold that object's `RefCell` borrow.
15634 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
15635 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
15636 Bound {
15637 target: Value,
15638 this: Value,
15639 leading: Vec<Value>,
15640 },
15641 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
15642 Revoker(crate::object::ProxyRef),
15643 /// A promise's `resolve`.
15644 PromiseResolve(Gc<JsObject>),
15645 /// A promise's `reject`.
15646 PromiseReject(Gc<JsObject>),
15647 /// The executor `NewPromiseCapability(C)` hands a user constructor.
15648 CapabilityExecutor {
15649 state: Gc<JsObject>,
15650 },
15651 /// One leg of a `then` that settles through a user capability.
15652 ThenShim {
15653 handler: Option<Value>,
15654 resolve: Value,
15655 reject: Value,
15656 fulfilled: bool,
15657 },
15658 /// One continuation of an `await`.
15659 AwaitResume {
15660 coroutine: Gc<JsObject>,
15661 promise: Gc<JsObject>,
15662 kind: ResumeKind,
15663 },
15664 /// One element of a `Promise` combinator settling.
15665 CombinatorSettle {
15666 state: Gc<JsObject>,
15667 index: usize,
15668 fulfilled: bool,
15669 },
15670 /// One of `Promise.prototype.finally`'s two shims.
15671 FinallyShim {
15672 callback: Option<Value>,
15673 fulfilled: bool,
15674 constructor: Value,
15675 },
15676 /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
15677 ReturnValue(Value),
15678 /// A thunk that throws a fixed value, for `finally`'s `thrower`.
15679 ThrowValue(Value),
15680 /// Settle a promise with a fixed outcome.
15681 SettlePromise {
15682 promise: Gc<JsObject>,
15683 value: Value,
15684 rejected: bool,
15685 },
15686 /// Continue an async generator after its `await` settled.
15687 GeneratorResume {
15688 generator: Gc<JsObject>,
15689 promise: Gc<JsObject>,
15690 kind: ResumeKind,
15691 },
15692 /// Read a module namespace's binding out of its cell.
15693 ModuleBinding(Gc<Cell>),
15694 /// Finish a completed async generator's `return(v)` once `v` has settled.
15695 CompletedReturn {
15696 generator: Gc<JsObject>,
15697 promise: Gc<JsObject>,
15698 rejected: bool,
15699 },
15700 /// Answer a pending async-generator method with `{value, done}`.
15701 YieldResult {
15702 generator: Gc<JsObject>,
15703 promise: Gc<JsObject>,
15704 done: bool,
15705 },
15706 /// One step of `AsyncDisposableStack.disposeAsync`.
15707 DisposeStep {
15708 remaining: Gc<JsObject>,
15709 promise: Gc<JsObject>,
15710 error: Value,
15711 rejected: bool,
15712 awaited: bool,
15713 needs_await: bool,
15714 },
15715}
15716
15717/// What a store does when the object refuses the write.
15718#[derive(Clone, Copy, PartialEq, Eq)]
15719pub enum DeleteFailure {
15720 /// Raise a `TypeError`, which is what strict mode and every built-in does.
15721 Throw,
15722 /// Ignore the write, which is what a sloppy-mode assignment does.
15723 Ignore,
15724}
15725
15726/// Whether `object` is a `Date` instance, by the class tag it carries.
15727///
15728/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
15729/// builtins module depending on the interpreter's conversion order.
15730fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
15731 interp
15732 .internal_get(object, "_class")
15733 .is_some_and(|value| value.to_js_string() == "Date")
15734}
15735
15736/// Which type `ToPrimitive` prefers when it converts an object.
15737#[derive(Clone, Copy, PartialEq, Eq)]
15738pub enum Hint {
15739 /// The default hint, which behaves like [`Hint::Number`].
15740 Default,
15741 /// `Number(obj)` and the arithmetic operators.
15742 Number,
15743 /// `String(obj)` and `ToPropertyKey`.
15744 String,
15745}
15746
15747/// Which table a binding slot indexes, for the messages that name it.
15748#[derive(Clone, Copy)]
15749enum VarSlot {
15750 Loc,
15751 Closure,
15752}
15753
15754/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
15755fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
15756 Ok(this)
15757}
15758
15759/// An internal iterator: the sequence plus a cursor.
15760pub(crate) struct Iterator {
15761 pub(crate) object: Value,
15762 pub(crate) next: Value,
15763}
15764
15765/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
15766/// and plain `a` for a method.
15767///
15768/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
15769/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
15770/// reads `at get a (file:1:2)`.
15771/// The same prefixing, for a name that may hold an unpaired surrogate.
15772fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
15773 let prefix = match flags & 3 {
15774 1 => "get ",
15775 2 => "set ",
15776 _ => return key.clone(),
15777 };
15778 let mut units: Vec<u16> = prefix.encode_utf16().collect();
15779 units.extend_from_slice(&key.to_units());
15780 crate::value::Wtf8::from_units(&units)
15781}
15782
15783/// `SetFunctionName`'s name for a symbol property key: `[description]`, or `""`.
15784///
15785/// §7.3.24 step 1. A symbol without a description names the function the empty string, not
15786/// `Symbol()` — the two are different and test262 checks both.
15787fn symbol_key_name(key: &PropertyKey) -> crate::value::Wtf8 {
15788 let PropertyKey::Symbol(symbol) = key else {
15789 return crate::value::Wtf8::default();
15790 };
15791 match symbol.description() {
15792 Some(description) => crate::value::Wtf8::new(format!("[{description}]")),
15793 None => crate::value::Wtf8::default(),
15794 }
15795}
15796
15797/// Define a method or accessor property, per the `define_method` flag byte.
15798///
15799/// The low two bits pick value/getter/setter and bit 2 marks the property
15800/// enumerable.
15801///
15802/// A getter and a setter arrive as two separate `define_method` instructions, and the
15803/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
15804/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
15805/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
15806/// `JS_DefineProperty`, which leaves the other half alone.
15807fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
15808 let enumerable = flags & 4 != 0;
15809 let kind = flags & 3;
15810 let existing = object.own_property_key(key);
15811 let property = match kind {
15812 1 => Property {
15813 getter: Some(function),
15814 // The setter half, if this literal already defined one.
15815 setter: existing
15816 .filter(Property::is_accessor)
15817 .and_then(|p| p.setter),
15818 enumerable,
15819 configurable: true,
15820 ..Property::default()
15821 },
15822 2 => Property {
15823 getter: existing
15824 .filter(Property::is_accessor)
15825 .and_then(|p| p.getter),
15826 setter: Some(function),
15827 enumerable,
15828 configurable: true,
15829 ..Property::default()
15830 },
15831 _ => Property {
15832 value: Some(function),
15833 writable: true,
15834 enumerable,
15835 configurable: true,
15836 ..Property::default()
15837 },
15838 };
15839 object.define_key(key, property);
15840}
15841
15842// ---------------------------------------------------------------------------
15843// Operand decoding
15844// ---------------------------------------------------------------------------
15845
15846/// How `print` renders a value: the reference's `JS_PrintValue`.
15847///
15848/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
15849/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
15850/// The format is reproduced closely because the test suite compares output text:
15851///
15852/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
15853/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
15854/// * a cycle prints `[circular N]` with `N` the stack index of the object;
15855/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
15856/// end print as `<N empty item(s)>`;
15857/// * a string is quoted inside a container but raw at the top level, which is why
15858/// `print("x")` and `print(["x"])` differ.
15859pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
15860 // A string argument is printed raw: `js_print` converts it with `ToString`
15861 // instead of dumping it, and the quoting only appears inside a container.
15862 if let Value::String(text) = value {
15863 return text.to_string_lossy().into_owned();
15864 }
15865 let mut printer = Printer {
15866 interp,
15867 out: String::new(),
15868 stack: Vec::new(),
15869 };
15870 printer.value(value, 0);
15871 printer.out
15872}
15873
15874/// The internal class name an object carries, when it has one.
15875fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
15876 interp
15877 .internal_get(object, "_class")
15878 .map(|value| value.to_js_string())
15879}
15880
15881/// A string property, looked up the way `GetProperty` does: own first, then the
15882/// prototype chain. Needed because the print formatter holds the interpreter
15883/// immutably and so cannot run getters.
15884fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
15885 let mut current = Some(object.clone());
15886 // Bounded, because a prototype cycle would otherwise loop forever.
15887 for _ in 0..100 {
15888 let node = current?;
15889 if let Some(property) = node.own_property(name)
15890 && let Some(value) = property.value
15891 {
15892 return Some(value.to_js_string());
15893 }
15894 current = node.with(|data| data.proto.clone());
15895 }
15896 None
15897}
15898
15899/// The `JS_PrintValue` state: output, and the objects currently being printed.
15900struct Printer<'a, 'rt> {
15901 /// Kept for the class-name lookups that typed arrays and `Date` will need.
15902 #[allow(dead_code)]
15903 interp: &'a Interp<'rt>,
15904 out: String,
15905 stack: Vec<Gc<JsObject>>,
15906}
15907
15908impl Printer<'_, '_> {
15909 /// Depth past which a container is summarised by its class name.
15910 const MAX_DEPTH: usize = 2;
15911
15912 fn value(&mut self, value: &Value, level: usize) {
15913 match value {
15914 Value::Undefined
15915 | Value::Uninitialized
15916 | Value::Hole
15917 | Value::CatchOffset(_)
15918 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
15919 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
15920 // The printer writes a bigint the way the language spells one, so a dump is
15921 // unambiguous about which kind of number it is showing.
15922 Value::BigInt(big) => {
15923 self.out.push_str(&big.to_decimal_string());
15924 self.out.push('n');
15925 }
15926 Value::Null => self.out.push_str("null"),
15927 Value::Bool(true) => self.out.push_str("true"),
15928 Value::Bool(false) => self.out.push_str("false"),
15929 Value::Int(number) => self.out.push_str(&number.to_string()),
15930 Value::Float(number) => {
15931 self.out
15932 .push_str(&crate::value::number_to_string_for_print(*number));
15933 }
15934 Value::String(text) => self.print_string(&text.to_string_lossy()),
15935 Value::Object(object) => self.object(object, level),
15936 }
15937 }
15938
15939 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
15940 // A cycle is reported rather than followed; the index is where the object
15941 // already sits in the print stack, which is what the reference shows.
15942 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
15943 self.out.push_str(&format!("[circular {index}]"));
15944 return;
15945 }
15946 if object.is_callable() {
15947 let name = object
15948 .own_property("name")
15949 .and_then(|property| property.value)
15950 .map(|value| value.to_js_string())
15951 .unwrap_or_default();
15952 if name.is_empty() {
15953 self.out.push_str("[Function (anonymous)]");
15954 } else {
15955 self.out.push_str(&format!("[Function {name}]"));
15956 }
15957 return;
15958 }
15959 if level >= Self::MAX_DEPTH {
15960 let class = if object.is_array() { "Array" } else { "Object" };
15961 self.out.push_str(&format!("[{class}]"));
15962 return;
15963 }
15964 // `Date` and `Error` print as themselves rather than as bags of properties:
15965 // the ISO string, and `Name: message` followed by the trace.
15966 if let Some(class) = class_of(self.interp, object) {
15967 if class == "Date" {
15968 self.date(object);
15969 return;
15970 }
15971 if class == "Error" {
15972 self.error(object);
15973 return;
15974 }
15975 }
15976 self.stack.push(object.clone());
15977 if object.is_array() {
15978 self.array(object, level);
15979 } else {
15980 self.plain_object(object, level);
15981 }
15982 self.stack.pop();
15983 }
15984
15985 /// A Date prints as its ISO string; an invalid one falls through to the plain
15986 /// object form, the way the reference falls back when `toISOString` throws.
15987 fn date(&mut self, object: &Gc<JsObject>) {
15988 let value = self
15989 .interp
15990 .internal_get(object, "_date_value")
15991 .map(|value| value.to_number());
15992 match value.and_then(crate::builtins::date::iso_string) {
15993 Some(text) => self.out.push_str(&text),
15994 None => self.plain_object(object, 0),
15995 }
15996 }
15997
15998 /// `Name: message`, then the trace with its trailing newline removed.
15999 fn error(&mut self, object: &Gc<JsObject>) {
16000 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
16001 self.out.push_str(&name);
16002 if let Some(message) = inherited(object, "message")
16003 && !message.is_empty()
16004 {
16005 self.out.push_str(": ");
16006 self.out.push_str(&message);
16007 }
16008 if let Some(stack) = inherited(object, "stack") {
16009 self.out.push('\n');
16010 self.out.push_str(stack.trim_end_matches('\n'));
16011 }
16012 }
16013
16014 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
16015 let elements = object.array_elements().unwrap_or_default();
16016 self.out.push_str("[ ");
16017 // An interior hole means the array is "sparse": the reference prints those
16018 // as `index: value` pairs and says nothing about the holes themselves, while
16019 // a hole run at the end becomes a single `<N empty items>` note.
16020 let last_present = elements
16021 .iter()
16022 .rposition(|value| !matches!(value, Value::Hole));
16023 let has_interior_hole = match last_present {
16024 Some(last) => elements[..last]
16025 .iter()
16026 .any(|value| matches!(value, Value::Hole)),
16027 None => false,
16028 };
16029 let mut first = true;
16030 if has_interior_hole {
16031 let mut index = 0;
16032 while index < elements.len() {
16033 let value = &elements[index];
16034 if matches!(value, Value::Hole) {
16035 index += 1;
16036 continue;
16037 }
16038 if !first {
16039 self.out.push_str(", ");
16040 }
16041 first = false;
16042 self.out.push_str(&format!("{index}: "));
16043 self.value(value, level + 1);
16044 index += 1;
16045 }
16046 } else {
16047 for (index, value) in elements.iter().enumerate() {
16048 if matches!(value, Value::Hole) {
16049 continue;
16050 }
16051 if !first {
16052 self.out.push_str(", ");
16053 }
16054 first = false;
16055 let _ = index;
16056 self.value(value, level + 1);
16057 }
16058 if let Some(last) = last_present {
16059 let trailing = elements.len() - last - 1;
16060 if trailing > 0 {
16061 if !first {
16062 self.out.push_str(", ");
16063 }
16064 self.out.push_str(&format!(
16065 "<{trailing} empty item{}>",
16066 if trailing > 1 { "s" } else { "" }
16067 ));
16068 }
16069 } else if !elements.is_empty() {
16070 let count = elements.len();
16071 self.out.push_str(&format!(
16072 "<{count} empty item{}>",
16073 if count > 1 { "s" } else { "" }
16074 ));
16075 }
16076 }
16077 self.out.push_str(" ]");
16078 }
16079
16080 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
16081 self.out.push_str("{ ");
16082 let mut first = true;
16083 for key in object.own_keys() {
16084 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
16085 continue;
16086 };
16087 if !property.enumerable {
16088 continue;
16089 }
16090 if !first {
16091 self.out.push_str(", ");
16092 }
16093 first = false;
16094 self.out
16095 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
16096 &key.to_string_lossy(),
16097 )));
16098 self.out.push_str(": ");
16099 // An accessor has no value to dump; the reference names the half that
16100 // exists instead of calling it.
16101 if property.is_accessor() {
16102 let text = match (property.getter.is_some(), property.setter.is_some()) {
16103 (true, true) => "[Getter/Setter]",
16104 (false, true) => "[Setter]",
16105 _ => "[Getter]",
16106 };
16107 self.out.push_str(text);
16108 } else {
16109 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
16110 }
16111 }
16112 self.out.push_str(" }");
16113 }
16114
16115 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
16116 fn print_string(&mut self, text: &str) {
16117 self.out.push('"');
16118 for character in text.chars() {
16119 match character {
16120 '"' => self.out.push_str("\\\""),
16121 '\\' => self.out.push_str("\\\\"),
16122 '\n' => self.out.push_str("\\n"),
16123 '\r' => self.out.push_str("\\r"),
16124 '\t' => self.out.push_str("\\t"),
16125 c if (c as u32) < 0x20 => {
16126 self.out.push_str(&format!("\\u{:04x}", c as u32));
16127 }
16128 c => self.out.push(c),
16129 }
16130 }
16131 self.out.push('"');
16132 }
16133}
16134
16135/// How `print` renders a value.
16136///
16137/// `ToString`, except that negative zero keeps its sign — the reference's host
16138/// printer does that while `String(-0)` is `"0"`.
16139pub fn display(value: &Value) -> String {
16140 match value {
16141 Value::Float(number) => crate::value::number_to_string_for_print(*number),
16142 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
16143 "undefined".to_string()
16144 }
16145 other => other.to_js_string(),
16146 }
16147}
16148
16149// ---------------------------------------------------------------------------
16150// Numeric operators
16151// ---------------------------------------------------------------------------
16152
16153/// `a + b` keeping the `Int` representation when it fits.
16154fn add_numbers(left: Value, right: Value) -> Value {
16155 match (&left, &right) {
16156 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
16157 Some(sum) => Value::Int(sum),
16158 None => Value::Float(*a as f64 + *b as f64),
16159 },
16160 _ => Value::Float(left.to_number() + right.to_number()),
16161 }
16162}
16163
16164/// The arithmetic operators other than `+`, which needs string concatenation.
16165fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16166 use Opcode::*;
16167 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
16168 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
16169 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
16170 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
16171 return Ok(match op {
16172 And => Value::Int(x & y),
16173 Or => Value::Int(x | y),
16174 Xor => Value::Int(x ^ y),
16175 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
16176 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
16177 Shr => match (*x as u32) >> ((*y as u32) & 31) {
16178 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
16179 shifted => Value::Float(shifted as f64),
16180 },
16181 Sub => match x.checked_sub(*y) {
16182 Some(value) => Value::Int(value),
16183 None => Value::Float(*x as f64 - *y as f64),
16184 },
16185 _ => return arithmetic_slow(op, left, right),
16186 });
16187 }
16188 arithmetic_slow(op, left, right)
16189}
16190
16191/// [`arithmetic`] for everything the integer fast path above does not take.
16192fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
16193 use Opcode::*;
16194 let (a, b) = (left.to_number(), right.to_number());
16195 Ok(match op {
16196 Sub => match (&left, &right) {
16197 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
16198 Some(value) => Value::Int(value),
16199 None => Value::Float(a - b),
16200 },
16201 _ => Value::Float(a - b),
16202 },
16203 Mul => Value::Float(a * b),
16204 Div => Value::Float(a / b),
16205 Mod => Value::Float(js_mod(a, b)),
16206 Pow => Value::Float(a.powf(b)),
16207 And => Value::Int(left.to_int32() & right.to_int32()),
16208 Or => Value::Int(left.to_int32() | right.to_int32()),
16209 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
16210 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
16211 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
16212 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
16213 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
16214 // fits the small-integer representation stays an `Int`; the rest become a
16215 // float, which is how the reference keeps `n >>> 0` non-negative.
16216 Shr => {
16217 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
16218 match i32::try_from(shifted) {
16219 Ok(value) => Value::Int(value),
16220 Err(_) => Value::Float(shifted as f64),
16221 }
16222 }
16223 _ => Value::Float(a),
16224 })
16225}
16226
16227/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
16228///
16229/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
16230/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
16231/// slow path where the rules live.
16232fn is_number(value: &Value) -> bool {
16233 matches!(value, Value::Int(_) | Value::Float(_))
16234}
16235
16236/// The `Value::Bool` a comparison operator answers for `ordering`.
16237///
16238/// `None` is the unordered case — a `NaN` on either side — and every operator answers
16239/// false for it, including `<=` and `>=`.
16240fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
16241 use Opcode::*;
16242 let answer = match (op, ordering) {
16243 (_, None) => false,
16244 (Lt, Some(ordering)) => ordering.is_lt(),
16245 (Lte, Some(ordering)) => ordering.is_le(),
16246 (Gt, Some(ordering)) => ordering.is_gt(),
16247 (Gte, Some(ordering)) => ordering.is_ge(),
16248 _ => false,
16249 };
16250 Value::Bool(answer)
16251}
16252
16253/// `%`, which follows the sign of the dividend rather than Rust's.
16254fn js_mod(left: f64, right: f64) -> f64 {
16255 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
16256 return f64::NAN;
16257 }
16258 if right.is_infinite() {
16259 return left;
16260 }
16261 let remainder = left % right;
16262 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
16263 // the spec makes the sign match the dividend.
16264 if remainder == 0.0 {
16265 0.0f64.copysign(left)
16266 } else {
16267 remainder
16268 }
16269}
16270
16271fn negate(value: Value) -> Value {
16272 match value {
16273 Value::Int(0) => Value::Float(-0.0),
16274 Value::Int(i) => Value::Int(-i),
16275 other => Value::Float(-other.to_number()),
16276 }
16277}
16278
16279fn increment(value: Value) -> Value {
16280 match value {
16281 Value::Int(i) => match i.checked_add(1) {
16282 Some(next) => Value::Int(next),
16283 None => Value::Float(i as f64 + 1.0),
16284 },
16285 other => Value::Float(other.to_number() + 1.0),
16286 }
16287}
16288
16289fn decrement(value: Value) -> Value {
16290 match value {
16291 Value::Int(i) => match i.checked_sub(1) {
16292 Some(next) => Value::Int(next),
16293 None => Value::Float(i as f64 - 1.0),
16294 },
16295 other => Value::Float(other.to_number() - 1.0),
16296 }
16297}
16298
16299/// Compare a `BigInt` with an `f64` on their mathematical values.
16300///
16301/// Neither side is rounded to the other's precision: the number is split into its integer
16302/// part (compared as an exact bigint) and its fraction, which is what decides the answer
16303/// when the integer parts are equal. An infinite value is larger than every bigint.
16304fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
16305 use std::cmp::Ordering;
16306 if number.is_nan() {
16307 return None;
16308 }
16309 if number.is_infinite() {
16310 return Some(if number > 0.0 {
16311 Ordering::Less
16312 } else {
16313 Ordering::Greater
16314 });
16315 }
16316 let truncated = number.trunc();
16317 // A number wider than `i128` still has an exact integer part, but no bigint form we can
16318 // build cheaply; the sign of the difference is all that is needed, so compare against
16319 // the bigint's own magnitude instead.
16320 if truncated.abs() >= 1.7e38 {
16321 let big_as_f64 = big.to_f64();
16322 return big_as_f64.partial_cmp(&number);
16323 }
16324 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
16325 match big.cmp(&integer) {
16326 Ordering::Equal => {
16327 // Same integer part: the fraction decides, and a negative number's fraction is
16328 // below the integer (`-1.5` truncates to `-1`).
16329 if number > truncated {
16330 Some(Ordering::Less)
16331 } else if number < truncated {
16332 Some(Ordering::Greater)
16333 } else {
16334 Some(Ordering::Equal)
16335 }
16336 }
16337 other => Some(other),
16338 }
16339}
16340
16341/// `CanonicalNumericIndexString(argument)` (§7.1.21).
16342///
16343/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
16344/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
16345/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
16346/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
16347/// rather than treating it as `0`.
16348fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
16349 let PropertyKey::String(text) = key else {
16350 // A symbol is never an index.
16351 return None;
16352 };
16353 let text = text.to_string_lossy();
16354 if text == "-0" {
16355 return Some(-0.0);
16356 }
16357 let number: f64 = text.parse().ok()?;
16358 // The round-trip test *is* the definition: only the canonical spelling qualifies.
16359 // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
16360 // `"0.10"` does not.
16361 let rendered = Value::Float(number).to_js_string();
16362 (rendered == text).then_some(number)
16363}
16364
16365/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
16366///
16367/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
16368/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
16369/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
16370/// numeric and invalid, which is why they stop the prototype chain instead of falling
16371/// through it.
16372///
16373/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
16374/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
16375/// `in`, `delete` and `defineProperty` separately to make sure it does not.
16376fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
16377 numeric.is_finite()
16378 && numeric.fract() == 0.0
16379 && !(numeric == 0.0 && numeric.is_sign_negative())
16380 && numeric >= 0.0
16381 && object
16382 .typed_array_length()
16383 .is_some_and(|length| (numeric as usize) < length)
16384}
16385
16386/// `ArrayCreate`'s length bound, `2**32 - 1`.
16387///
16388/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
16389/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
16390/// through — can enforce it without depending on a builtin module.
16391const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;