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 /// Module bodies currently running, innermost last.
1321 ///
1322 /// A dynamic `import()` resolves its specifier relative to the module that ran it, and
1323 /// this is the only place that knows which module that is.
1324 pub module_stack: Vec<String>,
1325 /// Rejections that no handler has claimed, with the promise they belong to.
1326 ///
1327 /// A `then` registered later prunes its entry, which is why the promise is kept: the
1328 /// reason alone cannot say whether somebody eventually listened.
1329 unhandled: Vec<(Gc<JsObject>, Value)>,
1330}
1331
1332impl<'a> Interp<'a> {
1333 /// Build an interpreter over `heap`, with a fresh realm.
1334 pub fn new(heap: &'a Heap) -> Interp<'a> {
1335 let object_proto = JsObject::ordinary(heap, None);
1336 let function_proto = JsObject::function(
1337 heap,
1338 Some(object_proto.clone()),
1339 Callable::Native {
1340 func: |_, _, _| Ok(Value::Undefined),
1341 own_instance: false,
1342 },
1343 );
1344 let array_proto = JsObject::array(heap, Some(object_proto.clone()), 0);
1345 let global = JsObject::ordinary(heap, Some(object_proto.clone()));
1346 let mut interp = Interp {
1347 heap,
1348 realm: Realm {
1349 global,
1350 object_proto,
1351 function_proto,
1352 array_proto,
1353 array_constructor: None,
1354 promise_constructor: None,
1355 object_proto_to_string: None,
1356 globals: BTreeMap::new(),
1357 declared: Vec::new(),
1358 lexical_consts: BTreeSet::new(),
1359 errors: BTreeMap::new(),
1360 string_proto: None,
1361 number_proto: None,
1362 boolean_proto: None,
1363 bigint_proto: None,
1364 error_proto: JsObject::ordinary(heap, None),
1365 date_proto: JsObject::ordinary(heap, None),
1366 throw_type_error: None,
1367 generator_proto: JsObject::ordinary(heap, None),
1368 promise_proto: None,
1369 async_generator_proto: None,
1370 async_iterator_proto: None,
1371 symbol_proto: None,
1372 symbol_registry: BTreeMap::new(),
1373 internal_slots: std::cell::RefCell::new(BTreeMap::new()),
1374 regexp_proto: None,
1375 regexp_ctor: None,
1376 suppressed_error_proto: None,
1377 disposable_stack_proto: None,
1378 map_proto: None,
1379 set_proto: None,
1380 finalization_registries: Vec::new(),
1381 array_buffer_proto: None,
1382 typed_array_proto: None,
1383 typed_array_protos: Vec::new(),
1384 data_view_proto: None,
1385 async_disposable_stack_proto: None,
1386 async_from_sync: None,
1387 iterator_proto: None,
1388 iterator_ctor: None,
1389 iterator_helper_proto: None,
1390 iterator_wrap_proto: None,
1391 generator_function_proto: None,
1392 async_function_proto: None,
1393 async_generator_function_proto: None,
1394 iterator_protos: std::collections::BTreeMap::new(),
1395 well_known_symbols: WellKnownSymbols::default(),
1396 host_classes: HostClasses::new(),
1397 },
1398 frames: Vec::new(),
1399 free_values: Vec::new(),
1400 global_cache: {
1401 let mut cache = Vec::new();
1402 cache.resize_with(GLOBAL_CACHE_SLOTS, || None);
1403 cache
1404 },
1405 eval_scope: None,
1406 eval_depth: 0,
1407 eval_bindings: Vec::new(),
1408 eval_arguments: None,
1409 eval_with: None,
1410 active_eval_scope: None,
1411 eval_caller: None,
1412 pending_new_target: None,
1413 active_new_target: Value::Undefined,
1414 eval_new_target: None,
1415 native_frames: Vec::new(),
1416 current_native: None,
1417 output: String::new(),
1418 output_sink: None,
1419 field_cache: {
1420 let mut cache = Vec::new();
1421 cache.resize_with(FIELD_CACHE_SLOTS, || None);
1422 cache
1423 },
1424 oom_reported_at: 0,
1425 interrupt: None,
1426 interrupt_counter: INTERRUPT_POLL_INTERVAL,
1427 uncatchable_next: false,
1428 uncatchable: false,
1429 // `JS_DEFAULT_STACK_SIZE`, which is what `qjs` uses when `--stack-size` is
1430 // absent.
1431 stack_limit: DEFAULT_STACK_SIZE,
1432 max_frames: MAX_FRAMES,
1433 jobs: std::collections::VecDeque::new(),
1434 tasks: Vec::new(),
1435 trace_barriers: Vec::new(),
1436 signal_handlers: std::collections::BTreeMap::new(),
1437 fd_handlers: std::collections::BTreeMap::new(),
1438 next_timer_id: 1,
1439 timer_errors: Vec::new(),
1440 modules: std::collections::BTreeMap::new(),
1441 module_loader: None,
1442 main_module_name: None,
1443 module_stack: Vec::new(),
1444 unhandled: Vec::new(),
1445 };
1446 crate::builtins::install(&mut interp);
1447 interp
1448 }
1449
1450 // -- allocation helpers -------------------------------------------------
1451
1452 /// A new string value.
1453 /// A `BigInt` value from a computed big integer.
1454 pub fn bigint(&self, value: crate::bigint::BigInt) -> Value {
1455 Value::BigInt(Gc::new(self.heap, value))
1456 }
1457
1458 /// A string value from bytes that are already WTF-8, which is how a string with an
1459 /// unpaired surrogate reaches a `Value`.
1460 pub fn string_wtf8(&self, text: crate::value::Wtf8) -> Value {
1461 Value::string_wtf8(self.heap, text)
1462 }
1463
1464 /// A new string value, from text that is valid UTF-8.
1465 pub fn string(&self, text: impl Into<String>) -> Value {
1466 Value::string(self.heap, text)
1467 }
1468
1469 /// A new ordinary object with the given prototype.
1470 pub fn new_object(&self, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1471 JsObject::ordinary(self.heap, proto)
1472 }
1473
1474 // -- host classes -------------------------------------------------------
1475
1476 /// Register a class and get its id: `JS_NewClassID` followed by `JS_NewClass`.
1477 pub fn register_host_class(&mut self, def: ClassDef) -> ClassId {
1478 self.realm.host_classes.register(def)
1479 }
1480
1481 /// Register `def` under an id the host already holds (`JS_NewClass`).
1482 ///
1483 /// Answers `false` for [`ClassId::INVALID`], which the C API reports as a failed
1484 /// `JS_NewClass`.
1485 pub fn define_host_class(&mut self, id: ClassId, def: ClassDef) -> bool {
1486 self.realm.host_classes.define(id, def)
1487 }
1488
1489 /// Install the prototype instances of `id` inherit (`JS_SetClassProto`).
1490 pub fn set_host_class_proto(&mut self, id: ClassId, proto: Gc<JsObject>) {
1491 self.realm.host_classes.set_proto(id, proto);
1492 }
1493
1494 /// The prototype installed for `id`, if any.
1495 pub fn host_class_proto(&self, id: ClassId) -> Option<Gc<JsObject>> {
1496 self.realm.host_classes.proto(id)
1497 }
1498
1499 /// A new instance of `id` (`JS_NewObjectProtoClass`).
1500 ///
1501 /// An explicit `proto` wins — that is what makes `class Point extends Base` hand the
1502 /// subclass's prototype through `new.target.prototype`. With `None` the prototype
1503 /// installed by [`Interp::set_host_class_proto`] is used, and `Object.prototype` if the
1504 /// host installed none.
1505 ///
1506 /// Answers `None` for an id that was never registered: the C API would return an
1507 /// exception, and silently making an ordinary object instead would move the failure to
1508 /// the first `JS_GetOpaque` that no longer matches.
1509 pub fn new_host_object(
1510 &mut self,
1511 proto: Option<Gc<JsObject>>,
1512 class_id: ClassId,
1513 ) -> Option<Gc<JsObject>> {
1514 let class = self.realm.host_classes.def(class_id)?;
1515 let proto = proto
1516 .or_else(|| self.realm.host_classes.proto(class_id))
1517 .or_else(|| Some(self.realm.object_proto.clone()));
1518 Some(JsObject::host_object(self.heap, proto, class_id, class))
1519 }
1520
1521 /// `JS_GetOpaque`: the payload of `value` when it is an instance of `class_id`.
1522 ///
1523 /// `None` covers both answers the C API gives as a null pointer — the value is not an
1524 /// object, it is an object of another class, or the class never got a payload. A host
1525 /// that has to tell them apart uses [`JsObject::host_class_id`].
1526 pub fn host_opaque(&self, value: &Value, class_id: ClassId) -> Option<Opaque> {
1527 let object = value.as_object()?;
1528 if object.host_class_id()? != class_id {
1529 return None;
1530 }
1531 object.host_opaque()
1532 }
1533
1534 /// `JS_SetOpaque`: store `opaque` on `value`, answering whether it worked.
1535 pub fn set_host_opaque(&self, value: &Value, opaque: Opaque) -> bool {
1536 match value.as_object() {
1537 Some(object) => object.set_host_opaque(opaque),
1538 None => false,
1539 }
1540 }
1541
1542 /// A prototype for a built-in iterator, inheriting from `Iterator.prototype`.
1543 ///
1544 /// Every built-in iterator has one — `%ArrayIteratorPrototype%`,
1545 /// `%StringIteratorPrototype%` and so on — and the whole point of the chain is that
1546 /// such an iterator *is* an `Iterator`: `[1,2].values().map(f)` resolves `map` by
1547 /// walking up to `Iterator.prototype`. These used to be plain objects hanging off
1548 /// `Object.prototype`, so `.map` was `undefined` and `Object.prototype.toString`
1549 /// said `[object Object]` instead of `[object Array Iterator]`.
1550 ///
1551 /// The prototype carries `next`, `[Symbol.iterator]` answering `this`, and the
1552 /// `@@toStringTag` that names it. `next` is passed in because each iterator kind has
1553 /// its own.
1554 pub fn new_iterator_prototype(
1555 &mut self,
1556 tag: &str,
1557 next: crate::object::NativeFn,
1558 ) -> Gc<JsObject> {
1559 if let Some(existing) = self.realm.iterator_protos.get(tag) {
1560 return existing.clone();
1561 }
1562 let parent = self.realm.iterator_proto.clone();
1563 let proto = self.new_object(parent);
1564 let next = self.new_native("next", 0, next);
1565 proto.define(
1566 "next",
1567 Property::with_attributes(Value::Object(next), true, false),
1568 );
1569 let key = self.realm.well_known_key(WellKnown::Iterator);
1570 let identity = self.new_native("[Symbol.iterator]", 0, self_iterator);
1571 proto.define_key(
1572 &key,
1573 Property::with_attributes(Value::Object(identity), true, false),
1574 );
1575 let tag_key = self.realm.well_known_key(WellKnown::ToStringTag);
1576 let tag_value = self.string(tag);
1577 // `{ writable: false, enumerable: false, configurable: true }` — `with_attributes`
1578 // cannot express that pair, and `RegExpStringIteratorPrototype/Symbol.toStringTag`
1579 // checks it.
1580 proto.define_key(&tag_key, Property::configurable_only(tag_value));
1581 self.realm
1582 .iterator_protos
1583 .insert(tag.to_string(), proto.clone());
1584 proto
1585 }
1586
1587 /// `[[OwnPropertyKeys]]`, with the `ownKeys` trap when there is one.
1588 ///
1589 /// A trap's list is used **as returned**: unlike an ordinary object, whose integer
1590 /// keys the engine sorts, a proxy is specified to hand back exactly what the handler
1591 /// produced. That is why the two branches are not merged.
1592 pub fn object_own_property_keys(
1593 &mut self,
1594 object: &Gc<JsObject>,
1595 ) -> JsResult<Vec<PropertyKey>> {
1596 if let Some(keys) = self.proxy_own_keys(object)? {
1597 return Ok(keys);
1598 }
1599 // Integer-like keys ascending, then the string keys in insertion order, then the
1600 // symbols — the order every schema that walks an object expects.
1601 let entries = object.property_entries();
1602 let mut numeric: Vec<u32> = Vec::new();
1603 // An integer-indexed exotic object reports its indices as own keys even though they
1604 // live in the buffer rather than in the property table (§10.4.5.9 step 2: the
1605 // canonical numeric indices `0..TypedArrayLength-1` come first and in ascending
1606 // order). The length is asked per call, so a resizable buffer's view reports the
1607 // indices it has *now* — `OwnPropertyKeys/integer-indexes-resizable-array-buffer-*`.
1608 if object.typed_array_parts().is_some() {
1609 for index in 0..object.typed_array_length().unwrap_or(0) {
1610 // `u32::try_from` cannot fail for a real length, but the length is a
1611 // `usize` from a `Vec`: a view over 4 GiB of `Int8Array` is representable
1612 // as an array index and one element beyond is not.
1613 match u32::try_from(index) {
1614 Ok(index) => numeric.push(index),
1615 Err(_) => break,
1616 }
1617 }
1618 }
1619 let mut strings: Vec<PropertyKey> = Vec::new();
1620 let mut symbols: Vec<PropertyKey> = Vec::new();
1621 for (key, _) in entries {
1622 match &key {
1623 // A class-private name is never reported by any enumeration: that is the
1624 // whole mechanism behind `#x`. `Object.getOwnPropertySymbols`,
1625 // `Reflect.ownKeys` and everything built on them (spread, `JSON.stringify`'s
1626 // symbol skip, `Object.assign`) therefore cannot see it.
1627 PropertyKey::Symbol(symbol) if symbol.is_private() => {}
1628 PropertyKey::Symbol(_) => symbols.push(key),
1629 PropertyKey::String(_) => match key.as_str().and_then(array_index) {
1630 Some(index) => {
1631 if !numeric.contains(&index) {
1632 numeric.push(index);
1633 }
1634 }
1635 None => strings.push(key),
1636 },
1637 }
1638 }
1639 // An array's `length` is an own property from the moment the array exists, so it
1640 // sits **before** every string key added afterwards — `arr.a = 1; arr.length` lists
1641 // as `["length", "a"]`, not `["a", "length"]`
1642 // (`getOwnPropertyNames/order-after-define-property`). It is synthesised rather
1643 // than stored in the property table, which is why it has to be placed here.
1644 if object.is_array() && object.proxy_state().is_none() {
1645 // Unconditionally: `Object.defineProperty(arr, "length", …)` files `length` in
1646 // the property table, at whatever position the *define* happened, but the key
1647 // lists it as the array's oldest string property because that is what it is.
1648 if let Some(position) = strings
1649 .iter()
1650 .position(|key| key.as_str() == Some("length"))
1651 {
1652 strings.remove(position);
1653 }
1654 strings.insert(0, PropertyKey::from("length"));
1655 }
1656 numeric.sort_unstable();
1657 let mut keys: Vec<PropertyKey> = numeric
1658 .into_iter()
1659 .map(|index| PropertyKey::from(index.to_string()))
1660 .collect();
1661 keys.extend(strings);
1662 keys.extend(symbols);
1663 Ok(keys)
1664 }
1665
1666 /// The state behind a promise object, or `None` when `object` is not one.
1667 pub fn promise_state(&self, object: &Gc<JsObject>) -> Option<crate::object::PromiseRef> {
1668 object.with(|data| match &data.kind {
1669 ObjectKind::Promise(state) => Some(state.clone()),
1670 _ => None,
1671 })
1672 }
1673
1674 /// A new pending promise.
1675 pub fn new_promise(&mut self) -> Gc<JsObject> {
1676 // `new.target` when there is one, so `new Sub(executor)` answers a `Sub`: this is
1677 // the one place every promise is built, and a subclass that builds its instances
1678 // somewhere else would be invisible to `instanceof`.
1679 let default = self.realm.promise_proto.clone();
1680 // A throwing `new.target.prototype` getter cannot be reported from here — this is
1681 // the raw promise constructor and its result is not `JsResult` — so the rejection is
1682 // swallowed and the intrinsic prototype is used. `new Sub(…)` with a poisonous
1683 // `prototype` getter therefore still gets a working promise; the alternative is a
1684 // panic, and the throwing path is covered by `Promise`'s own argument validation.
1685 let proto = self.ctor_prototype_opt(default).unwrap_or_default();
1686 Self::make_promise_object(self.heap, proto)
1687 }
1688
1689 /// A promise object with an explicit prototype, and nothing else.
1690 ///
1691 /// Separate from [`Interp::new_promise`] for the callers that have to *report* an abrupt
1692 /// `Get(newTarget, "prototype")` — `new Promise(executor)` is specified as
1693 /// `OrdinaryCreateFromConstructor`, so a throwing `prototype` getter on `new.target` is an
1694 /// exception rather than a reason to fall back (`Promise/get-prototype-abrupt`).
1695 pub fn make_promise_object(heap: &js_gc::Heap, proto: Option<Gc<JsObject>>) -> Gc<JsObject> {
1696 let promise = JsObject::ordinary(heap, proto);
1697 promise.with_mut(|data| {
1698 data.kind = ObjectKind::Promise(std::rc::Rc::new(std::cell::RefCell::new(
1699 crate::object::PromiseState::default(),
1700 )));
1701 });
1702 promise
1703 }
1704
1705 /// Fulfil `promise`, unless it has already settled.
1706 ///
1707 /// Settling is one-shot, and a script can see that: `resolve` called twice, or called
1708 /// after `reject`, changes nothing.
1709 pub fn fulfill_promise(&mut self, promise: &Gc<JsObject>, value: Value) {
1710 let Some(state) = self.promise_state(promise) else {
1711 return;
1712 };
1713 let reactions = {
1714 let mut state = state.borrow_mut();
1715 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1716 return;
1717 }
1718 state.status = crate::object::PromiseStatus::Fulfilled(value.clone());
1719 std::mem::take(&mut state.reactions)
1720 };
1721 self.queue_reactions(reactions, value, false);
1722 }
1723
1724 /// Reject `promise`, unless it has already settled.
1725 pub fn reject_promise(&mut self, promise: &Gc<JsObject>, reason: Value) {
1726 let Some(state) = self.promise_state(promise) else {
1727 return;
1728 };
1729 let reactions = {
1730 let mut state = state.borrow_mut();
1731 if !matches!(state.status, crate::object::PromiseStatus::Pending) {
1732 return;
1733 }
1734 state.status = crate::object::PromiseStatus::Rejected(reason.clone());
1735 std::mem::take(&mut state.reactions)
1736 };
1737 // Remember it only when nothing is listening *now*; a `then` registered later
1738 // prunes the entry in `perform_then`.
1739 if reactions.is_empty() {
1740 self.unhandled.push((promise.clone(), reason.clone()));
1741 }
1742 self.queue_reactions(reactions, reason, true);
1743 }
1744
1745 /// Queue one job per reaction.
1746 ///
1747 /// This is what makes `then` asynchronous even on an already-settled promise:
1748 /// `p.then(f); g()` calls `g` first.
1749 fn queue_reactions(
1750 &mut self,
1751 reactions: Vec<crate::object::PromiseReaction>,
1752 argument: Value,
1753 rejected: bool,
1754 ) {
1755 for reaction in reactions {
1756 let handler = if rejected {
1757 reaction.on_rejected.clone()
1758 } else {
1759 reaction.on_fulfilled.clone()
1760 };
1761 self.jobs.push_back(Job::Reaction {
1762 handler,
1763 argument: argument.clone(),
1764 rejected,
1765 promise: reaction.promise,
1766 });
1767 }
1768 }
1769
1770 /// `NewPromiseCapability` as the executor receives it: the promise plus its
1771 /// resolve/reject pair.
1772 ///
1773 /// The pair are callable objects rather than Rust closures, because the script gets
1774 /// them and may stash them for later.
1775 pub fn new_promise_capability(&mut self) -> (Gc<JsObject>, Value, Value) {
1776 let promise = self.new_promise();
1777 // Both handlers are built-ins with an empty name and length 1, in
1778 // `length`-then-`name` order — `reject-function-property-order` reads the order back
1779 // off `Object.getOwnPropertyNames`.
1780 let resolve = self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
1781 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
1782 (promise, Value::Object(resolve), Value::Object(reject))
1783 }
1784
1785 /// §27.2.1.5 `NewPromiseCapability(C)`.
1786 ///
1787 /// The combinator and `Promise.resolve`/`reject` statics are all specified against
1788 /// `this`, not against the intrinsic: `Promise.all.call(Sub, it)` must let `Sub`
1789 /// decide what capability it hands back. That is the whole mechanism behind subclassing
1790 /// `Promise`, and it also means a non-constructor `this` is a `TypeError` rather than a
1791 /// silently ignored argument.
1792 ///
1793 /// The intrinsic `%Promise%` takes the direct path, because `new Promise(executor)` with
1794 /// the engine's own executor is exactly what `new_promise_capability` builds.
1795 pub fn new_promise_capability_for(
1796 &mut self,
1797 constructor: &Value,
1798 ) -> JsResult<(Value, Value, Value)> {
1799 let Some(object) = constructor.as_object().cloned() else {
1800 return Err(self.type_error("promise constructor is not a constructor"));
1801 };
1802 if !object.is_constructor() {
1803 return Err(self.type_error("promise constructor is not a constructor"));
1804 }
1805 if self
1806 .realm
1807 .promise_constructor
1808 .as_ref()
1809 .is_some_and(|intrinsic| intrinsic.ptr_eq(&object))
1810 {
1811 let (promise, resolve, reject) = self.new_promise_capability();
1812 return Ok((Value::Object(promise), resolve, reject));
1813 }
1814 let state = self.new_object(Some(self.realm.object_proto.clone()));
1815 // §27.2.1.5 `NewPromiseCapability`: `CreateBuiltinFunction(executor, 2, "", …)` —
1816 // the executor takes `(resolve, reject)`, so its `length` is 2. It was 1 here,
1817 // which only a *custom* constructor can observe, and none of the combinator tests
1818 // looked until `allKeyed/ctx-ctor-constructed.js` asserted it.
1819 let executor = self.builtin_function(
1820 "",
1821 2,
1822 Callable::CapabilityExecutor {
1823 state: state.clone(),
1824 },
1825 );
1826 let promise = self.construct(
1827 Value::Object(object.clone()),
1828 Value::Object(object),
1829 vec![Value::Object(executor)],
1830 )?;
1831 // The pair is read *after* the constructor returns, so a constructor that never
1832 // called its executor, or called it with non-callables, is the spec's step 11
1833 // `TypeError` — not something the engine can paper over.
1834 let Some(resolve) = state.own_property("resolve").and_then(|p| p.value) else {
1835 return Err(self.type_error("promise executor never ran"));
1836 };
1837 let Some(reject) = state.own_property("reject").and_then(|p| p.value) else {
1838 return Err(self.type_error("promise executor never ran"));
1839 };
1840 for handler in [&resolve, &reject] {
1841 if !matches!(handler, Value::Object(object) if object.is_callable()) {
1842 return Err(self.type_error("promise capability handler is not callable"));
1843 }
1844 }
1845 Ok((promise, resolve, reject))
1846 }
1847
1848 /// §27.2.3.1 `PromiseResolve(C, x)`.
1849 ///
1850 /// `C` is a *constructor*, and the whole point is that `Sub.resolve(x)` answers a `Sub`:
1851 /// an `x` that is already a promise of exactly this constructor is handed back
1852 /// unchanged, and anything else gets a fresh capability from `C`.
1853 pub fn promise_resolve_for(&mut self, constructor: &Value, value: Value) -> JsResult<Value> {
1854 if let Value::Object(object) = &value
1855 && self.promise_state(object).is_some()
1856 {
1857 // `x.constructor === C` means "already the right kind", so no capability is
1858 // built — which is observable through a `resolve` that counts its calls.
1859 let x_constructor = self.get_property(object, "constructor")?;
1860 let same = match (
1861 x_constructor.as_ref().and_then(Value::as_object),
1862 constructor.as_object(),
1863 ) {
1864 (Some(x_constructor), Some(constructor)) => x_constructor.ptr_eq(constructor),
1865 _ => false,
1866 };
1867 if same {
1868 return Ok(value);
1869 }
1870 }
1871 let (promise, resolve, _reject) = self.new_promise_capability_for(constructor)?;
1872 // §27.2.4.6 step 5: `? Call(resolve, undefined, «x»)` — an exception from a
1873 // *user* resolve function propagates (`resolve/capability-invocation-error`), while
1874 // the intrinsic one swallows its own self-resolution error.
1875 self.call_value(resolve, Value::Undefined, vec![value])?;
1876 Ok(promise)
1877 }
1878
1879 /// `std.evalScript(source, { async: true })`: the completion value delivered through a
1880 /// promise, as `{ value: completion }`.
1881 ///
1882 /// The three cases are the reference's, and they differ on purpose:
1883 ///
1884 /// * a **syntax** error throws synchronously — `JS_Eval` reports a parse failure as an
1885 /// exception before any promise exists;
1886 /// * a **runtime** error rejects the returned promise;
1887 /// * success resolves it with `{ value }`, where the value is the script's completion
1888 /// value **literally**. It is not awaited: `std.evalScript("Promise.resolve(7)",
1889 /// {async: true})` answers `{value: <the promise>}`, and only an explicit top-level
1890 /// `await` produces `{value: 7}`. That is the reference's `JS_Eval` with
1891 /// `JS_EVAL_FLAG_ASYNC`, which stores the completion value rather than adopting it.
1892 ///
1893 /// # What this does not do
1894 ///
1895 /// The reference's `JS_EVAL_FLAG_ASYNC` also permits **top-level `await`**: the script
1896 /// is evaluated in an async context, so `await` outside a function is legal. That needs
1897 /// the parser and the suspension machinery to accept a suspended top-level script, and
1898 /// is not implemented — such source is a syntax error here. Everything else about the
1899 /// flag is reproduced.
1900 pub fn eval_in_global_async(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
1901 // The barrier goes up before compiling: a *parse* failure is reported with a trace
1902 // too, and the reference truncates that one at the same place as a runtime failure.
1903 if barrier {
1904 let depth = self.frames.len();
1905 self.trace_barriers.push(depth);
1906 }
1907 // Compiled before the promise exists, so a parse failure propagates as a throw
1908 // instead of being folded into a rejection.
1909 let compiled = match self.compile_global_script(source, EVAL_SCRIPT_FILE, true) {
1910 Ok(compiled) => compiled,
1911 Err(error) => {
1912 if barrier {
1913 self.trace_barriers.pop();
1914 }
1915 return Err(error);
1916 }
1917 };
1918 // An async body answers its own promise, and that promise is what the reference
1919 // hands back — the same object, not a wrapper around it. Its resolution value is
1920 // the `{value}` object the compiled epilogue built.
1921 if compiled.kind.is_async() {
1922 let strict = compiled.strict;
1923 let promise = self.run_eval_script(compiled, strict)?;
1924 if barrier {
1925 self.trace_barriers.pop();
1926 }
1927 return Ok(promise);
1928 }
1929 let (promise, resolve, reject) = self.new_promise_capability();
1930 let strict = compiled.strict;
1931 match self.run_eval_script(compiled, strict) {
1932 Ok(value) => {
1933 // `{ value }` is a plain object, so resolving with it adopts nothing even
1934 // when the completion value is itself a promise.
1935 let wrapped = self.new_object(Some(self.realm.object_proto.clone()));
1936 self.set_property(&wrapped, "value", value)?;
1937 self.call_value(resolve, Value::Undefined, vec![Value::Object(wrapped)])?;
1938 }
1939 Err(Signal::Throw(error)) => {
1940 self.call_value(reject, Value::Undefined, vec![error])?;
1941 }
1942 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
1943 }
1944 if barrier {
1945 self.trace_barriers.pop();
1946 }
1947 Ok(Value::Object(promise))
1948 }
1949
1950 /// A promise that resolves after `delay_ms`, which is `os.sleepAsync`.
1951 ///
1952 /// Built on [`Interp::schedule_timer`] rather than a second queue, so the resolution is
1953 /// ordered against `os.setTimeout` by the same event loop. The resolver is stored in the
1954 /// timer table, where the collector already scans it.
1955 pub fn sleep_async(&mut self, delay_ms: f64) -> JsResult<Value> {
1956 let (promise, resolve, _reject) = self.new_promise_capability();
1957 let resolve = self.new_host_function(
1958 "resolve",
1959 1,
1960 Box::new(
1961 move |interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
1962 let value = args.first().cloned().unwrap_or(Value::Undefined);
1963 interp.call_value(resolve.clone(), Value::Undefined, vec![value])
1964 },
1965 ),
1966 );
1967 // The timer keeps the resolver alive: it is a property of the timer entry, and the
1968 // timer table is part of what the collector walks.
1969 self.schedule_timer(Value::Object(resolve), delay_ms);
1970 Ok(Value::Object(promise))
1971 }
1972
1973 /// `PromiseResolve(value)`: the value itself when it is already a promise, otherwise a
1974 /// new promise resolved with it.
1975 pub fn promise_resolve_value(&mut self, value: Value) -> JsResult<Value> {
1976 if let Value::Object(object) = &value
1977 && self.promise_state(object).is_some()
1978 {
1979 return Ok(value);
1980 }
1981 let promise = self.new_promise();
1982 self.resolve_promise_with(&promise, value)?;
1983 Ok(Value::Object(promise))
1984 }
1985
1986 /// §27.2.4.7 `PromiseResolve(%Promise%, value)`.
1987 ///
1988 /// The difference from [`Interp::promise_resolve_value`] is step 1.a: when `value` is
1989 /// already a promise, its **`constructor` is read**, and only if that is the intrinsic
1990 /// `%Promise%` is `value` returned unchanged. A getter placed on `constructor` is
1991 /// therefore observable — which is exactly what
1992 /// `AsyncGeneratorPrototype/return/return-*-broken-promise*.js` use to check that the
1993 /// `AsyncGeneratorAwaitReturn` path goes through `PromiseResolve` rather than a private
1994 /// shortcut.
1995 pub fn promise_resolve_intrinsic(&mut self, value: Value) -> JsResult<Value> {
1996 if let Value::Object(object) = &value
1997 && self.promise_state(object).is_some()
1998 {
1999 let constructor = self.get_property(object, "constructor")?;
2000 let same = match (&constructor, &self.realm.promise_constructor) {
2001 (Some(Value::Object(found)), Some(intrinsic)) => found.ptr_eq(intrinsic),
2002 _ => false,
2003 };
2004 if same {
2005 return Ok(value);
2006 }
2007 }
2008 let promise = self.new_promise();
2009 self.resolve_promise_with(&promise, value)?;
2010 Ok(Value::Object(promise))
2011 }
2012
2013 /// Claim `[[AlreadyResolved]]` for `promise`: `true` for the first caller, `false` after.
2014 ///
2015 /// The pair of resolving functions a promise hands to its executor shares this record, so
2016 /// whichever runs first wins and the other is a silent no-op. Promise *status* is not a
2017 /// substitute: resolving with a thenable leaves the promise `Pending` for a whole job.
2018 pub fn claim_resolution(&mut self, promise: &Gc<JsObject>) -> bool {
2019 let Some(state) = self.promise_state(promise) else {
2020 return true;
2021 };
2022 let mut state = state.borrow_mut();
2023 if state.resolved {
2024 return false;
2025 }
2026 state.resolved = true;
2027 true
2028 }
2029
2030 /// Clear `[[AlreadyResolved]]`, for the job that hands out a fresh pair.
2031 fn forget_resolution(&mut self, promise: &Gc<JsObject>) {
2032 let Some(state) = self.promise_state(promise) else {
2033 return;
2034 };
2035 state.borrow_mut().resolved = false;
2036 }
2037
2038 /// `ResolvePromise`: fulfil, unless the value is a thenable — then follow it.
2039 pub fn resolve_promise_with(&mut self, promise: &Gc<JsObject>, value: Value) -> JsResult<()> {
2040 // Resolving a promise with itself is a `TypeError`. The check exists because the
2041 // alternative is a chain of self-reactions that never settles.
2042 if let Value::Object(object) = &value
2043 && object.ptr_eq(promise)
2044 {
2045 // The spec rejects *and* throws, so both the promise and the caller see it.
2046 let thrown = self.type_error("cannot resolve a promise with itself");
2047 let Signal::Throw(error) = thrown.clone() else {
2048 unreachable!("type_error always throws")
2049 };
2050 self.reject_promise(promise, error);
2051 return Err(thrown);
2052 }
2053 // §27.2.1.3.1 `NewPromiseResolveThenableJob` step 3: `Get(resolution, "then")` is a
2054 // `Completion`, and an abrupt one **rejects** the promise rather than throwing to
2055 // whoever resolved it — a poisoned `then` getter is the case every
2056 // `*-poisoned-then` test is written against.
2057 let then = match &value {
2058 Value::Object(object) => match self.get_property(object, "then") {
2059 Ok(then) => then,
2060 Err(signal) => {
2061 if let Signal::Throw(reason) = signal {
2062 self.reject_promise(promise, reason);
2063 return Ok(());
2064 }
2065 return Err(signal);
2066 }
2067 },
2068 _ => None,
2069 };
2070 let callable_then = matches!(&then, Some(Value::Object(object)) if object.is_callable());
2071 if !callable_then {
2072 // Not a thenable: a non-callable `then` makes the value fulfil as it is.
2073 self.fulfill_promise(promise, value);
2074 return Ok(());
2075 }
2076 // Adopting a thenable is asynchronous — `then` is called from a job, never from
2077 // inside `resolve`, so a script cannot make a promise settle synchronously.
2078 self.jobs.push_back(Job::Thenable {
2079 then: then.expect("checked callable"),
2080 value,
2081 promise: promise.clone(),
2082 });
2083 Ok(())
2084 }
2085
2086 /// `Invoke(thenable, "then", «onFulfilled, onRejected»)`, for an arbitrary value.
2087 ///
2088 /// `C.resolve` is user code and may answer a plain thenable rather than one of this
2089 /// realm's promises, so the attach cannot assume an `ObjectKind::Promise`.
2090 ///
2091 /// The property read is **not** short-circuitable even for a real promise: the spec says
2092 /// `Invoke`, and `invoke-then-error-close` plants a throwing own `then` on a promise and
2093 /// expects it to run. Skipping the read for promises not only lost the throw, it made
2094 /// the combinator's loop infinite — the test's iterator never sets `done`.
2095 pub fn invoke_then(
2096 &mut self,
2097 thenable: Value,
2098 on_fulfilled: Value,
2099 on_rejected: Value,
2100 ) -> JsResult<()> {
2101 let then = match &thenable {
2102 Value::Object(object) => self.get_property(object, "then")?,
2103 primitive => {
2104 let boxed = self.object_from(primitive)?;
2105 self.get_property(&boxed, "then")?
2106 }
2107 };
2108 let Some(then) = then else {
2109 return Err(self.type_error("thenable has no then method"));
2110 };
2111 if !matches!(&then, Value::Object(object) if object.is_callable()) {
2112 return Err(self.type_error("then is not a function"));
2113 }
2114 self.call_value(then, thenable, vec![on_fulfilled, on_rejected])?;
2115 Ok(())
2116 }
2117
2118 /// `PerformPromiseThen(promise, onFulfilled, onRejected)`.
2119 ///
2120 /// `Promise.prototype.then` in one step: register a reaction and answer the derived
2121 /// promise.
2122 pub fn perform_then(
2123 &mut self,
2124 promise: &Gc<JsObject>,
2125 on_fulfilled: Option<Value>,
2126 on_rejected: Option<Value>,
2127 ) -> JsResult<Value> {
2128 let Some(state) = self.promise_state(promise) else {
2129 return Err(self.type_error("not a promise"));
2130 };
2131 // Whether a rejection handler is being attached decides whether a recorded
2132 // rejection stops being unhandled, so it is read before the values are moved.
2133 let has_rejection_handler = on_rejected.is_some();
2134 let derived = self.new_promise();
2135 let reaction = crate::object::PromiseReaction {
2136 on_fulfilled,
2137 on_rejected,
2138 promise: derived.clone(),
2139 };
2140 let settled = {
2141 let mut state = state.borrow_mut();
2142 // A rejection somebody reacts to is no longer unhandled.
2143 state.handled = true;
2144 match &state.status {
2145 crate::object::PromiseStatus::Pending => {
2146 state.reactions.push(reaction.clone());
2147 None
2148 }
2149 crate::object::PromiseStatus::Fulfilled(value) => Some((value.clone(), false)),
2150 crate::object::PromiseStatus::Rejected(reason) => Some((reason.clone(), true)),
2151 }
2152 };
2153 // A `catch`/`then` attached to an already-rejected promise, or to one that rejects
2154 // later, means somebody is listening after all.
2155 if has_rejection_handler {
2156 self.unhandled.retain(|(owner, _)| !owner.ptr_eq(promise));
2157 }
2158 if let Some((argument, rejected)) = settled {
2159 let handler = if rejected {
2160 reaction.on_rejected
2161 } else {
2162 reaction.on_fulfilled
2163 };
2164 self.jobs.push_back(Job::Reaction {
2165 handler,
2166 argument,
2167 rejected,
2168 promise: reaction.promise,
2169 });
2170 }
2171 Ok(Value::Object(derived))
2172 }
2173
2174 /// The rejections nobody listened to, formatted the way the reference reports them.
2175 ///
2176 /// Each line is `Possibly unhandled promise rejection: <value>` followed by the stack
2177 /// when there is one. The adjective is the reference's: a rejection is only *possibly*
2178 /// unhandled at the point the queue drains, because a `then` may still be attached
2179 /// before the host acts on it.
2180 pub fn take_unhandled_rejections(&mut self) -> Vec<String> {
2181 let entries = std::mem::take(&mut self.unhandled);
2182 // Somebody may have attached a handler after the rejection was recorded, so the
2183 // promise is the authority rather than the list.
2184 let still_unhandled: Vec<Value> = entries
2185 .into_iter()
2186 .filter_map(|(promise, reason)| {
2187 let handled = self
2188 .promise_state(&promise)
2189 .map(|state| state.borrow().handled)
2190 .unwrap_or(true);
2191 (!handled).then_some(reason)
2192 })
2193 .collect();
2194 still_unhandled
2195 .into_iter()
2196 .map(|reason| {
2197 let text = self.describe_exception(&reason);
2198 let stack = match &reason {
2199 Value::Object(object) => self
2200 .get_property(object, "stack")
2201 .ok()
2202 .flatten()
2203 .map(|value| value.to_js_string())
2204 // `stack` carries a trailing newline of its own, which would leave
2205 // a blank line between two reported rejections.
2206 .map(|text| text.trim_end().to_string())
2207 .unwrap_or_default(),
2208 _ => String::new(),
2209 };
2210 if stack.is_empty() {
2211 format!("Possibly unhandled promise rejection: {text}")
2212 } else {
2213 format!("Possibly unhandled promise rejection: {text}\n{stack}")
2214 }
2215 })
2216 .collect()
2217 }
2218
2219 /// Run the microtask queue to exhaustion.
2220 ///
2221 /// Jobs queued while draining run in the same drain, FIFO, which is what makes
2222 /// `Promise.resolve().then(f).then(g)` call `f` before `g`.
2223 /// Parse `text` in the extended dialect that `std.parseExtJSON` exposes.
2224 ///
2225 /// Comments, unquoted keys, single quotes, trailing commas, `+` and `.1` numbers,
2226 /// `Infinity`/`NaN`, and `0x`/`0o`/`0b` literals — the same relaxations the reference
2227 /// gates behind `JS_PARSE_JSON_EXT`. `JSON.parse` does not see any of them.
2228 pub fn parse_ext_json(&mut self, text: &str) -> JsResult<Value> {
2229 crate::builtins::json::parse_text(self, text, true)
2230 }
2231
2232 /// Schedule `callback` to run after `delay_ms` milliseconds, returning its id.
2233 ///
2234 /// A negative or `NaN` delay runs as soon as possible rather than being rejected: the
2235 /// reference passes the delay through `JS_ToInt64`, so `setTimeout(f, NaN)` schedules
2236 /// immediately, and `setTimeout(f, -1)` is ordinary code.
2237 ///
2238 /// The callback is called with **no arguments**. The reference stores only the function
2239 /// (`th->func = JS_DupValue(ctx, func)`) and calls it bare, so the `setTimeout(f, 0, a,
2240 /// b)` passthrough that browsers offer does not exist here — verified against `qjs`:
2241 /// extra arguments arrive as `undefined`.
2242 pub fn schedule_timer(&mut self, callback: Value, delay_ms: f64) -> i32 {
2243 let id = self.next_timer_id;
2244 // Wrap rather than grow: the id reaches the script as an `Int32`.
2245 self.next_timer_id = if self.next_timer_id == i32::MAX {
2246 1
2247 } else {
2248 self.next_timer_id + 1
2249 };
2250 let due_at = std::time::Instant::now() + clamp_delay(delay_ms);
2251 self.tasks.push(Task::Timer {
2252 id,
2253 callback,
2254 due_at,
2255 });
2256 id
2257 }
2258
2259 /// Cancel a pending timer. `false` when the id is unknown or already fired, which is
2260 /// not an error — `clearTimeout` on a stale id is a no-op in the reference too.
2261 pub fn cancel_timer(&mut self, id: i32) -> bool {
2262 let before = self.tasks.len();
2263 self.tasks.retain(|task| match task {
2264 Task::Timer { id: task_id, .. } => *task_id != id,
2265 });
2266 self.tasks.len() != before
2267 }
2268
2269 /// How long until the earliest pending timer, or `None` when none is pending.
2270 pub fn next_timeout(&self) -> Option<std::time::Duration> {
2271 let now = std::time::Instant::now();
2272 self.tasks
2273 .iter()
2274 .map(|task| match task {
2275 Task::Timer { due_at, .. } => due_at.saturating_duration_since(now),
2276 })
2277 .min()
2278 }
2279
2280 /// Run one turn of the event loop.
2281 ///
2282 /// Structurally this is `js_std_loop`'s body minus the blocking: drain microtasks, then
2283 /// run at most one due timer, then drain again. The blocking belongs to the caller
2284 /// because `quickjs-pure` has no dependencies and no platform knowledge — [`Turn::Wait`]
2285 /// is how it asks.
2286 ///
2287 /// One timer per turn rather than all of them: a timer callback may schedule another
2288 /// timer, and running the whole batch would let a self-rescheduling `setTimeout(f, 0)`
2289 /// starve the microtask queue.
2290 pub fn run_one_turn(&mut self) -> JsResult<Turn> {
2291 self.drain_jobs()?;
2292 let now = std::time::Instant::now();
2293 // Earliest due first: timers are not ordered by insertion, and `setTimeout(f, 100)`
2294 // followed by `setTimeout(g, 1)` must run `g` first.
2295 let due = self
2296 .tasks
2297 .iter()
2298 .enumerate()
2299 .filter(|(_, task)| match task {
2300 Task::Timer { due_at, .. } => *due_at <= now,
2301 })
2302 .min_by_key(|(_, task)| match task {
2303 Task::Timer { due_at, .. } => *due_at,
2304 })
2305 .map(|(index, _)| index);
2306 let Some(index) = due else {
2307 // The reference caps its wait at `min_delay = 10000` (ten seconds) when a
2308 // descriptor is registered but no timer is closer, so a script that never
2309 // touches the descriptor still gets control back. Without a cap a handler on a
2310 // descriptor that is never ready would block for as long as the host allows.
2311 let timeout = self
2312 .next_timeout()
2313 .unwrap_or(std::time::Duration::from_secs(10))
2314 .min(std::time::Duration::from_secs(10));
2315 if !self.fd_handlers.is_empty() {
2316 // Blocking on a timer while descriptors are registered would starve them,
2317 // and blocking on the descriptors while a timer is due would delay it; the
2318 // host polls with the earlier of the two deadlines, which this timeout is.
2319 return Ok(Turn::Poll(timeout));
2320 }
2321 return Ok(match self.next_timeout() {
2322 Some(wait) => Turn::Wait(wait),
2323 None => Turn::Done,
2324 });
2325 };
2326 let Task::Timer { callback, .. } = self.tasks.remove(index);
2327 let this = Value::Undefined;
2328 // A throwing timer callback must not stop the loop: the reference reports it and
2329 // keeps going, because the alternative is that one bad timer silently stops every
2330 // later one.
2331 // No arguments: see `schedule_timer` — the reference calls the callback bare.
2332 match self.call_value(callback, this, Vec::new()) {
2333 Ok(_) => {}
2334 Err(Signal::Throw(value)) => {
2335 let text = self.describe_exception(&value);
2336 self.timer_errors.push(text);
2337 }
2338 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2339 }
2340 self.drain_jobs()?;
2341 Ok(Turn::Ran)
2342 }
2343
2344 /// Register or clear one direction of an `os.setReadHandler`/`os.setWriteHandler` pair.
2345 ///
2346 /// `callback` of `None` unregisters that direction, and an entry with neither direction
2347 /// left is removed — the reference does the same, so a script can rely on
2348 /// `os.setReadHandler(fd, null)` stopping the loop from waiting on that descriptor.
2349 pub fn set_fd_handler(&mut self, fd: i32, readable: bool, callback: Option<Value>) {
2350 let entry = self.fd_handlers.entry(fd).or_default();
2351 if readable {
2352 entry.read = callback;
2353 } else {
2354 entry.write = callback;
2355 }
2356 if entry.read.is_none() && entry.write.is_none() {
2357 self.fd_handlers.remove(&fd);
2358 }
2359 }
2360
2361 /// Register or clear an `os.signal` handler.
2362 ///
2363 /// `None` removes it; the host separately restores the default disposition or sets
2364 /// ignore, because which of those happened is the script's choice (`null` versus
2365 /// `undefined`) and not something this table can express.
2366 pub fn set_signal_handler(&mut self, signal: i32, handler: Option<Value>) {
2367 match handler {
2368 Some(handler) => {
2369 self.signal_handlers.insert(signal, handler);
2370 }
2371 None => {
2372 self.signal_handlers.remove(&signal);
2373 }
2374 }
2375 }
2376
2377 /// Run the handler for `signal`, reporting whether one ran.
2378 ///
2379 /// A throwing handler is reported and the loop continues, like a timer's.
2380 pub fn fire_signal(&mut self, signal: i32) -> JsResult<bool> {
2381 let Some(handler) = self.signal_handlers.get(&signal).cloned() else {
2382 return Ok(false);
2383 };
2384 match self.call_value(handler, Value::Undefined, Vec::new()) {
2385 Ok(_) => {}
2386 Err(Signal::Throw(value)) => {
2387 let text = self.describe_exception(&value);
2388 self.timer_errors.push(text);
2389 }
2390 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2391 }
2392 self.drain_jobs()?;
2393 Ok(true)
2394 }
2395
2396 /// The descriptors the host has to poll, and in which direction.
2397 ///
2398 /// Empty means the loop has nothing to wait for on any descriptor. The host turns each
2399 /// entry into a `pollfd` with `POLLIN`/`POLLOUT` — the same events the reference's
2400 /// `os_poll` asks for.
2401 pub fn pending_fds(&self) -> Vec<FdInterest> {
2402 self.fd_handlers
2403 .iter()
2404 .map(|(fd, entry)| FdInterest {
2405 fd: *fd,
2406 read: entry.read.is_some(),
2407 write: entry.write.is_some(),
2408 })
2409 .collect()
2410 }
2411
2412 /// Call the handler registered for `fd`, reporting whether one ran.
2413 ///
2414 /// `readable`/`writable` come from `poll(2)`. The reference calls **one** handler per
2415 /// poll iteration and then restarts the loop, because the handler may have changed the
2416 /// registration list underneath it; doing the same here keeps a handler that
2417 /// unregisters itself from being called with stale state.
2418 ///
2419 /// A throwing handler is reported and the loop continues — a bad handler must not stop
2420 /// every later one, exactly as with timers.
2421 pub fn fire_fd(&mut self, fd: i32, readable: bool, writable: bool) -> JsResult<bool> {
2422 let Some(entry) = self.fd_handlers.get(&fd) else {
2423 return Ok(false);
2424 };
2425 let callback = if readable {
2426 entry.read.clone()
2427 } else if writable {
2428 entry.write.clone()
2429 } else {
2430 None
2431 };
2432 let Some(callback) = callback else {
2433 return Ok(false);
2434 };
2435 self.drain_jobs()?;
2436 match self.call_value(callback, Value::Undefined, Vec::new()) {
2437 Ok(_) => {}
2438 Err(Signal::Throw(value)) => {
2439 let text = self.describe_exception(&value);
2440 self.timer_errors.push(text);
2441 }
2442 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
2443 }
2444 self.drain_jobs()?;
2445 Ok(true)
2446 }
2447
2448 /// Take the errors timer callbacks threw, leaving the list empty.
2449 pub fn take_timer_errors(&mut self) -> Vec<String> {
2450 std::mem::take(&mut self.timer_errors)
2451 }
2452
2453 /// Whether anything is still pending: a microtask or a timer.
2454 pub fn has_pending_work(&self) -> bool {
2455 !self.jobs.is_empty() || !self.tasks.is_empty() || !self.fd_handlers.is_empty()
2456 }
2457
2458 /// Whether a timer or a microtask is pending, ignoring descriptor handlers.
2459 pub fn has_pending_timers_or_jobs(&self) -> bool {
2460 !self.jobs.is_empty() || !self.tasks.is_empty()
2461 }
2462
2463 /// Run every queued microtask, including ones queued while draining.
2464 pub fn drain_jobs(&mut self) -> JsResult<()> {
2465 // A self-perpetuating chain (`function f(){ Promise.resolve().then(f) } f()`)
2466 // would spin forever, so the drain is bounded the way the call stack is.
2467 let mut budget = 1_000_000usize;
2468 while let Some(job) = self.jobs.pop_front() {
2469 if budget == 0 {
2470 return Err(Signal::Throw(
2471 self.make_error("InternalError", "promise job queue did not drain"),
2472 ));
2473 }
2474 budget -= 1;
2475 self.run_job(job)?;
2476 // `FinalizationRegistry` at the job boundary: this is the safe point where the
2477 // engine may run script that the script itself did not ask for. Doing it here
2478 // rather than from a drop hook is what keeps the callback out of arbitrary
2479 // engine bookkeeping — see `builtins::weak`'s header.
2480 crate::builtins::weak::drain_finalizers(self)?;
2481 }
2482 // A script that queued no jobs may still have dropped targets, so the checkpoint
2483 // runs once more after the queue empties.
2484 crate::builtins::weak::drain_finalizers(self)?;
2485 Ok(())
2486 }
2487
2488 /// Every live `FinalizationRegistry`, as `(handle, state)` pairs.
2489 ///
2490 /// The registry list is weak, so a registry the script dropped answers `upgrade` with
2491 /// `None` and is swept out here. This is also where the realm learns that a registry
2492 /// died, which is why it is a mutation rather than a read.
2493 pub fn live_registries(&mut self) -> Vec<(Gc<JsObject>, crate::object::FinalizationState)> {
2494 let handles = std::mem::take(&mut self.realm.finalization_registries);
2495 let mut live = Vec::with_capacity(handles.len());
2496 for handle in handles {
2497 let Some(object) = handle.upgrade() else {
2498 continue;
2499 };
2500 let Some(state) = object.finalization_state() else {
2501 continue;
2502 };
2503 live.push((object.clone(), *state));
2504 self.realm.finalization_registries.push(object.downgrade());
2505 }
2506 live
2507 }
2508
2509 /// Run one microtask.
2510 fn run_job(&mut self, job: Job) -> JsResult<()> {
2511 match job {
2512 Job::Reaction {
2513 handler: None,
2514 argument,
2515 rejected,
2516 promise,
2517 } => {
2518 // No handler: the settlement passes straight through to the derived
2519 // promise, which is why `p.catch(f)` ignores fulfilments.
2520 if rejected {
2521 self.reject_promise(&promise, argument);
2522 } else {
2523 self.fulfill_promise(&promise, argument);
2524 }
2525 Ok(())
2526 }
2527 Job::Reaction {
2528 handler: Some(handler),
2529 argument,
2530 promise,
2531 ..
2532 } => match self.call_value(handler, Value::Undefined, vec![argument]) {
2533 Ok(answer) => {
2534 if let Err(Signal::Throw(error)) = self.resolve_promise_with(&promise, answer) {
2535 self.reject_promise(&promise, error);
2536 }
2537 Ok(())
2538 }
2539 Err(Signal::Throw(reason)) => {
2540 self.reject_promise(&promise, reason);
2541 Ok(())
2542 }
2543 Err(other) => Err(other),
2544 },
2545 Job::Thenable {
2546 then,
2547 value,
2548 promise,
2549 } => {
2550 // §27.2.2.2: call the thenable's `then` with this promise's own pair, so
2551 // the value it produces settles `promise`.
2552 // The thenable's `then` gets this promise's own pair, so whatever it
2553 // produces settles `promise`.
2554 // `length: 1`, `name: ""` — a resolve/reject function is a
2555 // `%Promise.prototype.then%`-style pair, not a bare native. Building them
2556 // with `JsObject::function` left `length` at 0, which a test reads straight
2557 // off the function (`finally/resolved-observable-then-calls-argument`
2558 // requires `resolve.length === 1` for the pair handed to a thenable).
2559 let resolve =
2560 self.builtin_function("", 1, Callable::PromiseResolve(promise.clone()));
2561 let reject = self.builtin_function("", 1, Callable::PromiseReject(promise.clone()));
2562 // §27.2.2.2 step 1: the job builds a **fresh** pair of resolving functions,
2563 // so the one-shot record starts over. Without the reset the pair above was
2564 // already spent by the `resolve` that queued this job, and a thenable that
2565 // calls `reject` left the promise pending forever
2566 // (`Promise/all/reject-immed`).
2567 self.forget_resolution(&promise);
2568 let reject = Value::Object(reject);
2569 match self.call_value(then, value, vec![Value::Object(resolve), reject.clone()]) {
2570 Ok(_) => Ok(()),
2571 // Step 3.a is `Call(resolvingFunctions.[[Reject]], …)` — **through** the
2572 // reject function, whose one-shot record makes this a no-op once `then`
2573 // has already resolved the promise
2574 // (`exception-after-resolve-in-thenable-job`).
2575 Err(Signal::Throw(reason)) => {
2576 self.call_value(reject, Value::Undefined, vec![reason])?;
2577 Ok(())
2578 }
2579 Err(other) => Err(other),
2580 }
2581 }
2582 Job::Resume {
2583 coroutine,
2584 promise,
2585 kind,
2586 value,
2587 } => self.drive_async(&coroutine, &promise, kind, value),
2588 Job::GeneratorResume {
2589 generator,
2590 promise,
2591 kind,
2592 value,
2593 } => self.step_async_generator(&generator, &promise, kind, value),
2594 Job::Import {
2595 specifier,
2596 referrer,
2597 promise,
2598 } => {
2599 self.run_dynamic_import(&specifier, &referrer, &promise);
2600 Ok(())
2601 }
2602 }
2603 }
2604
2605 /// One element of a `Promise` combinator settled.
2606 ///
2607 /// The shared state object holds the result array, the number still outstanding, and
2608 /// the combinator's own `resolve`/`reject` **functions** — functions, not a promise:
2609 /// with a user constructor (`Promise.all.call(Sub, …)`) there is no `ObjectKind::Promise`
2610 /// to settle, only whatever `Sub` said a capability is.
2611 ///
2612 /// The `settled` flag replaces the one-shot rule a real promise gave for free: `race`
2613 /// and `any` must ignore every later settlement, and `all` must not report a second
2614 /// rejection after the first.
2615 fn settle_combinator(
2616 &mut self,
2617 state: &Gc<JsObject>,
2618 index: usize,
2619 fulfilled: bool,
2620 value: Value,
2621 ) -> JsResult<()> {
2622 let field = |name: &str| state.own_property(name).and_then(|property| property.value);
2623 // Each element settles at most once: a thenable may call `onFulfilled` twice
2624 // synchronously, and §27.2.4.1.1's `alreadyCalled` record is what makes the second
2625 // call a no-op. Without it the second call decremented `remaining` again and settled
2626 // `all` with a short values array (`call-resolve-element-items`).
2627 let done = field("done");
2628 let kind = field("kind").map(|value| value.to_int32()).unwrap_or(0);
2629 let settled = field("settled").is_some_and(|value| value.to_boolean());
2630 if settled {
2631 return Ok(());
2632 }
2633 if let Some(Value::Object(done)) = &done {
2634 if done
2635 .array_get(index)
2636 .is_some_and(|value| value.to_boolean())
2637 {
2638 return Ok(());
2639 }
2640 done.array_set(self.heap, index, Value::Bool(true));
2641 }
2642 let resolve = field("resolve");
2643 let reject = field("reject");
2644 let keys = field("keys");
2645 let results = field("results").and_then(|value| value.as_object().cloned());
2646 // `Call(capability.[[Resolve]], undefined, «v»)` — `this` is `undefined`, not the
2647 // promise: the handler is a plain function the constructor chose.
2648 let settle_with = |interp: &mut Self, handler: Option<Value>, value: Value| {
2649 if let Some(handler) = handler {
2650 interp.call_value(handler, Value::Undefined, vec![value])?;
2651 }
2652 Ok(())
2653 };
2654 match kind {
2655 // `race`: the first settlement wins and stops the rest.
2656 3 => {
2657 state.define_data("settled", Value::Bool(true));
2658 let handler = if fulfilled { resolve } else { reject };
2659 settle_with(self, handler, value)?;
2660 return Ok(());
2661 }
2662 // `all`, and `allKeyed` whose rejection handler *is* the capability's reject:
2663 // the first rejection wins outright.
2664 0 | 4 if !fulfilled => {
2665 state.define_data("settled", Value::Bool(true));
2666 settle_with(self, reject, value)?;
2667 return Ok(());
2668 }
2669 // `any`: the first fulfilment wins.
2670 2 if fulfilled => {
2671 state.define_data("settled", Value::Bool(true));
2672 settle_with(self, resolve, value)?;
2673 return Ok(());
2674 }
2675 _ => {}
2676 }
2677 let Some(results) = &results else {
2678 return Ok(());
2679 };
2680 match kind {
2681 4 => {
2682 results.array_set(self.heap, index, value);
2683 }
2684 0 => {
2685 results.array_set(self.heap, index, value);
2686 }
2687 // `allSettled` (and its keyed twin) never rejects; each slot records what
2688 // happened.
2689 1 | 5 => {
2690 let record = self.new_object(Some(self.realm.object_proto.clone()));
2691 if fulfilled {
2692 record.define_data("status", self.string("fulfilled"));
2693 record.define_data("value", value);
2694 } else {
2695 record.define_data("status", self.string("rejected"));
2696 record.define_data("reason", value);
2697 }
2698 results.array_set(self.heap, index, Value::Object(record));
2699 }
2700 // `any`: a rejection is parked in the errors array and the sweep continues.
2701 2 => {
2702 results.array_set(self.heap, index, value);
2703 }
2704 _ => {}
2705 }
2706 let remaining = field("remaining")
2707 .map(|value| value.to_int32())
2708 .unwrap_or(0);
2709 let left = remaining - 1;
2710 state.define_data("remaining", Value::Int(left));
2711 if left != 0 {
2712 return Ok(());
2713 }
2714 state.define_data("settled", Value::Bool(true));
2715 match kind {
2716 0 | 1 => settle_with(self, resolve, Value::Object(results.clone()))?,
2717 // The keyed result: an ordinary object with a **null** prototype, holding the
2718 // collected entries in input order (`CreateKeyedPromiseCombinatorResultObject`).
2719 4 | 5 => {
2720 let keyed = self.keyed_result_object(keys.as_ref(), results)?;
2721 settle_with(self, resolve, keyed)?;
2722 }
2723 2 => {
2724 // The rejection is an `AggregateError` whose `errors` is the results array
2725 // itself — the slots are the reasons, in input order.
2726 let errors = results.array_elements().unwrap_or_default();
2727 let error = self.aggregate_error(errors, "all promises were rejected");
2728 settle_with(self, reject, error)?;
2729 }
2730 _ => {}
2731 }
2732 Ok(())
2733 }
2734
2735 /// `CreateKeyedPromiseCombinatorResultObject(keys, values)`.
2736 ///
2737 /// A `null` prototype, and every entry created with `CreateDataPropertyOrThrow`
2738 /// (`{ [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }`). The null
2739 /// prototype is load-bearing in both directions: a key called `toString` must not
2740 /// collide with a method, and `result.hasOwnProperty` must be `undefined`
2741 /// (`resolves-empty-object.js`).
2742 pub(crate) fn keyed_result_object(
2743 &mut self,
2744 keys: Option<&Value>,
2745 values: &Gc<JsObject>,
2746 ) -> JsResult<Value> {
2747 let Some(keys) = keys.and_then(|value| value.as_object().cloned()) else {
2748 return Ok(Value::Object(self.new_object(None)));
2749 };
2750 let result = self.new_object(None);
2751 let count = values.array_length().unwrap_or(0);
2752 for index in 0..count {
2753 let Some(key) = keys.array_get(index) else {
2754 continue;
2755 };
2756 let Some(value) = values.array_get(index) else {
2757 continue;
2758 };
2759 let property = Property::with_attributes(value, true, true);
2760 match &key {
2761 Value::Symbol(symbol) => {
2762 result.define_key(&PropertyKey::Symbol(symbol.clone()), property);
2763 }
2764 other => {
2765 let text = self.to_js_string(other)?;
2766 result.define_key(&PropertyKey::from(text.as_str()), property);
2767 }
2768 }
2769 }
2770 Ok(Value::Object(result))
2771 }
2772
2773 /// Build an async function's result: a promise whose body runs as a coroutine.
2774 pub fn new_async_function(
2775 &mut self,
2776 function: Value,
2777 this: Value,
2778 args: Vec<Value>,
2779 ) -> JsResult<Value> {
2780 let promise = self.new_promise();
2781 let coroutine = self.new_coroutine(function, this, args)?;
2782 if let Err(Signal::Throw(reason)) =
2783 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2784 {
2785 self.reject_promise(&promise, reason);
2786 }
2787 Ok(Value::Object(promise))
2788 }
2789
2790 /// The coroutine an async body runs in.
2791 ///
2792 /// Generator-shaped and never exposed to the script: what makes `await` work is the
2793 /// same frame-detach-and-resume the generator protocol uses, so this reuses it rather
2794 /// than growing a second state machine. The difference is only in the ending — a
2795 /// `return` fulfils the caller's promise here instead of producing `{value, done}`.
2796 /// Run `code` as an async function body, answering the promise it settles.
2797 ///
2798 /// Used for a module with top-level `await`: its body is an async function whose
2799 /// caller is the host, so there is no function object to pass through
2800 /// [`Interp::new_async_function`].
2801 pub fn run_async_body(
2802 &mut self,
2803 code: Gc<CompiledCode>,
2804 env: Gc<ClosureEnv>,
2805 this: Value,
2806 ) -> JsResult<Value> {
2807 let promise = self.new_promise();
2808 let coroutine = self.new_coroutine_from(code, env, this, Vec::new())?;
2809 if let Err(Signal::Throw(reason)) =
2810 self.drive_async(&coroutine, &promise, ResumeKind::Start, Value::Undefined)
2811 {
2812 self.reject_promise(&promise, reason);
2813 }
2814 Ok(Value::Object(promise))
2815 }
2816
2817 fn new_coroutine(
2818 &mut self,
2819 function: Value,
2820 this: Value,
2821 args: Vec<Value>,
2822 ) -> JsResult<Gc<JsObject>> {
2823 let Some(object) = function.as_object().cloned() else {
2824 return Err(self.type_error("not a function"));
2825 };
2826 let Some((code, env)) = bytecode_of(&object) else {
2827 return Err(self.type_error("not a function"));
2828 };
2829 self.new_coroutine_from(code, env, this, args)
2830 }
2831
2832 /// Build a coroutine over an already-resolved body.
2833 fn new_coroutine_from(
2834 &mut self,
2835 code: Gc<CompiledCode>,
2836 env: Gc<ClosureEnv>,
2837 this: Value,
2838 args: Vec<Value>,
2839 ) -> JsResult<Gc<JsObject>> {
2840 let function = Value::Undefined;
2841 self.push_frame(code, env, this, args, function)?;
2842 let frame = self.frames.pop().expect("push_frame just pushed it");
2843 let state = GeneratorState {
2844 frame: Some(frame),
2845 phase: GeneratorPhase::SuspendedStart,
2846 parked_on_await: false,
2847 parked_on_yield_star: false,
2848 requests: std::collections::VecDeque::new(),
2849 async_busy: false,
2850 // An `async function` body is driven by `drive_async`, never by the generator
2851 // protocol, and the object is not reachable from script.
2852 is_async: false,
2853 };
2854 let coroutine = self.new_object(Some(self.realm.generator_proto.clone()));
2855 coroutine.with_mut(|data| {
2856 data.kind = ObjectKind::Generator(Box::new(state));
2857 });
2858 Ok(coroutine)
2859 }
2860
2861 /// Step a coroutine: `(value, done)`, where `done == false` means it parked on an
2862 /// `await` and `value` is what it awaited.
2863 fn resume_coroutine(
2864 &mut self,
2865 coroutine: &Gc<JsObject>,
2866 kind: ResumeKind,
2867 value: Value,
2868 ) -> JsResult<(Value, bool)> {
2869 let Some(mut state) = coroutine.with_mut(|data| match &mut data.kind {
2870 ObjectKind::Generator(state) => {
2871 let is_async = state.is_async;
2872 Some(std::mem::replace(
2873 state.as_mut(),
2874 GeneratorState {
2875 frame: None,
2876 phase: GeneratorPhase::Executing,
2877 parked_on_await: false,
2878 parked_on_yield_star: false,
2879 requests: std::collections::VecDeque::new(),
2880 async_busy: false,
2881 is_async,
2882 },
2883 ))
2884 }
2885 _ => None,
2886 }) else {
2887 return Err(self.type_error("not a coroutine"));
2888 };
2889 let result = self.step_generator(&mut state, kind, value);
2890 coroutine.with_mut(|data| {
2891 data.kind = ObjectKind::Generator(Box::new(state));
2892 });
2893 let (value, done, _ready, _reason) = result?;
2894 Ok((value, done))
2895 }
2896
2897 /// Advance an async body and settle its promise with the outcome.
2898 fn drive_async(
2899 &mut self,
2900 coroutine: &Gc<JsObject>,
2901 promise: &Gc<JsObject>,
2902 kind: ResumeKind,
2903 value: Value,
2904 ) -> JsResult<()> {
2905 match self.resume_coroutine(coroutine, kind, value) {
2906 Ok((value, true)) => {
2907 // `Ok` with `done` means the body finished *normally*, even when it was
2908 // resumed by a `throw` — `try { await p } catch {}` completes by
2909 // returning. Only the `Err` arm below is a rejection.
2910 //
2911 // Resolving rather than fulfilling matters: `return promise` in an async
2912 // body adopts the inner promise, so `async function f(){ return
2913 // Promise.resolve(1) }` answers a promise *of 1*, not a promise of a
2914 // promise.
2915 if let Err(Signal::Throw(reason)) = self.resolve_promise_with(promise, value) {
2916 self.reject_promise(promise, reason);
2917 }
2918 Ok(())
2919 }
2920 Ok((value, false)) => {
2921 // Parked on `await`: follow what it awaited and resume with the outcome.
2922 let awaited = match self.promise_resolve_value(value) {
2923 Ok(awaited) => awaited,
2924 Err(Signal::Throw(error)) => {
2925 self.reject_promise(promise, error);
2926 return Ok(());
2927 }
2928 Err(other) => return Err(other),
2929 };
2930 self.hook_await(awaited, coroutine, promise)
2931 }
2932 Err(Signal::Throw(reason)) => {
2933 self.reject_promise(promise, reason);
2934 Ok(())
2935 }
2936 Err(other) => Err(other),
2937 }
2938 }
2939
2940 /// Arrange for `coroutine` to resume when `awaited` settles.
2941 fn hook_await(
2942 &mut self,
2943 awaited: Value,
2944 coroutine: &Gc<JsObject>,
2945 promise: &Gc<JsObject>,
2946 ) -> JsResult<()> {
2947 let resumed = JsObject::function(
2948 self.heap,
2949 Some(self.realm.function_proto.clone()),
2950 Callable::AwaitResume {
2951 coroutine: coroutine.clone(),
2952 promise: promise.clone(),
2953 kind: ResumeKind::Next,
2954 },
2955 );
2956 let raised = JsObject::function(
2957 self.heap,
2958 Some(self.realm.function_proto.clone()),
2959 Callable::AwaitResume {
2960 coroutine: coroutine.clone(),
2961 promise: promise.clone(),
2962 kind: ResumeKind::Throw,
2963 },
2964 );
2965 // `perform_then` on a non-promise would be wrong, and `promise_resolve_value`
2966 // guarantees one; the fallback keeps a mis-shaped value from panicking.
2967 let Value::Object(awaited) = &awaited else {
2968 self.jobs.push_back(Job::Resume {
2969 coroutine: coroutine.clone(),
2970 promise: promise.clone(),
2971 kind: ResumeKind::Next,
2972 value: awaited,
2973 });
2974 return Ok(());
2975 };
2976 self.perform_then(
2977 awaited,
2978 Some(Value::Object(resumed)),
2979 Some(Value::Object(raised)),
2980 )?;
2981 Ok(())
2982 }
2983
2984 /// `[[GetOwnProperty]]` on an ordinary object: the property table, then the two
2985 /// things an engine keeps outside it — array elements and an array's `length`.
2986 fn ordinary_own_property(object: &Gc<JsObject>, key: &PropertyKey) -> Option<Property> {
2987 if let Some(property) = object.own_property_key(key) {
2988 return Some(property);
2989 }
2990 // A typed array's indices are bytes in its buffer, so a descriptor for one has to
2991 // be synthesized too — and every one of them is a plain writable, enumerable,
2992 // configurable data property. `Object.getOwnPropertyDescriptor(ta, "0")` answered
2993 // `undefined` before this, which made `key-is-numericindex` fail on its own
2994 // side effect check.
2995 //
2996 // The key has to be a *canonical* numeric index: `ta["1.0"]` is an ordinary
2997 // property that happens not to exist, while `ta["-0"]` and `ta["1.5"]` are
2998 // likewise not elements however numeric they look.
2999 if object.typed_array_element_type().is_some()
3000 && let Some(numeric) = canonical_numeric_index(key)
3001 && numeric.is_finite()
3002 && numeric.fract() == 0.0
3003 && !(numeric == 0.0 && numeric.is_sign_negative())
3004 && numeric >= 0.0
3005 && (numeric as usize) < object.typed_array_length().unwrap_or(0)
3006 {
3007 let value = object.typed_array_element(numeric as usize)?;
3008 return Some(Property::data(value));
3009 }
3010 // An array's elements live in their own vector rather than the property table, so
3011 // a descriptor for one has to be synthesized — with the attributes an element has.
3012 if let Some(index) = key.as_str().and_then(array_index)
3013 && let Some(value) = object.array_get(index as usize)
3014 && !matches!(value, Value::Hole)
3015 {
3016 return Some(Property::data(value));
3017 }
3018 // `length` is an own property of an array that is not in its property table
3019 // either: `[].hasOwnProperty("length")` is true, and its descriptor is writable
3020 // and non-enumerable.
3021 if key.as_str() == Some("length")
3022 && let Some(length) = object.array_length()
3023 {
3024 return Some(Property {
3025 value: Some(crate::object::length_value(length)),
3026 writable: object.length_writable(),
3027 enumerable: false,
3028 configurable: false,
3029 getter: None,
3030 setter: None,
3031 descriptor_fields: None,
3032 });
3033 }
3034 None
3035 }
3036
3037 /// `[[GetOwnProperty]]`, with the `getOwnPropertyDescriptor` trap when there is one.
3038 pub fn object_get_own_property(
3039 &mut self,
3040 object: &Gc<JsObject>,
3041 key: &PropertyKey,
3042 ) -> JsResult<Option<Property>> {
3043 if let Some(answer) = self.proxy_get_own_property(object, key)? {
3044 return Ok(answer);
3045 }
3046 if let Some(exotic) = object.exotic()
3047 && let Some(answer) = exotic.get_own_property(self, object, key)?
3048 {
3049 return Ok(answer);
3050 }
3051 // A mapped `arguments` index is a data property as far as script can see: the
3052 // accessor pair that aliases the parameter is plumbing, and exposing it would
3053 // make `Object.getOwnPropertyDescriptor(arguments, "0").value` undefined and
3054 // report a `get` where the spec has a `[[Value]]`.
3055 if let Some(index) = key.as_str().and_then(crate::object::array_index)
3056 && let Some(cell) = object.mapped_argument_cell(index as usize)
3057 {
3058 // Non-configurable is *not* the default: an ordinary mapped index is
3059 // configurable, and only becomes non-configurable once something
3060 // redefines it. Preserve whatever the property table currently says.
3061 // The attributes come from whatever the property table holds, because they
3062 // can be changed independently of the mapping; only the *value* and the
3063 // data-property *kind* are the accessor's secret.
3064 let flags = Self::ordinary_own_property(object, key);
3065 if let Some(existing) = &flags
3066 && !existing.is_accessor()
3067 {
3068 // Already demapped: the table entry is the answer, not the cell.
3069 return Ok(flags);
3070 }
3071 return Ok(Some(Property {
3072 value: Some(cell.get()),
3073 writable: true,
3074 enumerable: flags.as_ref().is_none_or(|p| p.enumerable),
3075 configurable: flags.as_ref().is_some_and(|p| p.configurable),
3076 ..Property::default()
3077 }));
3078 }
3079 Ok(Self::ordinary_own_property(object, key))
3080 }
3081
3082 /// §7.3.40 `SetterThatIgnoresPrototypeProperties(thisValue, home, propertyKey, value)`.
3083 ///
3084 /// Written for `Error.prototype.stack`'s setter and the exact mechanism
3085 /// `Iterator.prototype.constructor`'s poisoned setter needs, which is why it is an
3086 /// abstract operation here rather than a private helper in `error.rs`.
3087 ///
3088 /// The name is the whole point: the setter must behave as if the prototype were not
3089 /// consulted, so `Error.prototype.stack = "x"` **throws** instead of quietly shadowing
3090 /// the accessor for every error object in the realm. Everything below follows from that:
3091 ///
3092 /// 1. `thisValue` must be an object — otherwise `TypeError`.
3093 /// 2. `thisValue === home` is a `TypeError`. This is what makes an assignment to the
3094 /// accessor's own home an error rather than a self-shadow.
3095 /// 3. `value` must already be a String. There is no `ToString`, deliberately: the caller
3096 /// either has a string or has made a mistake.
3097 /// 4. An existing *own* property decides the path — an own setter is called, an own
3098 /// non-writable data property is a `TypeError` — and only a missing own property
3099 /// falls through to defining one.
3100 /// 5. The definition goes through `[[DefineOwnProperty]]`, so a proxy receiver gets its
3101 /// traps and a non-extensible receiver is a `TypeError`.
3102 ///
3103 /// The installed shape is writable + configurable, not enumerable.
3104 pub fn setter_that_ignores_prototype_properties(
3105 &mut self,
3106 this_value: Value,
3107 home: &Gc<JsObject>,
3108 property_key: &str,
3109 args: &[Value],
3110 ) -> JsResult<Value> {
3111 self.setter_that_ignores_prototype_properties_key(
3112 this_value,
3113 home,
3114 &PropertyKey::from(property_key),
3115 args,
3116 )
3117 }
3118
3119 /// [`Interp::setter_that_ignores_prototype_properties`] for a key that may be a symbol.
3120 ///
3121 /// `Iterator.prototype[@@toStringTag]`'s setter is the symbol-keyed caller.
3122 pub fn setter_that_ignores_prototype_properties_key(
3123 &mut self,
3124 this_value: Value,
3125 home: &Gc<JsObject>,
3126 key: &PropertyKey,
3127 args: &[Value],
3128 ) -> JsResult<Value> {
3129 let Some(receiver) = this_value.as_object().cloned() else {
3130 return Err(self.type_error("setter called on a non-object"));
3131 };
3132 if Gc::ptr_eq(&receiver, home) {
3133 return Err(self.type_error("cannot assign to the accessor's own home object"));
3134 }
3135 // No type check here: §7.3.40 takes an arbitrary `v`, and
3136 // `Iterator.prototype.constructor` genuinely accepts any value. The one place that
3137 // insists on a String is `Error.prototype.stack`'s setter, which does its own check
3138 // before calling this.
3139 let value = args.first().cloned().unwrap_or(Value::Undefined);
3140 // Step 4: an own property on the receiver changes what happens, and there are three
3141 // distinct paths. `setter-proxy-trap-rejects` spells out the split: the
3142 // `defineProperty` trap belongs to `CreateDataPropertyOrThrow`, the `set` trap to
3143 // `Set` with `throw = true`, and a test exists for each.
3144 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
3145 if existing.is_accessor() && existing.setter.is_none() {
3146 // A getter-only own accessor cannot be written through.
3147 return Err(self.type_error("no setter for the own property"));
3148 }
3149 // Everything else — an own data property, or an own accessor *with* a setter —
3150 // takes the `Set` path with `throw = true`. That is what routes a proxy's own
3151 // `stack` to its `set` trap (`setter-proxy-trap-rejects`), and it is also how
3152 // an own user setter receives the value (`setter-own-accessor`), because
3153 // `[[Set]]` calls it for us. Going through `[[Set]]` instead of calling the
3154 // setter directly is the difference between one code path and two that can
3155 // disagree.
3156 self.set_property_with_key(
3157 &receiver,
3158 key,
3159 value.clone(),
3160 crate::interp::DeleteFailure::Throw,
3161 )?;
3162 return Ok(Value::Undefined);
3163 }
3164 let property = Property {
3165 value: Some(value.clone()),
3166 writable: true,
3167 // Enumerable, despite the accessor it shadows not being. The reference installs
3168 // it that way and six cases check it (`setter-creates-own-property` and friends).
3169 enumerable: true,
3170 configurable: true,
3171 ..Property::default()
3172 };
3173 if !self.object_define_own_property(&receiver, key, property)? {
3174 return Err(self.type_error("the receiver refused the definition"));
3175 }
3176 Ok(Value::Undefined)
3177 }
3178
3179 /// §10.4.5.1 `IntegerIndexedDefineOwnProperty(O, index, Desc)`.
3180 ///
3181 /// The indices of a typed array are not properties at all — they are bytes in the
3182 /// view's buffer, and `[[GetOwnProperty]]` synthesizes a descriptor for them on the
3183 /// fly. That makes their descriptor shape fixed: every valid index is writable,
3184 /// enumerable and configurable, so a definition can only ever change the *value*, and
3185 /// every other descriptor is refused rather than applied.
3186 ///
3187 /// The order of the checks is the spec's, and two of them are load-bearing:
3188 ///
3189 /// * the index is validated **before** the value is converted, because the conversion
3190 /// itself can resize the buffer out from under the view — `tonumber-value-detached-buffer`
3191 /// detaches from a `valueOf` and still expects `true` with no store, which only
3192 /// happens when the index was valid on the way in;
3193 /// * the store is attempted even when the index has gone out of bounds by the time the
3194 /// conversion finishes, because the store is a silent no-op rather than a failure —
3195 /// the same rule `[[Set]]` follows, and for the same reason: `V` may itself resize
3196 /// the buffer back into range (`resized-out-of-bounds-to-in-bounds-index`).
3197 ///
3198 /// The descriptor arrives from `define_property_on` *merged* with the attributes of
3199 /// the existing element, which is harmless here: every valid index is already
3200 /// writable, enumerable and configurable, so a `false` in the merged property can only
3201 /// have come from the descriptor having named `false`.
3202 fn integer_indexed_define_own_property(
3203 &mut self,
3204 object: &Gc<JsObject>,
3205 numeric: f64,
3206 property: &Property,
3207 ) -> JsResult<bool> {
3208 // Step 2: `IsInteger(numericIndex)` must hold. `-0` *is* an integer and *is*
3209 // canonical, and the spec rejects it by name anyway, so it is tested for sign.
3210 if !typed_array_index_is_valid(object, numeric) {
3211 return Ok(false);
3212 }
3213 // Step 6: the indices are data properties, so an accessor descriptor is refused
3214 // rather than converted. `Object.defineProperty` turns the `false` into a
3215 // `TypeError`; `Reflect.defineProperty` reports it.
3216 if property.is_accessor() {
3217 return Ok(false);
3218 }
3219 // Steps 7–9: a typed-array index is writable, enumerable and configurable, so a
3220 // definition that asks for anything else cannot be honoured.
3221 if !property.writable || !property.enumerable || !property.configurable {
3222 return Ok(false);
3223 }
3224 // Step 10: only a descriptor that names a value stores anything.
3225 let Some(value) = property.value.clone() else {
3226 return Ok(true);
3227 };
3228 let Some(element) = object.typed_array_element_type() else {
3229 return Ok(false);
3230 };
3231 let stored = self.element_value(element, value)?;
3232 if let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored) {
3233 return Err(self.type_error(reason));
3234 }
3235 Ok(true)
3236 }
3237
3238 /// `[[DefineOwnProperty]]`, with the `defineProperty` trap when there is one.
3239 pub fn object_define_own_property(
3240 &mut self,
3241 object: &Gc<JsObject>,
3242 key: &PropertyKey,
3243 property: Property,
3244 ) -> JsResult<bool> {
3245 if let Some(accepted) = self.proxy_define_property(object, key, property.clone())? {
3246 return Ok(accepted);
3247 }
3248 // A proxy always answers above — with `Some` from its trap, or with `None` when
3249 // the trap is absent, and then the definition belongs to the **target**
3250 // (§10.5.4: `[[DefineOwnProperty]]` forwards to `target.[[DefineOwnProperty]]`
3251 // when there is no trap). Falling through to the ordinary path here defined the
3252 // property on the proxy object itself, so `new Proxy({}, {}).x = 1` invented a
3253 // property the target never saw.
3254 if object.proxy_state().is_some() {
3255 let Some((target, _handler)) = self.proxy_parts(object)? else {
3256 return Err(self.type_error("cannot use a proxy that has been revoked"));
3257 };
3258 return self.object_define_own_property(&target, key, property);
3259 }
3260 // §10.4.5.1 `IntegerIndexedDefineOwnProperty`: a typed array owns its indices, and
3261 // they accept exactly one descriptor shape. This has to happen before the
3262 // ordinary path, which would happily store a data property next to the buffer —
3263 // 99 cases across `TypedArrayConstructors/internals/{DefineOwnProperty,Set,Delete}`
3264 // and `TypedArray/prototype/set` are about this section.
3265 if object.typed_array_element_type().is_some()
3266 && let Some(index) = canonical_numeric_index(key)
3267 {
3268 return self.integer_indexed_define_own_property(object, index, &property);
3269 }
3270 // §10.1.6.3 step 2.a: `OrdinaryDefineOwnProperty` refuses to *add* a property to a
3271 // non-extensible object. The check lives here rather than in the callers because
3272 // every one of them then has to remember it — `CreateDataPropertyOrThrow` is what
3273 // `Array.prototype.filter` uses to store its result, and a species object made
3274 // non-extensible by its own constructor must make that a `TypeError`
3275 // (`target-array-non-extensible`).
3276 // Note the `is_none()`: an already-present property may still be **redefined** on a
3277 // non-extensible object, and only *adding* one is refused (as Distinct from
3278 // `SetIntegrityLevel`, which prevents extensions and then redefines the existing
3279 // properties — testing extensibility before looking for the property made every
3280 // `Object.freeze` of an ordinary object refuse its own second step).
3281 if !object.is_extensible() && self.object_get_own_property(object, key)?.is_none() {
3282 return Ok(false);
3283 }
3284 // A *partial* descriptor names only some fields, so the ones it omits keep whatever
3285 // the property already has (§10.1.6.3 `ValidateAndApplyPropertyDescriptor` step 9:
3286 // an omitted field is left alone). Merging here rather than at each call site is
3287 // what lets `SetIntegrityLevel` pass `{ [[Configurable]]: false }` and still leave
3288 // the value and `enumerable` in place.
3289 //
3290 // The merge is a no-op when the property is absent: there is nothing to keep.
3291 let was_partial = property.descriptor_fields.is_some();
3292 let property = match property.descriptor_fields {
3293 None => property,
3294 Some(fields) => {
3295 let base = self.object_get_own_property(object, key)?;
3296 let mut merged = base.clone().unwrap_or_default();
3297 // §10.1.6.3 steps 9–11: the *kind* is decided by which fields the
3298 // descriptor names, and switching kind discards the other half —
3299 // `{set: f}` on a data property is an accessor with no getter, not a data
3300 // property whose `get` happens to be absent.
3301 let wants_accessor = fields.get || fields.set;
3302 let wants_data = fields.value || fields.writable;
3303 if wants_accessor {
3304 merged.value = None;
3305 merged.writable = false;
3306 merged.getter = property.getter.clone();
3307 merged.setter = property.setter.clone();
3308 } else if wants_data {
3309 merged.getter = None;
3310 merged.setter = None;
3311 if fields.value {
3312 merged.value = property.value.clone();
3313 }
3314 if fields.writable {
3315 merged.writable = property.writable;
3316 }
3317 }
3318 if fields.enumerable {
3319 merged.enumerable = property.enumerable;
3320 }
3321 if fields.configurable {
3322 merged.configurable = property.configurable;
3323 }
3324 merged.descriptor_fields = None;
3325 merged
3326 }
3327 };
3328 // §10.1.6.3 steps 5–8 `ValidateAndApplyPropertyDescriptor`, on the **merged**
3329 // descriptor. `define_property_on` runs the same check before it calls here, so an
3330 // ordinary object is already covered; what is *not* is the forwarding a proxy does
3331 // when it has no `defineProperty` trap (`target.[[DefineOwnProperty]](P, Desc)`
3332 // lands here directly, because `object_define_own_property` is `[[DefineOwnProperty]]`
3333 // spelled out). Without it, `Object.defineProperty(new Proxy(new String("str"), {}),
3334 // "0", {value: "x"})` rewrote a non-writable, non-configurable index — the target's
3335 // own define would have refused.
3336 //
3337 // Only partial descriptors are validated here. A whole `Property` passed by an
3338 // internal caller (`Property::data(…)`) carries attributes that say nothing about
3339 // what the descriptor "named", and those callers rely on the write landing.
3340 if was_partial && let Some(existing) = self.object_get_own_property(object, key)? {
3341 // Every branch below is gated on `!existing.configurable`: a *configurable*
3342 // property may be reshaped however the descriptor likes, which is why an
3343 // ordinary `{value: 2}` redefine of `{writable: false, configurable: true}`
3344 // must succeed. Testing only `writable` refused that and broke
3345 // `Object.defineProperty(funcProxy, "name", {value: "foo"})`.
3346 let same_kind = existing.is_accessor() == property.is_accessor();
3347 if !same_kind {
3348 // Step 4: a non-configurable property may not change kind.
3349 if !existing.configurable {
3350 return Ok(false);
3351 }
3352 } else if existing.is_accessor() {
3353 // Step 6: an accessor's halves are its value.
3354 if !existing.configurable
3355 && (!crate::builtins::same_accessor_half(&property.getter, &existing.getter)
3356 || !crate::builtins::same_accessor_half(&property.setter, &existing.setter))
3357 {
3358 return Ok(false);
3359 }
3360 } else if !existing.configurable && !existing.writable {
3361 // Step 7: a non-configurable *and* non-writable data property's value is
3362 // fixed, and it may not become writable again.
3363 if property.writable {
3364 return Ok(false);
3365 }
3366 let current = existing.value.clone().unwrap_or(Value::Undefined);
3367 let requested = property.value.clone().unwrap_or(Value::Undefined);
3368 if !current.same_value(&requested) {
3369 return Ok(false);
3370 }
3371 }
3372 // Step 8: `[[Configurable]]: false` is a one-way door, and `[[Enumerable]]`
3373 // is frozen with it.
3374 if !existing.configurable
3375 && (property.configurable || property.enumerable != existing.enumerable)
3376 {
3377 return Ok(false);
3378 }
3379 }
3380 // A host class that intercepts definitions owns the attributes of the properties it
3381 // defines: `_class`-style storage on the native side is the usual reason.
3382 if let Some(exotic) = object.exotic()
3383 && let Some(accepted) = exotic.define_own_property(self, object, key, &property)?
3384 {
3385 return Ok(accepted);
3386 }
3387 // An array index is stored in the element vector, which can hold a plain value and
3388 // nothing else. An accessor — or a data property with non-default attributes —
3389 // therefore has to live in the property table, and the element slot is blanked so
3390 // the table is what a read finds. Without this `Object.defineProperty(a, "0",
3391 // {get})` stored the accessor where no read ever looked, and the array kept
3392 // answering its old value.
3393 // An array's `length` is not stored in the property table, so defining it has to
3394 // run `ArraySetLength`: it truncates or extends the element vector and refuses a
3395 // value that is not a valid index. Without this `Object.defineProperty(a, "length",
3396 // {value: 1})` reported success and changed nothing.
3397 if key.as_str() == Some("length") && object.is_array() {
3398 // `{writable: false}` on `length` does not change the length, but it does make
3399 // it read-only — after which neither a later `{writable: true}` nor a store
3400 // past the end may succeed.
3401 if property.value.is_none() {
3402 if !object.length_writable() && property.writable {
3403 return Ok(false);
3404 }
3405 object.set_length_writable(property.writable);
3406 return Ok(true);
3407 }
3408 if !object.length_writable() {
3409 return Ok(false);
3410 }
3411 }
3412 if key.as_str() == Some("length")
3413 && object.is_array()
3414 && let Some(value) = property.value.clone()
3415 {
3416 let requested = value.to_number();
3417 let valid = requested.is_finite()
3418 && requested >= 0.0
3419 && requested.fract() == 0.0
3420 && requested <= u32::MAX as f64;
3421 if !valid {
3422 return Err(self.range_error("invalid array length"));
3423 }
3424 // Truncating deletes the elements above the new length, and a non-configurable
3425 // one cannot be deleted: `Object.defineProperty(a, "3", {configurable: false})`
3426 // makes `a.length = 2` fail rather than quietly drop it.
3427 let current = object.array_length().unwrap_or(0);
3428 let requested = requested as usize;
3429 if requested < current && object.first_undeletable_at_or_above(requested).is_some() {
3430 // §10.4.2.4 `ArraySetLength` step 3.i.2: the refusal still applies
3431 // `[[Writable]]: false` when the descriptor asked for it — the length is
3432 // left at its old value but locked. Returning `false` alone left it
3433 // writable, which `verifyProperty` catches
3434 // (`defineProperties/15.2.3.7-6-a-164`).
3435 if property
3436 .descriptor_fields
3437 .is_some_and(|fields| fields.writable)
3438 && !property.writable
3439 && object.length_writable()
3440 {
3441 object.set_length_writable(false);
3442 }
3443 return Ok(false);
3444 }
3445 object.array_set_length(self.heap, requested);
3446 return Ok(true);
3447 }
3448 let plain = property.writable
3449 && property.enumerable
3450 && property.configurable
3451 && !property.is_accessor();
3452 if let Some(index) = key.as_str().and_then(array_index)
3453 && object.is_array()
3454 {
3455 // Growing the array needs a writable `length`: after
3456 // `Object.defineProperty(a, "length", {writable: false})` a new index cannot
3457 // be added.
3458 if (index as usize) >= object.array_length().unwrap_or(0) && !object.length_writable() {
3459 return Ok(false);
3460 }
3461 if plain && property.value.is_some() {
3462 // An ordinary element: the vector is where a read looks first, so it has
3463 // to be the vector that changes — unless the index is too far out to be
3464 // worth a dense slot. `a[2**32 - 2] = 1` is legal and costs the reference
3465 // one property, because past its own limit it stores the index as an
3466 // ordinary key. Falling through to `define_key` below is the same choice,
3467 // and the alternative was worse: the store used to be *dropped* and the
3468 // length left at 0, which is a silent wrong answer.
3469 let value = property.value.clone().unwrap_or(Value::Undefined);
3470 object.delete_key(key);
3471 if object.array_set(self.heap, index as usize, value) {
3472 return Ok(true);
3473 }
3474 // Past the dense limit the element lives in the table like any property.
3475 object.note_element_descriptor();
3476 object.define_key(key, property);
3477 // A sparse store past the dense limit still extends `length`, which is what
3478 // `a[a.length] = v` relies on — but only extends: shortening would delete
3479 // the sparse properties above the index, including this one.
3480 if index as usize + 1 > object.array_length().unwrap_or(0) {
3481 object.array_set_length(self.heap, index as usize + 1);
3482 }
3483 return Ok(true);
3484 }
3485 // A non-plain element — an accessor, or an attribute that is not the default —
3486 // lives in the table while the slot becomes a hole. Recording it keeps every
3487 // later `a[i] = v` off the dense path, where the write would have shadowed the
3488 // descriptor: `Object.defineProperty(a, "0", {get(){…}}); a[0] = 1` used to
3489 // replace the accessor with a plain data property.
3490 object.note_element_descriptor();
3491 object.define_key(key, property);
3492 // The slot stays, so `length` does not shrink; a hole is not an element, so
3493 // the table entry is now what a read finds.
3494 object.array_set(self.heap, index as usize, Value::Hole);
3495 // `ArraySetLength` step 2 of `OrdinaryDefineOwnProperty`'s index branch —
3496 // `length = index + 1` — applies whatever the descriptor's *attributes* are,
3497 // not just to a plain one: `Object.defineProperty(a, 4294967294, {value: 100})`
3498 // makes `a.length` 4294967295 (`defineProperty/15.2.3.6-4-183`).
3499 if index as usize + 1 > object.array_length().unwrap_or(0) {
3500 object.array_set_length(self.heap, index as usize + 1);
3501 }
3502 return Ok(true);
3503 }
3504 object.define_key(key, property);
3505 Ok(true)
3506 }
3507
3508 /// Build a proxy object over `target`, with its traps read from `handler`.
3509 pub fn new_proxy(&self, target: Gc<JsObject>, handler: Value) -> Gc<JsObject> {
3510 JsObject::proxy(self.heap, target, handler)
3511 }
3512
3513 /// The `revoke` function for a proxy's slots.
3514 pub fn new_revoker(&self, slots: crate::object::ProxyRef) -> Gc<JsObject> {
3515 let revoke = JsObject::function(
3516 self.heap,
3517 Some(self.realm.function_proto.clone()),
3518 Callable::Revoker(slots),
3519 );
3520 // §27.2.1.2 `Proxy.revocable` steps 6–7: the revoker is built with `length` 0 and
3521 // `name` `""`, and both are **own** properties, `length` first. Leaving them to be
3522 // inherited from `Function.prototype` reads the same but fails the three cases that
3523 // check the own-property list (`revocation-function-{length,name,property-order}`).
3524 revoke.define("length", Property::name_or_length(Value::Int(0)));
3525 revoke.define("name", Property::name_or_length(self.string("")));
3526 revoke
3527 }
3528
3529 /// A new array.
3530 pub fn new_array(&self, elements: Vec<Value>) -> Gc<JsObject> {
3531 let array = JsObject::array(
3532 self.heap,
3533 Some(self.realm.array_proto.clone()),
3534 elements.len(),
3535 );
3536 for (index, element) in elements.into_iter().enumerate() {
3537 array.array_set(self.heap, index, element);
3538 }
3539 array
3540 }
3541
3542 /// A new native function object.
3543 ///
3544 /// The observable `name` and `length` are installed as properties here, which is
3545 /// what `Function.prototype.name` and `.length` read; nothing else stores them,
3546 /// so `f.name = "x"` behaves like the writable property it is.
3547 /// A native constructor that builds its own instance after validating its arguments.
3548 ///
3549 /// `new` hands it `this = undefined` rather than a pre-made object, so any argument
3550 /// check runs before `new.target.prototype` is read.
3551 pub fn new_native_ctor(
3552 &self,
3553 name: impl Into<String>,
3554 length: u32,
3555 func: NativeFn,
3556 ) -> Gc<JsObject> {
3557 let function = JsObject::function(
3558 self.heap,
3559 Some(self.realm.function_proto.clone()),
3560 Callable::Native {
3561 func,
3562 own_instance: true,
3563 },
3564 );
3565 function.set_constructible(true);
3566 function.define(
3567 "length",
3568 Property::name_or_length(Value::Int(length as i32)),
3569 );
3570 function.define("name", Property::name_or_length(self.string(name)));
3571 function
3572 }
3573
3574 /// A native constructor that lets `new` build the instance first.
3575 ///
3576 /// The ordinary case for a built-in constructor: `new Array(3)` has no argument
3577 /// validation that must precede reading `new.target.prototype`, so the object can be
3578 /// created before the implementation runs. Distinct from [`Interp::new_native`],
3579 /// which makes a *method* and therefore not a constructor at all.
3580 pub fn new_native_constructor(
3581 &self,
3582 name: impl Into<String>,
3583 length: u32,
3584 func: NativeFn,
3585 ) -> Gc<JsObject> {
3586 let function = self.new_native(name, length, func);
3587 function.set_constructible(true);
3588 function
3589 }
3590
3591 /// A new host function object: a native closure that carries its own state.
3592 ///
3593 /// Same observable surface as [`Interp::new_native`] — `name`, `length` and, for a
3594 /// constructor, `prototype` — but the body is a closure, so it can hold an open-file
3595 /// table or a timer queue. See [`crate::object::HostFn`] for the one rule that makes
3596 /// this safe: the closure must not capture a `Gc`.
3597 pub fn new_host_function(
3598 &self,
3599 name: impl Into<String>,
3600 length: u32,
3601 func: crate::object::HostFn,
3602 ) -> Gc<JsObject> {
3603 self.new_host_inner(name.into(), length, func, false)
3604 }
3605
3606 /// A host constructor: `new` hands it `this = undefined`, so it validates its
3607 /// arguments before building an instance, exactly like [`Interp::new_native_ctor`].
3608 pub fn new_host_ctor(
3609 &self,
3610 name: impl Into<String>,
3611 length: u32,
3612 func: crate::object::HostFn,
3613 ) -> Gc<JsObject> {
3614 let function = self.new_host_inner(name.into(), length, func, true);
3615 function.set_constructible(true);
3616 // A constructor needs a `prototype` for `new` and for `instanceof`; the body
3617 // installs its own methods on it, so it starts as a plain object.
3618 let proto = JsObject::ordinary(self.heap, Some(self.realm.object_proto.clone()));
3619 function.define(
3620 "prototype",
3621 Property {
3622 value: Some(Value::Object(proto)),
3623 writable: true,
3624 enumerable: false,
3625 configurable: false,
3626 ..Property::default()
3627 },
3628 );
3629 function
3630 }
3631
3632 fn new_host_inner(
3633 &self,
3634 name: String,
3635 length: u32,
3636 func: crate::object::HostFn,
3637 own_instance: bool,
3638 ) -> Gc<JsObject> {
3639 let function = JsObject::function(
3640 self.heap,
3641 Some(self.realm.function_proto.clone()),
3642 Callable::Host {
3643 func: std::rc::Rc::new(std::cell::RefCell::new(func)),
3644 own_instance,
3645 },
3646 );
3647 function.define(
3648 "length",
3649 Property::name_or_length(Value::Int(length as i32)),
3650 );
3651 function.define("name", Property::name_or_length(self.string(name)));
3652 function
3653 }
3654
3655 /// A callable object with the `length`/`name` a built-in function has, in that order.
3656 ///
3657 /// The order is observable: `Object.getOwnPropertyNames(f)` is `["length", "name"]` and
3658 /// `Promise/all/resolve-element-function-property-order` asserts exactly that adjacency.
3659 /// [`JsObject::function`] defines neither, which is why every capability helper built
3660 /// with it reported no own `length` and no own `name` at all.
3661 ///
3662 /// The attributes are the spec's for a built-in: not writable, not enumerable,
3663 /// configurable.
3664 pub fn builtin_function(&self, name: &str, length: u32, callable: Callable) -> Gc<JsObject> {
3665 let function =
3666 JsObject::function(self.heap, Some(self.realm.function_proto.clone()), callable);
3667 function.define(
3668 "length",
3669 Property::name_or_length(Value::Int(length as i32)),
3670 );
3671 function.define("name", Property::name_or_length(self.string(name)));
3672 function
3673 }
3674
3675 /// A new native function object.
3676 pub fn new_native(&self, name: impl Into<String>, length: u32, func: NativeFn) -> Gc<JsObject> {
3677 let function = JsObject::function(
3678 self.heap,
3679 Some(self.realm.function_proto.clone()),
3680 Callable::Native {
3681 func,
3682 own_instance: false,
3683 },
3684 );
3685 // `length` before `name`: `FunctionCreate` sets `[[ParameterCount]]` first, and
3686 // `Object.getOwnPropertyNames` reports insertion order, so the reference lists
3687 // `length,name` and this listed `name,length`. A bytecode function already gets it
3688 // the right way round; only native ones were built backwards.
3689 function.define(
3690 "length",
3691 Property::name_or_length(Value::Int(length as i32)),
3692 );
3693 function.define("name", Property::name_or_length(self.string(name)));
3694 function
3695 }
3696
3697 /// A new bound function.
3698 pub fn new_bound(&self, target: Value, this: Value, args: Vec<Value>) -> Gc<JsObject> {
3699 // §10.4.1.3 BoundFunctionCreate: a bound function has `[[Call]]` because it was
3700 // made by calling `bind`, and `[[Construct]]` exactly when its target has one.
3701 // `new (function(){}.bind(null))()` works; `new (()=>{}).bind(null)()` does not.
3702 let constructible = target
3703 .as_object()
3704 .is_some_and(|target| target.is_constructor());
3705 let bound = JsObject::function(
3706 self.heap,
3707 Some(self.realm.function_proto.clone()),
3708 Callable::Bound { target, this, args },
3709 );
3710 bound.set_constructible(constructible);
3711 bound
3712 }
3713
3714 /// A new reference cell.
3715 pub fn new_cell(&self, value: Value) -> Gc<Cell> {
3716 Gc::new(self.heap, Cell::new(value))
3717 }
3718
3719 // -- running ------------------------------------------------------------
3720
3721 /// Evaluate `code` as a script body and return its completion value.
3722 /// Compile and run `source` for the engine's own use, returning its completion value.
3723 ///
3724 /// This is how a builtin can be written in JavaScript: [`crate::builtins::from_async`]
3725 /// needs to be a real async function, and the engine already runs those as coroutines,
3726 /// so compiling the algorithm is cheaper than rebuilding a coroutine by hand.
3727 ///
3728 /// Differences from [`Self::eval_in_global`], both deliberate:
3729 ///
3730 /// * It does **not** drain the microtask queue. Install runs while the realm is still
3731 /// being built, and the source is an IIFE that only constructs a closure, so there
3732 /// is nothing to drain — and draining here would run script-queued jobs in the
3733 /// middle of `install`.
3734 /// * It reports a syntax error as an `InternalError` throw rather than as the usual
3735 /// `SyntaxError` with a position: a malformed builtin source is this crate's bug,
3736 /// and it should not look like the user wrote something wrong.
3737 pub fn eval_builtin_source(&mut self, source: &str) -> JsResult<Value> {
3738 let program = match js_parse::parse_script(source) {
3739 Ok(program) => program,
3740 Err(error) => {
3741 let message = format!("builtin source does not parse: {error}");
3742 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3743 }
3744 };
3745 let mut code = match js_compile::compile_script_with_source(&program, source) {
3746 Ok(code) => code,
3747 Err(error) => {
3748 let message = format!("builtin source does not compile: {}", error.message);
3749 return Err(Signal::Throw(self.make_error("InternalError", &message)));
3750 }
3751 };
3752 // The frame has to name something, and `<builtin>` is what a stack trace through
3753 // this code should say.
3754 code.set_filename("<builtin>");
3755 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3756 let closure_vars = compiled.code.closure_vars.clone();
3757 let env = self.global_env(&closure_vars);
3758 let this = Value::Object(self.realm.global.clone());
3759 self.execute(compiled, env, this, Vec::new(), Value::Undefined)
3760 }
3761
3762 /// Run an already-parsed script and drain the microtasks it queued.
3763 ///
3764 /// The drain is what lets an `async` function's body advance past its first `await`
3765 /// before the host sees the result: nothing else pumps the job queue.
3766 pub fn run_script(&mut self, code: CompiledFunction) -> JsResult<Value> {
3767 let this = Value::Object(self.realm.global.clone());
3768 self.run_script_with_this(code, this)
3769 }
3770
3771 /// [`Interp::run_script`] with an explicit receiver — the C API's `JS_EvalThis`.
3772 ///
3773 /// The reference evaluates a global script with whatever `this_obj` the host passed, and
3774 /// it does so on the *script* path, not on the direct-eval one: a top-level `class` is
3775 /// script-scoped there, and `var` becomes a global. Sharing `run_script` guarantees that,
3776 /// where reusing the eval path made `JS_EvalThis` leave the variable environment in a
3777 /// state the next script evaluation tripped over.
3778 pub fn run_script_with_this(&mut self, code: CompiledFunction, this: Value) -> JsResult<Value> {
3779 let compiled = Gc::new(self.heap, CompiledCode::new(code));
3780 let closure_vars = compiled.code.closure_vars.clone();
3781 let env = self.global_env(&closure_vars);
3782 let callee = Value::Undefined;
3783 let result = self.execute(compiled, env, this, Vec::new(), callee)?;
3784 // The script is done, so the microtasks it queued run before the host sees the
3785 // result. Without this an `async` function's body would never advance past its
3786 // first `await`, because nothing else drains the queue.
3787 self.drain_jobs()?;
3788 Ok(result)
3789 }
3790
3791 /// Compile and run `source` in global scope, returning its completion value.
3792 ///
3793 /// This is what `eval` and `new Function` use. Running it as a script means it
3794 /// sees the global object and nothing else, which is right for `eval("1+1")` and
3795 /// for a `Function` body; a *direct* eval that reads a local variable would need
3796 /// the compiler to hand its variable environment over, which is not implemented.
3797 pub fn eval_in_global(&mut self, source: &str) -> JsResult<Value> {
3798 self.eval_in_global_named(source, EVAL_FILE, false)
3799 }
3800
3801 /// `std.evalScript(source)`: the same evaluation, reported under its own file name.
3802 ///
3803 /// The reference names the two separately — `eval` shows `<input>`, `std.evalScript`
3804 /// shows `<evalScript>` — and the name is visible in every stack trace that passes
3805 /// through the code, so they cannot share one constant.
3806 pub fn eval_script_in_global(&mut self, source: &str, barrier: bool) -> JsResult<Value> {
3807 self.eval_in_global_named(source, EVAL_SCRIPT_FILE, barrier)
3808 }
3809
3810 /// Evaluate `source` as a global script, reported under `file`.
3811 ///
3812 /// `barrier` marks the call as a separate evaluation for stack-trace purposes, which is
3813 /// what `std.evalScript` asks for. Public because the C API's `JS_Eval` needs to reach it
3814 /// from inside a C callback, where the interpreter is the running one rather than a
3815 /// context's own.
3816 pub fn eval_in_global_named(
3817 &mut self,
3818 source: &str,
3819 file: &str,
3820 barrier: bool,
3821 ) -> JsResult<Value> {
3822 // Marked for the duration, so `declare_var_global` knows a `var` from here is an
3823 // eval-created global binding — configurable, unlike a script's own `var`.
3824 self.eval_depth += 1;
3825 if barrier {
3826 let depth = self.frames.len();
3827 self.trace_barriers.push(depth);
3828 }
3829 let result = self.eval_in_global_inner(source, file);
3830 if barrier {
3831 self.trace_barriers.pop();
3832 }
3833 self.eval_depth -= 1;
3834 result
3835 }
3836
3837 fn eval_in_global_inner(&mut self, source: &str, file: &str) -> JsResult<Value> {
3838 let compiled = self.compile_global_script(source, file, false)?;
3839 let strict = compiled.strict;
3840 self.run_eval_script(compiled, strict)
3841 }
3842
3843 /// `JS_EvalThis`: compile `source` as a script and run it with the caller's receiver.
3844 ///
3845 /// Compiling is `parse_script` + `compile_script` — the script grammar, not the eval one,
3846 /// because that is what the reference's `JS_EVAL_TYPE_GLOBAL` means: a top-level `class`
3847 /// is script-scoped, `var` becomes a global, and the body is not confined the way a
3848 /// direct eval's is.
3849 pub fn eval_script_with_this(
3850 &mut self,
3851 source: &str,
3852 file: &str,
3853 this: Value,
3854 ) -> JsResult<Value> {
3855 let program = match js_parse::parse_script(source) {
3856 Ok(program) => program,
3857 Err(error) => {
3858 return Err(Signal::Throw(self.syntax_error_at(
3859 file,
3860 error.span.start.line,
3861 error.span.start.column,
3862 &error.message,
3863 )));
3864 }
3865 };
3866 let mut compiled = match js_compile::compile_script(&program) {
3867 Ok(compiled) => compiled,
3868 Err(error) => {
3869 return Err(Signal::Throw(self.syntax_error_at(
3870 file,
3871 error.span.start.line,
3872 error.span.start.column,
3873 &error.message,
3874 )));
3875 }
3876 };
3877 compiled.set_filename(file);
3878 self.run_script_with_this(compiled, this)
3879 }
3880
3881 /// Parse and compile `source` as a global script, without running it.
3882 ///
3883 /// Split out so [`Interp::eval_in_global_async`] can report a syntax error as a throw —
3884 /// before a promise exists to reject — while still evaluating in the same eval context
3885 /// (direct-eval strictness, `new.target`, `super`).
3886 fn compile_global_script(
3887 &mut self,
3888 source: &str,
3889 file: &str,
3890 async_body: bool,
3891 ) -> JsResult<CompiledFunction> {
3892 // A *direct* eval inherits the strictness of the code that called it, which is
3893 // why `eval("x = 1")` in a strict function is a ReferenceError instead of an
3894 // implicit global. The caller's frame is the innermost one here, because a
3895 // native function does not push a frame of its own.
3896 let strict = self.current_strict();
3897 // `eval` runs in the caller's function context, so `new.target` is legal here
3898 // even though the source is a bare script — and so is `super.x` when the caller
3899 // is a method. The eval'd code has no `[[HomeObject]]` of its own; it reads the
3900 // caller's, which is what `special_object 4` already does.
3901 let context = js_parse::EvalContext {
3902 in_method: self.enclosing_home_object().is_some(),
3903 // `super()` belongs to a derived constructor, and an eval'd body is not a
3904 // constructor at all: the caller frame's `this` is already built.
3905 in_derived_constructor: false,
3906 };
3907 // A *global* eval is not a function body: `new.target` and `super` are out of
3908 // reach there. Its `{async: true}` form differs in the other direction — the body
3909 // may `await` — so the two flags are independent and the reference sets both from
3910 // the eval type rather than from the caller.
3911 let parsed = if async_body {
3912 js_parse::parse_suspensible_global_eval(source, strict)
3913 } else {
3914 js_parse::parse_eval_script_in(source, strict, context)
3915 };
3916 let program = match parsed {
3917 Ok(program) => program,
3918 Err(error) => {
3919 // The message is bare: the position lives in `fileName`,
3920 // `lineNumber`, `columnNumber` and the stack frame above, which is where
3921 // the reference puts it. An `invalid source: L:C: ` prefix made
3922 // `e.message` differ from the reference while the stack already agreed.
3923 return Err(Signal::Throw(self.syntax_error_at(
3924 file,
3925 error.span.start.line,
3926 error.span.start.column,
3927 &error.message,
3928 )));
3929 }
3930 };
3931 let mut compiled = match if async_body {
3932 js_compile::compile_script_suspensible(&program)
3933 } else {
3934 js_compile::compile_script(&program)
3935 } {
3936 Ok(compiled) => compiled,
3937 // A construct the compiler does not handle yet is reported the same way a
3938 // parse error is: it happens before anything runs, so the trace is the
3939 // position in the source followed by the caller.
3940 Err(error) => {
3941 return Err(Signal::Throw(self.syntax_error_at(
3942 file,
3943 error.span.start.line,
3944 error.span.start.column,
3945 &error.message,
3946 )));
3947 }
3948 };
3949 compiled.set_filename(file);
3950 Ok(compiled)
3951 }
3952
3953 /// Run an `eval`'d script in the caller's scope.
3954 ///
3955 /// Three things have to come from the calling frame, because the eval'd code is a
3956 /// script and would otherwise see only the global object:
3957 ///
3958 /// * `this`, so `f.call(1, "this")` evaluates to `1`;
3959 /// * `arguments`, exposed as a binding of the eval's own scope, so
3960 /// `f("arguments.length", 1)` sees the caller's arguments;
3961 /// * a fresh variable environment for `var`, so a strict `eval` does not leak
3962 /// `eval("var v = 1")` into the global object.
3963 ///
3964 /// Locals of the calling function are *not* reachable: that needs the compiler to
3965 /// hand its variable environment over, which this milestone does not do.
3966 fn run_eval_script(&mut self, code: CompiledFunction, code_strict: bool) -> JsResult<Value> {
3967 // `this` and `arguments` come from the innermost frame only — those are not
3968 // lexical — while the name bindings come from the whole chain of frames, part
3969 // of it being ordinary scope resolution.
3970 // An arrow has no `this` of its own, so an `eval` inside one inherits the
3971 // enclosing function's receiver — the lexical `this` the arrow was compiled to
3972 // read from its closure.
3973 // `this` and `arguments` come from the innermost *non-arrow* frame, but the
3974 // variable environment is the innermost frame of all: an arrow's own body is where
3975 // `var`s declared by an `eval` inside it belong.
3976 let caller_index = self
3977 .frames
3978 .iter()
3979 .rposition(|frame| !frame.code.code.is_arrow)
3980 .or_else(|| self.frames.len().checked_sub(1));
3981 let env_index = self.frames.len().checked_sub(1);
3982 let caller = caller_index.and_then(|index| self.frames.get(index));
3983 let (this, passed) = match caller {
3984 Some(frame) => (frame.this.clone(), frame.passed().to_vec()),
3985 // No frame at all: the eval is running at the top level, so there is
3986 // nothing to inherit and the global receiver is right.
3987 None => (Value::Object(self.realm.global.clone()), Vec::new()),
3988 };
3989 // Innermost frame first, so the first binding found for a name is the one that
3990 // shadows the rest. A script frame (`<eval>`) contributes nothing.
3991 let mut bindings: Vec<EvalBinding> = Vec::new();
3992 // The calling function's own bindings, resolved by the compiler at the call
3993 // site. That table is the only reliable answer when a name is declared twice in
3994 // sibling scopes: the flat scan below cannot tell which `i` a `for (let i …)`
3995 // body means, and guessing by declaration order picks the wrong one as soon as
3996 // two loops in a row use the same name.
3997 // Only a *direct* eval sees the caller's scope. The compiler records a site for
3998 // every direct call — a bare `eval(...)` callee — so finding one at the current
3999 // position is the test: `(0, eval)(...)` and `f.call(null, ...)` resolve the
4000 // callee to a value first and leave no site behind.
4001 let mut direct = false;
4002 let mut resolved_here = false;
4003 if let Some(frame) = self.frames.last() {
4004 let (line, column) = frame
4005 .code
4006 .code
4007 .position_at(frame.at as u32)
4008 .unwrap_or_default();
4009 // The nearest site at or before the current position, not an exact match:
4010 // the recorded position of the `call` instruction is the callee's, which
4011 // sits a few columns inside the call expression the compiler recorded. A
4012 // site is unique per call, so "the closest one behind us" identifies it.
4013 if let Some(site) = frame
4014 .code
4015 .code
4016 .eval_sites
4017 .iter()
4018 .filter(|site| (site.line, site.column) <= (line, column))
4019 .max_by_key(|site| (site.line, site.column))
4020 {
4021 direct = true;
4022 resolved_here = true;
4023 for binding in &site.bindings {
4024 // An enclosing function's frame sits `owner` levels below the one
4025 // running the call.
4026 let Some(frame) = self.frames.len().checked_sub(1 + binding.owner as usize)
4027 else {
4028 continue;
4029 };
4030 bindings.push(EvalBinding {
4031 name: binding.name.clone(),
4032 frame,
4033 slot: if binding.is_arg {
4034 EvalSlot::Arg
4035 } else {
4036 EvalSlot::Local
4037 },
4038 index: binding.index as usize,
4039 });
4040 }
4041 }
4042 }
4043 for frame_index in (0..self.frames.len()).rev() {
4044 // Skip the innermost frame's flat scan when the compiler already answered
4045 // for it; an enclosing frame still needs one, because the eval resolves
4046 // those names dynamically.
4047 if resolved_here && frame_index == self.frames.len() - 1 {
4048 continue;
4049 }
4050 let frame = &self.frames[frame_index];
4051 for (index, arg) in frame.code.code.args.iter().enumerate() {
4052 bindings.push(EvalBinding {
4053 name: arg.name.clone(),
4054 frame: frame_index,
4055 slot: EvalSlot::Arg,
4056 index,
4057 });
4058 }
4059 for (index, local) in frame.code.code.vars.iter().enumerate() {
4060 bindings.push(EvalBinding {
4061 name: local.name.clone(),
4062 frame: frame_index,
4063 slot: EvalSlot::Local,
4064 index,
4065 });
4066 }
4067 }
4068 let mut seen = BTreeSet::new();
4069 bindings.retain(|binding| seen.insert(binding.name.clone()));
4070
4071 // The caller's `arguments`, as an array-like. Reading `length` and the indexed
4072 // elements is all the spec's ordinary uses need.
4073 //
4074 // Known divergence: this is bound for a *global* eval too, where there is no
4075 // caller and the reference throws `'arguments' is not defined`. Deciding properly
4076 // needs "does the calling frame have an `arguments` of its own", which is not
4077 // recorded anywhere the runtime can see — the caller of a direct eval has one, a
4078 // script or eval body does not, and `eval(b)` passes the callee as a value so even
4079 // the call-site detection does not answer it. Modelled as a binding in the caller's
4080 // variable environment, this would fall out; that is a larger change than the one
4081 // this comment is attached to.
4082 let arguments = Value::Object(self.new_array(passed));
4083
4084 // Only a *strict* eval gets a variable environment of its own. A sloppy one
4085 // declares its `var`s in the caller's — which for a top-level eval is the global
4086 // object, so `eval("var gv=1")` leaves `gv` globally visible. Deciding this on
4087 // strictness alone is the spec's rule; getting it wrong made every sloppy `var`
4088 // vanish into a scope nobody reads back from.
4089 let previous_scope = if code_strict {
4090 self.eval_scope.replace(BTreeMap::new())
4091 } else {
4092 None
4093 };
4094 let previous_arguments = self.eval_arguments.replace(arguments);
4095 let previous_with = self.eval_with.replace(self.with_objects());
4096 let inherited_new_target = self
4097 .frames
4098 .iter()
4099 .rev()
4100 .find(|frame| !frame.code.code.is_arrow)
4101 .map(|frame| frame.new_target.clone());
4102 let previous_new_target = self
4103 .eval_new_target
4104 .replace(inherited_new_target.unwrap_or(Value::Undefined));
4105 let eval_cells = self.eval_cells_for(&bindings);
4106 let previous_bindings = std::mem::replace(&mut self.eval_bindings, bindings);
4107 // A sloppy direct eval declares its `var`s in the caller's variable environment;
4108 // `declare_eval_local` needs to know which frame that is.
4109 // An indirect eval gets the global environment, so nothing of the caller's is
4110 // recorded as the place its `var`s belong.
4111 let previous_caller = self
4112 .eval_caller
4113 .replace(if direct { env_index } else { None });
4114 // The cell-based view of the same bindings, which is what a closure created
4115 // inside the eval keeps. Only cell-backed bindings can be shared, so a frame
4116 // whose compiler did not put a binding in a cell simply does not appear here —
4117 // reads and writes still work through `eval_bindings`, they just cannot outlive
4118 // the eval.
4119 let previous_eval_scope = self
4120 .active_eval_scope
4121 .replace(Gc::new(self.heap, EvalScope { names: eval_cells }));
4122 let compiled = Gc::new(self.heap, CompiledCode::new(code));
4123 let closure_vars = compiled.code.closure_vars.clone();
4124 let env = self.global_env(&closure_vars);
4125 let callee = Value::Undefined;
4126 // An async body does not run here: it becomes a coroutine and answers a promise,
4127 // which is what makes `await` legal in it. `this` still has to be the caller's
4128 // (for a global eval, the global object), because `this` is not part of `await`.
4129 let result = if compiled.code.kind.is_async() {
4130 self.run_async_body(compiled, env, this)
4131 } else {
4132 self.execute(compiled, env, this, Vec::new(), callee)
4133 };
4134 self.eval_scope = previous_scope;
4135 self.eval_arguments = previous_arguments;
4136 self.eval_with = previous_with;
4137 self.eval_new_target = previous_new_target;
4138 self.eval_bindings = previous_bindings;
4139 self.eval_caller = previous_caller;
4140 self.active_eval_scope = previous_eval_scope;
4141 result
4142 }
4143
4144 /// The cell-backed subset of `bindings`, in the same priority order.
4145 ///
4146 /// Both lookup routes have to agree — the eval's own reads go through
4147 /// [`Interp::eval_binding_value`] and the closures it builds go through
4148 /// [`ClosureEnv::eval_scope`] — so they are derived from one resolution rather than
4149 /// scanning the frames twice and disagreeing about a shadowed name. A binding that
4150 /// is not in a cell simply does not appear: reads and writes still work, they just
4151 /// cannot be handed to a closure that outlives the eval.
4152 fn eval_cells_for(&self, bindings: &[EvalBinding]) -> Vec<(String, Gc<Cell>)> {
4153 let mut names: Vec<(String, Gc<Cell>)> = Vec::new();
4154 for binding in bindings {
4155 let Some(frame) = self.frames.get(binding.frame) else {
4156 continue;
4157 };
4158 let cell = match binding.slot {
4159 EvalSlot::Arg => frame
4160 .code
4161 .arg_cell
4162 .get(binding.index)
4163 .copied()
4164 .unwrap_or(-1),
4165 EvalSlot::Local => frame
4166 .code
4167 .loc_cell
4168 .get(binding.index)
4169 .copied()
4170 .unwrap_or(-1),
4171 };
4172 if cell < 0 {
4173 continue;
4174 }
4175 if let Some(cell) = frame.cells.get(cell as usize) {
4176 names.push((binding.name.clone(), cell.clone()));
4177 }
4178 }
4179 names
4180 }
4181
4182 /// A `SyntaxError` that reports where in the source it happened.
4183 ///
4184 /// Compile-time failures never run, so they have no frame of their own; the
4185 /// reference still puts the position first in the trace, with no function name and
4186 /// no parentheses, and the caller's frames after it. It also defines `fileName`,
4187 /// `lineNumber` and `columnNumber` on the object (a SpiderMonkey convention the
4188 /// reference borrows), which is how a script reads the position without parsing
4189 /// the trace.
4190 /// A `SyntaxError` object for a `js_parse`/`js_compile` failure.
4191 ///
4192 /// The message is bare and the position goes on `stack`/`fileName`/`lineNumber`/
4193 /// `columnNumber`, which is how the reference prints one. A positionless error
4194 /// (`SyntaxError::positionless`) gets neither the trace line nor the position fields —
4195 /// the reference raises it from `js_resolve_module`, where there is no position.
4196 pub(crate) fn syntax_error_plain(
4197 &mut self,
4198 error: &js_parse::SyntaxError,
4199 file: &str,
4200 ) -> Value {
4201 if error.positionless {
4202 return self.make_error("SyntaxError", &error.message);
4203 }
4204 self.syntax_error_at(
4205 file,
4206 error.span.start.line,
4207 error.span.start.column,
4208 &error.message,
4209 )
4210 }
4211
4212 fn syntax_error_at(&mut self, file: &str, line: u32, column: u32, message: &str) -> Value {
4213 let blamed = format!(" at {file}:{line}:{column}\n{}", self.stack_trace());
4214 let value = self.make_error("SyntaxError", message);
4215 if let Value::Object(object) = &value {
4216 let text = self.string(blamed);
4217 // `stack` is an own data property, and the reference keeps it
4218 // non-enumerable so it does not leak into `Object.keys`/`JSON.stringify`.
4219 object.define("stack", Property::with_attributes(text, true, false));
4220 let name = self.string(file);
4221 object.define("fileName", Property::with_attributes(name, true, true));
4222 object.define(
4223 "lineNumber",
4224 Property::with_attributes(Value::Int(line as i32), true, true),
4225 );
4226 object.define(
4227 "columnNumber",
4228 Property::with_attributes(Value::Int(column as i32), true, true),
4229 );
4230 }
4231 value
4232 }
4233
4234 /// Run a compiled script whose completion value is a function, returning it.
4235 ///
4236 /// `new Function(...)` compiles `(function(params) { body })` and this runs it to
4237 /// get the closure out, which keeps the constant-pool plumbing in one place.
4238 pub fn run_function_source(&mut self, code: CompiledFunction) -> JsResult<Value> {
4239 self.run_script(code)
4240 }
4241
4242 /// The environment of a script or of any function compiled at global scope:
4243 /// every entry is a global binding, so each one resolves to the realm's cell.
4244 fn global_env(&mut self, closure_vars: &[js_compile::bytecode::ClosureVar]) -> Gc<ClosureEnv> {
4245 let mut cells = Vec::with_capacity(closure_vars.len());
4246 for closure_var in closure_vars {
4247 let cell = match closure_var.closure_type {
4248 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport
4249 if closure_var.is_lexical =>
4250 {
4251 // A lexical declaration: the cell is created here holding the
4252 // dead-zone marker, which is what makes the binding exist and
4253 // unreadable before its initialiser runs.
4254 self.declare_global(&closure_var.name, closure_var.is_const);
4255 self.realm.globals[&closure_var.name].clone()
4256 }
4257 ClosureType::GlobalDecl | ClosureType::ModuleDecl | ClosureType::ModuleImport => {
4258 // A `var` or function declaration becomes a property of the global
4259 // object, and it exists from here on — which is why
4260 // `print(v); var v = 1` prints `undefined` instead of raising.
4261 // Declaring it at instantiation time (rather than at the
4262 // initialiser) is also what makes it non-configurable: the store
4263 // then lands on an existing property instead of creating one.
4264 self.declare_var_global(&closure_var.name);
4265 // The cell is a placeholder that nothing indexes; it cannot be
4266 // omitted because the slot has to hold something.
4267 self.new_cell(Value::Undefined)
4268 }
4269 _ => {
4270 // An undeclared global is read by name; the cell is a
4271 // placeholder that nothing indexes.
4272 self.new_cell(Value::Undefined)
4273 }
4274 };
4275 cells.push(cell);
4276 }
4277 Gc::new(
4278 self.heap,
4279 ClosureEnv {
4280 cells,
4281 eval_scope: None,
4282 local_vars: None,
4283 local_phase: 1,
4284 },
4285 )
4286 }
4287
4288 /// Push a frame and run until it returns.
4289 pub(crate) fn execute(
4290 &mut self,
4291 code: Gc<CompiledCode>,
4292 env: Gc<ClosureEnv>,
4293 this: Value,
4294 args: Vec<Value>,
4295 callee: Value,
4296 ) -> JsResult<Value> {
4297 let depth = self.frames.len();
4298 if depth == 0 {
4299 // A throw that reached the host ends the *active* mode: the next one is catchable
4300 // again. The standing request (`uncatchable_next`) is deliberately untouched — a
4301 // host that calls `JS_SetUncatchableException(true)` and then `JS_Eval` is asking
4302 // for the throw that evaluation will raise.
4303 self.uncatchable = false;
4304 }
4305 self.push_frame(code, env, this, args, callee)?;
4306 loop {
4307 // The fast loop first: it runs whole runs of records with `pc` in a register.
4308 //
4309 // `step`'s `pc` lives in the frame, so every instruction writes it back and
4310 // reads it again — a store, a load and two bounds checks that a loop body does
4311 // not need, because nothing outside the loop can run in between. This is the
4312 // classic split: advance a register, and only spill it when leaving.
4313 //
4314 // `Some(value)` means the function ended by running off the end of its
4315 // instruction array, which is a normal return.
4316 let step = match self.run_fast() {
4317 Ok(Some(value)) => Ok(Step::Return(value)),
4318 Ok(None) => self.step(),
4319 Err(signal) => Err(signal),
4320 };
4321 match step {
4322 Ok(Step::Continue) => {}
4323 Ok(Step::Return(value)) => {
4324 self.pop_frame();
4325 // A frame that ended in a `tail_call` hands its value straight to
4326 // its caller: nothing after the call can run, so every frame above
4327 // the callee unwinds with the same value. See [`Frame::tail`] —
4328 // the reference does not reuse frames either, so recursion depth
4329 // and the stack-overflow limit behave the same way.
4330 while self.frames.len() > depth && self.frame().tail {
4331 self.pop_frame();
4332 }
4333 if self.frames.len() == depth {
4334 return Ok(value);
4335 }
4336 // The caller resumes with the value on its stack.
4337 self.frames
4338 .last_mut()
4339 .expect("a caller is live")
4340 .stack
4341 .push(value);
4342 }
4343 Err(Signal::Throw(value)) => {
4344 // The host's standing request becomes the active mode for this unwind,
4345 // and is consumed here so it does not leak into the next throw.
4346 if self.uncatchable_next {
4347 self.uncatchable_next = false;
4348 self.uncatchable = true;
4349 }
4350 // An uncatchable throw walks past every `catch` on the way out. The
4351 // frames are still popped, because the values they hold have to be
4352 // dropped — only the search for a handler is skipped.
4353 if self.uncatchable {
4354 while self.frames.len() > depth {
4355 self.frames.pop();
4356 }
4357 return Err(Signal::Throw(value));
4358 }
4359 // A handler lives on the stack of the frame that is throwing —
4360 // `catch` pushed it there — so this frame gets the first chance
4361 // to catch before it is popped.
4362 let value = value;
4363 loop {
4364 if self.frames.len() <= depth {
4365 return Err(Signal::Throw(value));
4366 }
4367 if self.catch_here(value.clone()).is_some() {
4368 break;
4369 }
4370 self.frames.pop();
4371 }
4372 }
4373 // A `yield` in a frame that `execute` is running directly means a
4374 // generator body was entered as an ordinary call, which only happens if
4375 // the generator check in `call_or_push` was bypassed.
4376 Ok(Step::Suspend(_)) => {
4377 return Err(Signal::Throw(self.make_error(
4378 "InternalError",
4379 "a generator body ran as an ordinary call",
4380 )));
4381 }
4382 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
4383 }
4384 }
4385 }
4386
4387 /// Install a handler for `value` if this frame has one, resuming at it.
4388 ///
4389 /// The scan is the reference's: walk the frame's stack downwards looking for the
4390 /// innermost [`Value::CatchOffset`], discarding whatever sat above it. Offset
4391 /// `0` is an enumerator marker rather than a handler — it exists so that a
4392 /// `break` out of a `for-of` can find and close the iterator — so it is skipped
4393 /// here and the unwinding continues.
4394 fn catch_here(&mut self, value: Value) -> Option<()> {
4395 let frame = self.frames.last_mut()?;
4396 while let Some(top) = frame.stack.pop() {
4397 if let Value::CatchOffset(offset) = top {
4398 if offset == 0 {
4399 continue;
4400 }
4401 frame.stack.push(value);
4402 frame.pc = offset as usize;
4403 return Some(());
4404 }
4405 }
4406 None
4407 }
4408
4409 fn push_frame(
4410 &mut self,
4411 code: Gc<CompiledCode>,
4412 env: Gc<ClosureEnv>,
4413 this: Value,
4414 mut args: Vec<Value>,
4415 callee: Value,
4416 ) -> JsResult<()> {
4417 // Two bounds, and the byte budget is the one that decides in practice. The
4418 // reference's message is `stack overflow` on an `InternalError`, not V8's
4419 // `Maximum call stack size exceeded` on a *string* — the difference is visible:
4420 // a script may `catch (e) { e.name }` and only the former answers `InternalError`.
4421 let frame_cost = Self::frame_cost(&code);
4422 let stack_base = self.stack_used();
4423 if self.frames.len() >= self.max_frames
4424 || stack_base.saturating_add(frame_cost) > self.stack_limit
4425 {
4426 return Err(Signal::Throw(
4427 self.make_error("InternalError", "stack overflow"),
4428 ));
4429 }
4430 let arg_count = code.code.args.len();
4431 // How many were actually passed, which `arguments.length` reports and
4432 // `assert(x)` depends on: a call with one argument must not look like a call
4433 // with one argument and an explicit `undefined`.
4434 let passed = args.len();
4435 // Missing arguments are `undefined` in their slots; extra ones are dropped
4436 // from the slots but still reachable through `arguments`.
4437 //
4438 // A call that passes no more than the declared parameters needs **no** copy:
4439 // after the resize below, `args[..passed]` *is* the passed values. Only the
4440 // extra ones — which `truncate` is about to drop — have to be kept, and they are
4441 // the rare case. This used to copy every call: one `Value` clone per argument
4442 // into a recycled buffer, 11.6% of `property:method-call` in the `memmove`.
4443 let passed_overflow = (passed > arg_count).then(|| {
4444 let mut values = self.take_values(passed, Value::Undefined);
4445 values[..passed].clone_from_slice(&args[..passed]);
4446 values
4447 });
4448 // Only when the counts differ, which for the overwhelmingly common call — as many
4449 // arguments as parameters — is never. `resize` followed by `truncate` on equal
4450 // lengths is two length compares and nothing else, but this is the hottest few
4451 // instructions in the engine: `call:recursion` executes it twice per `fib` step.
4452 if passed != arg_count {
4453 args.resize(arg_count, Value::Undefined);
4454 args.truncate(arg_count);
4455 }
4456 let cell_count = code.code.var_ref_count as usize;
4457 let mut cells = Vec::with_capacity(cell_count);
4458 for _ in 0..cell_count {
4459 cells.push(self.new_cell(Value::Undefined));
4460 }
4461 let locals = self.take_values(code.code.vars.len(), Value::Undefined);
4462 // A captured argument lives in its cell, not in the argument slot, so the
4463 // incoming value has to be moved there before the body runs.
4464 for (slot, cell) in code.arg_cell.iter().enumerate() {
4465 if *cell >= 0
4466 && let Some(value) = args.get(slot).cloned()
4467 {
4468 cells[*cell as usize].set(value);
4469 }
4470 }
4471 // Sloppy mode substitutes the global object for a missing receiver and boxes a
4472 // primitive one, so `function f(){ return typeof this }` called as `f.call(1)`
4473 // reports `object`. Strict mode passes the value through untouched.
4474 let this = if code.code.strict {
4475 this
4476 } else if this.is_nullish() {
4477 Value::Object(self.realm.global.clone())
4478 } else if matches!(this, Value::Object(_)) {
4479 this
4480 } else {
4481 match crate::builtins::this_object(self, &this) {
4482 Ok(boxed) => Value::Object(boxed),
4483 Err(_) => this,
4484 }
4485 };
4486 let stack_depth = code.code.stack_size as usize + 1;
4487 // Taken before the `push` borrows `self.frames`, because the operand stack comes
4488 // out of the same recycle pool the locals did.
4489 let stack = self.take_values(stack_depth, Value::Undefined);
4490 self.frames.push(Frame {
4491 code,
4492 env,
4493 this,
4494 args,
4495 passed_count: passed,
4496 passed_overflow: passed_overflow.map(Box::new),
4497 locals,
4498 cells,
4499 local_vars: None,
4500 // Exactly the depth the compiler computed, so the operand stack never
4501 // reallocates. (`16` was an arbitrary guess, and a loop that pushed more than
4502 // that reallocated on its way in — a malloc per call.) The recycle pool keeps
4503 // the buffer between calls, so "exactly" costs nothing after the first one.
4504 stack,
4505 pc: 0,
4506 at: 0,
4507 callee,
4508 new_target: self.pending_new_target.take().unwrap_or(Value::Undefined),
4509 cost: frame_cost,
4510 stack_base,
4511 tail: false,
4512 });
4513 Ok(())
4514 }
4515
4516 /// A value buffer of `len` slots, from the recycle pool when there is one.
4517 ///
4518 /// `clear` then `resize` reuses the capacity, so a warm pool allocates nothing.
4519 fn take_values(&mut self, len: usize, fill: Value) -> Vec<Value> {
4520 // A frame with no locals asks for nothing, and that is most frames: taking a
4521 // buffer out of the pool, clearing it and resizing it to zero is four operations
4522 // and a pool pop for an empty `Vec`, which is free to construct.
4523 if len == 0 {
4524 return Vec::new();
4525 }
4526 let mut buffer = self.free_values.pop().unwrap_or_default();
4527 buffer.clear();
4528 buffer.resize(len, fill);
4529 buffer
4530 }
4531
4532 /// Return a finished frame's value buffers for the next call to reuse.
4533 fn recycle(free_values: &mut Vec<Vec<Value>>, frame: &mut Frame) {
4534 for mut buffer in [
4535 std::mem::take(&mut frame.locals),
4536 frame
4537 .passed_overflow
4538 .take()
4539 .map(|buffer| *buffer)
4540 .unwrap_or_default(),
4541 std::mem::take(&mut frame.stack),
4542 ] {
4543 // **Empty it here, not when it is reused.** A holding buffer in the pool is a
4544 // GC root: it kept every value the frame held reachable, which is invisible
4545 // until a `WeakRef` or a `FinalizationRegistry` callback fails to fire. The
4546 // `finalization_registry_runs_its_callback_at_a_safe_point` test caught
4547 // exactly that within one run — the target `{}` of a finished IIFE was still
4548 // in its operand stack, in the pool.
4549 buffer.clear();
4550 // A buffer with no capacity is what `Vec::new` is; putting it back would just
4551 // fill the pool with nothing to offer.
4552 if free_values.len() < RECYCLE_SLOTS
4553 && buffer.capacity() > 0
4554 && buffer.capacity() <= RECYCLE_MAX_CAPACITY
4555 {
4556 free_values.push(buffer);
4557 }
4558 }
4559 }
4560
4561 /// Pop a finished frame and keep its buffers.
4562 ///
4563 /// Every place that drops a frame goes through here: a recycled buffer is also where
4564 /// the values it held are dropped (`clear` runs the drops), so skipping this loses
4565 /// nothing but the reuse.
4566 fn pop_frame(&mut self) -> Option<()> {
4567 // PROBE: 原地回收再 truncate。`Vec::pop` 会把 224 字节的 `Frame` 整个搬到栈上
4568 // 就为了取三个 `Vec` 缓冲;`truncate` 在原地 drop,一次搬运都没有。
4569 let last = self.frames.len().checked_sub(1)?;
4570 Self::recycle(&mut self.free_values, &mut self.frames[last]);
4571 self.frames.truncate(last);
4572 Some(())
4573 }
4574
4575 /// Poll the host's interrupt handler, if one is installed.
4576 ///
4577 /// The counter is what keeps this off the hot path when nobody asked: the early return is
4578 /// one `Option` test, and with no handler installed the whole function is that test —
4579 /// `check_memory` next door already costs more, so this cannot be what shows up in a
4580 /// benchmark. [`bench.sh`]'s checksums would have caught it if it were.
4581 #[inline]
4582 fn check_interrupt(&mut self) -> JsResult<()> {
4583 if self.interrupt.is_none() {
4584 return Ok(());
4585 }
4586 if self.interrupt_counter > 0 {
4587 self.interrupt_counter -= 1;
4588 return Ok(());
4589 }
4590 self.interrupt_counter = INTERRUPT_POLL_INTERVAL;
4591 // The closure is taken out for the duration so that a handler which re-enters the
4592 // engine (it should not, but a C callback can do anything) cannot alias the `&mut`.
4593 let mut handler = self.interrupt.take().expect("checked above");
4594 let abort = handler();
4595 self.interrupt = Some(handler);
4596 if abort {
4597 // The reference marks this one uncatchable (`JS_ThrowInterrupted` calls
4598 // `JS_SetUncatchableException`), so a script cannot keep the host's abort from
4599 // landing. Doing the same is what makes `JS_SetInterruptHandler` mean what its
4600 // documentation says.
4601 self.uncatchable = true;
4602 return Err(Signal::Throw(
4603 self.make_error("InternalError", "interrupted"),
4604 ));
4605 }
4606 Ok(())
4607 }
4608
4609 /// A memory checkpoint: does the heap still fit under its limit?
4610 ///
4611 /// Called once per instruction (see [`Interp::step`]). The cost when no limit is set is
4612 /// a `Cell` read and a predictable branch, and the point of asking that often is that
4613 /// `var a = []; for (;;) a.push({})` allocates one object per iteration — a checkpoint
4614 /// only at calls would let it run until the machine died, which is the exact failure
4615 /// `--memory-limit` exists to prevent.
4616 ///
4617 /// The failure is a thrown `InternalError`, not a `Signal::OutOfMemory`, because the
4618 /// reference's `js_throw_out_of_memory` produces a catchable exception — and because a
4619 /// script that catches it, drops the reference and carries on is legitimate: measured
4620 /// on `qjs --memory-limit 1M`, the engine recovers.
4621 fn check_memory(&mut self) -> JsResult<()> {
4622 // One `Cell` read and a predictable branch when no limit is set, and an integer
4623 // compare when one is. Containers report their own growth as it happens
4624 // (`Heap::adjust_payload`), so this total is up to date without walking the heap —
4625 // walking it here was the first version and it was O(live) per 256 instructions,
4626 // which turned a 100k-element push loop into a five-minute one.
4627 let Some(limit) = self.heap.memory_limit() else {
4628 return Ok(());
4629 };
4630 let used = self.heap.used_bytes();
4631 if used <= limit {
4632 // Back under the limit — a collection or a dropped reference did it. The next
4633 // time it goes over is a new failure, not a repeat of this one.
4634 self.oom_reported_at = 0;
4635 return Ok(());
4636 }
4637 // Only complain about *growth*. The reference fails in `js_malloc`, so a `catch`
4638 // block runs normally after `out of memory` — it allocates nothing, so nothing
4639 // fails. A check that re-fired on every instruction made the handler itself throw,
4640 // which is a dead end: the error became unobservable from script.
4641 //
4642 // Comparing against the total at the last report gives the same behaviour: the
4643 // handler runs while the total is unchanged, and the very next allocation over the
4644 // limit fails.
4645 if self.oom_reported_at != 0 && used <= self.oom_reported_at.saturating_add(OOM_HYSTERESIS)
4646 {
4647 return Ok(());
4648 }
4649 self.oom_reported_at = used;
4650 Err(Signal::Throw(
4651 self.make_error("InternalError", "out of memory"),
4652 ))
4653 }
4654
4655 /// Fail before allocating `payload` bytes, if they would not fit.
4656 ///
4657 /// For the allocations whose size comes from script data — `new Array(n)`,
4658 /// `'x'.repeat(n)`, `new Uint8Array(n)` — a checkpoint is too late: the request itself
4659 /// is what takes the machine down. The reference has the same shape, with `js_malloc`
4660 /// answering NULL for the one big request.
4661 pub fn reserve(&mut self, payload: usize) -> JsResult<()> {
4662 if self.heap.fits(payload) {
4663 return Ok(());
4664 }
4665 Err(Signal::Throw(
4666 self.make_error("InternalError", "out of memory"),
4667 ))
4668 }
4669
4670 /// Bytes of frame state the live call chain accounts for.
4671 pub fn stack_used(&self) -> usize {
4672 match self.frames.last() {
4673 Some(frame) => frame.stack_base + frame.cost,
4674 None => 0,
4675 }
4676 }
4677
4678 /// What one frame of `code` costs: the frame itself plus the slots it allocates.
4679 ///
4680 /// The slot formula is the reference's `alloca_size` (`sizeof(JSValue) * (arg_count +
4681 /// var_count + stack_size) + sizeof(JSVarRef*) * var_ref_count`), plus
4682 /// `size_of::<Frame>()`, which is the part the reference pays as a C stack frame
4683 /// instead. That is the whole difference between the two models: it rations C stack, we
4684 /// ration frame state, and both quantities are dominated by the value slots — which is
4685 /// why the two depths come out comparable rather than merely proportional.
4686 fn frame_cost(code: &CompiledCode) -> usize {
4687 let slots = code.code.args.len() + code.code.vars.len() + code.code.stack_size as usize;
4688 std::mem::size_of::<Frame>()
4689 + std::mem::size_of::<Value>() * slots
4690 + std::mem::size_of::<usize>() * code.code.var_ref_count as usize
4691 }
4692
4693 /// The cell a direct `eval` created for the closure entry at `slot`, if any.
4694 ///
4695 /// Only names the eval created are here: a name the frame already declared statically
4696 /// is written through to its own slot instead, so this cannot shadow a real local.
4697 fn eval_created_local(&self, slot: usize) -> Option<Gc<Cell>> {
4698 let name = &self.frame().code.code.closure_vars.get(slot)?.name;
4699 let (local_vars, phase) = self.visible_local_vars()?;
4700 if !local_vars.contains(name) {
4701 return None;
4702 }
4703 local_vars.get(name, phase)
4704 }
4705
4706 /// The variables a direct `eval` declared, as the code currently running sees them.
4707 ///
4708 /// Inside an eval that is the *caller's* set — the eval's own variable environment
4709 /// is the caller's, which is why `eval("var c = 1")` leaves `c` behind. Everywhere
4710 /// else it is the current frame's, falling back to the frame the closure was created
4711 /// in.
4712 /// Whether [`Self::visible_local_vars`] would find any, without building the handle.
4713 ///
4714 /// The only caller that does not need the `LocalVars` itself is `scopes_are_plain`,
4715 /// which runs on every global read — and the `Option` it was handed cost two `Gc`
4716 /// refcount operations (the clone out of the frame, the drop at the end of the match)
4717 /// just to be asked `is_none`.
4718 fn has_visible_local_vars(&self) -> bool {
4719 let index = match self.eval_caller.flatten() {
4720 Some(caller) => caller,
4721 None => match self.frames.len().checked_sub(1) {
4722 Some(top) => top,
4723 None => return false,
4724 },
4725 };
4726 match self.frames.get(index) {
4727 Some(frame) => frame.local_vars.is_some() || frame.env.local_vars.is_some(),
4728 None => false,
4729 }
4730 }
4731
4732 fn visible_local_vars(&self) -> Option<(Gc<LocalVars>, u8)> {
4733 // While an `eval` runs, its own frame is on top but its variable environment is
4734 // the *caller's* — so the caller is what the lookup has to start from.
4735 let (index, phase) = match self.eval_caller.flatten() {
4736 Some(caller) => (
4737 caller,
4738 if self.in_parameter_list_at(caller) {
4739 0
4740 } else {
4741 1
4742 },
4743 ),
4744 None => (
4745 self.frames.len().checked_sub(1)?,
4746 if self.in_parameter_list() { 0 } else { 1 },
4747 ),
4748 };
4749 let frame = self.frames.get(index)?;
4750 // The frame's own variables, or — for an arrow, which has no variable environment
4751 // of its own — the one it was created in, which `ClosureEnv` carries.
4752 if let Some(local_vars) = frame.local_vars.clone() {
4753 return Some((local_vars, phase));
4754 }
4755 frame
4756 .env
4757 .local_vars
4758 .clone()
4759 .map(|local_vars| (local_vars, frame.env.local_phase))
4760 }
4761
4762 /// Whether the innermost frame is still evaluating its parameter list.
4763 ///
4764 /// A direct `eval` that runs there declares its `var`s in the parameter environment,
4765 /// and a closure created there may only see that much of [`LocalVars`].
4766 fn in_parameter_list(&self) -> bool {
4767 self.in_parameter_list_at(self.frames.len().saturating_sub(1))
4768 }
4769
4770 /// [`Interp::in_parameter_list`] for a specific frame.
4771 fn in_parameter_list_at(&self, frame: usize) -> bool {
4772 let Some(frame) = self.frames.get(frame) else {
4773 return false;
4774 };
4775 let code = &frame.code.code;
4776 if !code.has_parameter_expressions {
4777 return false;
4778 }
4779 // `(0, 0)` means the compiler did not record a boundary, so treat the whole
4780 // function as its body and let a direct `eval` act accordingly.
4781 if code.body_start == (0, 0) {
4782 return false;
4783 }
4784 match code.position_at(frame.at as u32) {
4785 Some(position) => position < code.body_start,
4786 None => false,
4787 }
4788 }
4789
4790 fn frame(&self) -> &Frame {
4791 self.frames.last().expect("a frame is live")
4792 }
4793
4794 fn frame_mut(&mut self) -> &mut Frame {
4795 self.frames.last_mut().expect("a frame is live")
4796 }
4797
4798 // -- slot access --------------------------------------------------------
4799
4800 /// Move a local's value out, leaving `undefined` in the slot.
4801 ///
4802 /// `None` for a captured slot: its value lives in a cell shared with every closure
4803 /// that closed over it, so it can never be exclusively ours and must not be taken.
4804 ///
4805 /// Taking the value is what makes it uniquely owned. `get_loc` clones, which is right
4806 /// for every read and fatal for this one — a clone is exactly the second handle that
4807 /// rules out growing the string in place.
4808 fn take_loc(&mut self, slot: usize) -> Option<Value> {
4809 let frame = self.frames.last_mut()?;
4810 if frame.code.loc_cell.get(slot).copied().unwrap_or(-1) != -1 {
4811 return None;
4812 }
4813 frame
4814 .locals
4815 .get_mut(slot)
4816 .map(|value| std::mem::replace(value, Value::Undefined))
4817 }
4818
4819 /// `x += y` for the fused forms: append in place when `x` is the sole owner of its
4820 /// bytes, otherwise do the ordinary `get_loc`/`add`/`put_loc` sequence.
4821 ///
4822 /// The fallback is reached with the slot **exactly as the unfused bytecode would leave
4823 /// it** — the value is put back before the general path runs — so a `valueOf` that
4824 /// throws, or a `ToString` that rejects a symbol, sees the same state and the same
4825 /// error as it would have without the fusion. This is why the in-place attempt is a
4826 /// `take` and not a `get`: an optimisation that changes what an exception observes is
4827 /// a wrong answer with a good excuse.
4828 fn add_into_loc(&mut self, slot: usize, right: Value) -> JsResult<()> {
4829 // The take is `matches!`-guarded on the *right* operand only, and the taken value
4830 // is put back on every path that does not append. An earlier version wrote the two
4831 // conditions as one `if let` chain — `if right is a string && let Some(Value::String
4832 // (left)) = self.take_loc(slot)` — and a slot holding `5` when `x += "a"` ran fell
4833 // through with its value already taken and dropped: the general path below then
4834 // read the `undefined` left behind and answered `"undefineda"` instead of `"5a"`.
4835 // A wrong answer, from an optimisation, with every test green.
4836 if matches!(right, Value::String(_))
4837 && let Some(taken) = self.take_loc(slot)
4838 {
4839 if let Value::String(mut left) = taken {
4840 let appended = match left.get_mut() {
4841 Some(string) => string.append_in_place(
4842 // The pattern is the one `matches!` just checked.
4843 match &right {
4844 Value::String(text) => text,
4845 _ => unreachable!("guarded above"),
4846 },
4847 ),
4848 None => None,
4849 };
4850 self.put_loc(slot, Value::String(left));
4851 if let Some(added) = appended {
4852 // The buffer grew where it stood, so the heap's running total has to
4853 // be told: `measure_used` would report the new length, and the two must
4854 // agree or the subtraction at free time leaves the counter wrong.
4855 self.heap.adjust_payload(added as isize);
4856 return Ok(());
4857 }
4858 } else {
4859 self.put_loc(slot, taken);
4860 }
4861 }
4862 // The two-number case, without an operand stack round trip. Everything below
4863 // this point is the *general* path: push both, call `binary_add`, pop the answer,
4864 // store it — five operations and two `Value` clones for what is one integer add.
4865 // `AddImmLoc` already answers this shape that way; the fusion above it was written
4866 // for string append and never got the numeric half, so `t += i` — a counting loop
4867 // — was paying more than the unfused `get_loc; get_loc; add; put_loc` it replaced.
4868 let left = self.get_loc(slot);
4869 if let (Value::Int(a), Value::Int(b)) = (&left, &right) {
4870 self.put_loc(
4871 slot,
4872 match a.checked_add(*b) {
4873 Some(sum) => Value::Int(sum),
4874 None => Value::Float(*a as f64 + *b as f64),
4875 },
4876 );
4877 return Ok(());
4878 }
4879 self.push(left);
4880 self.push(right);
4881 self.binary_add()?;
4882 let value = self.pop();
4883 self.put_loc(slot, value);
4884 Ok(())
4885 }
4886
4887 fn get_arg(&self, slot: usize) -> Value {
4888 self.frame().read_arg(slot)
4889 }
4890
4891 fn put_arg(&mut self, slot: usize, value: Value) {
4892 let cell = self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1);
4893 if cell == -1 {
4894 if let Some(slot) = self.frame_mut().args.get_mut(slot) {
4895 *slot = value;
4896 }
4897 } else {
4898 self.frame().cells[cell as usize].set(value);
4899 }
4900 }
4901
4902 fn get_loc(&self, slot: usize) -> Value {
4903 // The cell mapping is `-1` for every slot that was not captured — which is all of
4904 // them in a function that creates no closure. `Frame::read_loc` tests that first,
4905 // so the common case is one array read and a clone: 20% of every loop iteration
4906 // used to go through a helper call for it (`get_loc` 10.8% + `read_slot` 6.4% in a
4907 // sample of `dispatch:arith`).
4908 self.frame().read_loc(slot)
4909 }
4910
4911 fn put_loc(&mut self, slot: usize, value: Value) {
4912 // One borrow instead of three, and the cell check on the frame we already hold.
4913 let frame = self.frames.last_mut().expect("a frame is live");
4914 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
4915 if cell < 0 {
4916 if let Some(slot) = frame.locals.get_mut(slot) {
4917 *slot = value;
4918 }
4919 } else if let Some(cell) = frame.cells.get(cell as usize) {
4920 cell.set(value);
4921 }
4922 }
4923
4924 // -- globals ------------------------------------------------------------
4925
4926 /// The name a global-slot operand refers to.
4927 fn global_name(&self, slot: usize) -> String {
4928 self.frame()
4929 .code
4930 .code
4931 .closure_vars
4932 .get(slot)
4933 .map(|c| c.name.clone())
4934 .unwrap_or_default()
4935 }
4936
4937 /// The facts about a global binding that decide where it lives.
4938 ///
4939 /// A script's globals split in two, and the split is observable: `var` and
4940 /// function declarations become properties of the global object (`globalThis.v`
4941 /// works, `delete` refuses, `for-in` lists them), while `let`/`const`/`class`
4942 /// declarations live in the global *lexical* environment and are invisible there
4943 /// (`"c" in globalThis` is false). Keeping the difference in the closure var's
4944 /// `is_lexical` flag means the answer is already in the bytecode.
4945 fn global_binding(&self, slot: usize) -> (String, bool, bool) {
4946 let name = self.global_name(slot);
4947 // "Lexical" is *not* read from the closure var's flag: a `GlobalRef` created
4948 // while forwarding a reference through a nested function is built with the
4949 // flags cleared, so `const c` would look like an ordinary `var` from inside a
4950 // closure. Presence in the realm's lexical table is the same fact, recorded
4951 // once, and every slot sees it.
4952 let lexical = self.realm.globals.contains_key(&name);
4953 let is_const = self.realm.lexical_consts.contains(&name);
4954 (name, lexical, is_const)
4955 }
4956
4957 /// The value of `name` in the innermost active `with` object, if any.
4958 ///
4959 /// The active objects are the [`VarKind::With`] locals of every frame still running,
4960 /// innermost frame first and innermost block first within one. Walking frames rather
4961 /// than keeping a separate stack is what makes a closure called from inside a `with`
4962 /// see it, and what keeps the object alive only as long as the block is.
4963 /// The innermost active `with` object that has `name`, if any.
4964 fn with_owner(&mut self, name: &str) -> Option<Gc<JsObject>> {
4965 let objects = self.eval_with.clone().unwrap_or_default();
4966 for object in objects {
4967 let key = self.string(name.to_string());
4968 if self
4969 .has_property(&key, &Value::Object(object.clone()))
4970 .ok()?
4971 {
4972 return Some(object);
4973 }
4974 }
4975 None
4976 }
4977
4978 /// Every active `with` object, innermost first.
4979 fn with_objects(&self) -> Vec<Gc<JsObject>> {
4980 let mut objects = Vec::new();
4981 for frame in self.frames.iter().rev() {
4982 for (index, var) in frame.code.code.vars.iter().enumerate().rev() {
4983 if var.kind != js_compile::VarKind::With {
4984 continue;
4985 }
4986 // A captured binding lives in its cell and not in the slot list, so the
4987 // cell is consulted first — a closure created inside the block is exactly
4988 // what makes the object captured. Before the store runs the slot still
4989 // holds `undefined`, and a `with` object is always boxed, so a non-object
4990 // entry is simply not in scope yet.
4991 let value = frame
4992 .code
4993 .loc_cell
4994 .get(index)
4995 .copied()
4996 .filter(|cell| *cell >= 0)
4997 .and_then(|cell| frame.cells.get(cell as usize))
4998 .map(|cell| cell.get())
4999 .or_else(|| frame.locals.get(index).cloned());
5000 if let Some(Value::Object(object)) = value {
5001 objects.push(object);
5002 }
5003 }
5004 }
5005 objects
5006 }
5007
5008 fn with_lookup(&mut self, name: &str) -> JsResult<Option<Value>> {
5009 for object in self.eval_with.clone().unwrap_or_default() {
5010 let key = self.string(name.to_string());
5011 if self.has_property(&key, &Value::Object(object.clone()))? {
5012 return Ok(Some(self.read_field(&Value::Object(object), name)?));
5013 }
5014 }
5015 Ok(None)
5016 }
5017
5018 /// Whether every scope between here and the global object is an ordinary one.
5019 ///
5020 /// `eval` and `with` install extra scopes, and each of them may shadow the name the
5021 /// bytecode resolved; when any is live the general path has to run in full order. When
5022 /// none is — every ordinary program — a global read is a property read and nothing
5023 /// else, and that is worth caching.
5024 fn scopes_are_plain(&self) -> bool {
5025 self.eval_caller.is_none()
5026 && self.eval_with.is_none()
5027 && self.eval_arguments.is_none()
5028 && self.eval_bindings.is_empty()
5029 && self.eval_scope.is_none()
5030 // **Not** `frame().local_vars.is_none()`: a closure created inside a frame
5031 // that ran a direct `eval("var z = 1")` inherits the eval's variables through
5032 // its `ClosureEnv`, so the test has to be the same one the general path makes.
5033 // Asking the frame only was a wrong answer — `test_with` lost `z`, which the
5034 // upstream corpus caught and no unit test did.
5035 && !self.has_visible_local_vars()
5036 && self.frame().env.eval_scope.is_none()
5037 }
5038
5039 fn get_global(&mut self, slot: usize) -> JsResult<Value> {
5040 // Borrowed, not copied. `global_binding` builds a `String` for the name, so a
5041 // `get_var` in a loop was one allocation *and* one `HashMap` hash per read — 17.7%
5042 // of `global:read` in `global_binding` plus 4.2% in `malloc`, for a name that sits
5043 // in the code object unchanged. The `Gc` clone is a refcount bump that lets the
5044 // borrow outlive the `&mut self` the lookup needs.
5045 //
5046 // "Lexical" stays the presence test `global_binding` documents — a `GlobalRef`
5047 // forwarded through a nested function has its flags cleared, so the flag cannot
5048 // be believed.
5049 let code = self.frame().code.clone();
5050 let name = code
5051 .code
5052 .closure_vars
5053 .get(slot)
5054 .map(|c| c.name.as_str())
5055 .unwrap_or_default();
5056 let lexical = self.realm.globals.contains_key(name);
5057 // The common case, first: an ordinary global `var`, with a cache in front of the
5058 // prototype walk. Everything below is the `eval`/`with`/lexical ordering, which
5059 // cannot apply when `scopes_are_plain` — and when it does not apply we take the
5060 // cache hit and return without touching any of it.
5061 if !lexical && self.scopes_are_plain() {
5062 return self.get_plain_global(name, slot);
5063 }
5064 if name == "arguments"
5065 && let Some(arguments) = &self.eval_arguments
5066 {
5067 return Ok(arguments.clone());
5068 }
5069 // A `with` block around the *call site* is part of the scope an `eval` sees, so
5070 // the objects live when the eval started are consulted before anything else. The
5071 // snapshot is taken at entry rather than scanning the frames on every read: a
5072 // block that has already finished still leaves its object in the slot, and a
5073 // bytecode read outside the block must not see it.
5074 if let Some(value) = self.with_lookup(name)? {
5075 return Ok(value);
5076 }
5077 // A variable a direct `eval` declared shadows everything the compiler resolved,
5078 // including an enclosing function's binding: the eval put it in the caller's own
5079 // variable environment, which is nearer than any captured scope.
5080 if let Some((local_vars, phase)) = self.visible_local_vars()
5081 && let Some(cell) = local_vars.get(name, phase)
5082 {
5083 return Ok(cell.get());
5084 }
5085 // The frame that called `eval` is the innermost scope the eval'd code sees, so
5086 // its local `a` wins over a global `a`.
5087 if let Some(value) = self.eval_binding_value(name) {
5088 return Ok(value);
5089 }
5090 // A closure created by an `eval` resolves its free names against the bindings
5091 // that eval saw, even after the eval (and its frames) are gone.
5092 if let Some(cell) = self
5093 .frame()
5094 .env
5095 .eval_scope
5096 .as_ref()
5097 .and_then(|scope| scope.get(name))
5098 {
5099 let value = cell.get();
5100 if matches!(value, Value::Uninitialized) {
5101 return Err(self.throw_reference(name));
5102 }
5103 return Ok(value);
5104 }
5105 // A binding declared by the strict `eval` currently running shadows anything
5106 // further out, so `eval("var v = 1")`'s `v` is found before `globalThis.v`.
5107 if let Some(scope) = &self.eval_scope
5108 && let Some(value) = scope.get(name)
5109 {
5110 return Ok(value.clone());
5111 }
5112 if lexical {
5113 // A lexical global is a binding in a side table, so the dead zone is
5114 // visible and it is nowhere on the global object.
5115 if let Some(cell) = self.realm.globals.get(name) {
5116 let value = cell.get();
5117 if matches!(value, Value::Uninitialized) {
5118 return Err(self.throw_reference(name));
5119 }
5120 return Ok(value);
5121 }
5122 return Err(self.throw_reference(name));
5123 }
5124 // A `var` global is an ordinary property, so the prototype chain and the
5125 // global object's own builtins are all reachable through it.
5126 match self.get_property(&self.realm.global.clone(), name)? {
5127 Some(value) => Ok(value),
5128 None => Err(self.throw_reference(name)),
5129 }
5130 }
5131
5132 /// Read a plain global `var`: a cached own data property, or the full lookup.
5133 ///
5134 /// Doing it here rather than inline in [`Interp::get_global`] keeps the ordering
5135 /// — "the cache is only consulted when no `eval`/`with` scope exists" — in one place.
5136 fn get_plain_global(&mut self, name: &str, slot: usize) -> JsResult<Value> {
5137 let object = self.realm.global.clone();
5138 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5139 if let Some(cached) = &self.global_cache[site]
5140 && object.upgrades_to(&cached.object)
5141 && let Some(value) = object.data_property_at(cached.index, name)
5142 {
5143 return Ok(value);
5144 }
5145 // A miss: the global is inherited, or is an accessor, or the table moved. Walk the
5146 // chain exactly as before, then remember the answer if it is worth remembering.
5147 let Some(value) = self.get_property(&object, name)? else {
5148 return Err(self.throw_reference(name));
5149 };
5150 if let Some(index) = object.own_data_index(name) {
5151 self.global_cache[site] = Some(GlobalCache {
5152 object: object.downgrade(),
5153 index,
5154 });
5155 }
5156 Ok(value)
5157 }
5158
5159 /// Store to a global binding.
5160 ///
5161 /// Returns a signal when the store is refused: a `const` global may only be
5162 /// written by its initialiser, and a non-configurable `var` global may not be
5163 /// deleted but is always writable.
5164 fn put_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5165 let (name, lexical, is_const) = self.global_binding(slot);
5166
5167 // An assignment inside a `with` writes through to the object that supplies the
5168 // name, which for an `eval` means consulting the same chain `get_global` does.
5169 if let Some(owner) = self.with_owner(&name) {
5170 self.set_property_with(&owner, &name, value, DeleteFailure::Ignore)?;
5171 return Ok(());
5172 }
5173 // A variable the running eval *declared* takes the write before any caller
5174 // binding: `eval("var c = 1")` creates `c` in the eval's own variable
5175 // environment even when an enclosing function has a `var c` of its own.
5176 if self.eval_caller.flatten().is_some()
5177 && let Some((local_vars, phase)) = self.visible_local_vars()
5178 && local_vars.contains(&name)
5179 && let Some(cell) = local_vars.get(&name, phase)
5180 {
5181 cell.set(value);
5182 return Ok(());
5183 }
5184 // A binding of the frame that called `eval` takes the write, which is what
5185 // makes `f("a = 3")` change the caller's `a`.
5186 if self.set_eval_binding(&name, &value)? {
5187 return Ok(());
5188 }
5189 // A closure that outlived its `eval` writes through to the same cell it reads.
5190 if let Some(cell) = self
5191 .frame()
5192 .env
5193 .eval_scope
5194 .as_ref()
5195 .and_then(|scope| scope.get(&name))
5196 .cloned()
5197 {
5198 cell.set(value);
5199 return Ok(());
5200 }
5201 // Inside a strict `eval`, a name it declared itself is stored there. An
5202 // *assignment* to a name nobody declared is not a declaration, so it falls
5203 // through: strict mode raises `ReferenceError` for it, which is what
5204 // `eval("1 + (@not_def = 1)")` has to do.
5205 if let Some(scope) = self.eval_scope.as_mut()
5206 && scope.contains_key(&name)
5207 {
5208 scope.insert(name, value);
5209 return Ok(());
5210 }
5211 if lexical {
5212 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5213 if is_const && !matches!(cell.get(), Value::Uninitialized) {
5214 return Err(self.read_only_global(&name));
5215 }
5216 cell.set(value);
5217 return Ok(());
5218 }
5219 // Writing an undeclared lexical global is a `ReferenceError` in strict
5220 // mode and a silent global creation otherwise; creating the cell here
5221 // keeps both paths from losing the value.
5222 let cell = self.new_cell(value);
5223 self.realm.globals.insert(name, cell);
5224 return Ok(());
5225 }
5226 // A variable a direct `eval` declared in this call shadows the global object, even
5227 // when the global already has a property of that name — `var c = "global"` at the
5228 // top level must not capture `eval("var c = 1")` inside a function.
5229 if let Some((local_vars, phase)) = self.visible_local_vars()
5230 && local_vars.contains(&name)
5231 && let Some(cell) = local_vars.get(&name, phase)
5232 {
5233 cell.set(value);
5234 return Ok(());
5235 }
5236 // The write half of [`Self::get_plain_global`]'s cache. `get_plain_global` has
5237 // remembered a global's slot index since M12b, but the *store* side never did: it
5238 // converted the name to a `PropertyKey` (two allocations) and then scanned the
5239 // global object's whole table — which holds every builtin — on every assignment to
5240 // a global `var`. A loop like `for (…) s += o.x` over a global `s` therefore paid a
5241 // full global lookup per iteration; measured with a counter, `s` as a global made
5242 // 20,000,036 `own_property_key` calls where the same loop with `s` local made 32.
5243 //
5244 // Re-validated exactly like the read: same object, same index, still the name, and
5245 // — the one extra check a store needs — still writable. A global that is an
5246 // accessor, non-writable, or inherited fails here and falls through to the full
5247 // path below, which reports the failure the way it always did.
5248 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
5249 let global = self.realm.global.clone();
5250 if let Some(cached) = &self.global_cache[site]
5251 && global.upgrades_to(&cached.object)
5252 && global.write_data_at(cached.index, &name, value.clone())
5253 {
5254 return Ok(());
5255 }
5256 match global.own_property(&name) {
5257 // A `var` global is writable, so the store goes straight through — but
5258 // through the property, so `globalThis.v = 3` and `v = 3` agree. A failed
5259 // store (a non-writable or accessor-without-setter global) is a silent
5260 // no-op in sloppy mode and a `TypeError` in strict mode, which is the same
5261 // split every other assignment has.
5262 Some(_) => {
5263 let on_failure = if self.current_strict() {
5264 DeleteFailure::Throw
5265 } else {
5266 DeleteFailure::Ignore
5267 };
5268 let result = self.set_property_with(&global, &name, value, on_failure);
5269 // Teach the cache the slot for a plain writable own data property, which is
5270 // what a declared `var` is. Without this the fast path above could never
5271 // fire for a global that is only ever *written* — its entry would have to
5272 // be put there by a read of the same slot, and a write-only loop has none.
5273 if result.is_ok()
5274 && let Some(index) = global.own_data_index(&name)
5275 {
5276 self.global_cache[site] = Some(GlobalCache {
5277 object: global.downgrade(),
5278 index,
5279 });
5280 }
5281 result
5282 }
5283 // Only an implicit global reaches here. In sloppy mode `x = 1` with no
5284 // declaration creates a *configurable* property, which is what makes it
5285 // deletable and is the one way a global differs from a declared `var`.
5286 // In strict mode the same store is a `ReferenceError` instead: that is the
5287 // whole point of strict mode, and creating the global silently meant
5288 // `"use strict"; x = 1` looked like it worked.
5289 None => {
5290 if self.current_strict() {
5291 return Err(self.throw_reference(&name));
5292 }
5293 // A direct eval declares here rather than on the global object: its
5294 // `var`s belong to the caller's variable environment. `declare_eval_local`
5295 // also covers a plain assignment to a variable an earlier eval made.
5296 if let Some(cell) = self.declare_eval_local(&name) {
5297 cell.set(value);
5298 return Ok(());
5299 }
5300 global.define_data(&name, value);
5301 Ok(())
5302 }
5303 }
5304 }
5305
5306 /// The value of a binding of the frame that called `eval`, if there is one.
5307 fn eval_binding_value(&self, name: &str) -> Option<Value> {
5308 let binding = self
5309 .eval_bindings
5310 .iter()
5311 .find(|binding| binding.name == name)?;
5312 let owner = self.frames.get(binding.frame)?;
5313 let (slot, index) = (binding.slot, binding.index);
5314 Some(match slot {
5315 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5316 cell if cell >= 0 => owner
5317 .cells
5318 .get(cell as usize)
5319 .map(|cell| cell.get())
5320 .unwrap_or(Value::Undefined),
5321 _ => owner.args.get(index).cloned().unwrap_or(Value::Undefined),
5322 },
5323 EvalSlot::Local => match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5324 cell if cell >= 0 => owner
5325 .cells
5326 .get(cell as usize)
5327 .map(|cell| cell.get())
5328 .unwrap_or(Value::Undefined),
5329 _ => owner.locals.get(index).cloned().unwrap_or(Value::Undefined),
5330 },
5331 })
5332 }
5333
5334 /// Write to a binding of the frame that called `eval`.
5335 ///
5336 /// `Ok(false)` means no binding matched and the caller should keep looking. A
5337 /// matched binding can still refuse the store, which is why this is fallible: a
5338 /// `const` is read-only everywhere, and a named function expression's own name is
5339 /// read-only in strict mode.
5340 fn set_eval_binding(&mut self, name: &str, value: &Value) -> JsResult<bool> {
5341 let Some(binding) = self
5342 .eval_bindings
5343 .iter()
5344 .find(|binding| binding.name == name)
5345 else {
5346 return Ok(false);
5347 };
5348 let (slot, index, frame) = (binding.slot, binding.index, binding.frame);
5349 let strict = self.current_strict();
5350 let Some(owner) = self.frames.get_mut(frame) else {
5351 return Ok(false);
5352 };
5353 match slot {
5354 EvalSlot::Arg => match owner.code.arg_cell.get(index).copied().unwrap_or(-1) {
5355 cell if cell >= 0 => {
5356 if let Some(cell) = owner.cells.get(cell as usize) {
5357 cell.set(value.clone());
5358 }
5359 }
5360 _ => {
5361 if let Some(slot) = owner.args.get_mut(index) {
5362 *slot = value.clone();
5363 }
5364 }
5365 },
5366 EvalSlot::Local => {
5367 let declared = owner.code.code.vars.get(index);
5368 // A `const` is read-only even through `eval`. The realm records this for
5369 // globals (see `lexical_consts`), but a local's `const`-ness is only in
5370 // the bytecode, so this is where it has to be enforced.
5371 if declared.is_some_and(|var| var.is_const) {
5372 return Err(self.read_only_local(name));
5373 }
5374 // The name of a named function expression is read-only too, but only
5375 // strict mode reports the attempt: a sloppy `eval("m = 1")` where `m` is
5376 // such a name is ignored, the same as a direct store would be.
5377 if declared.is_some_and(|var| var.kind == js_compile::VarKind::FunctionName) {
5378 return if strict {
5379 Err(self.read_only_local(name))
5380 } else {
5381 Ok(true)
5382 };
5383 }
5384 match owner.code.loc_cell.get(index).copied().unwrap_or(-1) {
5385 cell if cell >= 0 => {
5386 if let Some(cell) = owner.cells.get(cell as usize) {
5387 cell.set(value.clone());
5388 }
5389 }
5390 _ => {
5391 if let Some(slot) = owner.locals.get_mut(index) {
5392 *slot = value.clone();
5393 }
5394 }
5395 }
5396 }
5397 }
5398 Ok(true)
5399 }
5400
5401 /// The `TypeError` an assignment to a read-only binding raises.
5402 fn read_only_local(&self, name: &str) -> Signal {
5403 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5404 }
5405
5406 /// Declare `name` as a variable of the frame that called the running `eval`.
5407 ///
5408 /// `None` when there is no direct eval in progress, or it was called from the top
5409 /// level — then the caller's variable environment *is* the global one and the
5410 /// existing path is right.
5411 fn declare_eval_local(&mut self, name: &str) -> Option<Gc<Cell>> {
5412 let caller = self.eval_caller.flatten()?;
5413 // The bottom frame is the top-level script, whose variable environment *is* the
5414 // global one — so `eval("var x = 1")` at the top level still creates a global.
5415 if caller == 0 {
5416 return None;
5417 }
5418 // A name the eval's *own* variable environment already binds is not a new
5419 // variable: `eval("var arguments = 1")` inside a parameter list writes that list's
5420 // `arguments`, and creating a second binding would leave the first — the one
5421 // closures read — untouched. A binding of an *outer* frame does not count: a
5422 // declaration shadows it rather than writing through.
5423 if self
5424 .eval_bindings
5425 .iter()
5426 .any(|binding| binding.name == name && binding.frame == caller)
5427 {
5428 return None;
5429 }
5430 let phase = if self.in_parameter_list_at(caller) {
5431 0
5432 } else {
5433 1
5434 };
5435 self.frame_local_vars(caller)?;
5436 let local_vars = self.frames.get(caller)?.local_vars.clone()?;
5437 if let Some(cell) = local_vars.get(name, 1) {
5438 return Some(cell);
5439 }
5440 let cell = self.new_cell(Value::Undefined);
5441 Some(local_vars.declare(name, phase, cell))
5442 }
5443
5444 /// Make sure `frame` has a `LocalVars`, creating it on demand.
5445 fn frame_local_vars(&mut self, frame: usize) -> Option<Gc<LocalVars>> {
5446 if let Some(local_vars) = &self.frames.get(frame)?.local_vars {
5447 return Some(local_vars.clone());
5448 }
5449 let local_vars = Gc::new(self.heap, LocalVars::new());
5450 self.frames.get_mut(frame)?.local_vars = Some(local_vars.clone());
5451 Some(local_vars)
5452 }
5453
5454 /// Whether the realm already has a binding for `name`, lexically or as an *own*
5455 /// property of the global object. Used to decide whether a store inside an
5456 /// `eval` writes through to the realm or declares a binding of its own.
5457 ///
5458 /// Own rather than inherited: `eval("var toString = 1")` must not be taken for a
5459 /// write to `Object.prototype.toString`, and must not shadow it either.
5460 fn global_knows(&mut self, name: &str) -> bool {
5461 if self.realm.globals.contains_key(name) {
5462 return true;
5463 }
5464 self.realm.global.own_property(name).is_some()
5465 }
5466
5467 /// Whether the code currently running is strict.
5468 ///
5469 /// Read off the frame's function, which is where the parser's answer ended up; a
5470 /// native function never runs strict-only checks, and there is no frame at all
5471 /// before the first script.
5472 pub fn current_strict(&self) -> bool {
5473 self.frames
5474 .last()
5475 .is_some_and(|frame| frame.code.code.strict)
5476 }
5477
5478 /// Initialise a declared global, which is what ends its dead zone.
5479 ///
5480 /// A `var` global becomes a property of the global object: writable, so a later
5481 /// assignment goes through, and non-configurable, so `delete` refuses.
5482 fn init_global(&mut self, slot: usize, value: Value) -> JsResult<()> {
5483 let (name, lexical, _) = self.global_binding(slot);
5484 // A `var` declared by the strict `eval` currently running belongs to the
5485 // eval's scope, not to the global object: `eval("var v = 1")` must not make
5486 // `typeof v` answer `"number"` afterwards. A name the realm already has is
5487 // initialised in place, which is what a re-declaration inside eval does.
5488 if self.eval_scope.is_some() && !lexical && !self.global_knows(&name) {
5489 self.eval_scope
5490 .as_mut()
5491 .expect("checked above")
5492 .insert(name, value);
5493 return Ok(());
5494 }
5495 if let Some(scope) = self.eval_scope.as_mut()
5496 && scope.contains_key(&name)
5497 {
5498 scope.insert(name, value);
5499 return Ok(());
5500 }
5501 if lexical {
5502 // The cell exists (created at declaration time) holding the dead-zone
5503 // marker; storing the value is what makes the binding readable.
5504 if let Some(cell) = self.realm.globals.get(&name).cloned() {
5505 cell.set(value);
5506 return Ok(());
5507 }
5508 let cell = self.new_cell(value);
5509 self.realm.globals.insert(name, cell);
5510 return Ok(());
5511 }
5512 let global = self.realm.global.clone();
5513 // Writable and enumerable, but *not* configurable: `delete globalThis.v` has
5514 // to answer `false` and leave the binding in place. `with_attributes` ties
5515 // `configurable` to `writable`, so the property is built field by field.
5516 global.define(
5517 &name,
5518 Property {
5519 value: Some(value),
5520 writable: true,
5521 enumerable: true,
5522 configurable: false,
5523 ..Property::default()
5524 },
5525 );
5526 Ok(())
5527 }
5528
5529 /// The `TypeError` a store to a `const` global raises.
5530 fn read_only_global(&self, name: &str) -> Signal {
5531 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
5532 }
5533
5534 // -- properties ---------------------------------------------------------
5535
5536 /// Read `object[key]`, following the prototype chain.
5537 ///
5538 /// An inherited accessor runs with the *receiver* as `this`, which is why the
5539 /// lookup returns the owner rather than just the value.
5540 pub fn get_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<Option<Value>> {
5541 self.get_property_key(object, &PropertyKey::from(key))
5542 }
5543
5544 /// [`Interp::get_property`] with a key that may be a symbol.
5545 pub fn get_property_key(
5546 &mut self,
5547 object: &Gc<JsObject>,
5548 key: &PropertyKey,
5549 ) -> JsResult<Option<Value>> {
5550 self.get_property_key_for(object, None, key)
5551 }
5552
5553 /// [`Interp::get_property_key`], with an explicit `this` for an inherited accessor.
5554 ///
5555 /// The receiver matters when the property is found on a *prototype*: a getter has to
5556 /// see the object the read started from. For a primitive that is the primitive
5557 /// itself — `Symbol("x").description` runs the getter with the symbol as `this`,
5558 /// not with `Symbol.prototype` — which is why the receiver cannot be inferred from
5559 /// the owner.
5560 pub fn get_property_key_for(
5561 &mut self,
5562 object: &Gc<JsObject>,
5563 receiver: Option<&Value>,
5564 key: &PropertyKey,
5565 ) -> JsResult<Option<Value>> {
5566 // A proxy answers for itself, before any of the shortcuts below: `new
5567 // Proxy([], {get: …})` must not read `length` out of an element vector it does not
5568 // have.
5569 if object.proxy_state().is_some() {
5570 let receiver = receiver
5571 .cloned()
5572 .unwrap_or_else(|| Value::Object(object.clone()));
5573 return self.proxy_get(object, &receiver, key);
5574 }
5575 // A host class's `get_property` trap replaces the whole read, prototype walk
5576 // included — that is what makes a native accessor free rather than a JavaScript
5577 // getter call.
5578 if let Some(exotic) = object.exotic() {
5579 let receiver_value = receiver
5580 .cloned()
5581 .unwrap_or_else(|| Value::Object(object.clone()));
5582 if let Some(value) = exotic.get_property(self, object, key, &receiver_value)? {
5583 return Ok(Some(value));
5584 }
5585 // With no `get_property` trap, a `get_own_property` trap still answers for the
5586 // object itself: `[[Get]]` asks each object in the chain for its own descriptor
5587 // and the hook lives exactly there. A key the trap reports as absent is still
5588 // looked for on the prototype, which is why the search resumes *above*.
5589 if let Some(property) = exotic.get_own_property(self, object, key)? {
5590 return match property {
5591 Some(property) => self.read_property(property, object, receiver),
5592 None => match lookup_key_above(object, key) {
5593 Some((_, property)) => self.read_property(property, object, receiver),
5594 None => Ok(None),
5595 },
5596 };
5597 }
5598 }
5599 // `caller`/`arguments` on a **constructible** function are `undefined`, and on every
5600 // other callable they throw through `%ThrowTypeError%` on `Function.prototype`.
5601 // The `[[Get]]` short-circuit therefore belongs to this one arm.
5602 //
5603 // Constructibility is exactly the split the reference makes: `function f(){}` and
5604 // `function f(){"use strict"}` both answer `undefined`, while a method, an arrow, a
5605 // generator and a `bind`-ed function all throw. It is not a proxy for "is a normal
5606 // function" — it *is* the predicate, which is why no extra marker is needed.
5607 if let Some(text) = key.as_str()
5608 && (text == "caller" || text == "arguments")
5609 && object.is_constructor()
5610 && object.is_callable()
5611 && !object.is_bound_function()
5612 // …and only when the body is **sloppy**. A strict body reaches the
5613 // `%ThrowTypeError%` pair on `Function.prototype` instead, which is what the
5614 // whole `Function/15.3.5.4_2-*gs` family is written against
5615 // (`onlyStrict`, so every function in them is strict).
5616 && !object.function_is_strict()
5617 && object.own_property(text).is_none()
5618 {
5619 return Ok(Some(Value::Undefined));
5620 }
5621 // The element-vector and `length` shortcuts are string-only: an array index
5622 // has no symbol spelling.
5623 if let Some(text) = key.as_str() {
5624 if let Some(value) = self.own_element(object, text) {
5625 return Ok(Some(value));
5626 }
5627 // `length` is not stored as a property: an array's length is its element
5628 // count, and keeping one copy of it is what makes `push`/`pop` and
5629 // `a.length = n` agree.
5630 if let Some(length) = object.array_length()
5631 && text == "length"
5632 {
5633 // Not `Value::Int(length as i32)`: see [`length_value`].
5634 return Ok(Some(crate::object::length_value(length)));
5635 }
5636 }
5637 // A proxy or a hooked exotic object anywhere above `object` makes the static
5638 // table walk below wrong: a proxy's own table is *empty by design* (the properties
5639 // live on its target), so the walk skipped that link entirely and everything behind
5640 // it read as `undefined`. `Object.create(new Proxy({get x(){return this}}, {})).x`
5641 // was the smallest case; test262's `Proxy/get/trap-is-{missing,null,undefined}
5642 // -target-is-proxy.js` are the four.
5643 if Self::chain_needs_dispatch(object) {
5644 return self.walk_get(object, receiver, key);
5645 }
5646 match lookup_key(object, key) {
5647 Some((_, property)) => self.read_property(property, object, receiver),
5648 None => Ok(None),
5649 }
5650 }
5651
5652 /// `[[Get]]` over the prototype chain, one link at a time, with every link allowed to
5653 /// answer for itself.
5654 ///
5655 /// The counterpart of the `lookup_key` shortcut above, used only when a link needs
5656 /// dispatch. Each step is a real `[[GetOwnProperty]]` (so a proxy traps and an exotic
5657 /// object hooks) and the read reports to `receiver`, which is what makes `this` inside
5658 /// an inherited getter the object the read started from.
5659 fn walk_get(
5660 &mut self,
5661 start: &Gc<JsObject>,
5662 receiver: Option<&Value>,
5663 key: &PropertyKey,
5664 ) -> JsResult<Option<Value>> {
5665 let receiver = receiver
5666 .cloned()
5667 .unwrap_or_else(|| Value::Object(start.clone()));
5668 let mut current = Some(start.clone());
5669 while let Some(holder) = current {
5670 // A **proxy** in the chain answers `[[Get]]` itself — trap or not — so the walk
5671 // has to ask it, not read its (empty) own-property table. `Object.create(new
5672 // Proxy({}, {get: () => 3})).anything` is 3, and asking for the own property
5673 // instead found nothing.
5674 if let Some(value) = self.proxy_get(&holder, &receiver, key)? {
5675 return Ok(Some(value));
5676 }
5677 // A host class's `get_property` trap replaces the whole read for that holder,
5678 // prototype walk included — the same rule `get_property_key_for` applies to the
5679 // first object.
5680 if let Some(exotic) = holder.exotic()
5681 && let Some(value) = exotic.get_property(self, &holder, key, &receiver)?
5682 {
5683 return Ok(Some(value));
5684 }
5685 if let Some(property) = self.object_get_own_property(&holder, key)? {
5686 return self.read_property(property, &holder, Some(&receiver));
5687 }
5688 current = self.object_prototype_of(&holder)?;
5689 }
5690 Ok(None)
5691 }
5692
5693 /// Whether `object` or anything above it has properties that cannot be read out of a
5694 /// property table — a proxy, or an exotic object with a `get_own_property` hook.
5695 ///
5696 /// The static shortcut in [`Interp::get_property_key_for`] is worth keeping because it
5697 /// is the hot path for every property read; this is the check that decides whether it
5698 /// is safe to take it.
5699 fn chain_needs_dispatch(object: &Gc<JsObject>) -> bool {
5700 object
5701 .chain()
5702 .iter()
5703 .any(|ancestor| ancestor.proxy_state().is_some() || ancestor.exotic().is_some())
5704 }
5705
5706 /// The value a property read answers.
5707 ///
5708 /// One place rather than three, because an accessor has to run with the *receiver* as
5709 /// `this` whether the descriptor came from the property table, an exotic
5710 /// `get_own_property` trap, or a prototype above one.
5711 fn read_property(
5712 &mut self,
5713 property: Property,
5714 object: &Gc<JsObject>,
5715 receiver: Option<&Value>,
5716 ) -> JsResult<Option<Value>> {
5717 if property.is_accessor() {
5718 match &property.getter {
5719 Some(getter) if !matches!(getter, Value::Undefined) => {
5720 let receiver = receiver
5721 .cloned()
5722 .unwrap_or_else(|| Value::Object(object.clone()));
5723 self.call_value(getter.clone(), receiver, Vec::new())
5724 .map(Some)
5725 }
5726 // An accessor with no getter reads as `undefined`.
5727 _ => Ok(Some(Value::Undefined)),
5728 }
5729 } else {
5730 Ok(property.value)
5731 }
5732 }
5733
5734 /// `super.key` — start the search at `proto`, but report to `receiver`.
5735 ///
5736 /// The difference from [`Interp::get_property`] is exactly the receiver: a getter
5737 /// found on the prototype of a class has to see the *instance* as `this`, and a
5738 /// plain property read off `proto` would lose that.
5739 fn super_read(&mut self, receiver: &Value, proto: &Value, key: &Value) -> JsResult<Value> {
5740 let start = self.require_object(proto)?;
5741 let key = self.propkey(key)?;
5742 // `super.x` on a null prototype (a class extending `null`) resolves to nothing.
5743 if matches!(proto, Value::Null) {
5744 return Ok(Value::Undefined);
5745 }
5746 match lookup_key(&start, &key) {
5747 Some((_, property)) if property.is_accessor() => match &property.getter {
5748 Some(getter) if !matches!(getter, Value::Undefined) => {
5749 self.call_value(getter.clone(), receiver.clone(), Vec::new())
5750 }
5751 _ => Ok(Value::Undefined),
5752 },
5753 Some((_, property)) => Ok(property.value.unwrap_or(Value::Undefined)),
5754 None => Ok(Value::Undefined),
5755 }
5756 }
5757
5758 /// `super.key = value` — a store that starts at `proto` but lands on `receiver`.
5759 ///
5760 /// A setter found on the prototype runs with `receiver` as `this`; a data property
5761 /// is shadowed by a new own property on the receiver, the same rule an ordinary
5762 /// assignment follows.
5763 fn super_write(
5764 &mut self,
5765 receiver: &Value,
5766 proto: &Value,
5767 key: &Value,
5768 value: Value,
5769 ) -> JsResult<()> {
5770 let target = self.require_object(receiver)?;
5771 let key = self.propkey(key)?;
5772 if !matches!(proto, Value::Null)
5773 && let Some((owner, property)) = lookup_key(&self.require_object(proto)?, &key)
5774 {
5775 if property.is_accessor() {
5776 if let Some(setter) = &property.setter
5777 && !matches!(setter, Value::Undefined)
5778 {
5779 self.call_value(setter.clone(), receiver.clone(), vec![value])?;
5780 }
5781 return Ok(());
5782 }
5783 // A data property on the prototype is writable or not; reading `owner` at
5784 // all is only for the attribute check.
5785 if !property.writable {
5786 return Err(self.type_error(format!("'{key}' is read-only")));
5787 }
5788 let _ = owner;
5789 }
5790 self.set_property_with_key(&target, &key, value, DeleteFailure::Throw)
5791 }
5792
5793 /// The object a `super` operation needs, or the `TypeError` the spec raises.
5794 fn require_object(&self, value: &Value) -> JsResult<Gc<JsObject>> {
5795 match value.as_object() {
5796 Some(object) => Ok(object.clone()),
5797 None => Err(Signal::Throw(
5798 self.make_error("TypeError", "value is not an object"),
5799 )),
5800 }
5801 }
5802
5803 /// Build the class object `define_class` produces.
5804 ///
5805 /// `[parent, ctor]` becomes `[ctor, proto]`: the constructor becomes a constructor
5806 /// whose prototype property is a fresh object inheriting from the parent's
5807 /// prototype, and whose own prototype is the parent constructor — which is what makes
5808 /// a static method inherited too.
5809 fn define_class(&mut self, name: &str, flags: u32) -> JsResult<(Value, Gc<JsObject>)> {
5810 let ctor = self.pop();
5811 let parent = self.pop();
5812 let Value::Object(function) = &ctor else {
5813 return Err(Signal::Throw(
5814 self.make_error("TypeError", "class constructor must be a function"),
5815 ));
5816 };
5817 // A heritage of `null` keeps `Object.prototype` as the constructor's prototype
5818 // but gives the instances no prototype at all.
5819 let (parent_ctor, parent_proto) = if flags & 1 != 0 {
5820 match &parent {
5821 Value::Null => (Some(self.realm.function_proto.clone()), None),
5822 Value::Object(parent_class) => {
5823 if !parent_class.is_callable() {
5824 return Err(Signal::Throw(
5825 self.make_error("TypeError", "parent class must be constructor"),
5826 ));
5827 }
5828 let proto = self.get_property(parent_class, "prototype")?;
5829 match proto {
5830 Some(Value::Object(proto)) => (Some(parent_class.clone()), Some(proto)),
5831 Some(Value::Null) => (Some(parent_class.clone()), None),
5832 _ => {
5833 return Err(Signal::Throw(self.make_error(
5834 "TypeError",
5835 "parent prototype must be an object or null",
5836 )));
5837 }
5838 }
5839 }
5840 _ => {
5841 return Err(Signal::Throw(
5842 self.make_error("TypeError", "parent class must be constructor"),
5843 ));
5844 }
5845 }
5846 } else {
5847 (
5848 Some(self.realm.function_proto.clone()),
5849 Some(self.realm.object_proto.clone()),
5850 )
5851 };
5852 let proto = self.new_object(parent_proto);
5853 function.set_proto(parent_ctor);
5854 // A class is not callable without `new`, and its `prototype` is not writable —
5855 // both follow from being a class and are what `class A {}; A()` throws on.
5856 function.set_class_constructor(true);
5857 function.set_home_object(None);
5858 self.set_function_name(&ctor, name);
5859 self.define_class_properties(function, &ctor, &proto)?;
5860 Ok((ctor, proto))
5861 }
5862
5863 /// Give the constructor its `prototype` and `length`, and the prototype its
5864 /// `constructor` back-pointer.
5865 fn define_class_properties(
5866 &mut self,
5867 function: &Gc<JsObject>,
5868 ctor: &Value,
5869 proto: &Gc<JsObject>,
5870 ) -> JsResult<()> {
5871 proto.define(
5872 "constructor",
5873 Property::with_attributes(ctor.clone(), true, false),
5874 );
5875 function.define(
5876 "prototype",
5877 Property::prototype_of(Value::Object(proto.clone()), false),
5878 );
5879 if let Some((code, _)) = bytecode_of(function) {
5880 let length = code.code.defined_args;
5881 function.define(
5882 "length",
5883 Property::name_or_length(Value::Int(length as i32)),
5884 );
5885 }
5886 Ok(())
5887 }
5888
5889 /// The own array element `key` names, if this object has one.
5890 fn own_element(&self, object: &Gc<JsObject>, key: &str) -> Option<Value> {
5891 // A typed array's elements live in its buffer, not in a property list: reading one
5892 // goes through the view's element type so a bounds check and a detached buffer are
5893 // both handled there.
5894 //
5895 // The key test is `CanonicalNumericIndexString`, not `array_index`, and the
5896 // difference is the whole of `Get/key-is-out-of-bounds`: `"-1"`, `"1.5"` and
5897 // `"-0"` are canonical numeric indices of a typed array, so §10.4.5.4 answers them
5898 // from `IntegerIndexedElementGet` — `undefined` — and the prototype chain is never
5899 // consulted. Testing with `array_index` rejected all three, which let a throwing
5900 // getter installed on `TypedArray.prototype["-1"]` run.
5901 if object.typed_array_parts().is_some() {
5902 let property_key = PropertyKey::from(key);
5903 let numeric = canonical_numeric_index(&property_key)?;
5904 if typed_array_index_is_valid(object, numeric) {
5905 return object.typed_array_element(numeric as usize);
5906 }
5907 // Canonical, but not a valid index: `undefined`, and *final*.
5908 return Some(Value::Undefined);
5909 }
5910 let index = array_index(key)?;
5911 // A hole answers `None`, not `undefined`: it is *not* an own property, so the read
5912 // has to continue up the prototype chain. Mapping it to `undefined` here ended the
5913 // search early, which is why `Array.prototype[1] = 9` could not be seen through
5914 // `[1,,3][1]`.
5915 match object.array_get(index as usize) {
5916 Some(Value::Hole) | None => None,
5917 other => other,
5918 }
5919 }
5920
5921 /// Store `object[key] = value`, honouring setters and inherited properties.
5922 pub fn set_property(&mut self, object: &Gc<JsObject>, key: &str, value: Value) -> JsResult<()> {
5923 self.set_property_with(object, key, value, DeleteFailure::Throw)
5924 }
5925
5926 /// Store a property, choosing what to do when the object refuses.
5927 ///
5928 /// A rejected store is a `TypeError` in strict mode and a silent no-op in sloppy
5929 /// mode, which is the one place assignment differs by mode. Native code (the array
5930 /// methods, `JSON`) always asks for the throw.
5931 pub fn set_property_with(
5932 &mut self,
5933 object: &Gc<JsObject>,
5934 key: &str,
5935 value: Value,
5936 on_failure: DeleteFailure,
5937 ) -> JsResult<()> {
5938 self.set_property_with_key(object, &PropertyKey::from(key), value, on_failure)
5939 }
5940
5941 /// [`Interp::set_property_with`] with a key that may be a symbol.
5942 pub fn set_property_with_key(
5943 &mut self,
5944 object: &Gc<JsObject>,
5945 key: &PropertyKey,
5946 value: Value,
5947 on_failure: DeleteFailure,
5948 ) -> JsResult<()> {
5949 self.set_property_with_key_receiver_aware(object, key, value, on_failure)
5950 }
5951
5952 /// [`Interp::set_property_with_key`], for a receiver that *is* the object.
5953 ///
5954 /// The receiver split lives one level up, in
5955 /// [`Interp::set_property_with_key_receiver`]: a typed array's canonical index with a
5956 /// different receiver goes to `OrdinarySetWithOwnDescriptor` on that receiver instead
5957 /// of ever reaching this function (§10.4.5.5 step 1.b). Everything here therefore
5958 /// stores into `object` itself, which is why the element branch below converts `V`
5959 /// before asking whether the index is valid: `V` may put it back in bounds
5960 /// (`Set/resized-out-of-bounds-to-in-bounds-index`).
5961 fn set_property_with_key_receiver_aware(
5962 &mut self,
5963 object: &Gc<JsObject>,
5964 key: &PropertyKey,
5965 value: Value,
5966 on_failure: DeleteFailure,
5967 ) -> JsResult<()> {
5968 // A proxy's `set` trap decides, and its `false` means the same thing an
5969 // ordinary refusal means: a `TypeError` in strict code, nothing in sloppy code.
5970 if object.proxy_state().is_some() {
5971 let receiver = Value::Object(object.clone());
5972 if let Some(accepted) = self.proxy_set(object, key, value.clone(), &receiver)? {
5973 return match (accepted, on_failure) {
5974 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5975 (false, DeleteFailure::Throw) => {
5976 Err(self.type_error(format!("proxy 'set' refused to write '{key}'")))
5977 }
5978 };
5979 }
5980 }
5981 // A host class's `set_property` trap decides for itself. `Some(false)` is a
5982 // refusal and means exactly what a proxy's `false` means.
5983 if let Some(exotic) = object.exotic() {
5984 let receiver = Value::Object(object.clone());
5985 if let Some(accepted) = exotic.set_property(self, object, key, &value, &receiver)? {
5986 return match (accepted, on_failure) {
5987 (true, _) | (false, DeleteFailure::Ignore) => Ok(()),
5988 (false, DeleteFailure::Throw) => {
5989 Err(self.type_error(format!("property '{key}' is read-only")))
5990 }
5991 };
5992 }
5993 }
5994 // The element and `length` shortcuts only exist for string keys: an array
5995 // index has no symbol spelling, and a symbol named `length` is an ordinary
5996 // property.
5997 let text = key.as_str();
5998 // A typed array's elements are a window onto its buffer: the store has to go
5999 // through the view's element type so the value is wrapped (or clamped) and so an
6000 // out-of-range or detached write is a silent no-op, as the spec says.
6001 //
6002 // The key test is `CanonicalNumericIndexString`, like every other index operation
6003 // on a view: `ta["-0"] = 1` and `ta["1.5"] = 1` are stores to an *element* that
6004 // does not exist, so they do nothing and leave no own property behind
6005 // (`Set/key-is-minus-zero`). Testing with `array_index` sent both to the ordinary
6006 // path, which created a property named `"-0"`.
6007 //
6008 // The conversion comes **first**, before the index is checked at all, and that
6009 // order is observable twice over:
6010 //
6011 // * `V` can put the index back in bounds — `resized-out-of-bounds-to-in-bounds-index`
6012 // has a `valueOf` that resizes a 0-byte buffer to 1, and `ta[0] = value` must
6013 // then store the converted value;
6014 // * `Set/tonumber-value-throws` assigns to `ta["1.1"]`, `ta["-0"]`, `ta["-1"]` and
6015 // `ta["2"]` — every one of them an invalid index — and expects the `valueOf` to
6016 // run and its exception to escape.
6017 //
6018 // So this is `IntegerIndexedElementSet`, which is `ToNumber`/`ToBigInt` and then a
6019 // validity check, not a validity check that skips the conversion. The store itself
6020 // is a no-op when the index is invalid by then, which is why no extra guard is
6021 // needed around `typed_array_set`.
6022 if let Some(element) = object.typed_array_element_type()
6023 && let Some(numeric) = canonical_numeric_index(key)
6024 {
6025 // A BigInt view refuses a Number and a numeric one refuses a Symbol; the spec
6026 // makes both a `TypeError` rather than a silent skip. The conversion runs here,
6027 // in `Interp`, because it is script-observable and the storage borrow inside
6028 // `typed_array_set` must not be held across it.
6029 let stored = self.element_value(element, value)?;
6030 if typed_array_index_is_valid(object, numeric)
6031 && let Some(Err(reason)) = object.typed_array_set(numeric as usize, stored)
6032 {
6033 return Err(self.type_error(reason));
6034 }
6035 return Ok(());
6036 }
6037 if let Some(text) = text
6038 && let Some(index) = array_index(text)
6039 && object.is_array()
6040 {
6041 // An accessor defined on an index lives in the property table while the
6042 // element slot is a hole, so the store has to go through the property first.
6043 // Writing the vector directly skipped the setter entirely.
6044 if let Some(existing) = object.own_property_key(key) {
6045 if existing.is_accessor() {
6046 return match existing.setter.clone() {
6047 Some(setter) if !matches!(setter, Value::Undefined) => {
6048 let receiver = Value::Object(object.clone());
6049 self.call_value(setter, receiver, vec![value]).map(|_| ())
6050 }
6051 _ => match on_failure {
6052 DeleteFailure::Throw => Err(self.type_error(format!(
6053 "cannot set property '{text}', it has only a getter"
6054 ))),
6055 DeleteFailure::Ignore => Ok(()),
6056 },
6057 };
6058 }
6059 if !existing.writable {
6060 return match on_failure {
6061 DeleteFailure::Throw => {
6062 Err(self.type_error(format!("'{text}' is read-only")))
6063 }
6064 DeleteFailure::Ignore => Ok(()),
6065 };
6066 }
6067 }
6068 {
6069 // Growing the array needs a writable `length`.
6070 if (index as usize) >= object.array_length().unwrap_or(0)
6071 && !object.length_writable()
6072 {
6073 return match on_failure {
6074 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6075 DeleteFailure::Ignore => Ok(()),
6076 };
6077 }
6078 // Adding an index past the end makes the array longer, which a
6079 // non-extensible array refuses.
6080 if index as usize >= object.array_length().unwrap_or(0) && !object.is_extensible() {
6081 return match on_failure {
6082 DeleteFailure::Throw => Err(self.type_error(format!(
6083 "cannot add property '{key}', object is not extensible"
6084 ))),
6085 DeleteFailure::Ignore => Ok(()),
6086 };
6087 }
6088 if object.element_is_locked(index) {
6089 return match on_failure {
6090 DeleteFailure::Throw => {
6091 Err(self.type_error(format!("'{key}' is read-only")))
6092 }
6093 DeleteFailure::Ignore => Ok(()),
6094 };
6095 }
6096 // The element vector is only half of `[[Set]]` for an index: the
6097 // prototype chain is consulted first, and a setter there answers instead
6098 // of the element store. This branch used to write the element directly, so
6099 // an `Object.defineProperty(Array.prototype, '0', {set})` never ran —
6100 // `arr[0] = 7` stored 7 in the array and left the setter untouched, where
6101 // the reference calls the setter and the array keeps no own index.
6102 //
6103 // An *exotic* prototype has no entry to find, because its indices live
6104 // outside the property table — `Object.setPrototypeOf([], typedArray)`
6105 // then looked like "nothing on the chain" and the store created the
6106 // element, where the view's `[[Set]]` answers `true` and does nothing for
6107 // an invalid index (`key-is-canonical-invalid-index-prototype-chain-set`
6108 // checks the array's `length` stays 0). So the dispatch comes first.
6109 if !object.has_own_key(key)
6110 && let Some(proto) = object.proto()
6111 && (proto.typed_array_element_type().is_some() || proto.proxy_state().is_some())
6112 {
6113 let receiver = Value::Object(object.clone());
6114 let accepted =
6115 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6116 return if accepted {
6117 Ok(())
6118 } else {
6119 match on_failure {
6120 DeleteFailure::Throw => {
6121 Err(self.type_error(format!("'{key}' is read-only")))
6122 }
6123 DeleteFailure::Ignore => Ok(()),
6124 }
6125 };
6126 }
6127 if let Some((owner, property)) = lookup_key(object, key)
6128 && !owner.ptr_eq(object)
6129 {
6130 match &property {
6131 property if property.is_accessor() => {
6132 match &property.setter {
6133 Some(setter) if !matches!(setter, Value::Undefined) => {
6134 let receiver = Value::Object(object.clone());
6135 self.call_value(setter.clone(), receiver, vec![value])?;
6136 }
6137 _ => {
6138 return match on_failure {
6139 DeleteFailure::Throw => Err(self.type_error(format!(
6140 "cannot set property '{text}', it has only a getter"
6141 ))),
6142 DeleteFailure::Ignore => Ok(()),
6143 };
6144 }
6145 }
6146 return Ok(());
6147 }
6148 property if !property.writable => {
6149 return match on_failure {
6150 DeleteFailure::Throw => {
6151 Err(self.type_error(format!("'{text}' is read-only")))
6152 }
6153 DeleteFailure::Ignore => Ok(()),
6154 };
6155 }
6156 _ => {}
6157 }
6158 }
6159 if object.array_set(self.heap, index as usize, value.clone()) {
6160 return Ok(());
6161 }
6162 // Past the dense limit the slot is too far out to be worth one `Value`
6163 // per hole — `a[2**32 - 2] = 1` is legal and the reference answers it in
6164 // constant time by keeping the index as an ordinary property. The store
6165 // used to be *dropped* here, leaving `length` at 0: a silent wrong answer
6166 // to a legal program.
6167 object.define_key(key, Property::with_attributes(value, true, true));
6168 // Extend, never shorten: the index may be *inside* the current length (a
6169 // huge `length` with a sparse store), and shortening would delete the
6170 // sparse properties above it — including the one just stored.
6171 if index as usize + 1 > object.array_length().unwrap_or(0) {
6172 object.array_set_length(self.heap, index as usize + 1);
6173 }
6174 return Ok(());
6175 }
6176 }
6177 if text == Some("length") && object.is_array() {
6178 // §10.4.2.4 steps 3–5: **two** `ToNumber` conversions, then the writability
6179 // test. A `valueOf` that locks `length` on its second call therefore turns the
6180 // store into a refused write rather than a silent success
6181 // (`length/define-own-prop-length-coercion-order-set`).
6182 let rounded = self.coerce_array_length_twice(&value)?;
6183 if !object.length_writable() {
6184 return match on_failure {
6185 DeleteFailure::Throw => Err(self.type_error("'length' is read-only")),
6186 DeleteFailure::Ignore => Ok(()),
6187 };
6188 }
6189 // `ArraySetLength` converts with `ToNumber`, so a `new Number(6)` gives 6 and
6190 // not `NaN` — `to_number` on the object itself skips `ToPrimitive` and
6191 // answered `NaN`, which left the assignment silently ignored
6192 // (`S15.4.5.2_A3_T2`).
6193 let _ = rounded;
6194 let length = self.to_js_number(&value)?;
6195 // Step 3: `ToUint32(value)` must round-trip, or the length is not an array
6196 // length at all. `a.length = 4294967297` and `a.length = 4.5` are both
6197 // `RangeError`s; the old code only tested "finite and non-negative" and then
6198 // truncated, so `[].length = 4294967297` quietly produced a length no array can
6199 // hold (`Array/length/S15.4.5.1_A1.1_T1`).
6200 let valid = length.is_finite()
6201 && length >= 0.0
6202 && length.fract() == 0.0
6203 && length <= u32::MAX as f64;
6204 if !valid {
6205 return Err(self.range_error("invalid array length"));
6206 }
6207 {
6208 let length = length as usize;
6209 // `a.length = n` with `n` below a non-configurable element cannot
6210 // drop that element, so the whole assignment fails. The spec makes
6211 // this a `TypeError` rather than a silent no-op, in any mode.
6212 if let Some(blocked) = object.first_undeletable_at_or_above(length) {
6213 // Sloppy mode stops the truncation at the blocking element
6214 // instead of failing; strict mode raises.
6215 // Both modes stop at the blocking element; they differ in
6216 // whether that is reported. The reference truncates *then*
6217 // throws, so the array is left in the shortened state.
6218 object.array_truncate(self.heap, blocked + 1);
6219 return match on_failure {
6220 DeleteFailure::Throw => {
6221 Err(self.type_error(format!("cannot delete property '{blocked}'")))
6222 }
6223 DeleteFailure::Ignore => Ok(()),
6224 };
6225 }
6226 object.array_set_length(self.heap, length);
6227 return Ok(());
6228 }
6229 }
6230 // §10.1.9 `OrdinarySet`, and the *order* of these three steps is the whole
6231 // point. Step 1 reads the **own** descriptor and acts on it; step 2 **dispatches**
6232 // to the prototype's `[[Set]]`; and only step 3 creates a property on `object`.
6233 //
6234 // The prototype step is a dispatch, not a lookup. Walking the chain here and
6235 // applying whatever came back is the same thing for an ordinary prototype and
6236 // completely different for an exotic one: `var p = new Uint8Array(1); var o =
6237 // Object.create(p); o[0] = v` must ask *the view* to store index 0, and the view
6238 // answers "not mine, the receiver is not me" without touching the buffer. This
6239 // code used to find nothing owned by `o`, find no property on the view either,
6240 // and then create `o[0]` as an ordinary data property — so `o[0]` was the raw
6241 // object and never converted (`key-is-valid-index-prototype-chain-set`,
6242 // `key-is-canonical-invalid-index-prototype-chain-set`).
6243 //
6244 // The read-only and accessor rules of step 1 are what make
6245 // `Object.create(Object.freeze({x: 1})).x = 9` a no-op: the *prototype's* own
6246 // `[[Set]]` is asked, and it refuses on its own non-writable `x`.
6247 let own = match self.lookup_for_write(object, key)? {
6248 Some((owner, property)) if owner.ptr_eq(object) => Some(property),
6249 _ => None,
6250 };
6251 if let Some(property) = own {
6252 if property.is_accessor() {
6253 return match property.setter.filter(|v| !matches!(v, Value::Undefined)) {
6254 Some(setter) => {
6255 let receiver = Value::Object(object.clone());
6256 self.call_value(setter, receiver, vec![value])?;
6257 Ok(())
6258 }
6259 // §10.1.9.2 step 3: an accessor with no setter refuses the write.
6260 // Sloppy code swallows that refusal, strict code raises — the same
6261 // rule the read-only *data* property below follows, and skipping it
6262 // made `(function(){"use strict"; o.x = 9})()` on a getter-only `x`
6263 // return silently. The reference answers `TypeError: 'x' is
6264 // read-only`.
6265 None => match on_failure {
6266 DeleteFailure::Throw => {
6267 Err(self.type_error(format!("'{key}' is read-only")))
6268 }
6269 DeleteFailure::Ignore => Ok(()),
6270 },
6271 };
6272 }
6273 // An own non-writable data property stops here: nothing may change it.
6274 if !property.writable {
6275 return match on_failure {
6276 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6277 DeleteFailure::Ignore => Ok(()),
6278 };
6279 }
6280 // An existing writable own property keeps its attributes: only the value
6281 // moves. Redefining instead would reset them, which is how a
6282 // non-configurable global `var` used to become deletable.
6283 if object.write_value_key(key, value.clone()) {
6284 return Ok(());
6285 }
6286 }
6287 // Step 2: hand the store to the prototype, with `object` as the receiver.
6288 if let Some(proto) = object.proto() {
6289 let receiver = Value::Object(object.clone());
6290 let accepted =
6291 self.ordinary_set_with_receiver(&proto, &receiver, key, value, on_failure)?;
6292 return if accepted {
6293 Ok(())
6294 } else {
6295 match on_failure {
6296 DeleteFailure::Throw => Err(self.type_error(format!("'{key}' is read-only"))),
6297 DeleteFailure::Ignore => Ok(()),
6298 }
6299 };
6300 }
6301 // Step 3: create one, and a non-extensible object cannot.
6302 if !object.is_extensible() {
6303 return match on_failure {
6304 DeleteFailure::Throw => Err(self.type_error(format!(
6305 "cannot add property {key}, object is not extensible"
6306 ))),
6307 DeleteFailure::Ignore => Ok(()),
6308 };
6309 }
6310 object.define_data_key(key, value);
6311 Ok(())
6312 }
6313
6314 /// §10.1.9 `OrdinarySet(O, P, V, Receiver)` when `Receiver` may not be `O`.
6315 ///
6316 /// The distinction the fast path above does not need: it is called with the store's
6317 /// receiver already being the object it writes to. Here `object` is the one whose
6318 /// **own descriptor** decides what happens, and `receiver` is the one that ends up
6319 /// holding the value — which is why step 3 is `CreateDataProperty(Receiver, …)`
6320 /// and not a write to `object`.
6321 ///
6322 /// This is what makes a typed array a usable prototype. `var p = new Uint8Array(1);
6323 /// var o = Object.create(p); o[0] = v` walks to `p`, finds a writable data descriptor
6324 /// for `0`, and *creates* `o[0]` — the view's buffer is untouched, and that is what
6325 /// `Set/key-is-valid-index-prototype-chain-set` asserts. A non-writable or accessor
6326 /// descriptor on the prototype refuses instead, which is the same rule that keeps
6327 /// `Object.create(Object.freeze({x: 1})).x = 9` a no-op.
6328 ///
6329 /// Answers `false` where the spec says `false`; the caller turns that into the
6330 /// strict-mode `TypeError` or the sloppy-mode silence.
6331 fn ordinary_set_with_receiver(
6332 &mut self,
6333 object: &Gc<JsObject>,
6334 receiver: &Value,
6335 key: &PropertyKey,
6336 value: Value,
6337 on_failure: DeleteFailure,
6338 ) -> JsResult<bool> {
6339 // A proxy's own `[[Set]]` is its `set` trap, and the trap receives the receiver.
6340 if object.proxy_state().is_some() {
6341 return Ok(self
6342 .proxy_set(object, key, value, receiver)?
6343 .unwrap_or(true));
6344 }
6345 // A host class decides for itself, with the receiver the caller named.
6346 if let Some(exotic) = object.exotic()
6347 && let Some(accepted) = exotic.set_property(self, object, key, &value, receiver)?
6348 {
6349 return Ok(accepted);
6350 }
6351 // §10.4.5.5 step 1.b, both halves. This is reached when a view is an ancestor
6352 // rather than the receiver, but the receiver may still *be* the view:
6353 // `Reflect.set(Object.create(view), 100, v, view)` delegates down to the view with
6354 // itself as receiver, and then the first half applies — convert `V` once, store
6355 // if the index is valid, answer `true` either way. The conversion is the observable
6356 // part (`key-is-out-of-bounds-receiver-is-proto` counts the `valueOf` calls).
6357 //
6358 // Only the second half, a view that is *not* the receiver, skips the conversion
6359 // (`key-is-canonical-invalid-index-prototype-chain-set` expects `valueOfCalls` to
6360 // stay 0), and a *valid* index there falls through to `OrdinarySetWithOwnDescriptor`
6361 // below with the value still unconverted.
6362 if object.typed_array_element_type().is_some()
6363 && let Some(numeric) = canonical_numeric_index(key)
6364 {
6365 if matches!(receiver, Value::Object(other) if other.ptr_eq(object)) {
6366 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
6367 return Ok(true);
6368 }
6369 if !typed_array_index_is_valid(object, numeric) {
6370 return Ok(true);
6371 }
6372 }
6373 let own = self.object_get_own_property(object, key)?;
6374 if let Some(own) = own {
6375 if own.is_accessor() {
6376 return match own.setter.filter(|v| !matches!(v, Value::Undefined)) {
6377 Some(setter) => {
6378 self.call_value(setter, receiver.clone(), vec![value])?;
6379 Ok(true)
6380 }
6381 None => Ok(false),
6382 };
6383 }
6384 // A non-writable data descriptor refuses, own or inherited. Either way the
6385 // receiver must not gain a shadowing property.
6386 if !own.writable {
6387 return Ok(false);
6388 }
6389 // Step 1.d: the *receiver's* own descriptor decides whether it can be
6390 // created or written, and it is created as an ordinary data property.
6391 let Some(receiver_object) = receiver.as_object().cloned() else {
6392 return Ok(false);
6393 };
6394 return match self.object_get_own_property(&receiver_object, key)? {
6395 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6396 Some(existing) => self.object_define_own_property(
6397 &receiver_object,
6398 key,
6399 Property {
6400 value: Some(value),
6401 ..existing
6402 },
6403 ),
6404 None => {
6405 self.object_define_own_property(&receiver_object, key, Property::data(value))
6406 }
6407 };
6408 }
6409 // Step 2: the proto's own `[[Set]]` answers next, with the same receiver.
6410 if let Some(proto) = object.proto() {
6411 return self.ordinary_set_with_receiver(&proto, receiver, key, value, on_failure);
6412 }
6413 // Step 3: nowhere above to inherit from. §10.1.9.2 step 1.d.iii substitutes the
6414 // *default* data descriptor here, so control falls into step 2 exactly as if the
6415 // target had owned a writable property — which means the **receiver's** own
6416 // descriptor is asked for before the write. Skipping that question went straight to
6417 // `CreateDataProperty`, so a proxy receiver's `getOwnPropertyDescriptor` trap never
6418 // ran on an absent key (`Proxy/set/trap-is-missing-receiver-multiple-calls` counts
6419 // exactly those calls).
6420 let Some(receiver_object) = receiver.as_object().cloned() else {
6421 return Ok(false);
6422 };
6423 match self.object_get_own_property(&receiver_object, key)? {
6424 Some(existing) if existing.is_accessor() || !existing.writable => Ok(false),
6425 Some(existing) => self.object_define_own_property(
6426 &receiver_object,
6427 key,
6428 Property {
6429 value: Some(value),
6430 ..existing
6431 },
6432 ),
6433 None => self.object_define_own_property(&receiver_object, key, Property::data(value)),
6434 }
6435 }
6436
6437 /// [`lookup_key`] for a store, with a host class's `get_own_property` trap first.
6438 ///
6439 /// The reference's `JS_SetPropertyInternal` asks the exotic `set_property` trap, and
6440 /// *failing that* asks `get_own_property` for the descriptor — which is how a class with
6441 /// a virtual accessor gets its setter run without implementing `set_property` at all.
6442 /// Answering `Some(None)` from the hook does not end the search: the key may still be on
6443 /// the prototype, so the walk resumes above the object.
6444 fn lookup_for_write(
6445 &mut self,
6446 object: &Gc<JsObject>,
6447 key: &PropertyKey,
6448 ) -> JsResult<Option<(Gc<JsObject>, Property)>> {
6449 let Some(exotic) = object.exotic() else {
6450 return Ok(lookup_key(object, key));
6451 };
6452 Ok(match exotic.get_own_property(self, object, key)? {
6453 Some(Some(property)) => Some((object.clone(), property)),
6454 Some(None) => lookup_key_above(object, key),
6455 None => lookup_key(object, key),
6456 })
6457 }
6458
6459 /// Delete `object[key]`.
6460 pub fn delete_property(&mut self, object: &Gc<JsObject>, key: &str) -> JsResult<bool> {
6461 self.delete_property_key(object, &PropertyKey::from(key))
6462 }
6463
6464 /// [`Interp::delete_property`] with a key that may be a symbol.
6465 pub fn delete_property_key(
6466 &mut self,
6467 object: &Gc<JsObject>,
6468 key: &PropertyKey,
6469 ) -> JsResult<bool> {
6470 // A proxy decides for itself, and may even throw; the invariant checks live in
6471 // `proxy_delete`.
6472 if let Some(answer) = self.proxy_delete(object, key)? {
6473 return Ok(answer);
6474 }
6475 // A host class's `delete_property` trap decides; `false` is a refusal, which the
6476 // caller reports as a failed delete.
6477 if let Some(exotic) = object.exotic()
6478 && let Some(answer) = exotic.delete_property(self, object, key)?
6479 {
6480 return Ok(answer);
6481 }
6482 // §10.4.5.5 `IntegerIndexedDelete`: a canonical numeric index never reaches the
6483 // property table. Every *invalid* index — out of range, `"-0"`, `"1.5"`, a
6484 // detached buffer — answers `true` (there is nothing to delete), and a *valid*
6485 // one answers `false` because the elements are non-configurable. The prototype
6486 // chain is not consulted either, which is what makes a throwing getter on
6487 // `TypedArray.prototype["-1"]` stay unrun.
6488 if object.typed_array_parts().is_some()
6489 && object.proxy_state().is_none()
6490 && let Some(numeric) = canonical_numeric_index(key)
6491 {
6492 return Ok(!typed_array_index_is_valid(object, numeric));
6493 }
6494 let mapped_index = key.as_str().and_then(array_index);
6495 if let Some(index) = mapped_index
6496 && let Some(length) = object.array_length()
6497 && (index as usize) < length
6498 {
6499 // An accessor defined on an index lives in the property table rather than the
6500 // element vector, so both have to be cleared: `delete` after
6501 // `Object.defineProperty(a, "1", {get})` used to leave the getter answering.
6502 object.delete_key(key);
6503 // A hole rather than a shift: `delete a[0]` leaves `length` alone and the
6504 // index stops answering `in`.
6505 if object.element_is_undeletable(index) {
6506 return Ok(false);
6507 }
6508 // §10.4.4.2 step 3: a *successful* delete of a mapped index ends the alias,
6509 // so a later `defineProperty(arguments, "0", {value})` writes to the object
6510 // and no longer through to the parameter. A refused delete leaves the
6511 // mapping alone.
6512 object.drop_mapped_argument(index as usize);
6513 object.array_set(self.heap, index as usize, Value::Hole);
6514 return Ok(true);
6515 }
6516 // An array's `length` is a non-configurable own property that lives outside the
6517 // property table, so `delete_key` finds nothing and reports success — `Reflect
6518 // .deleteProperty([1], "length")` answered `true` and left `length` in place.
6519 // §10.4.4.1 step 3 refuses it.
6520 if key.as_str() == Some("length") && object.array_length().is_some() {
6521 return Ok(false);
6522 }
6523 // The same for an object that is not an array: only a delete that actually
6524 // removed the property ends the alias.
6525 let deleted = object.delete_key(key);
6526 if deleted && let Some(index) = mapped_index {
6527 object.drop_mapped_argument(index as usize);
6528 }
6529 Ok(deleted)
6530 }
6531
6532 // -- proxy traps --------------------------------------------------------
6533 //
6534 // A proxy's internal methods all look the same: ask the handler for the trap, call it
6535 // with the target and the operation's own arguments, then check the answer against
6536 // the target. The checks are not decoration — they are what stops a proxy from
6537 // reporting a `non-configurable` property as missing, which would let a frozen object
6538 // be rewritten by standing in front of it.
6539
6540 /// The target and handler of `object`, or `None` when it is not a proxy.
6541 ///
6542 /// A *revoked* proxy is a `TypeError` rather than `None`, because every operation on
6543 /// one has to fail: the slots the traps would have been read from are gone.
6544 pub(crate) fn proxy_parts(
6545 &mut self,
6546 object: &Gc<JsObject>,
6547 ) -> JsResult<Option<(Gc<JsObject>, Value)>> {
6548 let Some(state) = object.proxy_state() else {
6549 return Ok(None);
6550 };
6551 let state = state.borrow();
6552 match (&state.target, &state.handler) {
6553 (Some(target), Some(handler)) => Ok(Some((target.clone(), handler.clone()))),
6554 _ => Err(self.type_error("cannot use a proxy that has been revoked")),
6555 }
6556 }
6557
6558 /// Call `handler[name]`, or answer `None` when the trap is absent.
6559 ///
6560 /// §10.5.1 `GetMethod(handler, name)`: **`null` and `undefined` both mean "no trap"**,
6561 /// and only a value that is neither is `IsCallable`-checked and refused. Treating
6562 /// `null` as "present but not callable" made every `{ get: null }` proxy throw
6563 /// `TypeError`, where the spec says to fall through to the target — 15 test262 cases,
6564 /// one per trap plus the `target-is-proxy` variants.
6565 ///
6566 /// `{ get: 1 }` still throws: that is the `IsCallable` refusal, and it is the reason
6567 /// this cannot simply be "any non-callable means no trap".
6568 fn proxy_trap(
6569 &mut self,
6570 handler: &Value,
6571 name: &str,
6572 args: Vec<Value>,
6573 ) -> JsResult<Option<Value>> {
6574 let Value::Object(table) = handler else {
6575 return Err(self.type_error("proxy handler is not an object"));
6576 };
6577 let trap = self.get_property(table, name)?.unwrap_or(Value::Undefined);
6578 match trap {
6579 Value::Undefined | Value::Null => Ok(None),
6580 Value::Object(function) if function.is_callable() => {
6581 let answer = self.call_value(Value::Object(function), handler.clone(), args)?;
6582 Ok(Some(answer))
6583 }
6584 _ => Err(self.type_error(format!("proxy trap '{name}' is not a function"))),
6585 }
6586 }
6587
6588 /// Whether the target's own property `key` is one it refuses to lose.
6589 ///
6590 /// A non-configurable property is fixed: no trap may hide it, delete it, or change
6591 /// its value behind the target's back.
6592 ///
6593 /// A **method**, not a free function, because §10.5.1's invariants say
6594 /// `target.[[GetOwnProperty]](P)` and the target may itself be a proxy: reading its
6595 /// property table directly finds nothing (a proxy's table is empty by design), so every
6596 /// invariant check silently passed for a proxy target. That is what
6597 /// `Proxy/*/trap-is-*-target-is-proxy.js` are for, and what the batch-B commit fixes.
6598 /// [`Self::ordinary_own_property`] still does the work for an ordinary target, which is
6599 /// where an array's elements and its `length` — both fixed, both outside the table —
6600 /// are covered.
6601 fn fixed_property(
6602 &mut self,
6603 target: &Gc<JsObject>,
6604 key: &PropertyKey,
6605 ) -> JsResult<Option<Property>> {
6606 Ok(self
6607 .object_get_own_property(target, key)?
6608 .filter(|property| !property.configurable))
6609 }
6610
6611 /// `[[Get]]` on a proxy. `Some` means the proxy answered, `None` means "not a proxy".
6612 fn proxy_get(
6613 &mut self,
6614 object: &Gc<JsObject>,
6615 receiver: &Value,
6616 key: &PropertyKey,
6617 ) -> JsResult<Option<Value>> {
6618 let Some((target, handler)) = self.proxy_parts(object)? else {
6619 return Ok(None);
6620 };
6621 let key_value = self.key_value(key);
6622 let Some(result) = self.proxy_trap(
6623 &handler,
6624 "get",
6625 vec![Value::Object(target.clone()), key_value, receiver.clone()],
6626 )?
6627 else {
6628 // No trap: forward to the target's own `[[Get]]`, keeping the receiver so an
6629 // inherited getter still sees the proxy.
6630 return Ok(Some(
6631 self.get_property_key_for(&target, Some(receiver), key)?
6632 .unwrap_or(Value::Undefined),
6633 ));
6634 };
6635 if let Some(fixed) = self.fixed_property(&target, key)? {
6636 if fixed.is_accessor() {
6637 // A fixed accessor with no getter must read as `undefined`.
6638 let has_getter = fixed
6639 .getter
6640 .as_ref()
6641 .is_some_and(|getter| !matches!(getter, Value::Undefined));
6642 if !has_getter && !matches!(result, Value::Undefined) {
6643 return Err(self.type_error(format!(
6644 "proxy 'get' must report undefined for the non-configurable property '{key}'"
6645 )));
6646 }
6647 } else if !fixed.writable {
6648 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6649 if !fixed_value.same_value(&result) {
6650 return Err(self.type_error(format!(
6651 "proxy 'get' disagrees with the non-configurable property '{key}'"
6652 )));
6653 }
6654 }
6655 }
6656 Ok(Some(result))
6657 }
6658
6659 /// `[[Set]]` on a proxy.
6660 ///
6661 /// The boolean is the trap's answer: the caller turns `false` into a `TypeError` in
6662 /// strict mode and a silent no-op in sloppy mode, which is the same split an ordinary
6663 /// read-only store has.
6664 fn proxy_set(
6665 &mut self,
6666 object: &Gc<JsObject>,
6667 key: &PropertyKey,
6668 value: Value,
6669 receiver: &Value,
6670 ) -> JsResult<Option<bool>> {
6671 let Some((target, handler)) = self.proxy_parts(object)? else {
6672 return Ok(None);
6673 };
6674 let key_value = self.key_value(key);
6675 let Some(result) = self.proxy_trap(
6676 &handler,
6677 "set",
6678 vec![
6679 Value::Object(target.clone()),
6680 key_value,
6681 value.clone(),
6682 receiver.clone(),
6683 ],
6684 )?
6685 else {
6686 // No trap: `[[Set]]` on the target, but with the *receiver* the proxy was
6687 // given — not the target. `OrdinarySet` step 3 is
6688 // `CreateDataProperty(Receiver, …)`, so a proxy standing in front of an
6689 // object whose prototype is a typed array has to reach the proxy's own
6690 // `defineProperty` trap: `key-is-valid-index-prototype-chain-set` counts the
6691 // calls and expects exactly one. Storing on the target instead put the value
6692 // in the target and never consulted the trap.
6693 let accepted = self.ordinary_set_with_receiver(
6694 &target,
6695 receiver,
6696 key,
6697 value,
6698 DeleteFailure::Ignore,
6699 )?;
6700 return Ok(Some(accepted));
6701 };
6702 if !result.to_boolean() {
6703 return Ok(Some(false));
6704 }
6705 if let Some(fixed) = self.fixed_property(&target, key)? {
6706 if fixed.is_accessor() {
6707 let has_setter = fixed
6708 .setter
6709 .as_ref()
6710 .is_some_and(|setter| !matches!(setter, Value::Undefined));
6711 if !has_setter {
6712 return Err(self.type_error(format!(
6713 "proxy 'set' succeeded on the non-configurable accessor '{key}', which has no setter"
6714 )));
6715 }
6716 } else if !fixed.writable {
6717 let fixed_value = fixed.value.unwrap_or(Value::Undefined);
6718 if !fixed_value.same_value(&value) {
6719 return Err(self.type_error(format!(
6720 "proxy 'set' changed the non-configurable property '{key}'"
6721 )));
6722 }
6723 }
6724 }
6725 // A new property cannot appear on a target that refuses new properties.
6726 if self.object_get_own_property(&target, key)?.is_none()
6727 && !self.object_is_extensible(&target)?
6728 {
6729 return Err(self.type_error(format!(
6730 "proxy 'set' added '{key}' to a non-extensible target"
6731 )));
6732 }
6733 Ok(Some(true))
6734 }
6735
6736 /// `[[HasProperty]]` on a proxy, which is the `in` operator.
6737 fn proxy_has(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6738 let Some((target, handler)) = self.proxy_parts(object)? else {
6739 return Ok(None);
6740 };
6741 let key_value = self.key_value(key);
6742 let Some(result) = self.proxy_trap(
6743 &handler,
6744 "has",
6745 vec![Value::Object(target.clone()), key_value],
6746 )?
6747 else {
6748 return Ok(Some(self.has_own_or_inherited(&target, key)?));
6749 };
6750 if !result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
6751 return Err(self.type_error(format!(
6752 "proxy 'has' denied the non-configurable property '{key}'"
6753 )));
6754 }
6755 // A non-extensible target cannot grow, so every own property it *has* is fixed.
6756 if !result.to_boolean()
6757 && !self.object_is_extensible(&target)?
6758 && self.object_get_own_property(&target, key)?.is_some()
6759 {
6760 return Err(self.type_error(format!(
6761 "proxy 'has' denied the own property '{key}' of a non-extensible target"
6762 )));
6763 }
6764 Ok(Some(result.to_boolean()))
6765 }
6766
6767 /// `[[Delete]]` on a proxy.
6768 fn proxy_delete(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<Option<bool>> {
6769 let Some((target, handler)) = self.proxy_parts(object)? else {
6770 return Ok(None);
6771 };
6772 let key_value = self.key_value(key);
6773 let Some(result) = self.proxy_trap(
6774 &handler,
6775 "deleteProperty",
6776 vec![Value::Object(target.clone()), key_value],
6777 )?
6778 else {
6779 return Ok(Some(self.delete_property_key(&target, key)?));
6780 };
6781 if result.to_boolean() && self.fixed_property(&target, key)?.is_some() {
6782 return Err(self.type_error(format!(
6783 "proxy 'deleteProperty' removed the non-configurable property '{key}'"
6784 )));
6785 }
6786 if result.to_boolean()
6787 && !self.object_is_extensible(&target)?
6788 && self.object_get_own_property(&target, key)?.is_some()
6789 {
6790 return Err(self.type_error(format!(
6791 "proxy 'deleteProperty' removed '{key}' from a non-extensible target"
6792 )));
6793 }
6794 Ok(Some(result.to_boolean()))
6795 }
6796
6797 /// The own keys a proxy reports, after the `ownKeys` trap and its invariants.
6798 fn proxy_own_keys(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Vec<PropertyKey>>> {
6799 let Some((target, handler)) = self.proxy_parts(object)? else {
6800 return Ok(None);
6801 };
6802 let Some(result) =
6803 self.proxy_trap(&handler, "ownKeys", vec![Value::Object(target.clone())])?
6804 else {
6805 // No trap: the target's own keys, already in the order an object reports.
6806 return Ok(Some(self.object_own_property_keys(&target)?));
6807 };
6808 // `CreateListFromArrayLike` with the string-or-symbol restriction.
6809 let list = self.list_from_array_like(&result, true)?;
6810 let mut keys: Vec<PropertyKey> = Vec::with_capacity(list.len());
6811 for value in list {
6812 let key = self.propkey(&value)?;
6813 if keys.contains(&key) {
6814 return Err(self.type_error(format!(
6815 "proxy 'ownKeys' returned the duplicate key '{key}'"
6816 )));
6817 }
6818 keys.push(key);
6819 }
6820 // The invariants are stated over `target.[[OwnPropertyKeys]]()` and
6821 // `target.[[GetOwnProperty]](key)`, so both have to dispatch: a proxy target's own
6822 // table is empty, which made every check below vacuous.
6823 let target_keys = self.object_own_property_keys(&target)?;
6824 let extensible = self.object_is_extensible(&target)?;
6825 for key in &target_keys {
6826 if keys.contains(key) {
6827 continue;
6828 }
6829 if self.fixed_property(&target, key)?.is_some() {
6830 return Err(self.type_error(format!(
6831 "proxy 'ownKeys' dropped the non-configurable key '{key}'"
6832 )));
6833 }
6834 if !extensible {
6835 return Err(self.type_error(format!(
6836 "proxy 'ownKeys' dropped '{key}', which a non-extensible target owns"
6837 )));
6838 }
6839 }
6840 if !extensible {
6841 // §10.5.11 step 12: the lists must match one for one, in any order.
6842 if keys.len() != target_keys.len() || target_keys.iter().any(|key| !keys.contains(key))
6843 {
6844 return Err(
6845 self.type_error("proxy 'ownKeys' does not match its non-extensible target")
6846 );
6847 }
6848 }
6849 Ok(Some(keys))
6850 }
6851
6852 /// `[[GetOwnProperty]]` on a proxy.
6853 fn proxy_get_own_property(
6854 &mut self,
6855 object: &Gc<JsObject>,
6856 key: &PropertyKey,
6857 ) -> JsResult<Option<Option<Property>>> {
6858 let Some((target, handler)) = self.proxy_parts(object)? else {
6859 return Ok(None);
6860 };
6861 let key_value = self.key_value(key);
6862 let Some(result) = self.proxy_trap(
6863 &handler,
6864 "getOwnPropertyDescriptor",
6865 vec![Value::Object(target.clone()), key_value],
6866 )?
6867 else {
6868 // No trap: `? target.[[GetOwnProperty]](P)` — the **internal method**, not the
6869 // property table. Two things ride on that choice: a target that is itself a
6870 // proxy has to re-dispatch (its own table is empty, so reading it reported
6871 // `undefined` for every key, `Object.keys` then dropped them all), and an array's
6872 // indices and `length` live outside the table and need the ordinary synthesis.
6873 // `object_get_own_property` does both.
6874 return Ok(Some(self.object_get_own_property(&target, key)?));
6875 };
6876 // §10.5.5 step 10: neither `undefined` nor an object is a `TypeError` **before**
6877 // `ToPropertyDescriptor` runs, because that operation would box the primitive
6878 // (`ToPropertyDescriptor(1)` is not `ToPropertyDescriptor(Object(1))`) and answer an
6879 // empty descriptor instead of refusing.
6880 if !matches!(result, Value::Undefined | Value::Object(_)) {
6881 return Err(self.type_error(
6882 "proxy 'getOwnPropertyDescriptor' must return an object or undefined",
6883 ));
6884 }
6885 let target_desc = self.object_get_own_property(&target, key)?;
6886 let extensible = self.object_is_extensible(&target)?;
6887 let Some(descriptor) = (match result {
6888 Value::Undefined => None,
6889 _ => Some(self.property_from_descriptor(&result)?),
6890 }) else {
6891 // Steps 12.a–12.d: reporting absent is allowed only when the target's own
6892 // descriptor is configurable *and* the target can still grow back.
6893 if let Some(target_desc) = &target_desc {
6894 if !target_desc.configurable {
6895 return Err(self.type_error(format!(
6896 "proxy 'getOwnPropertyDescriptor' hid the non-configurable property '{key}'"
6897 )));
6898 }
6899 if !extensible {
6900 return Err(self.type_error(format!(
6901 "proxy 'getOwnPropertyDescriptor' hid '{key}' from a non-extensible target"
6902 )));
6903 }
6904 }
6905 return Ok(Some(None));
6906 };
6907 // Steps 15/16: a non-configurable answer has to be *compatible* with the target,
6908 // which is a stronger requirement than "the target is not contradicting it" — the
6909 // four branches below are each one test262 case.
6910 if !descriptor.configurable {
6911 let Some(target_desc) = &target_desc else {
6912 return Err(self.type_error(format!(
6913 "proxy 'getOwnPropertyDescriptor' invented the non-configurable property '{key}'"
6914 )));
6915 };
6916 if target_desc.configurable {
6917 return Err(self.type_error(format!(
6918 "proxy 'getOwnPropertyDescriptor' made '{key}' non-configurable"
6919 )));
6920 }
6921 let target_is_data = !target_desc.is_accessor();
6922 let result_is_data = !descriptor.is_accessor();
6923 if result_is_data && !target_is_data {
6924 return Err(self.type_error(format!(
6925 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6926 )));
6927 }
6928 if target_is_data && !target_desc.writable {
6929 if !result_is_data {
6930 return Err(self.type_error(format!(
6931 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6932 )));
6933 }
6934 if descriptor.writable {
6935 return Err(self.type_error(format!(
6936 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
6937 )));
6938 }
6939 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
6940 let reported = descriptor.value.clone().unwrap_or(Value::Undefined);
6941 if !fixed_value.same_value(&reported) {
6942 return Err(self.type_error(format!(
6943 "proxy 'getOwnPropertyDescriptor' changed the value of '{key}'"
6944 )));
6945 }
6946 }
6947 // Step 16.d: a reported *read-only* data property needs a real read-only data
6948 // property behind it. Missing this let a trap bolt a frozen property onto a
6949 // writable target intent (`resultdesc-is-not-configurable-not-writable-
6950 // targetdesc-is-writable`).
6951 if result_is_data && !descriptor.writable {
6952 if !target_is_data {
6953 return Err(self.type_error(format!(
6954 "proxy 'getOwnPropertyDescriptor' changed the kind of '{key}'"
6955 )));
6956 }
6957 if target_desc.writable {
6958 return Err(self.type_error(format!(
6959 "proxy 'getOwnPropertyDescriptor' made '{key}' read-only"
6960 )));
6961 }
6962 }
6963 if descriptor.is_accessor() {
6964 // Step 16.e: a getter the target does not have may not be invented, and
6965 // vice versa.
6966 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
6967 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
6968 (Some(a), Some(b)) => a.same_value(b),
6969 _ => false,
6970 };
6971 if !same(&target_desc.getter, &descriptor.getter)
6972 || !same(&target_desc.setter, &descriptor.setter)
6973 {
6974 return Err(self.type_error(format!(
6975 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
6976 )));
6977 }
6978 }
6979 }
6980 // Step 18, the mirror of 17.b: a trap may not report a **configurable** property
6981 // where the target's own is locked. Without it a handler could advertise
6982 // `{value: 1, configurable: true}` for a non-configurable property, and a caller
6983 // that believed it would try to redefine something it cannot.
6984 if descriptor.configurable
6985 && let Some(target_desc) = &target_desc
6986 && !target_desc.configurable
6987 {
6988 return Err(self.type_error(format!(
6989 "proxy 'getOwnPropertyDescriptor' made '{key}' configurable"
6990 )));
6991 }
6992 // §10.5.5 step 17: a target that cannot grow may not have a property **appear**
6993 // through the trap either, however well-formed the descriptor is. This is the
6994 // `resultdesc-is-invalid-descriptor` case: a perfectly valid descriptor for a key
6995 // the frozen target does not own.
6996 if !extensible {
6997 let Some(target_desc) = &target_desc else {
6998 return Err(self.type_error(format!(
6999 "proxy 'getOwnPropertyDescriptor' invented '{key}' on a non-extensible target"
7000 )));
7001 };
7002 if target_desc.is_accessor() == descriptor.is_accessor() {
7003 let target_is_data = !target_desc.is_accessor();
7004 let result_is_data = !descriptor.is_accessor();
7005 if target_is_data && !target_desc.writable && descriptor.writable {
7006 return Err(self.type_error(format!(
7007 "proxy 'getOwnPropertyDescriptor' made the read-only '{key}' writable"
7008 )));
7009 }
7010 if !result_is_data && !target_is_data {
7011 let same = |a: &Option<Value>, b: &Option<Value>| match (a, b) {
7012 (None | Some(Value::Undefined), None | Some(Value::Undefined)) => true,
7013 (Some(a), Some(b)) => a.same_value(b),
7014 _ => false,
7015 };
7016 if !same(&target_desc.getter, &descriptor.getter)
7017 || !same(&target_desc.setter, &descriptor.setter)
7018 {
7019 return Err(self.type_error(format!(
7020 "proxy 'getOwnPropertyDescriptor' changed the accessors of '{key}'"
7021 )));
7022 }
7023 }
7024 }
7025 }
7026 Ok(Some(Some(descriptor)))
7027 }
7028
7029 /// One `[[DefineOwnProperty]]` step of `SetIntegrityLevel` on a proxy (§7.3.3 step 3.a).
7030 ///
7031 /// Separate from [`Interp::object_define_own_property`] for one reason: the descriptor
7032 /// a proxy's `defineProperty` trap receives must be the *partial* one the spec built —
7033 /// `{ [[Configurable]]: false }`, plus `{ [[Writable]]: false }` at `Frozen` and only
7034 /// for a data property. `Property` cannot express "this field is absent", so the whole
7035 /// property path is skipped and the descriptor is assembled here field by field.
7036 ///
7037 /// `current` is the property the trap reported, used only to tell a data property from
7038 /// an accessor.
7039 pub fn proxy_seal_property(
7040 &mut self,
7041 object: &Gc<JsObject>,
7042 key: &PropertyKey,
7043 frozen: bool,
7044 current: &Property,
7045 ) -> JsResult<bool> {
7046 let Some((_target, handler)) = self.proxy_parts(object)? else {
7047 return Err(self.type_error("not a proxy"));
7048 };
7049 let descriptor = self.new_object(None);
7050 descriptor.define_data("configurable", Value::Bool(false));
7051 if frozen && !current.is_accessor() {
7052 descriptor.define_data("writable", Value::Bool(false));
7053 }
7054 let key_value = self.key_value(key);
7055 let target = object
7056 .proxy_state()
7057 .and_then(|state| state.borrow().target.clone());
7058 let Some(target) = target else {
7059 return Err(self.type_error("cannot use a proxy that has been revoked"));
7060 };
7061 let Some(result) = self.proxy_trap(
7062 &handler,
7063 "defineProperty",
7064 vec![Value::Object(target), key_value, Value::Object(descriptor)],
7065 )?
7066 else {
7067 // No trap means the definition belongs to the target; `false` is its answer.
7068 return Ok(false);
7069 };
7070 Ok(result.to_boolean())
7071 }
7072
7073 /// `[[DefineOwnProperty]]` on a proxy.
7074 fn proxy_define_property(
7075 &mut self,
7076 object: &Gc<JsObject>,
7077 key: &PropertyKey,
7078 property: Property,
7079 ) -> JsResult<Option<bool>> {
7080 let Some((target, handler)) = self.proxy_parts(object)? else {
7081 return Ok(None);
7082 };
7083 let key_value = self.key_value(key);
7084 let descriptor = self.descriptor_from_property(&property);
7085 let Some(result) = self.proxy_trap(
7086 &handler,
7087 "defineProperty",
7088 vec![Value::Object(target.clone()), key_value, descriptor],
7089 )?
7090 else {
7091 // No trap: `? target.[[DefineOwnProperty]](P, Desc)`. `None` is the "keep
7092 // going" answer and `object_define_own_property` turns it into exactly that
7093 // forwarding — see the note there. (Reading it as "not a proxy" would define
7094 // the property on the proxy object itself, whose table is empty and which no
7095 // read ever consults.)
7096 return Ok(None);
7097 };
7098 if !result.to_boolean() {
7099 return Ok(Some(false));
7100 }
7101 // §10.5.4 steps 9–15. Every branch below is keyed on a descriptor field being
7102 // **named** (`Desc has [[Writable]]`), which is what `descriptor_fields` carries:
7103 // `{writable: false}` and an omitted `writable` are the same `Property` otherwise,
7104 // and treating them alike made four cases pass a descriptor the target contradicts.
7105 let target_desc = self.object_get_own_property(&target, key)?;
7106 let extensible = self.object_is_extensible(&target)?;
7107 let named = property
7108 .descriptor_fields
7109 .unwrap_or(crate::object::DescriptorFields {
7110 value: false,
7111 writable: false,
7112 enumerable: false,
7113 configurable: false,
7114 get: false,
7115 set: false,
7116 });
7117 if named.configurable && !property.configurable {
7118 let Some(target_desc) = &target_desc else {
7119 return Err(self.type_error(format!(
7120 "proxy 'defineProperty' invented the non-configurable '{key}'"
7121 )));
7122 };
7123 if target_desc.configurable {
7124 return Err(self.type_error(format!(
7125 "proxy 'defineProperty' made '{key}' non-configurable"
7126 )));
7127 }
7128 }
7129 // Step 11's other half: reporting that a property was made *configurable* needs a
7130 // property that is configurable. Without it `Object.defineProperty(proxy, "foo",
7131 // {value: 1, configurable: true})` claimed success over a non-configurable `foo`
7132 // and changed nothing (`targetdesc-not-compatible-descriptor-not-configurable-
7133 // target`).
7134 if named.configurable
7135 && property.configurable
7136 && let Some(target_desc) = &target_desc
7137 && !target_desc.configurable
7138 {
7139 return Err(
7140 self.type_error(format!("proxy 'defineProperty' made '{key}' configurable"))
7141 );
7142 }
7143 // Step 12: a property cannot be reported *made writable* when the target's copy is
7144 // read-only. Note the `Some` — an absent target property is *not* a contradiction:
7145 // the trap is allowed to claim a definition it did not perform, as long as the
7146 // target can still grow (`{value: 2, writable: true}` on an empty proxy target is
7147 // legal, and refusing it broke the commonest way to seed a proxy).
7148 if named.writable
7149 && property.writable
7150 && let Some(target_desc) = &target_desc
7151 && !target_desc.writable
7152 {
7153 return Err(self.type_error(format!(
7154 "proxy 'defineProperty' made the read-only '{key}' writable"
7155 )));
7156 }
7157 // Step 13: making a property read-only needs an existing read-only property.
7158 if named.writable
7159 && !property.writable
7160 && let Some(target_desc) = &target_desc
7161 && !target_desc.is_accessor()
7162 && target_desc.writable
7163 {
7164 return Err(self.type_error(format!("proxy 'defineProperty' made '{key}' read-only")));
7165 }
7166 // Step 14: a non-writable, non-configurable property's value is fixed.
7167 if named.value
7168 && let Some(target_desc) = &target_desc
7169 && !target_desc.is_accessor()
7170 && !target_desc.writable
7171 && !target_desc.configurable
7172 {
7173 let fixed_value = target_desc.value.clone().unwrap_or(Value::Undefined);
7174 let reported = property.value.clone().unwrap_or(Value::Undefined);
7175 if !fixed_value.same_value(&reported) {
7176 return Err(self.type_error(format!(
7177 "proxy 'defineProperty' changed the value of '{key}'"
7178 )));
7179 }
7180 }
7181 // Step 15: a non-extensible target cannot grow.
7182 if target_desc.is_none() && !extensible {
7183 return Err(self.type_error(format!(
7184 "proxy 'defineProperty' added '{key}' to a non-extensible target"
7185 )));
7186 }
7187 Ok(Some(true))
7188 }
7189
7190 /// `[[GetPrototypeOf]]` on a proxy.
7191 fn proxy_get_prototype_of(
7192 &mut self,
7193 object: &Gc<JsObject>,
7194 ) -> JsResult<Option<Option<Gc<JsObject>>>> {
7195 let Some((target, handler)) = self.proxy_parts(object)? else {
7196 return Ok(None);
7197 };
7198 let Some(result) = self.proxy_trap(
7199 &handler,
7200 "getPrototypeOf",
7201 vec![Value::Object(target.clone())],
7202 )?
7203 else {
7204 // `? target.[[GetPrototypeOf]]()`. A proxy object stores **no** prototype of its
7205 // own (`JsObject::proxy` passes `None`), so `target.proto()` answered `None` for
7206 // a proxy target and the chain ended there — `Object.getPrototypeOf(new
7207 // Proxy(/(?:)/i, {}))` was `null`, which cost the whole
7208 // `trap-is-*-target-is-proxy` family in `Proxy/get`.
7209 return Ok(Some(self.object_prototype_of(&target)?));
7210 };
7211 let proto = match &result {
7212 Value::Null => None,
7213 Value::Object(proto) => Some(proto.clone()),
7214 _ => {
7215 return Err(self.type_error("proxy 'getPrototypeOf' must return an object or null"));
7216 }
7217 };
7218 if !self.object_is_extensible(&target)? {
7219 let actual = self.object_prototype_of(&target)?;
7220 if !same_proto(proto.as_ref(), actual.as_ref()) {
7221 return Err(self.type_error(
7222 "proxy 'getPrototypeOf' changed the prototype of a non-extensible target",
7223 ));
7224 }
7225 }
7226 Ok(Some(proto))
7227 }
7228
7229 /// `[[SetPrototypeOf]]` on a proxy.
7230 fn proxy_set_prototype_of(
7231 &mut self,
7232 object: &Gc<JsObject>,
7233 proto: Option<Gc<JsObject>>,
7234 ) -> JsResult<Option<bool>> {
7235 let Some((target, handler)) = self.proxy_parts(object)? else {
7236 return Ok(None);
7237 };
7238 let proto_value = match &proto {
7239 Some(proto) => Value::Object(proto.clone()),
7240 None => Value::Null,
7241 };
7242 let Some(result) = self.proxy_trap(
7243 &handler,
7244 "setPrototypeOf",
7245 vec![Value::Object(target.clone()), proto_value],
7246 )?
7247 else {
7248 // `? target.[[SetPrototypeOf]](V)` — dispatch, so a proxy target keeps its own
7249 // `setPrototypeOf` trap (and its own non-extensible refusal) instead of having
7250 // its stored prototype overwritten behind its back.
7251 return Ok(Some(self.object_set_prototype_of(&target, proto)?));
7252 };
7253 if result.to_boolean()
7254 && !self.object_is_extensible(&target)?
7255 && !same_proto(
7256 Some(&proto).and_then(|p| p.clone()).as_ref(),
7257 self.object_prototype_of(&target)?.as_ref(),
7258 )
7259 {
7260 return Err(self.type_error(
7261 "proxy 'setPrototypeOf' changed the prototype of a non-extensible target",
7262 ));
7263 }
7264 Ok(Some(result.to_boolean()))
7265 }
7266
7267 /// `[[IsExtensible]]` on a proxy.
7268 fn proxy_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7269 let Some((target, handler)) = self.proxy_parts(object)? else {
7270 return Ok(None);
7271 };
7272 let Some(result) = self.proxy_trap(
7273 &handler,
7274 "isExtensible",
7275 vec![Value::Object(target.clone())],
7276 )?
7277 else {
7278 return Ok(Some(self.object_is_extensible(&target)?));
7279 };
7280 // The answer is not the proxy's to invent: it must agree with the target, or a
7281 // script could learn `false` while the target keeps accepting new properties.
7282 if result.to_boolean() != self.object_is_extensible(&target)? {
7283 return Err(self.type_error("proxy 'isExtensible' disagrees with its target"));
7284 }
7285 Ok(Some(result.to_boolean()))
7286 }
7287
7288 /// `[[PreventExtensions]]` on a proxy.
7289 fn proxy_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<Option<bool>> {
7290 let Some((target, handler)) = self.proxy_parts(object)? else {
7291 return Ok(None);
7292 };
7293 let Some(result) = self.proxy_trap(
7294 &handler,
7295 "preventExtensions",
7296 vec![Value::Object(target.clone())],
7297 )?
7298 else {
7299 // `? target.[[PreventExtensions]]()` — a proxy target must run *its* trap, and
7300 // its answer can be `false`.
7301 return Ok(Some(self.object_prevent_extensions(&target)?));
7302 };
7303 if result.to_boolean() && self.object_is_extensible(&target)? {
7304 return Err(self.type_error(
7305 "proxy 'preventExtensions' reported success but the target is still extensible",
7306 ));
7307 }
7308 Ok(Some(result.to_boolean()))
7309 }
7310
7311 /// `[[Call]]` on a proxy, through the `apply` trap.
7312 fn proxy_apply(
7313 &mut self,
7314 object: &Gc<JsObject>,
7315 this: Value,
7316 args: Vec<Value>,
7317 ) -> JsResult<Option<Value>> {
7318 let Some((target, handler)) = self.proxy_parts(object)? else {
7319 return Ok(None);
7320 };
7321 // The trap gets the arguments as one array, which is the shape the spec passes
7322 // and the shape `apply` traps are written against (`args[0]` is the first one).
7323 let arguments = self.new_array(args.clone());
7324 let this_for_trap = this.clone();
7325 let Some(result) = self.proxy_trap(
7326 &handler,
7327 "apply",
7328 vec![
7329 Value::Object(target.clone()),
7330 this_for_trap,
7331 Value::Object(arguments),
7332 ],
7333 )?
7334 else {
7335 return Ok(Some(self.call_value(Value::Object(target), this, args)?));
7336 };
7337 Ok(Some(result))
7338 }
7339
7340 /// `[[Construct]]` on a proxy, through the `construct` trap.
7341 fn proxy_construct(
7342 &mut self,
7343 object: &Gc<JsObject>,
7344 args: Vec<Value>,
7345 new_target: &Value,
7346 ) -> JsResult<Option<Value>> {
7347 let Some((target, handler)) = self.proxy_parts(object)? else {
7348 return Ok(None);
7349 };
7350 if !target.is_callable() {
7351 return Err(self.type_error("proxy target is not a constructor"));
7352 }
7353 let arguments = self.new_array(args.clone());
7354 let Some(result) = self.proxy_trap(
7355 &handler,
7356 "construct",
7357 vec![
7358 Value::Object(target.clone()),
7359 Value::Object(arguments),
7360 new_target.clone(),
7361 ],
7362 )?
7363 else {
7364 return Ok(Some(self.construct(
7365 Value::Object(target),
7366 new_target.clone(),
7367 args,
7368 )?));
7369 };
7370 if !matches!(result, Value::Object(_)) {
7371 return Err(self.type_error("proxy 'construct' must return an object"));
7372 }
7373 Ok(Some(result))
7374 }
7375
7376 /// `[[HasProperty]]` on an ordinary object, which the proxy fallback needs.
7377 pub(crate) fn has_own_or_inherited(
7378 &mut self,
7379 object: &Gc<JsObject>,
7380 key: &PropertyKey,
7381 ) -> JsResult<bool> {
7382 // The object itself first: it may be a proxy, and then the answer is its trap's.
7383 if let Some(answer) = self.proxy_has(object, key)? {
7384 return Ok(answer);
7385 }
7386 // An integer-indexed exotic object answers a canonical numeric index from
7387 // `IsValidIntegerIndex` alone (§10.4.5.2 step 1.b) — **without** walking the
7388 // prototype chain. That is observable twice: a view the buffer has been resized
7389 // away from has no indices, so `2 in view` is `false` even when
7390 // `Object.getPrototypeOf(view)[2]` exists (what
7391 // `TypedArray/out-of-bounds-behaves-like-detached` catches), and a
7392 // canonical-but-invalid key such as `"-0"` or `"1.5"` answers `false` where the
7393 // chain would have answered `true`. The `[[HasProperty]]` that `in` compiles to
7394 // goes through here, which is why the same rule is repeated in `has_property_key`
7395 // rather than living only there.
7396 if object.typed_array_parts().is_some()
7397 && let Some(numeric) = canonical_numeric_index(key)
7398 {
7399 return Ok(typed_array_index_is_valid(object, numeric));
7400 }
7401 // A host class answers `in` for its own keys, which may live nowhere in a property
7402 // table — `"x" in point` is true because the class says so, not because a property
7403 // exists.
7404 if let Some(exotic) = object.exotic()
7405 && let Some(answer) = exotic.has_property(self, object, key)?
7406 {
7407 return Ok(answer);
7408 }
7409 // `has_own` rather than `own_property_key`: an array's elements and its derived
7410 // `length` are invisible to the property table, and `Array.prototype` is an array.
7411 // A host class's `get_own_property` counts too, because the reference's
7412 // `JS_HasProperty` asks `JS_GetOwnPropertyInternal`, and that is where the hook
7413 // lives — a class with only `get_own_property` answers `in` through it.
7414 if self.exotic_has_own(object, key)? {
7415 return Ok(true);
7416 }
7417 // A hole is *not* the end of the search: the chain may still have the key, which
7418 // is why `Array.prototype[4] = 5` makes `4 in [1,2,3,4,]` true.
7419 for ancestor in object.chain() {
7420 // A proxy further up the chain answers for itself.
7421 if let Some(answer) = self.proxy_has(&ancestor, key)? {
7422 return Ok(answer);
7423 }
7424 // Same for a host class: a prototype may be one, and `in` reaches it.
7425 if let Some(exotic) = ancestor.exotic()
7426 && let Some(answer) = exotic.has_property(self, &ancestor, key)?
7427 {
7428 return Ok(answer);
7429 }
7430 if self.exotic_has_own(&ancestor, key)? {
7431 return Ok(true);
7432 }
7433 }
7434 Ok(false)
7435 }
7436
7437 /// Whether `object` reports `key` as an own property, its class's `get_own_property`
7438 /// trap included.
7439 ///
7440 /// The trap's `Some(Some(_))` means the key exists even though nothing in the property
7441 /// table has it, which is what makes `"x" in nativeObject` true for a virtual property.
7442 fn exotic_has_own(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
7443 if let Some(exotic) = object.exotic()
7444 && let Some(answer) = exotic.get_own_property(self, object, key)?
7445 {
7446 return Ok(answer.is_some());
7447 }
7448 Ok(has_own(object, key))
7449 }
7450
7451 /// `CreateListFromArrayLike`, optionally restricted to property keys.
7452 ///
7453 /// The `ownKeys` trap is the one place a script's array reaches the engine this way,
7454 /// and refusing a non-key element there is what makes `ownKeys: () => [1.5]` a
7455 /// `TypeError` instead of a property named `"1.5"`.
7456 fn list_from_array_like(&mut self, value: &Value, keys_only: bool) -> JsResult<Vec<Value>> {
7457 let object = self.object_from(value)?;
7458 let length = self
7459 .get_property(&object, "length")?
7460 .map(|value| value.to_number())
7461 .unwrap_or(0.0);
7462 if !length.is_finite() || length < 0.0 {
7463 return Err(self.type_error("invalid array-like length"));
7464 }
7465 let length = length as usize;
7466 let mut items = Vec::with_capacity(length.min(1024));
7467 for index in 0..length {
7468 let item = self
7469 .get_property(&object, &index.to_string())?
7470 .unwrap_or(Value::Undefined);
7471 if keys_only && matches!(&item, Value::Symbol(_)) {
7472 items.push(item);
7473 continue;
7474 }
7475 if keys_only && !matches!(&item, Value::String(_)) {
7476 return Err(self.type_error("proxy 'ownKeys' must return strings and symbols"));
7477 }
7478 items.push(item);
7479 }
7480 Ok(items)
7481 }
7482
7483 /// A `Property` from the descriptor object a trap returned.
7484 fn property_from_descriptor(&mut self, value: &Value) -> JsResult<Property> {
7485 let object = self.object_from(value)?;
7486 let field = |interp: &mut Self, name: &str| -> JsResult<Option<Value>> {
7487 interp.get_property(&object, name)
7488 };
7489 let getter = field(self, "get")?;
7490 let setter = field(self, "set")?;
7491 let accessor = getter.is_some() || setter.is_some();
7492 let boolean = |interp: &mut Self, name: &str| -> JsResult<bool> {
7493 Ok(interp
7494 .get_property(&object, name)?
7495 .is_some_and(|value| value.to_boolean()))
7496 };
7497 let enumerable = boolean(self, "enumerable")?;
7498 let configurable = boolean(self, "configurable")?;
7499 if accessor {
7500 if field(self, "value")?.is_some() || field(self, "writable")?.is_some() {
7501 return Err(
7502 self.type_error("a descriptor cannot be both a data property and an accessor")
7503 );
7504 }
7505 Ok(Property {
7506 getter: getter.or(Some(Value::Undefined)),
7507 setter: setter.or(Some(Value::Undefined)),
7508 enumerable,
7509 configurable,
7510 writable: false,
7511 value: None,
7512 descriptor_fields: None,
7513 })
7514 } else {
7515 Ok(Property {
7516 value: Some(field(self, "value")?.unwrap_or(Value::Undefined)),
7517 writable: boolean(self, "writable")?,
7518 enumerable,
7519 configurable,
7520 getter: None,
7521 setter: None,
7522 descriptor_fields: None,
7523 })
7524 }
7525 }
7526
7527 /// The descriptor object for a `Property`, which the `defineProperty` trap receives.
7528 fn descriptor_from_property(&mut self, property: &Property) -> Value {
7529 let object = self.new_object(None);
7530 // A partial descriptor names only some fields, and the trap must see exactly those:
7531 // `proxy-with-defineProperty-handler` asserts `descriptor.value === undefined` on
7532 // the descriptor `Object.freeze` hands over. `None` is the ordinary whole-property
7533 // case, where every field is present.
7534 let fields = property.descriptor_fields;
7535 let names = |field: fn(&crate::object::DescriptorFields) -> bool| {
7536 fields.is_none_or(|fields| field(&fields))
7537 };
7538 if property.is_accessor() {
7539 let getter = property.getter.clone().unwrap_or(Value::Undefined);
7540 let setter = property.setter.clone().unwrap_or(Value::Undefined);
7541 object.define_data("get", getter);
7542 object.define_data("set", setter);
7543 } else {
7544 if names(|fields| fields.value) {
7545 let value = property.value.clone().unwrap_or(Value::Undefined);
7546 object.define_data("value", value);
7547 }
7548 if names(|fields| fields.writable) {
7549 object.define_data("writable", Value::Bool(property.writable));
7550 }
7551 }
7552 if names(|fields| fields.enumerable) {
7553 object.define_data("enumerable", Value::Bool(property.enumerable));
7554 }
7555 if names(|fields| fields.configurable) {
7556 object.define_data("configurable", Value::Bool(property.configurable));
7557 }
7558 Value::Object(object)
7559 }
7560
7561 // -- calling ------------------------------------------------------------
7562
7563 /// Call `callee` with `this` and `args`.
7564 pub fn call_value(&mut self, callee: Value, this: Value, args: Vec<Value>) -> JsResult<Value> {
7565 let Value::Object(function) = &callee else {
7566 // `typeof x === "function"` is not enough to make `x()` legal: only a
7567 // callable object is. `null` and `undefined` need no special wording
7568 // here — their `ToString` already reads the way the reference's does.
7569 let what = format!("{} is not a function", callee.to_js_string());
7570 return Err(Signal::Throw(self.make_error("TypeError", &what)));
7571 };
7572 // A proxy of a function is called through its `apply` trap. It has no
7573 // `ObjectKind::Function` of its own, so this has to come before the dispatch
7574 // below, and a proxy of a non-function has nothing to forward to.
7575 if function.proxy_state().is_some() {
7576 return match self.proxy_apply(function, this, args)? {
7577 Some(result) => Ok(result),
7578 None => Err(Signal::Throw(
7579 self.make_error("TypeError", "proxy target is not callable"),
7580 )),
7581 };
7582 }
7583 let callable = function.with(|data| match &data.kind {
7584 ObjectKind::Function(callable) => match callable {
7585 Callable::Native { func, .. } => Some(NativeCall::Native(*func)),
7586 // The `Rc` is cloned out so the borrow of this object's data is released
7587 // before the closure runs: the closure may touch the same object.
7588 Callable::Host { func, .. } => Some(NativeCall::Host(func.clone())),
7589 Callable::Bound {
7590 target,
7591 this,
7592 args: leading,
7593 } => Some(NativeCall::Bound {
7594 target: target.clone(),
7595 this: this.clone(),
7596 leading: leading.clone(),
7597 }),
7598 Callable::Bytecode { code, env } => {
7599 Some(NativeCall::Bytecode(code.clone(), env.clone()))
7600 }
7601 Callable::Revoker(slots) => Some(NativeCall::Revoker(slots.clone())),
7602 Callable::PromiseResolve(promise) => {
7603 Some(NativeCall::PromiseResolve(promise.clone()))
7604 }
7605 Callable::PromiseReject(promise) => {
7606 Some(NativeCall::PromiseReject(promise.clone()))
7607 }
7608 Callable::CapabilityExecutor { state } => Some(NativeCall::CapabilityExecutor {
7609 state: state.clone(),
7610 }),
7611 Callable::ThenShim {
7612 handler,
7613 resolve,
7614 reject,
7615 fulfilled,
7616 } => Some(NativeCall::ThenShim {
7617 handler: handler.clone(),
7618 resolve: resolve.clone(),
7619 reject: reject.clone(),
7620 fulfilled: *fulfilled,
7621 }),
7622 Callable::AwaitResume {
7623 coroutine,
7624 promise,
7625 kind,
7626 } => Some(NativeCall::AwaitResume {
7627 coroutine: coroutine.clone(),
7628 promise: promise.clone(),
7629 kind: *kind,
7630 }),
7631 Callable::CombinatorSettle {
7632 state,
7633 index,
7634 fulfilled,
7635 } => Some(NativeCall::CombinatorSettle {
7636 state: state.clone(),
7637 index: *index,
7638 fulfilled: *fulfilled,
7639 }),
7640 Callable::FinallyShim {
7641 callback,
7642 fulfilled,
7643 constructor,
7644 } => Some(NativeCall::FinallyShim {
7645 callback: callback.clone(),
7646 fulfilled: *fulfilled,
7647 constructor: constructor.clone(),
7648 }),
7649 Callable::ModuleBinding { cell } => Some(NativeCall::ModuleBinding(cell.clone())),
7650 Callable::CompletedReturn {
7651 generator,
7652 promise,
7653 rejected,
7654 } => Some(NativeCall::CompletedReturn {
7655 generator: generator.clone(),
7656 promise: promise.clone(),
7657 rejected: *rejected,
7658 }),
7659 Callable::YieldResult {
7660 generator,
7661 promise,
7662 done,
7663 } => Some(NativeCall::YieldResult {
7664 generator: generator.clone(),
7665 promise: promise.clone(),
7666 done: *done,
7667 }),
7668 Callable::DisposeStep {
7669 remaining,
7670 promise,
7671 error,
7672 rejected,
7673 awaited,
7674 needs_await,
7675 } => Some(NativeCall::DisposeStep {
7676 remaining: remaining.clone(),
7677 promise: promise.clone(),
7678 error: error.clone(),
7679 rejected: *rejected,
7680 awaited: *awaited,
7681 needs_await: *needs_await,
7682 }),
7683 Callable::GeneratorResume {
7684 generator,
7685 promise,
7686 kind,
7687 } => Some(NativeCall::GeneratorResume {
7688 generator: generator.clone(),
7689 promise: promise.clone(),
7690 kind: *kind,
7691 }),
7692 Callable::ReturnValue(value) => Some(NativeCall::ReturnValue(value.clone())),
7693 Callable::ThrowValue(value) => Some(NativeCall::ThrowValue(value.clone())),
7694 Callable::SettlePromise {
7695 promise,
7696 value,
7697 rejected,
7698 } => Some(NativeCall::SettlePromise {
7699 promise: promise.clone(),
7700 value: value.clone(),
7701 rejected: *rejected,
7702 }),
7703 },
7704 _ => None,
7705 });
7706 match callable {
7707 Some(NativeCall::Host(func)) => {
7708 // Same frame bookkeeping as a `Native`, so a stack trace shows the host
7709 // function by name rather than stopping at the caller.
7710 let frame_less = function
7711 .own_property("_frame_less")
7712 .and_then(|property| property.value)
7713 .is_some_and(|value| value.to_boolean());
7714 let outer = if frame_less {
7715 None
7716 } else {
7717 self.native_frames
7718 .push((function.clone(), self.frames.len()));
7719 Some(self.current_native.replace(function.clone()))
7720 };
7721 // Same frame bookkeeping as a `Native`, plus `new.target`: a host
7722 // constructor reads it through `current_new_target` because it is handed
7723 // `undefined` for `this`. Taking the parked value here is what stops a
7724 // *plain* call made from inside a constructor body from seeing the
7725 // enclosing `new.target`.
7726 let parked = self.pending_new_target.take();
7727 let result = {
7728 let outer_new_target = std::mem::replace(
7729 &mut self.active_new_target,
7730 parked.unwrap_or(Value::Undefined),
7731 );
7732 let result = {
7733 let mut body = func.borrow_mut();
7734 body(self, this, &args)
7735 };
7736 self.active_new_target = outer_new_target;
7737 result
7738 };
7739 if !frame_less {
7740 self.native_frames.pop();
7741 self.current_native = outer.flatten();
7742 }
7743 result
7744 }
7745 Some(NativeCall::Native(func)) => {
7746 // A function marked `_frame_less` is one the reference implements
7747 // without a call frame — `eval` is the only one so far.
7748 let frame_less = function
7749 .own_property("_frame_less")
7750 .and_then(|property| property.value)
7751 .is_some_and(|value| value.to_boolean());
7752 let outer = if frame_less {
7753 None
7754 } else {
7755 self.native_frames
7756 .push((function.clone(), self.frames.len()));
7757 Some(self.current_native.replace(function.clone()))
7758 };
7759 let parked = self.pending_new_target.take();
7760 let outer_new_target = std::mem::replace(
7761 &mut self.active_new_target,
7762 parked.unwrap_or(Value::Undefined),
7763 );
7764 let result = func(self, this, &args);
7765 self.active_new_target = outer_new_target;
7766 if !frame_less {
7767 self.native_frames.pop();
7768 self.current_native = outer.flatten();
7769 }
7770 result
7771 }
7772 Some(NativeCall::Revoker(slots)) => {
7773 // Idempotent: revoking twice answers `undefined` again rather than
7774 // complaining, which is what the spec says and what a `finally` block
7775 // relies on.
7776 let mut state = slots.borrow_mut();
7777 state.target = None;
7778 state.handler = None;
7779 Ok(Value::Undefined)
7780 }
7781 Some(NativeCall::PromiseResolve(promise)) => {
7782 // §27.2.1.3.2 step 4: `[[AlreadyResolved]]` is checked **before** anything
7783 // else, so a resolve after a reject does nothing *and* a resolve after a
7784 // resolve-with-thenable does nothing — the promise is still `Pending` then,
7785 // because the adoption is a queued job.
7786 let value = args.first().cloned().unwrap_or(Value::Undefined);
7787 if !self.claim_resolution(&promise) {
7788 return Ok(Value::Undefined);
7789 }
7790 // §27.2.1.3.2 steps 7–8: a self-resolution is **rejected, not thrown** —
7791 // the resolve function performs `RejectPromise` and returns `undefined`.
7792 // (`ResolvePromise` itself throws as well, so the engine's own callers see
7793 // it; only this wrapper swallows it.)
7794 let _ = self.resolve_promise_with(&promise, value);
7795 Ok(Value::Undefined)
7796 }
7797 Some(NativeCall::PromiseReject(promise)) => {
7798 let reason = args.first().cloned().unwrap_or(Value::Undefined);
7799 // §27.2.1.3.1 step 3: same one-shot record as `resolve`.
7800 if !self.claim_resolution(&promise) {
7801 return Ok(Value::Undefined);
7802 }
7803 self.reject_promise(&promise, reason);
7804 Ok(Value::Undefined)
7805 }
7806 Some(NativeCall::ThenShim {
7807 handler,
7808 resolve,
7809 reject,
7810 fulfilled,
7811 }) => {
7812 // `PerformPromiseThen` with a capability: run the handler, then settle
7813 // through the capability's own pair. A throw from the handler is the
7814 // rejection, and a throw from the capability's `resolve` is not caught —
7815 // exactly the spec's `?`.
7816 let value = args.first().cloned().unwrap_or(Value::Undefined);
7817 match handler {
7818 Some(handler) => {
7819 match self.call_value(handler, Value::Undefined, vec![value]) {
7820 Ok(result) => {
7821 self.call_value(resolve, Value::Undefined, vec![result])?;
7822 }
7823 Err(Signal::Throw(reason)) => {
7824 self.call_value(reject, Value::Undefined, vec![reason])?;
7825 }
7826 Err(signal) => return Err(signal),
7827 }
7828 }
7829 None => {
7830 let handler = if fulfilled { resolve } else { reject };
7831 self.call_value(handler, Value::Undefined, vec![value])?;
7832 }
7833 }
7834 Ok(Value::Undefined)
7835 }
7836 Some(NativeCall::CapabilityExecutor { state }) => {
7837 // §27.2.1.5 steps 3–4: the executor may be called again as long as neither
7838 // slot holds a value yet. The test is on the *values*, not on a call count —
7839 // `executor()` followed by `executor(f, g)` is legal (`capability-executor-
7840 // called-twice`'s first case does exactly that), while a second call after a
7841 // real pair is the `TypeError`.
7842 let defined = |name: &str| {
7843 state
7844 .own_property(name)
7845 .and_then(|property| property.value)
7846 .is_some_and(|value| !matches!(value, Value::Undefined))
7847 };
7848 if defined("resolve") || defined("reject") {
7849 return Err(self.type_error("promise capability executor called twice"));
7850 }
7851 let resolve = args.first().cloned().unwrap_or(Value::Undefined);
7852 let reject = args.get(1).cloned().unwrap_or(Value::Undefined);
7853 state.define_data("resolve", resolve);
7854 state.define_data("reject", reject);
7855 Ok(Value::Undefined)
7856 }
7857 Some(NativeCall::CombinatorSettle {
7858 state,
7859 index,
7860 fulfilled,
7861 }) => {
7862 let value = args.first().cloned().unwrap_or(Value::Undefined);
7863 self.settle_combinator(&state, index, fulfilled, value)?;
7864 Ok(Value::Undefined)
7865 }
7866 Some(NativeCall::AwaitResume {
7867 coroutine,
7868 promise,
7869 kind,
7870 }) => {
7871 // Resume *inline*, in the reaction that delivered the value. Deferring it
7872 // by another job inserts a tick between every `await` and its
7873 // continuation, which reorders `await` against unrelated `then` chains —
7874 // `f().then(g)` then runs before `f`'s own next statement.
7875 self.drive_async(
7876 &coroutine,
7877 &promise,
7878 kind,
7879 args.first().cloned().unwrap_or(Value::Undefined),
7880 )
7881 .map(|()| Value::Undefined)
7882 }
7883 Some(NativeCall::ReturnValue(value)) => Ok(value),
7884 Some(NativeCall::ThrowValue(value)) => Err(Signal::Throw(value)),
7885 Some(NativeCall::FinallyShim {
7886 callback,
7887 fulfilled,
7888 constructor,
7889 }) => {
7890 // §27.2.5.3's `thenFinally`/`catchFinally`, step for step. The callback's
7891 // own value is discarded; what the caller sees is the *original* outcome,
7892 // delayed until `PromiseResolve(C, result)` has settled.
7893 //
7894 // Two details are observable and both have a test:
7895 //
7896 // * the wait goes through **`Invoke(promise, "then", …)`**, not an internal
7897 // `PerformPromiseThen`. A callback that returns a thenable with its own
7898 // `then` must have that `then` called
7899 // (`resolved-observable-then-calls` counts it);
7900 // * only the **fulfil** handler is supplied. A returned promise that
7901 // *rejects* rejects the whole `finally`, rather than having its failure
7902 // swallowed and the original value passed through.
7903 let original = args.first().cloned().unwrap_or(Value::Undefined);
7904 let result = match &callback {
7905 Some(callback) => {
7906 self.call_value(callback.clone(), Value::Undefined, Vec::new())?
7907 }
7908 None => Value::Undefined,
7909 };
7910 // `PromiseResolve(C, result)`: a `result` that is already a promise of this
7911 // constructor is reused rather than rewrapped, which is what keeps
7912 // `mp1.finally(() => mp2)` from gaining a layer.
7913 let resolved = self.promise_resolve_for(&constructor, result)?;
7914 let thunk = if fulfilled {
7915 Callable::ReturnValue(original)
7916 } else {
7917 Callable::ThrowValue(original)
7918 };
7919 // `length: 0` and `name: ""`, and **not** a constructor — the three things
7920 // `resolved-observable-then-calls-argument` reads off the thunk while it has
7921 // `Promise.prototype.then` replaced. `JsObject::function` on its own gives a
7922 // function with no `length` at all.
7923 let thunk = self.builtin_function("", 0, thunk);
7924 let then = self.read_field(&resolved, "then")?;
7925 if !matches!(&then, Value::Object(object) if object.is_callable()) {
7926 return Err(self.type_error("then is not a function"));
7927 }
7928 self.call_value(then, resolved, vec![Value::Object(thunk)])
7929 }
7930 Some(NativeCall::DisposeStep {
7931 remaining,
7932 promise,
7933 error,
7934 rejected,
7935 awaited,
7936 needs_await,
7937 }) => {
7938 let error = if rejected {
7939 let reason = args.first().cloned().unwrap_or(Value::Undefined);
7940 self.merge_dispose_error(reason, error)
7941 } else {
7942 error
7943 };
7944 self.dispose_step(&remaining, &promise, error, awaited, needs_await)?;
7945 Ok(Value::Undefined)
7946 }
7947 Some(NativeCall::ModuleBinding(cell)) => Ok(cell.get()),
7948 Some(NativeCall::CompletedReturn {
7949 generator,
7950 promise,
7951 rejected,
7952 }) => {
7953 let value = args.first().cloned().unwrap_or(Value::Undefined);
7954 let outcome = if rejected {
7955 AsyncOutcome::Error(value)
7956 } else {
7957 AsyncOutcome::Value(self.iterator_result(value, true)?)
7958 };
7959 self.settle_async_request(&generator, &promise, outcome)?;
7960 Ok(Value::Undefined)
7961 }
7962 Some(NativeCall::YieldResult {
7963 generator,
7964 promise,
7965 done,
7966 }) => {
7967 let value = args.first().cloned().unwrap_or(Value::Undefined);
7968 let result = self.iterator_result(value, done)?;
7969 self.settle_async_request(&generator, &promise, AsyncOutcome::Value(result))?;
7970 Ok(Value::Undefined)
7971 }
7972 Some(NativeCall::GeneratorResume {
7973 generator,
7974 promise,
7975 kind,
7976 }) => {
7977 // Inline for the same reason as `AwaitResume`: a deferred resume adds a
7978 // tick and reorders the generator against other chains.
7979 self.step_async_generator(
7980 &generator,
7981 &promise,
7982 kind,
7983 args.first().cloned().unwrap_or(Value::Undefined),
7984 )
7985 .map(|()| Value::Undefined)
7986 }
7987 Some(NativeCall::SettlePromise {
7988 promise,
7989 value,
7990 rejected,
7991 }) => {
7992 if rejected {
7993 self.reject_promise(&promise, value);
7994 } else {
7995 self.fulfill_promise(&promise, value);
7996 }
7997 Ok(Value::Undefined)
7998 }
7999 Some(NativeCall::Bound {
8000 target,
8001 this: bound_this,
8002 leading,
8003 }) => {
8004 let mut all = leading;
8005 all.extend(args);
8006 self.call_value(target, bound_this, all)
8007 }
8008 Some(NativeCall::Bytecode(code, env)) => {
8009 if code.code.kind.is_generator() {
8010 return self.new_generator(callee, this, args);
8011 }
8012 if code.code.kind.is_async() {
8013 // Same coroutine machinery as a generator; the difference is only in
8014 // what the completion does — see `new_async_function`.
8015 return self.new_async_function(callee, this, args);
8016 }
8017 self.execute(code, env, this, args, callee)
8018 }
8019 None => Err(Signal::Throw(
8020 self.make_error("TypeError", "not a function"),
8021 )),
8022 }
8023 }
8024
8025 /// Give a freshly built function its own `prototype` object.
8026 ///
8027 /// Every function that can be used with `new` carries one, and its
8028 /// `constructor` points back at the function — a reference cycle, which is
8029 /// exactly what the collector's cycle pass exists to reclaim.
8030 fn install_function_prototype(&mut self, function: &Gc<JsObject>) {
8031 self.install_function_prototype_with(function, None);
8032 }
8033
8034 /// [`Interp::install_function_prototype`] with an explicit parent for the new
8035 /// `prototype` object.
8036 ///
8037 /// A generator function's per-function `prototype` inherits from `%GeneratorPrototype%`
8038 /// rather than from `Object.prototype` (§27.3.3.1), which is what makes
8039 /// `Object.getPrototypeOf(Object.getPrototypeOf(g()))` reach `next`/`return`/`throw`.
8040 /// `None` means `%Object.prototype%`.
8041 fn install_function_prototype_with(
8042 &mut self,
8043 function: &Gc<JsObject>,
8044 parent: Option<Gc<JsObject>>,
8045 ) {
8046 let parent = parent.unwrap_or_else(|| self.realm.object_proto.clone());
8047 let prototype = self.new_object(Some(parent));
8048 let constructor = Value::Object(function.clone());
8049 prototype.define(
8050 "constructor",
8051 Property::with_attributes(constructor, true, false),
8052 );
8053 let value = Value::Object(prototype);
8054 function.define("prototype", Property::prototype_of(value, true));
8055 }
8056
8057 /// The `prototype` object of a **generator** function: `OrdinaryObjectCreate` with
8058 /// `%GeneratorPrototype%` (or the async one) as parent, and — unlike
8059 /// [`Interp::install_function_prototype`] — **no `constructor` property**.
8060 ///
8061 /// §27.3.3.1 builds it in two steps (`OrdinaryObjectCreate` then
8062 /// `DefinePropertyOrThrow(F, "prototype", …)`) and never calls `MakeConstructor`, so
8063 /// the object is bare. The reference agrees: `Object.getOwnPropertyNames(g.prototype)`
8064 /// is `[]` there.
8065 fn install_generator_prototype(&mut self, function: &Gc<JsObject>, parent: Gc<JsObject>) {
8066 let prototype = self.new_object(Some(parent));
8067 let value = Value::Object(prototype);
8068 function.define("prototype", Property::prototype_of(value, true));
8069 }
8070
8071 /// The `[[Prototype]]` a newly created generator object gets:
8072 /// `OrdinaryCreateFromConstructor(genFun, defaultProto)`.
8073 ///
8074 /// `genFun.prototype` when that is an object, and the intrinsic otherwise — a generator
8075 /// function's `prototype` is writable, so a script can replace it with anything, and
8076 /// only an *object* is consulted.
8077 fn generator_instance_proto(
8078 &mut self,
8079 function: &Gc<JsObject>,
8080 default: Gc<JsObject>,
8081 ) -> JsResult<Gc<JsObject>> {
8082 match self.get_property(function, "prototype")? {
8083 Some(Value::Object(prototype)) => Ok(prototype),
8084 _ => Ok(default),
8085 }
8086 }
8087
8088 /// A getter or setter that reads or writes the reference cell behind a mapped
8089 /// `arguments` index.
8090 ///
8091 /// The cell is cloned into the closure, and `Gc::clone` bumps the box's strong
8092 /// count — which is what the collector treats as "a reference from outside the
8093 /// heap". The closure therefore keeps the cell alive for exactly as long as the
8094 /// accessor is reachable, which is the same lifetime the arguments object has.
8095 ///
8096 /// The `Gc` is not *traced* from the closure, so a cycle closed only through this
8097 /// borrow would not be reclaimed; that is acceptable here because the cell holds a
8098 /// parameter value and the arguments object reaches the closure, never the other
8099 /// way round. Nothing the collector has to see is hidden.
8100 fn new_mapped_arguments_accessor(&self, cell: Gc<Cell>, is_setter: bool) -> Gc<JsObject> {
8101 let name = if is_setter { "set" } else { "get" };
8102 let func = move |_interp: &mut Interp<'_>, _this: Value, args: &[Value]| {
8103 if is_setter {
8104 cell.set(args.first().cloned().unwrap_or(Value::Undefined));
8105 Ok(Value::Undefined)
8106 } else {
8107 Ok(cell.get())
8108 }
8109 };
8110 self.new_host_function(name, 1, Box::new(func))
8111 }
8112
8113 /// The object `special_object` builds.
8114 ///
8115 /// Only `arguments` is implemented. It is an ordinary object with a `length` and
8116 /// one property per passed argument, which is what `typeof`, `arguments[i]` and
8117 /// `arguments.length` observe. Mapped arguments — sloppy mode's aliasing between
8118 /// `arguments[i]` and the parameter it came from — is *not* implemented, so a
8119 /// write through `arguments` does not reach the parameter.
8120 fn special_object(&mut self, magic: u32) -> JsResult<Value> {
8121 match magic {
8122 0 | 1 => {
8123 let args = self.frame().passed().to_vec();
8124 let proto = self.realm.object_proto.clone();
8125 let object = self.new_object(Some(proto));
8126 // The marker `Object.prototype.toString` needs: an arguments object is an
8127 // ordinary object apart from reporting `[object Arguments]`, and that has
8128 // no `Symbol.toStringTag` of its own. Set before the indices so it does not
8129 // show up ahead of them in a key listing anyway — it is non-enumerable.
8130 self.internal_set(&object, "_class", self.string("Arguments"));
8131 // `length` is writable and configurable but neither enumerable nor a
8132 // plain data property: `Object.keys(arguments)` lists the indices only,
8133 // which is how `{...arguments}` copies them without the length.
8134 object.define(
8135 "length",
8136 Property::with_attributes(Value::Int(args.len() as i32), true, false),
8137 );
8138 // `magic == 1` is sloppy mode, where each index is *mapped* to the
8139 // parameter it came from (ES §10.4.4): writing `arguments[0]` has to
8140 // change `a`, and assigning `a` has to change `arguments[0]`.
8141 //
8142 // The shared storage is the parameter's reference cell. The compiler
8143 // gives every parameter of such a function one (see
8144 // `provide_body_arguments`), and the cell outlives the frame, so this
8145 // keeps working after the arguments object escapes.
8146 //
8147 // The index becomes an accessor rather than a data property. A mapped
8148 // index reports as a plain writable/enumerable data property through
8149 // `Object.getOwnPropertyDescriptor`, which `own_property_key` arranges;
8150 // the getter/setter pair is only the plumbing underneath.
8151 let mapped_cells: Vec<Option<Gc<Cell>>> = if magic == 1 {
8152 let frame = self.frame();
8153 frame
8154 .code
8155 .arg_cell
8156 .iter()
8157 .map(|cell| {
8158 (*cell >= 0)
8159 .then(|| frame.cells.get(*cell as usize).cloned())
8160 .flatten()
8161 })
8162 .collect()
8163 } else {
8164 Vec::new()
8165 };
8166 // Tell the object which indices are mapped, so
8167 // `Object.getOwnPropertyDescriptor` can report them as the data
8168 // properties the spec describes instead of the accessors that
8169 // implement the aliasing.
8170 if magic == 1 {
8171 let mut table: Vec<Option<Gc<Cell>>> = Vec::with_capacity(mapped_cells.len());
8172 for cell in &mapped_cells {
8173 table.push(cell.clone());
8174 }
8175 object.set_mapped_arguments(table);
8176 }
8177 for (index, value) in args.into_iter().enumerate() {
8178 match mapped_cells.get(index).cloned().flatten() {
8179 Some(cell) => {
8180 let getter = self.new_mapped_arguments_accessor(cell.clone(), false);
8181 let setter = self.new_mapped_arguments_accessor(cell, true);
8182 object.define(
8183 &index.to_string(),
8184 Property::accessor_with(
8185 Some(Value::Object(getter)),
8186 Some(Value::Object(setter)),
8187 true,
8188 ),
8189 );
8190 }
8191 None => object.define_data(&index.to_string(), value),
8192 }
8193 }
8194 // §10.4.4.6: an *unmapped* (strict) arguments object gets a
8195 // `callee` **accessor** whose getter and setter are `%ThrowTypeError%`,
8196 // non-enumerable and non-configurable. It is not a nicety — it is the only
8197 // documented way to reach `%ThrowTypeError%`:
8198 //
8199 // Object.getOwnPropertyDescriptor(function(){"use strict";
8200 // return arguments;}(), "callee").get
8201 //
8202 // and the whole `ThrowTypeError/` directory is written against that
8203 // expression. Without it 13 cases failed with `cannot read property 'get'
8204 // of undefined`, which reads like a test harness bug rather than a missing
8205 // accessor.
8206 //
8207 // §10.4.4.7: a *mapped* (sloppy) one instead carries `callee` as a
8208 // writable data property holding the function being called, and
8209 // `arguments.callee` works. The legacy `S10.6_*` tests ask only that
8210 // `hasOwnProperty("callee")` hold there.
8211 if magic == 1 {
8212 let callee = self.frame().callee.clone();
8213 // `{ DontEnum }`: `for (var x in arguments)` must not list it.
8214 object.define("callee", Property::with_attributes(callee, true, false));
8215 } else if let Some(thrower) = self.realm.throw_type_error.clone()
8216 && object.own_property("callee").is_none()
8217 {
8218 object.define(
8219 "callee",
8220 Property {
8221 getter: Some(Value::Object(thrower.clone())),
8222 setter: Some(Value::Object(thrower)),
8223 enumerable: false,
8224 configurable: false,
8225 ..Property::default()
8226 },
8227 );
8228 }
8229 // An arguments object is iterable: `[...arguments]` and
8230 // `for (const a of arguments)` both work, through the *array* iterator
8231 // because the object is array-like. Without this the whole spread form
8232 // reported "not iterable".
8233 let iterator_key = self.realm.well_known_key(WellKnown::Iterator);
8234 let values = self
8235 .realm
8236 .array_proto
8237 .own_property("values")
8238 .and_then(|property| property.value);
8239 if let Some(values) = values {
8240 object.define_key(
8241 &iterator_key,
8242 Property::with_attributes(values, true, false),
8243 );
8244 }
8245 Ok(Value::Object(object))
8246 }
8247 // `this.active_func`: the constructor `super()` resolves against.
8248 //
8249 // Only ever asked of a *non-arrow* frame. An arrow has no `[[ThisMode]]` of its
8250 // own, so it inherits this from the function it was written in along with `this`
8251 // — and that is a lexical relationship, not a stack one: an arrow that escaped
8252 // the constructor and is called back later (`iter.return = () => super()`) has
8253 // the constructor nowhere on the stack. The compiler therefore reads it out of
8254 // a closure variable of the enclosing function, exactly as the reference does
8255 // with its `this_active_func` local.
8256 2 => Ok(self
8257 .current_callee()
8258 .map_or(Value::Undefined, Value::Object)),
8259 // `new.target`: set by `construct`, `undefined` for an ordinary call, and
8260 // inherited from the caller inside an `eval`. An arrow has no `new.target` of
8261 // its own either, so the lookup walks out to the nearest non-arrow frame for
8262 // the same reason as `this.active_func` above — without that, `super()` inside
8263 // an arrow passed `undefined` as the new target and the parent constructor was
8264 // then rejected for being invoked without `new`.
8265 3 => Ok(self
8266 .eval_new_target
8267 .clone()
8268 .unwrap_or_else(|| self.frame().new_target.clone())),
8269 // `[[HomeObject]]` of the function being run: what `super` is relative to.
8270 // An arrow has none of its own, so the lookup walks out to the enclosing
8271 // method — which is why `super` works inside an arrow inside a method.
8272 4 => Ok(self
8273 .frames
8274 .iter()
8275 .rev()
8276 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8277 .map_or(Value::Undefined, Value::Object)),
8278 // `import.meta`: the innermost module body's meta object. Outside a module
8279 // the compiler never emits this, so an empty fallback is unreachable rather
8280 // than permissive.
8281 6 => {
8282 let name = self.module_stack.last().cloned();
8283 let meta = name
8284 .and_then(|name| self.modules.get(&name).cloned())
8285 .and_then(|module| module.with(|r| r.import_meta.clone()));
8286 Ok(meta.map_or(Value::Undefined, Value::Object))
8287 }
8288 other => Err(Signal::Throw(self.make_error(
8289 "InternalError",
8290 &format!("special_object {other} is not implemented yet"),
8291 ))),
8292 }
8293 }
8294
8295 /// `[[HomeObject]]` of the innermost function that has one, if any.
8296 ///
8297 /// An arrow has none, so the search walks out to the enclosing method — the same
8298 /// rule `special_object 4` follows, and the reason `super` works inside an arrow
8299 /// inside a method.
8300 fn enclosing_home_object(&self) -> Option<Gc<JsObject>> {
8301 self.frames
8302 .iter()
8303 .rev()
8304 .find_map(|frame| frame.callee.as_object().and_then(|f| f.home_object()))
8305 }
8306
8307 /// The dispose method a `using` declaration should snapshot, or an error.
8308 ///
8309 /// `await`-using prefers `Symbol.asyncDispose` and falls back to `Symbol.dispose`, which
8310 /// is what makes a resource that only knows the synchronous protocol usable in both
8311 /// forms.
8312 pub fn using_method_for(&mut self, value: &Value, await_form: bool) -> JsResult<Value> {
8313 // `null` and `undefined` are explicitly allowed and simply dispose to nothing.
8314 if value.is_nullish() {
8315 return Ok(Value::Undefined);
8316 }
8317 let Some(object) = value.as_object() else {
8318 return Err(self.type_error("not an object"));
8319 };
8320 let mut method = if await_form {
8321 let found = self.get_property_key(
8322 object,
8323 &self.realm.well_known_key(WellKnown::AsyncDisposable),
8324 )?;
8325 match found {
8326 Some(found) if !found.is_nullish() => Some(found),
8327 _ => self
8328 .get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?,
8329 }
8330 } else {
8331 self.get_property_key(object, &self.realm.well_known_key(WellKnown::Disposable))?
8332 };
8333 let Some(found) = method.take() else {
8334 return Err(self.type_error("value is not disposable"));
8335 };
8336 if found.is_nullish() {
8337 return Err(self.type_error("value is not disposable"));
8338 }
8339 let callable = found.as_object().is_some_and(|object| object.is_callable());
8340 if !callable {
8341 return Err(self.type_error("dispose method is not a function"));
8342 }
8343 Ok(found)
8344 }
8345
8346 /// Call one resource's disposer, folding a failure into `error_state`.
8347 ///
8348 /// The value is read through [`Interp::get_loc`] rather than off `locals` directly,
8349 /// because a captured `using` binding lives in its reference cell and the local slot is
8350 /// stale — a closure over the resource is legal and must not change what is disposed.
8351 fn using_dispose_once(&mut self, slot: usize, error_state: Value) -> JsResult<Value> {
8352 let value = self.get_loc(slot);
8353 let method = self.get_loc(slot + 1);
8354 // A resource that was never initialised — its declaration threw — or that is
8355 // `null`/`undefined` has nothing to dispose.
8356 if value.is_nullish() || matches!(value, Value::Uninitialized) {
8357 return Ok(error_state);
8358 }
8359 if matches!(method, Value::Undefined | Value::Uninitialized) {
8360 return Ok(error_state);
8361 }
8362 match self.call_value(method, value, Vec::new()) {
8363 Ok(_) => Ok(error_state),
8364 Err(Signal::Throw(thrown)) => Ok(self.merge_dispose_error(thrown, error_state)),
8365 Err(other) => Err(other),
8366 }
8367 }
8368
8369 /// Combine a disposal failure with whatever was already going wrong.
8370 pub fn merge_dispose_error(&mut self, new_error: Value, error_state: Value) -> Value {
8371 if matches!(error_state, Value::Uninitialized) {
8372 return new_error;
8373 }
8374 self.new_suppressed_error(new_error, error_state)
8375 }
8376
8377 /// A `SuppressedError` instance built straight from its prototype.
8378 ///
8379 /// Not through the constructor: a script that rewrites
8380 /// `SuppressedError.prototype.constructor` must not be able to divert the engine's own
8381 /// error wrapping.
8382 pub fn new_suppressed_error(&mut self, error: Value, suppressed: Value) -> Value {
8383 let proto = self
8384 .realm
8385 .suppressed_error_proto
8386 .clone()
8387 .unwrap_or_else(|| self.realm.error_proto.clone());
8388 let object = self.new_object(Some(proto));
8389 object.define("error", Property::with_attributes(error, true, true));
8390 object.define(
8391 "suppressed",
8392 Property::with_attributes(suppressed, true, true),
8393 );
8394 object.define(
8395 "message",
8396 Property::with_attributes(self.string("SuppressedError"), true, true),
8397 );
8398 self.internal_set(&object, "_class", self.string("Error"));
8399 self.add_stack(&object);
8400 Value::Object(object)
8401 }
8402
8403 /// Call `callee`, or push its frame and let the main loop run it.
8404 ///
8405 /// This is what keeps deep JavaScript recursion off the Rust stack: a bytecode
8406 /// callee becomes a frame on [`Interp::frames`] and the instruction loop simply
8407 /// continues, so `function f(){ return f() }` costs heap and stops at
8408 /// [`Interp::max_frames`] instead of aborting the process. Only a native callee
8409 /// is entered directly, and natives do not re-enter JavaScript in this
8410 /// milestone.
8411 ///
8412 /// `Ok(None)` means a frame was pushed: the caller must not push a result,
8413 /// because the returning frame will.
8414 /// The elements of an array-like value, as a call argument list.
8415 ///
8416 /// `apply` accepts any array-like, not only a real array: the reference reads
8417 /// `length` and then each index, so `{length: 2, 0: "a", 1: "b"}` works too.
8418 /// `ToIndex(value)`: `ToIntegerOrInfinity` and then the `2^53 - 1` bound.
8419 ///
8420 /// Used by the paths that take a *length* from script data — the typed-array
8421 /// constructor's array-like argument, `Array.from`. `ToIntegerOrInfinity` runs
8422 /// `ToNumber`, so a Symbol is a `TypeError`; a value past `2^53 - 1` is a
8423 /// `RangeError` rather than a silently clamped count.
8424 pub fn to_index(&mut self, value: &Value) -> JsResult<usize> {
8425 let number = self.to_js_number(value)?;
8426 if number.is_nan() {
8427 return Ok(0);
8428 }
8429 let number = number.trunc();
8430 if number < 0.0 || number > 9_007_199_254_740_991.0 {
8431 return Err(self.range_error("invalid length"));
8432 }
8433 Ok(number as usize)
8434 }
8435
8436 /// `CreateListFromArrayLike(value)`: the elements of an array-like, for `apply` and the
8437 /// other callers that take an argument list from script data.
8438 ///
8439 /// The length is `ToLength`, which *clamps* rather than refusing — the typed-array
8440 /// constructor and `Array.from` need `ToIndex` instead (see
8441 /// [`Interp::to_index`]), which is why they do not go through here.
8442 pub fn array_like_to_args(&mut self, value: &Value) -> JsResult<Vec<Value>> {
8443 let Some(object) = value.as_object().cloned() else {
8444 if value.is_nullish() {
8445 // `f.apply(this, null)` passes no arguments at all.
8446 return Ok(Vec::new());
8447 }
8448 return Err(self.type_error("createListFromArrayLike called on non-object"));
8449 };
8450 let length = match self.get_property(&object, "length")? {
8451 Some(length) => length.to_number(),
8452 None => 0.0,
8453 };
8454 if !length.is_finite() || length <= 0.0 {
8455 return Ok(Vec::new());
8456 }
8457 let length = (length as usize).min(1_000_000);
8458 let mut args = Vec::with_capacity(length);
8459 for index in 0..length {
8460 let element = self.get_property(&object, &index.to_string())?;
8461 args.push(element.unwrap_or(Value::Undefined));
8462 }
8463 Ok(args)
8464 }
8465
8466 /// Turn a call to a generator function into a generator object.
8467 ///
8468 /// The frame is built exactly as an ordinary call would build it, then detached and
8469 /// stored in the generator before any body instruction runs — which is what makes
8470 /// `function* g(){ sideEffect() }` inert until `next()`. The one thing that does run
8471 /// is `initial_yield`, the first instruction of every suspending body.
8472 pub fn new_generator(
8473 &mut self,
8474 function: Value,
8475 this: Value,
8476 args: Vec<Value>,
8477 ) -> JsResult<Value> {
8478 let Some(object) = function.as_object().cloned() else {
8479 return Err(self.type_error("not a generator function"));
8480 };
8481 let Some((code, env)) = bytecode_of(&object) else {
8482 return Err(self.type_error("not a generator function"));
8483 };
8484 let is_async = code.code.kind.is_async();
8485 self.push_frame(code, env, this, args, function)?;
8486 let frame = self.frames.pop().expect("push_frame just pushed it");
8487 // A fresh generator is *suspended at start*: the body has not run, so a
8488 // `return`/`throw` on it finishes without executing anything.
8489 let mut state = GeneratorState {
8490 frame: Some(frame),
8491 phase: GeneratorPhase::SuspendedStart,
8492 parked_on_await: false,
8493 parked_on_yield_star: false,
8494 requests: std::collections::VecDeque::new(),
8495 async_busy: false,
8496 is_async,
8497 };
8498 // Run to the first suspension. For a generator that is `initial_yield`, so no
8499 // body code runs; for a malformed body it would be the first `yield`.
8500 // An `async function*` answers an async generator: same coroutine, but its
8501 // methods return promises and `for await` reaches it through `Symbol.asyncIterator`.
8502 let default_proto = if is_async {
8503 self.realm
8504 .async_generator_proto
8505 .clone()
8506 .unwrap_or_else(|| self.realm.generator_proto.clone())
8507 } else {
8508 self.realm.generator_proto.clone()
8509 };
8510 // `OrdinaryCreateFromConstructor(genFun, "%GeneratorPrototype%")`: the per-function
8511 // `prototype` object when it is one, the intrinsic otherwise. Every generator having
8512 // `%GeneratorPrototype%` as its *direct* prototype put `next` one level too high in
8513 // the chain and made `Object.getPrototypeOf(g()) === g.prototype` false.
8514 let proto = self.generator_instance_proto(&object, default_proto)?;
8515 let generator = self.new_object(Some(proto));
8516 match self.step_generator(&mut state, ResumeKind::Start, Value::Undefined) {
8517 Ok(_) => {}
8518 Err(error) => return Err(error),
8519 }
8520 generator.with_mut(|data| {
8521 data.kind = ObjectKind::Generator(Box::new(state));
8522 });
8523 Ok(Value::Object(generator))
8524 }
8525
8526 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8527 ///
8528 /// Returns the `{value, done}` object itself rather than the pair, because a
8529 /// `yield*` suspension already has one — the inner iterator's own result — and the
8530 /// protocol says to hand that straight through rather than nest it.
8531 /// Advance a generator and report *why* it parked.
8532 ///
8533 /// The sync `next()` does not need the reason — a `yield` and an `await` both mean
8534 /// "hand this value to the caller" — but an async generator does: an `await` has to
8535 /// settle before it can answer, while a `yield` is the answer.
8536 fn resume_generator_detailed(
8537 &mut self,
8538 generator: &Gc<JsObject>,
8539 kind: ResumeKind,
8540 value: Value,
8541 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
8542 let Some(mut state) = generator.with_mut(|data| match &mut data.kind {
8543 ObjectKind::Generator(state) => {
8544 let is_async = state.is_async;
8545 Some(std::mem::replace(
8546 state.as_mut(),
8547 GeneratorState {
8548 frame: None,
8549 phase: GeneratorPhase::Executing,
8550 parked_on_await: false,
8551 parked_on_yield_star: false,
8552 requests: std::collections::VecDeque::new(),
8553 // **Busy while the body runs**, so a `next()` called *from inside*
8554 // the body queues instead of being served. §27.6.3.7
8555 // `AsyncGeneratorResumeNext` returns immediately for the state
8556 // "executing", and the request is served once the body suspends;
8557 // with `false` here the re-entrant call found an empty frame and
8558 // rejected (`request-queue-order-state-executing`).
8559 async_busy: is_async,
8560 is_async,
8561 },
8562 ))
8563 }
8564 _ => None,
8565 }) else {
8566 return Err(self.type_error("not a generator"));
8567 };
8568 let result = self.step_generator(&mut state, kind, value);
8569 // Requests queued *while* the body ran live on the placeholder, because the real
8570 // state is out of the object for the duration. They have to be folded back in
8571 // before the placeholder is overwritten, or the promise they carry never settles.
8572 let queued = generator.with_mut(|data| match &mut data.kind {
8573 ObjectKind::Generator(placeholder) => std::mem::take(&mut placeholder.requests),
8574 _ => std::collections::VecDeque::new(),
8575 });
8576 state.requests.extend(queued);
8577 generator.with_mut(|data| {
8578 data.kind = ObjectKind::Generator(Box::new(state));
8579 });
8580 result
8581 }
8582
8583 /// Advance a generator object, as `%GeneratorPrototype%.next` and friends do.
8584 ///
8585 /// Returns the `{value, done}` object itself rather than the pair, because a
8586 /// `yield*` suspension already has one — the inner iterator's own result — and the
8587 /// protocol says to hand that straight through rather than nest it.
8588 pub fn resume_generator(
8589 &mut self,
8590 generator: &Gc<JsObject>,
8591 kind: ResumeKind,
8592 value: Value,
8593 ) -> JsResult<Value> {
8594 let (value, done, ready, _reason) =
8595 self.resume_generator_detailed(generator, kind, value)?;
8596 if ready {
8597 return Ok(value);
8598 }
8599 self.iterator_result(value, done)
8600 }
8601
8602 /// `next`/`return`/`throw` on an async generator, which answer a promise.
8603 ///
8604 /// The body is the same coroutine a sync generator runs; what changes is that an
8605 /// `await` inside it has to settle before the method can answer, so the step is
8606 /// driven off the job queue rather than returning inline.
8607 pub fn resume_async_generator(
8608 &mut self,
8609 generator: &Gc<JsObject>,
8610 kind: ResumeKind,
8611 value: Value,
8612 ) -> JsResult<Value> {
8613 let promise = self.new_promise();
8614 // Queue, then serve if nothing else is: `it.next(); it.next(v)` has to answer in
8615 // that order, and the second value must reach the *second* `yield`.
8616 let idle = generator.with_mut(|data| match &mut data.kind {
8617 ObjectKind::Generator(state) => {
8618 state.requests.push_back(AsyncRequest {
8619 kind,
8620 value,
8621 promise: promise.clone(),
8622 });
8623 !state.async_busy
8624 }
8625 _ => false,
8626 });
8627 if idle {
8628 self.next_async_request(generator)?;
8629 }
8630 Ok(Value::Object(promise))
8631 }
8632
8633 /// Serve the front queued request, if the generator is free to run one.
8634 ///
8635 /// A finished generator answers from the queue without running anything:
8636 /// `next` is `{undefined, done:true}`, `return(v)` is `{v, done:true}` with `v` awaited
8637 /// first, and `throw(e)` rejects.
8638 fn next_async_request(&mut self, generator: &Gc<JsObject>) -> JsResult<()> {
8639 enum Front {
8640 Idle,
8641 Run(ResumeKind, Value, Gc<JsObject>),
8642 Finished(ResumeKind, Value, Gc<JsObject>),
8643 }
8644 let front = generator.with_mut(|data| match &mut data.kind {
8645 ObjectKind::Generator(state) => {
8646 let Some(request) = state.requests.front() else {
8647 return Front::Idle;
8648 };
8649 // Busy means a request is still in flight — awaiting inside the body, not
8650 // finished. Serving another now would interleave two requests.
8651 if state.async_busy && state.phase != GeneratorPhase::Completed {
8652 return Front::Idle;
8653 }
8654 let kind = request.kind;
8655 let value = request.value.clone();
8656 let promise = request.promise.clone();
8657 state.async_busy = true;
8658 if state.phase == GeneratorPhase::Completed {
8659 Front::Finished(kind, value, promise)
8660 } else {
8661 Front::Run(kind, value, promise)
8662 }
8663 }
8664 _ => Front::Idle,
8665 });
8666 match front {
8667 Front::Idle => Ok(()),
8668 Front::Run(kind, value, promise) => {
8669 self.step_async_generator(generator, &promise, kind, value)
8670 }
8671 Front::Finished(kind, value, promise) => match kind {
8672 ResumeKind::Throw => {
8673 self.settle_async_request(generator, &promise, AsyncOutcome::Error(value))
8674 }
8675 ResumeKind::Next | ResumeKind::Start => {
8676 let result = self.iterator_result(Value::Undefined, true)?;
8677 self.settle_async_request(generator, &promise, AsyncOutcome::Value(result))
8678 }
8679 ResumeKind::Return => {
8680 // `js_async_generator_completed_return`: the value is awaited before it
8681 // becomes `{value, done: true}`, so `it.return(Promise.resolve(1))` on a
8682 // finished generator answers `1`, not a promise.
8683 let resolved = match self.promise_resolve_intrinsic(value) {
8684 Ok(resolved) => resolved,
8685 Err(Signal::Throw(reason)) => {
8686 return self.settle_async_request(
8687 generator,
8688 &promise,
8689 AsyncOutcome::Error(reason),
8690 );
8691 }
8692 Err(other) => return Err(other),
8693 };
8694 let done = JsObject::function(
8695 self.heap,
8696 Some(self.realm.function_proto.clone()),
8697 Callable::CompletedReturn {
8698 generator: generator.clone(),
8699 promise: promise.clone(),
8700 rejected: false,
8701 },
8702 );
8703 let failed = JsObject::function(
8704 self.heap,
8705 Some(self.realm.function_proto.clone()),
8706 Callable::CompletedReturn {
8707 generator: generator.clone(),
8708 promise: promise.clone(),
8709 rejected: true,
8710 },
8711 );
8712 let Value::Object(resolved) = resolved else {
8713 return self.settle_async_request(
8714 generator,
8715 &promise,
8716 AsyncOutcome::Error(Value::Undefined),
8717 );
8718 };
8719 self.perform_then(
8720 &resolved,
8721 Some(Value::Object(done)),
8722 Some(Value::Object(failed)),
8723 )?;
8724 Ok(())
8725 }
8726 },
8727 }
8728 }
8729
8730 /// Settle the front request and start the next one.
8731 ///
8732 /// Every path out of [`Interp::step_async_generator`] goes through here, so the
8733 /// "busy" flag and the queue cannot drift: a promise settled without releasing the
8734 /// generator would strand every later request.
8735 fn settle_async_request(
8736 &mut self,
8737 generator: &Gc<JsObject>,
8738 promise: &Gc<JsObject>,
8739 outcome: AsyncOutcome,
8740 ) -> JsResult<()> {
8741 let settled = generator.with_mut(|data| match &mut data.kind {
8742 ObjectKind::Generator(state) => {
8743 let front = state.requests.front();
8744 debug_assert!(
8745 front.is_some_and(|request| Gc::ptr_eq(&request.promise, promise)),
8746 "a request settled outside its turn"
8747 );
8748 state.requests.pop_front();
8749 state.async_busy = false;
8750 true
8751 }
8752 _ => false,
8753 });
8754 if settled {
8755 match outcome {
8756 AsyncOutcome::Value(value) => self.fulfill_promise(promise, value),
8757 AsyncOutcome::Error(reason) => self.reject_promise(promise, reason),
8758 }
8759 }
8760 self.next_async_request(generator)
8761 }
8762
8763 /// Dispose a list of `(resource, disposeMethod)` pairs, awaiting each disposer.
8764 ///
8765 /// Returns the promise `AsyncDisposableStack.disposeAsync` hands back. The first
8766 /// disposer runs **synchronously** — the reference starts it before returning, which
8767 /// a test can observe by logging after the call — and the rest follow once their
8768 /// predecessor settles.
8769 pub fn dispose_async_all(&mut self, resources: Vec<(Value, Value)>) -> JsResult<Value> {
8770 let promise = self.new_promise();
8771 // §24.4.3.6 `DisposeResources` step 1: `needsAwait` is true as soon as the stack holds
8772 // any resource at all, because every `await using` resource has the async-dispose
8773 // hint — including the null/undefined ones that have nothing to call. If none of them
8774 // turned out to be awaitable, step 4 still performs one `Await(undefined)`, which is
8775 // why `stack.use(null); stack.disposeAsync()` settles one microtask later rather than
8776 // in the tick it was called from (`disposeAsync/explicit-await-for-null`).
8777 let needs_await = !resources.is_empty();
8778 let mut pairs = Vec::with_capacity(resources.len());
8779 for (value, method) in resources {
8780 let pair = self.new_array(vec![value, method]);
8781 pairs.push(Value::Object(pair));
8782 }
8783 let remaining = self.new_array(pairs);
8784 self.dispose_step(
8785 &remaining,
8786 &promise,
8787 Value::Uninitialized,
8788 false,
8789 needs_await,
8790 )?;
8791 Ok(Value::Object(promise))
8792 }
8793
8794 /// One link of the `disposeAsync` chain.
8795 ///
8796 /// Loops while the disposers finish synchronously, and parks on the first thenable it
8797 /// meets — pushing itself back in as the continuation, with the accumulated error
8798 /// carried along so a later failure can still be folded into the `SuppressedError`.
8799 fn dispose_step(
8800 &mut self,
8801 remaining: &Gc<JsObject>,
8802 promise: &Gc<JsObject>,
8803 mut error: Value,
8804 awaited: bool,
8805 needs_await: bool,
8806 ) -> JsResult<()> {
8807 loop {
8808 let length = remaining.array_length().unwrap_or(0);
8809 if length == 0 {
8810 // Step 4: `needsAwait` true and `hasAwaited` false means one `Await(undefined)`
8811 // still has to happen. Re-entering this same step past an already-fulfilled
8812 // promise is exactly one tick, and it keeps the folding of `error` in one place.
8813 if needs_await && !awaited {
8814 let finished = self.new_array(Vec::new());
8815 let thunk = JsObject::function(
8816 self.heap,
8817 Some(self.realm.function_proto.clone()),
8818 Callable::DisposeStep {
8819 remaining: finished.clone(),
8820 promise: promise.clone(),
8821 error,
8822 rejected: false,
8823 awaited: true,
8824 needs_await: false,
8825 },
8826 );
8827 let tick = self.promise_resolve_value(Value::Undefined)?;
8828 if let Value::Object(tick) = tick {
8829 self.perform_then(
8830 &tick,
8831 Some(Value::Object(thunk.clone())),
8832 Some(Value::Object(thunk)),
8833 )?;
8834 }
8835 return Ok(());
8836 }
8837 if matches!(error, Value::Uninitialized) {
8838 self.fulfill_promise(promise, Value::Undefined);
8839 } else {
8840 self.reject_promise(promise, error);
8841 }
8842 return Ok(());
8843 }
8844 let Some(Value::Object(pair)) = remaining
8845 .array_get(length - 1)
8846 .filter(|v| !matches!(v, Value::Hole))
8847 else {
8848 remaining.array_truncate(self.heap, length - 1);
8849 continue;
8850 };
8851 remaining.array_truncate(self.heap, length - 1);
8852 let value = pair.array_get(0).unwrap_or(Value::Undefined);
8853 let Some(Value::Object(method)) = pair.array_get(1) else {
8854 continue;
8855 };
8856 if !method.is_callable() {
8857 continue;
8858 }
8859 match self.call_value(Value::Object(method), value, Vec::new()) {
8860 Ok(result) => {
8861 if !self.is_thenable(&result)? {
8862 // Finished synchronously; the next disposer is the next iteration.
8863 continue;
8864 }
8865 let awaited = match self.promise_resolve_value(result) {
8866 Ok(awaited) => awaited,
8867 Err(Signal::Throw(reason)) => {
8868 self.reject_promise(promise, reason);
8869 return Ok(());
8870 }
8871 Err(other) => return Err(other),
8872 };
8873 let Value::Object(awaited) = awaited else {
8874 continue;
8875 };
8876 let ok = JsObject::function(
8877 self.heap,
8878 Some(self.realm.function_proto.clone()),
8879 Callable::DisposeStep {
8880 remaining: remaining.clone(),
8881 promise: promise.clone(),
8882 error: error.clone(),
8883 rejected: false,
8884 awaited: true,
8885 needs_await,
8886 },
8887 );
8888 let failed = JsObject::function(
8889 self.heap,
8890 Some(self.realm.function_proto.clone()),
8891 Callable::DisposeStep {
8892 remaining: remaining.clone(),
8893 promise: promise.clone(),
8894 error,
8895 rejected: true,
8896 awaited: true,
8897 needs_await,
8898 },
8899 );
8900 self.perform_then(
8901 &awaited,
8902 Some(Value::Object(ok)),
8903 Some(Value::Object(failed)),
8904 )?;
8905 return Ok(());
8906 }
8907 Err(Signal::Throw(thrown)) => {
8908 error = self.merge_dispose_error(thrown, error);
8909 }
8910 Err(other) => return Err(other),
8911 }
8912 }
8913 }
8914
8915 /// Whether `value` would be followed by `ResolvePromise` rather than fulfilled as-is.
8916 fn is_thenable(&mut self, value: &Value) -> JsResult<bool> {
8917 let Value::Object(object) = value else {
8918 return Ok(false);
8919 };
8920 Ok(matches!(
8921 self.get_property(object, "then")?,
8922 Some(Value::Object(then)) if then.is_callable()
8923 ))
8924 }
8925
8926 /// One step of an async generator, settling `promise` with an `{value, done}` result.
8927 fn step_async_generator(
8928 &mut self,
8929 generator: &Gc<JsObject>,
8930 promise: &Gc<JsObject>,
8931 kind: ResumeKind,
8932 value: Value,
8933 ) -> JsResult<()> {
8934 // §27.6.3.4 step 9 → `AsyncGeneratorAwaitReturn` step 6 evaluates
8935 // `PromiseResolve(%Promise%, value)` **before** the body is resumed. When that read
8936 // is abrupt — a `constructor` getter that throws — the generator is resumed with a
8937 // *throw* completion instead, so the body's own `try { yield } catch` sees it:
8938 // `return-suspendedYield-broken-promise-try-catch.js` asserts exactly that, and the
8939 // two sibling cases (`…suspendedStart…`, `…state-completed…`) get the same error
8940 // out of the same read, one as a rejection and one as a rethrow.
8941 //
8942 // Narrow on purpose: only a value that is *already a promise* is inspected, so
8943 // nothing changes for `return 1` and the extra read is a plain data-property
8944 // lookup on the intrinsic case.
8945 if kind == ResumeKind::Return
8946 && let Value::Object(object) = &value
8947 && self.promise_state(object).is_some()
8948 && let Err(Signal::Throw(reason)) = self.get_property(object, "constructor")
8949 {
8950 return self.step_async_generator(generator, promise, ResumeKind::Throw, reason);
8951 }
8952 let stepped = self.resume_generator_detailed(generator, kind, value);
8953 let (value, done, ready, reason) = match stepped {
8954 Ok(stepped) => stepped,
8955 Err(Signal::Throw(reason)) => {
8956 return self.settle_async_request(generator, promise, AsyncOutcome::Error(reason));
8957 }
8958 Err(other) => return Err(other),
8959 };
8960 // Only an `await` has to wait before the method can answer.
8961 if !done && reason == Some(SuspendKind::Await) {
8962 let awaited = match self.promise_resolve_value(value) {
8963 Ok(awaited) => awaited,
8964 Err(Signal::Throw(reason)) => {
8965 return self.settle_async_request(
8966 generator,
8967 promise,
8968 AsyncOutcome::Error(reason),
8969 );
8970 }
8971 Err(other) => return Err(other),
8972 };
8973 let Value::Object(awaited) = awaited else {
8974 return Ok(());
8975 };
8976 let resumed = JsObject::function(
8977 self.heap,
8978 Some(self.realm.function_proto.clone()),
8979 Callable::GeneratorResume {
8980 generator: generator.clone(),
8981 promise: promise.clone(),
8982 kind: ResumeKind::Next,
8983 },
8984 );
8985 let raised = JsObject::function(
8986 self.heap,
8987 Some(self.realm.function_proto.clone()),
8988 Callable::GeneratorResume {
8989 generator: generator.clone(),
8990 promise: promise.clone(),
8991 kind: ResumeKind::Throw,
8992 },
8993 );
8994 self.perform_then(
8995 &awaited,
8996 Some(Value::Object(resumed)),
8997 Some(Value::Object(raised)),
8998 )?;
8999 return Ok(());
9000 }
9001 // `yield v` in an *async* generator awaits `v`, and so does the `return v` that
9002 // completes it — both arrive as the settled value rather than as the promise
9003 // object. A plain value skips the round trip, which is also what keeps `yield 1`
9004 // from costing an extra tick.
9005 let awaits_value = self.is_thenable(&value)?;
9006 if awaits_value {
9007 // A **completed** generator's value is `AsyncGeneratorAwaitReturn`'s, which
9008 // says `PromiseResolve(%Promise%, value)` — the `constructor`-reading one. A
9009 // value that merely gets `yield`ed is awaited by the body's own `Await`, where
9010 // no `PromiseResolve` appears, so that path keeps the shortcut.
9011 let awaited = match if done {
9012 self.promise_resolve_intrinsic(value)
9013 } else {
9014 self.promise_resolve_value(value)
9015 } {
9016 Ok(awaited) => awaited,
9017 Err(Signal::Throw(reason)) => {
9018 return self.settle_async_request(
9019 generator,
9020 promise,
9021 AsyncOutcome::Error(reason),
9022 );
9023 }
9024 Err(other) => return Err(other),
9025 };
9026 let Value::Object(awaited) = awaited else {
9027 return Ok(());
9028 };
9029 // A rejected yield throws *at the yield* inside the body, so the rejection
9030 // resumes the generator rather than the method's promise.
9031 let answer = JsObject::function(
9032 self.heap,
9033 Some(self.realm.function_proto.clone()),
9034 Callable::YieldResult {
9035 generator: generator.clone(),
9036 promise: promise.clone(),
9037 done,
9038 },
9039 );
9040 let raise = JsObject::function(
9041 self.heap,
9042 Some(self.realm.function_proto.clone()),
9043 Callable::GeneratorResume {
9044 generator: generator.clone(),
9045 promise: promise.clone(),
9046 kind: ResumeKind::Throw,
9047 },
9048 );
9049 self.perform_then(
9050 &awaited,
9051 Some(Value::Object(answer)),
9052 Some(Value::Object(raise)),
9053 )?;
9054 return Ok(());
9055 }
9056 let result = if ready {
9057 // `yield*` handed back the inner iterator's own result object.
9058 value
9059 } else {
9060 self.iterator_result(value, done)?
9061 };
9062 self.settle_async_request(generator, promise, AsyncOutcome::Value(result))
9063 }
9064
9065 /// The `{value, done}` object an iterator method answers with.
9066 pub fn iterator_result(&mut self, value: Value, done: bool) -> JsResult<Value> {
9067 let result = self.new_object(Some(self.realm.object_proto.clone()));
9068 result.define_data("value", value);
9069 result.define_data("done", Value::Bool(done));
9070 Ok(Value::Object(result))
9071 }
9072
9073 /// Advance a generator, returning the `{value, done}` pair the protocol wants.
9074 fn step_generator(
9075 &mut self,
9076 state: &mut GeneratorState,
9077 kind: ResumeKind,
9078 value: Value,
9079 ) -> JsResult<(Value, bool, bool, Option<SuspendKind>)> {
9080 match state.phase {
9081 GeneratorPhase::Executing => {
9082 return Err(self.type_error("cannot invoke a running generator"));
9083 }
9084 GeneratorPhase::Completed => {
9085 // A finished generator answers every resumption without running.
9086 return Ok(match kind {
9087 ResumeKind::Throw => return Err(Signal::Throw(value)),
9088 ResumeKind::Return => (value, true, false, None),
9089 ResumeKind::Next | ResumeKind::Start => (Value::Undefined, true, false, None),
9090 });
9091 }
9092 GeneratorPhase::SuspendedStart => {
9093 if kind != ResumeKind::Next && kind != ResumeKind::Start {
9094 // The body never started, so there is nothing to unwind or return
9095 // from: `return(v)` finishes, `throw(e)` rethrows at the caller.
9096 state.frame = None;
9097 state.phase = GeneratorPhase::Completed;
9098 return Ok(match kind {
9099 ResumeKind::Throw => return Err(Signal::Throw(value)),
9100 _ => (value, true, false, None),
9101 });
9102 }
9103 }
9104 GeneratorPhase::SuspendedYield => {}
9105 }
9106
9107 let Some(mut frame) = state.frame.take() else {
9108 return Ok((Value::Undefined, true, false, None));
9109 };
9110 // `next(v)` and `return(v)` re-enter the `yield` with the value *and* the magic
9111 // number that says which method resumed it; the emitted `if_false` branches on
9112 // the magic. `initial_yield` reads neither, and a `throw` does not resume at all.
9113 let mut raised = None;
9114 match kind {
9115 ResumeKind::Next | ResumeKind::Start => {
9116 if state.phase == GeneratorPhase::SuspendedYield {
9117 frame.stack.push(value);
9118 // An `await` resumes with its value alone; only a `yield` gets the
9119 // magic number that says which of `next`/`return` resumed it.
9120 if !state.parked_on_await {
9121 frame.stack.push(Value::Int(RESUME_NEXT));
9122 }
9123 }
9124 }
9125 ResumeKind::Return => {
9126 // A `return` on a not-yet-started generator is handled above, so this is
9127 // always a real resumption.
9128 frame.stack.push(value);
9129 frame.stack.push(Value::Int(RESUME_RETURN));
9130 }
9131 ResumeKind::Throw => {
9132 // At a `yield*` the exception is *data* for the delegation: the compiled
9133 // code resumes with the value and magic `2` and calls the inner iterator's
9134 // `throw`. Everywhere else it is raised at the suspension point, so the
9135 // body's own handler sees it.
9136 if state.phase == GeneratorPhase::SuspendedYield && state.parked_on_yield_star {
9137 frame.stack.push(value);
9138 frame.stack.push(Value::Int(RESUME_THROW));
9139 } else {
9140 raised = Some(value);
9141 }
9142 }
9143 }
9144 state.phase = GeneratorPhase::Executing;
9145
9146 let depth = self.frames.len();
9147 self.frames.push(frame);
9148 // A `throw` unwinds from where the frame parked, exactly as if the exception had
9149 // happened at the `yield`.
9150 if let Some(exception) = raised {
9151 if self.catch_here(exception.clone()).is_none() {
9152 self.pop_frame();
9153 state.phase = GeneratorPhase::Completed;
9154 return Err(Signal::Throw(exception));
9155 }
9156 }
9157
9158 // Only the generator's *own* frame ends the generator. The body may call ordinary
9159 // functions, and those push frames of their own: a `Step::Return` from one of them
9160 // is a nested call finishing, not the generator completing. Miscounting that is
9161 // silent — the generator reports the callee's value as its own result and marks
9162 // itself done — so the depth comparison is load-bearing, not defensive.
9163 let own_frame = depth + 1;
9164 loop {
9165 match self.step() {
9166 Ok(Step::Continue) => {}
9167 Ok(Step::Suspend(reason)) if self.frames.len() == own_frame => {
9168 let mut frame = self.frames.pop().expect("a frame is live");
9169 // `yield` left the value on the stack; `initial_yield` left nothing.
9170 let yielded = if reason == SuspendKind::Initial {
9171 Value::Undefined
9172 } else {
9173 frame.stack.pop().unwrap_or(Value::Undefined)
9174 };
9175 state.frame = Some(frame);
9176 state.parked_on_await = reason == SuspendKind::Await;
9177 state.parked_on_yield_star =
9178 matches!(reason, SuspendKind::YieldStar | SuspendKind::AsyncYieldStar);
9179 state.phase = if reason == SuspendKind::Initial {
9180 GeneratorPhase::SuspendedStart
9181 } else {
9182 GeneratorPhase::SuspendedYield
9183 };
9184 // `yield*` hands the inner iterator's own result object straight
9185 // back, so the caller sees one `{value, done}` rather than a nested
9186 // one — which is why the third field says "already a result".
9187 return Ok((
9188 yielded,
9189 false,
9190 reason == SuspendKind::YieldStar,
9191 Some(reason),
9192 ));
9193 }
9194 Ok(Step::Suspend(_)) => {
9195 // A `yield` in a frame other than the generator's would mean a
9196 // generator body entered as an ordinary call, which
9197 // `call_or_push` prevents.
9198 self.unwind_to(depth);
9199 state.phase = GeneratorPhase::Completed;
9200 return Err(Signal::Throw(self.make_error(
9201 "InternalError",
9202 "a generator body ran as an ordinary call",
9203 )));
9204 }
9205 Ok(Step::Return(value)) => {
9206 self.pop_frame();
9207 if self.frames.len() > depth {
9208 // A nested call finished: hand the value back to its caller and
9209 // keep running the generator body.
9210 self.frames
9211 .last_mut()
9212 .expect("a caller is live")
9213 .stack
9214 .push(value);
9215 continue;
9216 }
9217 state.phase = GeneratorPhase::Completed;
9218 // The reference closes the generator's closure variables here; ours
9219 // live in cells the frame owned, which the drop below releases.
9220 return Ok((value, true, false, None));
9221 }
9222 Err(Signal::Throw(exception)) => {
9223 // The frame that threw gets the first chance to catch, exactly as in
9224 // the ordinary call loop; a frame above the generator's is popped and
9225 // the exception carries on down.
9226 let exception = exception;
9227 loop {
9228 if self.frames.len() <= depth {
9229 // The generator's own frame is gone, so nothing here caught it.
9230 state.phase = GeneratorPhase::Completed;
9231 return Err(Signal::Throw(exception));
9232 }
9233 if self.catch_here(exception.clone()).is_some() {
9234 break;
9235 }
9236 self.pop_frame();
9237 }
9238 }
9239 Err(Signal::OutOfMemory) => return Err(Signal::OutOfMemory),
9240 }
9241 }
9242 }
9243
9244 /// Pop frames until `depth` are left, keeping their buffers.
9245 fn unwind_to(&mut self, depth: usize) {
9246 while self.frames.len() > depth {
9247 self.pop_frame();
9248 }
9249 }
9250 fn call_or_push(
9251 &mut self,
9252 callee: Value,
9253 this: Value,
9254 args: Vec<Value>,
9255 ) -> JsResult<Option<Value>> {
9256 if let Value::Object(function) = &callee
9257 && let Some((code, env)) = bytecode_of(function)
9258 {
9259 // Calling a generator function does not run anything: it captures the
9260 // arguments in a frame and hands back the generator object.
9261 if code.code.kind.is_generator() {
9262 return self.new_generator(callee, this, args).map(Some);
9263 }
9264 // An async function answers a promise and runs its body as a coroutine, so it
9265 // takes the same path as a plain call into it.
9266 if code.code.kind.is_async() {
9267 return self.new_async_function(callee, this, args).map(Some);
9268 }
9269 self.push_frame(code, env, this, args, callee)?;
9270 return Ok(None);
9271 }
9272 self.call_value(callee, this, args).map(Some)
9273 }
9274
9275 /// `new callee(args)`.
9276 ///
9277 /// A constructor differs from a plain call in three ways: it gets a fresh object
9278 /// as `this` whose prototype is the constructor's `prototype` property, its
9279 /// return value is *replaced* by that object unless it returns an object itself,
9280 /// and a native constructor is expected to initialise the object it is given
9281 /// rather than build one.
9282 pub fn construct(
9283 &mut self,
9284 callee: Value,
9285 new_target: Value,
9286 args: Vec<Value>,
9287 ) -> JsResult<Value> {
9288 // `new` on a bound function constructs its *target*, prepending the arguments
9289 // the bind fixed and ignoring the bound `this` — a bound function is a
9290 // constructor only when its target is one, and `new` always makes a fresh
9291 // object of the target's prototype rather than reusing the bound receiver.
9292 // Without this unwrapping, `constructor1.bind(null, 1)` called under `new`
9293 // ran the body with `this === null` and threw on `this.x = a`.
9294 let mut callee = callee;
9295 let mut new_target = new_target;
9296 let mut args = args;
9297 loop {
9298 let Some(object) = callee.as_object().cloned() else {
9299 return Err(Signal::Throw(
9300 self.make_error("TypeError", "not a constructor"),
9301 ));
9302 };
9303 // A proxy of a function constructs through its `construct` trap, and the
9304 // trap's answer is the result directly — no fresh object is made here.
9305 if object.proxy_state().is_some() {
9306 return match self.proxy_construct(&object, args, &new_target)? {
9307 Some(result) => Ok(result),
9308 None => Err(Signal::Throw(
9309 self.make_error("TypeError", "proxy target is not a constructor"),
9310 )),
9311 };
9312 }
9313 // A generator function has no `[[Construct]]`, and the reference names it in
9314 // the message: `new (function* G(){})()` reports "G is not a constructor".
9315 if object.with(|data| match &data.kind {
9316 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9317 code.code.kind.is_generator()
9318 }
9319 _ => false,
9320 }) {
9321 let name = object
9322 .own_property("name")
9323 .and_then(|property| property.value)
9324 .map(|value| value.to_js_string())
9325 .unwrap_or_default();
9326 return Err(Signal::Throw(
9327 self.make_error("TypeError", &format!("{name} is not a constructor")),
9328 ));
9329 }
9330 let bound = object.with(|data| match &data.kind {
9331 ObjectKind::Function(Callable::Bound {
9332 target,
9333 args: leading,
9334 ..
9335 }) => Some((target.clone(), leading.clone())),
9336 _ => None,
9337 });
9338 let Some((target, leading)) = bound else {
9339 // Not a bound function, so this object is the callee. §7.2.4
9340 // `IsConstructor` decides whether `new` may proceed, and the two ad-hoc
9341 // refusals above cover only the built-ins the reference also refuses by
9342 // name. Everything else — a method, an arrow, an async function — has no
9343 // `[[Construct]]` either, and answering "yes" here made
9344 // `new (Array.prototype.map)` build an object instead of throwing.
9345 if !object.is_constructor() {
9346 let name = object
9347 .own_property("name")
9348 .and_then(|property| property.value)
9349 .map(|value| value.to_js_string())
9350 .unwrap_or_default();
9351 return Err(Signal::Throw(
9352 self.make_error("TypeError", &format!("{name} is not a constructor")),
9353 ));
9354 }
9355 break;
9356 };
9357 let mut all = leading;
9358 all.extend(args);
9359 args = all;
9360 // A bound function that is its own `new.target` stands in for its target:
9361 // `new (C.bind(null))()` makes a `C` instance, so the object has to come
9362 // from `C.prototype`, not from the bound wrapper (which has no `prototype`).
9363 let same_wrapper = match (new_target.as_object(), callee.as_object()) {
9364 (Some(new_target), Some(bound)) => new_target.ptr_eq(bound),
9365 _ => false,
9366 };
9367 if same_wrapper {
9368 new_target = target.clone();
9369 }
9370 callee = target;
9371 }
9372 let Value::Object(function) = &callee else {
9373 unreachable!("the loop above only breaks on an object");
9374 };
9375 // The fresh object's prototype comes from `new.target`, not from the callee: a
9376 // derived constructor reaches here through `super()`, and the instance must be a
9377 // `new.target` instance, so `class D extends C { constructor(){ super() } }` makes
9378 // an object inheriting `D.prototype` rather than `C.prototype`.
9379 let prototype_source = match new_target.as_object() {
9380 Some(target) => target.clone(),
9381 None => function.clone(),
9382 };
9383 // A native constructor builds its own instance, through `new_ctor_instance`, once it
9384 // has validated its arguments. Pre-building one here would read
9385 // `new.target.prototype` too early: `Reflect.construct(Promise, [], badTarget)` has
9386 // to throw `TypeError` for a non-callable executor *before* a throwing `prototype`
9387 // getter runs, and `new DataView(detached, …)` likewise for the detached check.
9388 let is_native = function.native_creates_own_instance();
9389 let this = if is_native {
9390 Value::Undefined
9391 } else {
9392 let prototype = self.get_property(&prototype_source, "prototype")?;
9393 let prototype = match prototype {
9394 Some(Value::Object(proto)) => Some(proto),
9395 // `GetPrototypeFromConstructor`: when the requested `prototype` is not an
9396 // object, the answer is the realm's *intrinsic* prototype for this
9397 // constructor, not `%Object.prototype%`.
9398 _ => {
9399 // `GetPrototypeFromConstructor` step 4 is `GetFunctionRealm(constructor)`,
9400 // and that is a `TypeError` for a revoked proxy. Without it, `new
9401 // revokedProxy()` quietly produced an `%Object.prototype%` instance —
9402 // `base-ctor-revoked-proxy` revokes the proxy from inside its own `get`
9403 // trap, so it is already revoked when this fallback runs.
9404 if prototype_source.proxy_state().is_some() {
9405 self.proxy_parts(&prototype_source)?;
9406 }
9407 let fallback = self.get_property(function, "prototype")?;
9408 match fallback {
9409 Some(Value::Object(proto)) => Some(proto),
9410 _ => Some(self.realm.object_proto.clone()),
9411 }
9412 }
9413 };
9414 Value::Object(self.new_object(prototype))
9415 };
9416 // `new.target` inside the body is the constructor that was written, so a bound
9417 // function's target sees itself rather than the bound wrapper.
9418 //
9419 // The save/restore is not cosmetic: a constructor that *throws* leaves through the
9420 // `?`, so assigning `None` after the call would be skipped and the failed
9421 // `new.target` would stay visible to every later native call. The symptom was a
9422 // native constructor refusing a plain call — `var s = Symbol(); new
9423 // FinalizationRegistry(1)` (which throws) followed by `Symbol()` reported
9424 // "FinalizationRegistry is not a constructor".
9425 let outer_new_target = self.pending_new_target.replace(new_target);
9426 let callee = callee.clone();
9427 let result = self.call_value(callee, this.clone(), args);
9428 self.pending_new_target = outer_new_target;
9429 let result = result?;
9430 // A constructor that returns an object overrides `this`; any other return value
9431 // (including `undefined`) is ignored — **except** in a derived constructor, where
9432 // §15.7.1 step 12 makes a non-object return a `TypeError`
9433 // (`Function/internals/Construct/derived-return-val`).
9434 let derived = function.with(|data| match &data.kind {
9435 ObjectKind::Function(Callable::Bytecode { code, .. }) => {
9436 code.code.is_derived_constructor
9437 }
9438 _ => false,
9439 });
9440 Ok(match result {
9441 Value::Object(_) => result,
9442 // A bare `return;` answers `undefined`, which is **legal** even in a derived
9443 // constructor — §9.2.2 step 12 only refuses a *non-undefined* primitive.
9444 Value::Undefined => this,
9445 _ if derived => {
9446 return Err(Signal::Throw(self.make_error(
9447 "TypeError",
9448 "derived constructor may only return an object or undefined",
9449 )));
9450 }
9451 _ => this,
9452 })
9453 }
9454
9455 /// `new.target` for the call currently being made.
9456 ///
9457 /// A native constructor normally gets it as an argument ([`Interp::construct`] passes
9458 /// it as `this`), but a *host* constructor that builds its own instance is handed
9459 /// `undefined` for `this` — which is the shape the C API's `JS_CFUNC_constructor` has.
9460 /// Its `new_target` is the one thing such a closure cannot otherwise see, so it reads
9461 /// it here.
9462 ///
9463 /// Answers `undefined` outside a `new` call, matching the `this_val` a C function
9464 /// receives for a plain call.
9465 pub fn current_new_target(&self) -> Value {
9466 self.active_new_target.clone()
9467 }
9468
9469 /// `new AggregateError(errors, message)`, for `Promise.any`'s rejection.
9470 ///
9471 /// Not `make_error`: the rejection carries an `errors` **array**, and `errors` is the
9472 /// only thing a caller looks at — `Promise/any/*` destructures it in nearly every test.
9473 pub fn aggregate_error(&mut self, errors: Vec<Value>, message: &str) -> Value {
9474 let constructor = self.realm.errors.get("AggregateError").cloned();
9475 let Some(constructor) = constructor else {
9476 return self.make_error("AggregateError", message);
9477 };
9478 let list = self.new_array(errors);
9479 match self.construct(
9480 Value::Object(constructor.clone()),
9481 Value::Object(constructor),
9482 vec![Value::Object(list), self.string(message)],
9483 ) {
9484 Ok(value) => value,
9485 // A user could have replaced `AggregateError` with something that throws; the
9486 // engine still owes the caller a rejection, so it falls back rather than
9487 // turning `Promise.any`'s rejection into a throw.
9488 Err(_) => self.make_error("AggregateError", message),
9489 }
9490 }
9491
9492 /// A `TypeError`/`ReferenceError`/`RangeError` object, as the value to throw.
9493 ///
9494 /// The error classes themselves arrive with the builtins milestone; what
9495 /// matters here is that the thrown value stringifies the way a script printing
9496 /// the caught value expects.
9497 ///
9498 /// `name` and `message` become own properties, which is what makes `e.name` cheap and
9499 /// `Error.prototype.name` merely the fallback — the same shape `make_error`'s callers
9500 /// rely on when they print a caught value.
9501 pub fn make_error(&self, name: &str, message: &str) -> Value {
9502 let proto = self
9503 .realm
9504 .errors
9505 .get(name)
9506 .map(|constructor| self.prototype_of(constructor))
9507 .unwrap_or_else(|| self.realm.error_proto.clone());
9508 let error = self.new_object(Some(proto));
9509 // `name` and `message` are own properties of the instance, which is what
9510 // makes `e.name` cheap and `Error.prototype.name` the fallback for a plain
9511 // `Error`.
9512 error.define(
9513 "name",
9514 Property::with_attributes(self.string(name), true, false),
9515 );
9516 error.define(
9517 "message",
9518 Property::with_attributes(self.string(message), true, false),
9519 );
9520 // The internal class, which is what tells a printer this is an error rather than a
9521 // plain object with `name` and `message` properties. The constructor path sets it
9522 // (`builtins/error.rs`); without it here an engine-thrown `TypeError` printed as
9523 // `{ stack: … }` while `new TypeError(...)` printed as `TypeError: …`. It is
9524 // literally `"Error"` in both places — the *name* is read from `name`, which is why
9525 // a `RangeError` still prints as `RangeError`.
9526 self.internal_set(&error, "_class", self.string("Error"));
9527 // `[[ErrorData]]` as well, and for a while this was missing: an engine-thrown error
9528 // answered `false` from `Error.isError` while a constructed one answered `true`,
9529 // because only the constructor set the slot. The reference answers `true` for both
9530 // (`try { null.x } catch (e) { Error.isError(e) }`), and once `stack` became an
9531 // accessor gated on this slot the omission stopped being cosmetic: `print_error`
9532 // tests `typeof stack === "string"` to decide on a trailing newline, so every
9533 // engine-thrown error lost its blank line.
9534 self.internal_set(&error, "_error_data", Value::Bool(true));
9535 // The trace is captured where the error is *made*, which is where the reference
9536 // captures it too: `JS_ThrowTypeError` and friends call `build_backtrace` on the
9537 // way out, so a caught engine error already has its stack even if the handler
9538 // never rethrows it.
9539 self.add_stack(&error);
9540 Value::Object(error)
9541 }
9542
9543 /// Give an error object its `stack` property, from the current frame stack.
9544 ///
9545 /// Only objects get one — `throw 42` has no stack anywhere — and an object that
9546 /// already has a `stack` keeps it, so an error caught and rethrown, or one whose
9547 /// `stack` a script set, is not rewritten.
9548 pub fn add_stack(&self, object: &Gc<JsObject>) {
9549 self.add_stack_skipping(object, 0);
9550 }
9551
9552 /// [`Interp::add_stack`], omitting the `skip` innermost frames.
9553 ///
9554 /// An `Error` constructor passes 1: the reference builds those traces with
9555 /// `JS_BACKTRACE_FLAG_SKIP_FIRST_LEVEL`, so `new Error()` does not report the
9556 /// constructor itself, while a `RangeError` raised inside `toISOString` does
9557 /// report `at toISOString (native)`.
9558 pub fn add_stack_skipping(&self, object: &Gc<JsObject>, skip: usize) {
9559 if object.has_own("stack") {
9560 return;
9561 }
9562 // The trace is *captured* here but not installed as a property: `stack` is an
9563 // accessor on `Error.prototype`, and a fresh error has no own `stack` at all
9564 // (`docs/test262-status.md` §4.45). The frames are only available now, so the text
9565 // is kept in a hidden slot and the getter materialises it on first read.
9566 //
9567 // The slot name is an internal `_`-prefixed key, so `[[OwnPropertyKeys]]` never
9568 // shows it — this is the same discipline `_error_data` and `_class` follow.
9569 let trace = self.stack_trace_skipping(skip);
9570 let text = self.string(trace);
9571 self.internal_set(object, "_stack_trace", text);
9572 }
9573
9574 /// The function object currently being called, if any.
9575 ///
9576 /// A native function is a bare `fn` pointer, so it cannot capture which class
9577 /// it belongs to; it reads that from the callee instead. This is also what a
9578 /// stack trace would use.
9579 pub fn current_callee(&self) -> Option<Gc<JsObject>> {
9580 match &self.frames.last()?.callee {
9581 Value::Object(object) => Some(object.clone()),
9582 _ => None,
9583 }
9584 }
9585
9586 /// The `prototype` property of a constructor, falling back to
9587 /// `Object.prototype` for anything that is not shaped like one.
9588 pub fn prototype_of(&self, constructor: &Gc<JsObject>) -> Gc<JsObject> {
9589 constructor
9590 .own_property("prototype")
9591 .and_then(|property| property.value)
9592 .and_then(|value| value.as_object().cloned())
9593 .unwrap_or_else(|| self.realm.object_proto.clone())
9594 }
9595
9596 /// Throw a `TypeError` carrying `message`.
9597 pub fn type_error(&self, message: impl AsRef<str>) -> Signal {
9598 Signal::Throw(self.make_error("TypeError", message.as_ref()))
9599 }
9600
9601 /// Throw a `RangeError` carrying `message`.
9602 pub fn range_error(&self, message: impl AsRef<str>) -> Signal {
9603 Signal::Throw(self.make_error("RangeError", message.as_ref()))
9604 }
9605
9606 /// A `ReferenceError`, as the value to throw.
9607 ///
9608 /// `throw` uses it for "called on a disposed stack": `DisposableStack.prototype.defer`
9609 /// and its siblings report a `ReferenceError` there, which is what
9610 /// `adopt|defer|move/throws-if-disposed` assert.
9611 pub fn reference_error(&self, message: impl AsRef<str>) -> Signal {
9612 Signal::Throw(self.make_error("ReferenceError", message.as_ref()))
9613 }
9614
9615 /// The `ReferenceError` a read of an uninitialised binding raises.
9616 /// The name of the binding `slot` refers to, for an error message.
9617 fn binding_name(&self, slot: usize, kind: VarSlot) -> String {
9618 match kind {
9619 VarSlot::Loc => self
9620 .frame()
9621 .code
9622 .code
9623 .vars
9624 .get(slot)
9625 .map(|v| v.name.clone()),
9626 VarSlot::Closure => self
9627 .frame()
9628 .code
9629 .code
9630 .closure_vars
9631 .get(slot)
9632 .map(|c| c.name.clone()),
9633 }
9634 .unwrap_or_default()
9635 }
9636
9637 /// Whether `slot` names a `const` binding, which rejects every store after its
9638 /// initialiser.
9639 fn is_read_only(&self, slot: usize, kind: VarSlot) -> bool {
9640 match kind {
9641 VarSlot::Loc => self
9642 .frame()
9643 .code
9644 .code
9645 .vars
9646 .get(slot)
9647 .is_some_and(|v| v.is_const),
9648 VarSlot::Closure => self
9649 .frame()
9650 .code
9651 .code
9652 .closure_vars
9653 .get(slot)
9654 .is_some_and(|c| c.is_const),
9655 }
9656 }
9657
9658 /// The `TypeError` a store to a `const` binding raises.
9659 ///
9660 /// `const` is enforced here rather than at compile time because the binding can be
9661 /// assigned from a place the compiler cannot classify — `c = 2` inside a closure
9662 /// is just a `put_var_ref_check`. `PutLocCheck`/`PutVarRefCheck` therefore check
9663 /// both halves of what "checked store" means: the dead zone is over, and the
9664 /// binding is writable.
9665 fn read_only(&self, slot: usize, kind: VarSlot) -> Signal {
9666 let name = self.binding_name(slot, kind);
9667 Signal::Throw(self.make_error("TypeError", &format!("'{name}' is read-only")))
9668 }
9669
9670 fn dead_zone(&self, slot: usize, kind: VarSlot) -> Signal {
9671 let name = match kind {
9672 VarSlot::Loc => self
9673 .frame()
9674 .code
9675 .code
9676 .vars
9677 .get(slot)
9678 .map(|v| v.name.clone()),
9679 VarSlot::Closure => self
9680 .frame()
9681 .code
9682 .code
9683 .closure_vars
9684 .get(slot)
9685 .map(|c| c.name.clone()),
9686 }
9687 .unwrap_or_default();
9688 Signal::Throw(self.make_error(
9689 "ReferenceError",
9690 &format!("cannot access '{name}' before initialization"),
9691 ))
9692 }
9693
9694 fn throw_reference(&self, name: &str) -> Signal {
9695 Signal::Throw(self.make_error("ReferenceError", &format!("'{name}' is not defined")))
9696 }
9697
9698 // -- the instruction loop -----------------------------------------------
9699
9700 // One call site, one exit: this is the dispatch fetch, and `execute` is the loop
9701 // that wants it inlined. Left as a call it costs a call/ret per *instruction* —
9702 // measured at 16% of a tight arithmetic loop's total time.
9703 #[inline(always)]
9704 fn step(&mut self) -> JsResult<Step> {
9705 // The instruction is already decoded (see [`crate::insn`]), so this is an index
9706 // and a `Copy` read rather than a table lookup plus a width switch. Only the
9707 // borrow lives across the boundary; nothing is cloned.
9708 // **One** borrow of the frame: fetch the record, then advance in the same scope.
9709 // The obvious version borrowed it three times (`last` to read, `last_mut` to
9710 // write, and once more inside the handler), and each is a bounds check plus an
9711 // `Option` unwrap — on the one path every instruction takes.
9712 let Some((insn, next)) = ({
9713 let frame = self
9714 .frames
9715 .last_mut()
9716 .expect("step() is only called with a live frame");
9717 // Past the last instruction is a normal return: the compiler ends a function
9718 // with `return`, and a jump to the end of a block lands here.
9719 let insn = frame.insns().get(frame.pc).copied();
9720 match insn {
9721 None => None,
9722 Some(insn) => {
9723 // A fused record stands for the next few instructions, so the next
9724 // `pc` is its width ahead — the instructions it replaces are never
9725 // dispatched. `at` is the byte offset a stack trace reports; it stays
9726 // an offset because the line table is keyed by bytes.
9727 frame.at = insn.offset as usize;
9728 frame.pc += insn.width();
9729 Some((insn, frame.pc))
9730 }
9731 }
9732 }) else {
9733 return Ok(Step::Return(Value::Undefined));
9734 };
9735 self.check_memory()?;
9736 self.check_interrupt()?;
9737 if insn.fused == crate::insn::Fused::None {
9738 self.execute_instruction(insn.op, insn.a, insn.b, next)
9739 } else {
9740 self.execute_fused(insn)
9741 }
9742 }
9743
9744 /// Run a fused instruction: several bytecode instructions in one dispatch.
9745 ///
9746 /// Each arm is exactly the sequence it replaces. The integer case is the fast one —
9747 /// it cannot throw and cannot allocate — and anything else falls back to the real
9748 /// instructions, in their real order, so an exception leaves the operand stack
9749 /// exactly as it would have been.
9750 #[inline]
9751 fn execute_fused(&mut self, insn: crate::insn::Insn) -> JsResult<Step> {
9752 use crate::insn::Fused;
9753 let slot = insn.a as usize;
9754 match insn.fused {
9755 // `x = k`: `push k; put_loc x`.
9756 Fused::StoreImm => self.put_loc(slot, Value::Int(insn.b as i32)),
9757 // `x += k`: `get_loc x; push k; add; put_loc x`.
9758 Fused::AddImmLoc => {
9759 let delta = insn.b as i32;
9760 match self.get_loc(slot) {
9761 Value::Int(left) => {
9762 // Inline rather than `add_numbers(Value::Int(..), Value::Int(..))`:
9763 // that built two `Value`s, called a function, and matched on them
9764 // again to reach this same `checked_add`. It is the innermost
9765 // operation of every accumulator in every program.
9766 let answer = match left.checked_add(delta) {
9767 Some(sum) => Value::Int(sum),
9768 None => Value::Float(left as f64 + delta as f64),
9769 };
9770 self.put_loc(slot, answer);
9771 }
9772 other => {
9773 self.push(other);
9774 self.push(Value::Int(delta));
9775 self.binary_add()?;
9776 let value = self.pop();
9777 self.put_loc(slot, value);
9778 }
9779 }
9780 }
9781 // `x += "literal"` and `x += y`: the two shapes that can append in place.
9782 Fused::AddAtomLoc => {
9783 let text = self.atom_wtf8(insn.b as usize);
9784 let right = self.string_wtf8(text);
9785 self.add_into_loc(slot, right)?;
9786 }
9787 Fused::AddLocLoc => {
9788 let source = (insn.a & 0xFFFF) as usize;
9789 let target = (insn.a >> 16) as usize;
9790 let right = self.get_loc(source);
9791 self.add_into_loc(target, right)?;
9792 }
9793 Fused::AddArgLoc => {
9794 let source = (insn.a & 0xFFFF) as usize;
9795 let target = (insn.a >> 16) as usize;
9796 let right = self.get_arg(source);
9797 self.add_into_loc(target, right)?;
9798 }
9799 // `x++` with the old value dropped: `get_loc x; post_inc; put_loc x; drop`.
9800 Fused::PostIncLoc => match self.get_loc(slot) {
9801 Value::Int(left) => {
9802 let answer = match left.checked_add(1) {
9803 Some(sum) => Value::Int(sum),
9804 None => Value::Float(left as f64 + 1.0),
9805 };
9806 self.put_loc(slot, answer);
9807 }
9808 other => {
9809 self.push(other);
9810 let raw = self.pop();
9811 let (old, updated) = self.advance_numeric(raw, true)?;
9812 self.push(old);
9813 self.push(updated);
9814 let value = self.pop();
9815 self.put_loc(slot, value);
9816 self.pop();
9817 }
9818 },
9819 // `if (!(x < arg)) goto target`: a loop header.
9820 //
9821 // The comparison is computed rather than replayed on the operand stack. That
9822 // is safe even when an operand is an object and `ToNumber` runs a `valueOf`
9823 // that throws: the effects happen in the same order, and a handler truncates
9824 // the stack down to its marker, so the intermediate values are unobservable.
9825 Fused::LtLocArgJump => {
9826 let loc = (insn.a >> 16) as usize;
9827 let arg = (insn.a & 0xFFFF) as usize;
9828 let left = self.get_loc(loc);
9829 let right = self.get_arg(arg);
9830 let taken = match (&left, &right) {
9831 (Value::Int(left), Value::Int(right)) => !(left < right),
9832 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9833 };
9834 if taken {
9835 self.frame_mut().pc = insn.b as usize;
9836 }
9837 }
9838 // `i < k` in a loop header, where `k` is an integer literal.
9839 Fused::LtLocImmJump => {
9840 let left = self.get_loc(insn.a as usize);
9841 let right = Value::Int(insn.imm as i32);
9842 let taken = match &left {
9843 Value::Int(left) => !(*left < insn.imm as i32),
9844 _ => !self.relational(Opcode::Lt, left, right)?.to_boolean(),
9845 };
9846 if taken {
9847 self.frame_mut().pc = insn.b as usize;
9848 }
9849 }
9850 Fused::None => unreachable!("only called for a fused record"),
9851 }
9852 Ok(Step::Continue)
9853 }
9854
9855 /// Run records that cannot call script, cannot throw and cannot change frames.
9856 ///
9857 /// Returns `Some(value)` when the function ran off the end of its instructions (a
9858 /// normal return), and `None` when it stopped in front of an instruction the slow path
9859 /// has to handle — `pc` is written back either way, so `step` resumes at the right
9860 /// place.
9861 ///
9862 /// **The invariant is the whole point.** Every arm here is restricted to work that
9863 /// cannot run a getter, a `valueOf`, a `Symbol.toPrimitive`, or anything else in
9864 /// script: no property access, no `ToPrimitive`, no `ToString`, no call, no allocation
9865 /// that the memory limit has to see. An opcode whose operands turn out to need any of
9866 /// that **stops the loop** instead of trying, so the slow path gets the instruction
9867 /// untouched and with its operands still on the stack. That is why the fallback is a
9868 /// `break` and not a duplicated slow arm: a second implementation of the same
9869 /// semantics is how a wrong answer gets in with no test noticing.
9870 ///
9871 /// Each arm below is the *same* helper the slow arm calls (`get_loc`, `put_loc`,
9872 /// `push`, `pop`, `binary_add`), so only the dispatch bookkeeping is new.
9873 fn run_fast(&mut self) -> JsResult<Option<Value>> {
9874 use crate::insn::Fused;
9875 // The outer loop exists only so a `Call` can come back through here: once a
9876 // bytecode callee's frame is on top, `insns` — which borrows the *caller's*
9877 // `CompiledCode` — describes the wrong function, and `pc` belongs to that wrong
9878 // frame. Re-entering re-reads both from whichever frame is now on top. Every
9879 // other exit from the inner loop returns, so this costs one loop per call.
9880 'outer: loop {
9881 // One reference-count bump per *slow* instruction (a call, an allocation, a
9882 // property access), never one per instruction — that distinction is worth
9883 // two orders of magnitude and was measured as such.
9884 let (code, mut pc) = {
9885 let frame = self.frame();
9886 (frame.code.clone(), frame.pc)
9887 };
9888 let insns = &code.insns;
9889 loop {
9890 let Some(insn) = insns.get(pc).copied() else {
9891 self.frame_mut().pc = pc;
9892 return Ok(Some(Value::Undefined));
9893 };
9894 match insn.fused {
9895 // `x = k`
9896 Fused::StoreImm => self.put_loc(insn.a as usize, Value::Int(insn.b as i32)),
9897 // `x += k` on an integer. Anything else — a string, a float, a BigInt, an
9898 // object — stops the loop so `binary_add` can decide.
9899 Fused::AddImmLoc => {
9900 let slot = insn.a as usize;
9901 let delta = insn.b as i32;
9902 let Value::Int(left) = self.get_loc(slot) else {
9903 return Ok(self.stop(pc));
9904 };
9905 let sum = match left.checked_add(delta) {
9906 Some(sum) => Value::Int(sum),
9907 None => Value::Float(left as f64 + delta as f64),
9908 };
9909 self.put_loc(slot, sum);
9910 }
9911 // `x += "literal"` / `x += y`: the operand is a string, so the append
9912 // either allocates one or grows one. Both are the slow path's business;
9913 // the fusion's job is only to make the *slot* the sole owner, which is what
9914 // `execute_fused` needs and what `get_loc` alone destroys.
9915 Fused::AddAtomLoc | Fused::AddLocLoc | Fused::AddArgLoc => {
9916 return Ok(self.stop(pc));
9917 }
9918 // `x++` on an integer, old value dropped.
9919 Fused::PostIncLoc => {
9920 // One borrow, one `loc_cell` lookup, and no `Value::clone`: the old
9921 // value is read in place and overwritten in place, so the reference
9922 // count it held is released by the same assignment that stores the
9923 // new one. `get_loc` plus `put_loc` did two borrows, two table
9924 // lookups and a clone, and this arm is the whole body of a counting
9925 // loop's increment — 32% of an empty `for (j = 0; j < n; j++)`.
9926 let slot = insn.a as usize;
9927 let frame = self.frames.last_mut().expect("a frame is live");
9928 let cell = frame.code.loc_cell.get(slot).copied().unwrap_or(-1);
9929 let target = if cell < 0 {
9930 frame.locals.get_mut(slot)
9931 } else {
9932 None
9933 };
9934 let Some(target) = target else {
9935 return Ok(self.stop(pc));
9936 };
9937 let Value::Int(left) = *target else {
9938 return Ok(self.stop(pc));
9939 };
9940 *target = match left.checked_add(1) {
9941 Some(sum) => Value::Int(sum),
9942 None => Value::Float(left as f64 + 1.0),
9943 };
9944 }
9945 // A loop header, `if (!(x < arg)) goto target`, with both sides already
9946 // integers — which is every `for (i = 0; i < n; i++)` whose counter and
9947 // bound stayed small integers.
9948 Fused::LtLocArgJump => {
9949 let loc = (insn.a >> 16) as usize;
9950 let arg = (insn.a & 0xFFFF) as usize;
9951 // One borrow for both slots: this arm *is* the whole loop of a
9952 // `for (i = 0; i < n; i++)` with an argument bound, so a second
9953 // `frames.last()` here is paid on every iteration. Measured 7.5% on
9954 // `dispatch:empty-loop`.
9955 let (left, right) = {
9956 let frame = self.frame();
9957 (frame.read_loc(loc), frame.read_arg(arg))
9958 };
9959 // Heavily measured: the bound is very often a `Float` even when the
9960 // counter is an `Int` — anything that came from `+scriptArgs[2]`,
9961 // `JSON.parse` or a division is one — so requiring both sides to be
9962 // `Int` sent every iteration of those loops down the slow path. The
9963 // comparison below is the same one `relational` makes for two numbers.
9964 if !is_number(&left) || !is_number(&right) {
9965 return Ok(self.stop(pc));
9966 }
9967 // `if_false` branches on the comparison being false, which is **not**
9968 // `a >= b`: a `NaN` bound makes `<` false, so the loop exits, while
9969 // `>=` is also false and would keep it running forever. Clippy wants the
9970 // negation folded; that would be a wrong answer.
9971 let ordered = left.to_number() < right.to_number();
9972 let take_branch = !ordered;
9973 if take_branch {
9974 pc = insn.b as usize;
9975 continue;
9976 }
9977 }
9978 // The same header with a literal bound: `if (!(x < k)) goto target`.
9979 // The bound is an immediate, so only the counter needs a type test.
9980 #[allow(clippy::neg_cmp_op_on_partial_ord)]
9981 Fused::LtLocImmJump => {
9982 let left = self.get_loc(insn.a as usize);
9983 if !is_number(&left) {
9984 return Ok(self.stop(pc));
9985 }
9986 let take_branch = !(left.to_number() < insn.imm as i32 as f64);
9987 if take_branch {
9988 pc = insn.b as usize;
9989 continue;
9990 }
9991 }
9992 Fused::None => match insn.op {
9993 // -- branches ---------------------------------------------------
9994 // A jump is an assignment now, because the target is an instruction
9995 // index. No arithmetic, no resolution table.
9996 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9997 let target = insn.a as usize;
9998 // A **back-edge** is a loop, and it is the only place an
9999 // instruction-level checkpoint can stop one: `for(;;){}` compiles
10000 // to a jump to itself and never leaves this loop, so the
10001 // per-instruction checks in `step` never run. That is exactly the
10002 // hole this arm closes — a host's `JS_SetInterruptHandler` did
10003 // nothing to a `for(;;){}` until it did, which is what
10004 // `tests/c/embed.c` is for.
10005 //
10006 // Polling here rather than on every instruction in this loop is
10007 // also the reference's choice (`OP_goto` calls
10008 // `js_poll_interrupts`), and it costs one compare per branch
10009 // instead of one decrement per instruction.
10010 if target <= pc {
10011 self.frame_mut().pc = target;
10012 self.check_memory()?;
10013 self.check_interrupt()?;
10014 }
10015 pc = target;
10016 continue;
10017 }
10018 // `if_true`/`if_false` pop and test. `to_boolean` cannot run script.
10019 Opcode::IfTrue | Opcode::IfTrue8 | Opcode::IfFalse | Opcode::IfFalse8 => {
10020 let taken = self.pop().to_boolean();
10021 let want = matches!(insn.op, Opcode::IfTrue | Opcode::IfTrue8);
10022 if taken == want {
10023 pc = insn.a as usize;
10024 continue;
10025 }
10026 }
10027 // -- slot access -------------------------------------------------
10028 // A load's slot is already an operand (see `insn::implicit_operand`);
10029 // a captured one goes through its cell, which runs no script.
10030 Opcode::GetLoc
10031 | Opcode::GetLoc8
10032 | Opcode::GetLoc0
10033 | Opcode::GetLoc1
10034 | Opcode::GetLoc2
10035 | Opcode::GetLoc3 => {
10036 let value = self.get_loc(insn.a as usize);
10037 self.push(value);
10038 }
10039 Opcode::PutLoc
10040 | Opcode::PutLoc8
10041 | Opcode::PutLoc0
10042 | Opcode::PutLoc1
10043 | Opcode::PutLoc2
10044 | Opcode::PutLoc3 => {
10045 let value = self.pop();
10046 self.put_loc(insn.a as usize, value);
10047 }
10048 Opcode::GetArg
10049 | Opcode::GetArg0
10050 | Opcode::GetArg1
10051 | Opcode::GetArg2
10052 | Opcode::GetArg3 => {
10053 let value = self.get_arg(insn.a as usize);
10054 self.push(value);
10055 }
10056 Opcode::PutArg
10057 | Opcode::PutArg0
10058 | Opcode::PutArg1
10059 | Opcode::PutArg2
10060 | Opcode::PutArg3 => {
10061 let value = self.pop();
10062 self.put_arg(insn.a as usize, value);
10063 }
10064 // `a[i]` with an integer index on a dense array: see `fast_array_get`
10065 // for why a non-hole own element is exactly the slow path's answer.
10066 // The two operands are *peeked*, so a miss leaves the stack as the
10067 // slow path expects to find it.
10068 Opcode::GetArrayEl => {
10069 // One lookup, not two. The guard used `if …is_some()` and the arm
10070 // then called it again to get the value — two `peek`s, two
10071 // `array_get`s and two `Value` clones for one element.
10072 // `fast_array_get` was 13.1% of `array:indexed`, and the same
10073 // double call was the first version of the `get_field` fast path.
10074 let Some(value) = self.fast_array_get() else {
10075 return Ok(self.stop(pc));
10076 };
10077 // `a[i]` consumes both operands and leaves the element in their
10078 // place: one `truncate` and one write, no `pop`/`push` pair.
10079 let frame = self.frame_mut();
10080 frame.stack.truncate(frame.stack.len() - 2);
10081 frame.stack.push(value);
10082 }
10083 // `a[i] = v` on a dense array with an integer index: see
10084 // `fast_array_set` for why the whole store is one step.
10085 Opcode::PutArrayEl if self.fast_array_set() => {}
10086 // `o.x` resolved from the inline cache without leaving the loop.
10087 //
10088 // The cache is keyed by `(receiver identity, atom, site)` and a
10089 // monomorphic read re-validates the same chain every iteration, so
10090 // each one used to cost a `stop(pc)` — a write of `pc` into the
10091 // frame, a return out of this loop, a re-dispatch through `step` and
10092 // a re-entry. `property:monomorphic` spent 18% in
10093 // `read_field_cached` and 21% in `push`, both across that boundary.
10094 //
10095 // The site is `pc + width`, which is exactly the `next` the slow arm
10096 // passes — the two must agree or every fast lookup misses and
10097 // re-records the same entry forever.
10098 //
10099 // A miss leaves the stack untouched (`fast_field_get` peeks) so the
10100 // slow arm finds the receiver where it expects it.
10101 // `name` resolved from the global-variable cache inside the loop.
10102 //
10103 // Same shape as `get_field` above and for the same reason: `get_var`
10104 // was not in the fast loop, so reading a global — which `fib` does
10105 // once per recursive call, for its own name — cost a `stop(pc)`, a
10106 // return out of the loop, a `step` re-dispatch and a re-entry, before
10107 // `get_global` even started its `scopes_are_plain` checks.
10108 //
10109 // Everything here is exactly `get_global`'s first branch: not lexical,
10110 // no `eval` scope, cache hit. Anything else leaves the stack untouched
10111 // and lets the slow arm decide.
10112 Opcode::GetVar => {
10113 let Some(value) = self.fast_get_plain_global(insn.a as usize) else {
10114 return Ok(self.stop(pc));
10115 };
10116 self.push(value);
10117 }
10118 Opcode::GetField | Opcode::GetField2 => {
10119 let Some(value) =
10120 self.fast_field_get(insn.a as usize, pc + insn.width())
10121 else {
10122 return Ok(self.stop(pc));
10123 };
10124 if insn.op == Opcode::GetField2 {
10125 // `get_field2` keeps the receiver for the `call_method` that
10126 // follows.
10127 self.push(value);
10128 } else {
10129 // `get_field` replaces the receiver, so this is one store over
10130 // the top slot rather than a `pop` and a `push`: the length
10131 // never changes, so neither `Vec` arm has a capacity check or a
10132 // drop to run beyond the one the overwrite itself does.
10133 let frame = self.frame_mut();
10134 match frame.stack.last_mut() {
10135 Some(slot) => *slot = value,
10136 None => return Ok(self.stop(pc)),
10137 }
10138 }
10139 }
10140 // -- constants ---------------------------------------------------
10141 Opcode::PushMinus1
10142 | Opcode::Push0
10143 | Opcode::Push1
10144 | Opcode::Push2
10145 | Opcode::Push3
10146 | Opcode::Push4
10147 | Opcode::Push5
10148 | Opcode::Push6
10149 | Opcode::Push7
10150 | Opcode::PushI8
10151 | Opcode::PushI16
10152 | Opcode::PushI32 => self.push(Value::Int(insn.a as i32)),
10153 // -- stack shuffling ---------------------------------------------
10154 Opcode::Drop => {
10155 self.pop();
10156 }
10157 // -- arithmetic on two integers ----------------------------------
10158 //
10159 // The operands are *looked at* before they are popped, so a non-integer
10160 // pair leaves the stack exactly as the slow path expects to find it.
10161 Opcode::Add if self.numeric_pair() => {
10162 let right = self.pop();
10163 let left = self.pop();
10164 // Exactly [`add_numbers`], which is what the slow arm reaches.
10165 let answer = match (&left, &right) {
10166 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
10167 Some(sum) => Value::Int(sum),
10168 None => Value::Float(*a as f64 + *b as f64),
10169 },
10170 _ => Value::Float(left.to_number() + right.to_number()),
10171 };
10172 self.push(answer);
10173 }
10174 Opcode::Sub
10175 | Opcode::And
10176 | Opcode::Or
10177 | Opcode::Xor
10178 | Opcode::Shl
10179 | Opcode::Sar
10180 | Opcode::Shr
10181 if self.numeric_pair() =>
10182 {
10183 let right = self.pop();
10184 let left = self.pop();
10185 let answer =
10186 arithmetic(insn.op, left, right).expect("numbers cannot throw");
10187 self.push(answer);
10188 }
10189 Opcode::Lt | Opcode::Lte | Opcode::Gt | Opcode::Gte
10190 if self.numeric_pair() =>
10191 {
10192 let right = self.pop();
10193 let left = self.pop();
10194 let answer = self
10195 .relational(insn.op, left, right)
10196 .expect("numbers cannot throw");
10197 self.push(answer);
10198 }
10199 // -- calls -------------------------------------------------------
10200 //
10201 // A plain call: `callee(arg0, …, argN) -> result`.
10202 //
10203 // This arm exists because of one measurement. `call:recursion` had
10204 // **20.4% of its profile in `execute_instruction`** — the *slow*
10205 // executor — and `fib`'s recursive call is the only thing in that
10206 // function which is not a fast arm. Every call therefore left this
10207 // loop via `stop()`, went through `step()`'s dispatch and
10208 // `execute_instruction`'s match over every opcode, and came back here
10209 // by re-reading the frame and re-cloning the `Gc<CompiledCode>`.
10210 //
10211 // Two things make it safe to do here rather than only in the slow path:
10212 //
10213 // * the caller's `pc` is stored *before* the call, which is what
10214 // `step` does too — so when the callee returns, the caller resumes
10215 // after the call and not at it;
10216 // * `check_memory` runs, because `step` calls it once per instruction
10217 // and a call allocates a frame, its locals and its cells. Skipping
10218 // the checkpoint here would let a `--memory-limit` script overshoot
10219 // by one call per instruction.
10220 Opcode::Call
10221 | Opcode::Call0
10222 | Opcode::Call1
10223 | Opcode::Call2
10224 | Opcode::Call3 => {
10225 let argc = self.argc_operand(insn.op, insn.a);
10226 let next = pc + insn.width();
10227 {
10228 let frame = self
10229 .frames
10230 .last_mut()
10231 .expect("run_fast() is only called with a live frame");
10232 // `at` is what a stack trace reports for this frame, so a throw
10233 // inside the callee has to see the call site and not whatever
10234 // the last `stop()` left there.
10235 frame.at = insn.offset as usize;
10236 frame.pc = next;
10237 }
10238 self.check_memory()?;
10239 self.check_interrupt()?;
10240 let args = self.pop_n(argc);
10241 let callee = self.pop();
10242 // A plain call has no receiver; the callee decides what to do with
10243 // `undefined` (a sloppy function substitutes the global object).
10244 if let Some(result) =
10245 self.call_or_push(callee, Value::Undefined, args)?
10246 {
10247 // Native, host, generator, async, bound — no frame was pushed,
10248 // so this loop is still describing the right function. `pc`
10249 // is advanced by the loop tail like every other arm; only the
10250 // frame's copy had to be written here, and it already was.
10251 self.push(result);
10252 } else {
10253 // A bytecode callee: its frame is on top now, and `insns` and
10254 // `pc` both belong to the caller. Start over on the new frame.
10255 continue 'outer;
10256 }
10257 }
10258 // -- return ------------------------------------------------------
10259 Opcode::Return => {
10260 let value = self.pop();
10261 self.frame_mut().pc = pc + insn.width();
10262 return Ok(Some(value));
10263 }
10264 Opcode::ReturnUndef => {
10265 self.frame_mut().pc = pc + insn.width();
10266 return Ok(Some(Value::Undefined));
10267 }
10268 // Everything else needs the slow path.
10269 _ => return Ok(self.stop(pc)),
10270 },
10271 }
10272 pc += insn.width();
10273 }
10274 }
10275 }
10276
10277 /// Whether the top two operand-stack values are both numbers.
10278 ///
10279 /// The guard the fast loop uses before it takes an arithmetic record: two numbers
10280 /// cannot run script, so the arm may not throw and may not change frames.
10281 fn numeric_pair(&self) -> bool {
10282 is_number(&self.peek(0)) && is_number(&self.peek(1))
10283 }
10284
10285 /// `a[i]` for a dense array and an integer index, without the string round trip.
10286 ///
10287 /// The slow path answers this by turning `i` into a string (`propkey` →
10288 /// `number_to_string`) and then parsing it straight back (`read_field_key` →
10289 /// `array_index`). Measured on `array:indexed`: the element access costs 224ns per
10290 /// iteration beyond the loop it sits in, and that往返 is the bulk of it — a `String`
10291 /// key is *slower* still (6.00s vs 5.42s for 5M reads) because it pays the parse
10292 /// without even the cheap `Int` formatting.
10293 ///
10294 /// Returns `None` — leaving the stack untouched for the slow path — unless the answer is
10295 /// unambiguously the one the slow path would give:
10296 ///
10297 /// * the key is a non-negative integer below `2^32-1` (that bound is `array_index`'s:
10298 /// `2^32-1` is the length, not an index),
10299 /// * the receiver is an array's dense prefix (`array_get` answers `None` for a proxy, a
10300 /// typed array or an ordinary object, all of which have their own rules),
10301 /// * the slot holds a real value, not a [`Value::Hole`] — a hole is where the slow path
10302 /// starts walking the prototype chain, and `a[i]` on a hole must find
10303 /// `Array.prototype[i]` if it exists rather than `undefined`.
10304 ///
10305 /// The last condition is the one that makes this safe rather than merely fast: an own
10306 /// element always wins over the prototype, so a non-hole hit needs no further lookup.
10307 /// `get_var` answered from the global-variable cache, or `None`.
10308 ///
10309 /// The guard is `get_global`'s first branch, inlined and read-only: an ordinary global
10310 /// `var` (not lexical), no `eval`/`with` in scope, and a live cache entry. A miss
10311 /// records nothing — the slow arm is about to walk the chain and record it.
10312 fn fast_get_plain_global(&self, slot: usize) -> Option<Value> {
10313 let frame = self.frame();
10314 let name = frame.code.code.closure_vars.get(slot)?.name.as_str();
10315 // "Lexical" is presence in the realm's table, not the closure var's flag: a
10316 // `GlobalRef` forwarded through a nested function has its flags cleared.
10317 if self.realm.globals.contains_key(name) {
10318 return None;
10319 }
10320 if !self.scopes_are_plain() {
10321 return None;
10322 }
10323 let object = &self.realm.global;
10324 let site = slot & (GLOBAL_CACHE_SLOTS - 1);
10325 let cached = self.global_cache[site].as_ref()?;
10326 if !object.upgrades_to(&cached.object) {
10327 return None;
10328 }
10329 object.data_property_at(cached.index, name)
10330 }
10331
10332 /// `o.x` answered entirely from the inline cache, or `None`.
10333 ///
10334 /// Read-only on purpose: a miss must not record an entry, because the slow arm is
10335 /// about to do exactly that and recording it twice would rebuild the chain for every
10336 /// first access. The hit test is the same one [`Self::read_field_cached`] makes — same
10337 /// slot, same key, same [`Self::cached_hit`] guard — so a hit here is that answer.
10338 fn fast_field_get(&self, atom: usize, site: usize) -> Option<Value> {
10339 // Borrowed straight out of the operand stack: `peek` clones a `Value`, which for
10340 // an object receiver is a reference-count bump that the answer never needs.
10341 let frame = self.frame();
10342 let object = frame.stack.last()?;
10343 let Value::Object(target) = object else {
10344 return None;
10345 };
10346 // A proxy traps the lookup, so no cache entry ever describes it.
10347 if target.proxy_state().is_some() {
10348 return None;
10349 }
10350 let key = frame.code.atom_keys.get(atom)?;
10351 let cached = self.field_cache[Self::field_cache_slot(object, key, site)].as_ref()?;
10352 if cached.key != *key {
10353 return None;
10354 }
10355 Self::cached_hit(target, cached)
10356 }
10357
10358 fn fast_array_get(&self) -> Option<Value> {
10359 let Value::Int(index) = self.peek(0) else {
10360 return None;
10361 };
10362 // `array_index` rejects `2^32-1` and every negative number; `0..u32::MAX` is that
10363 // set for an `i32`.
10364 if index < 0 {
10365 return None;
10366 }
10367 let Value::Object(object) = self.peek(1) else {
10368 return None;
10369 };
10370 match object.array_get(index as usize) {
10371 Some(value) if !matches!(value, Value::Hole) => Some(value),
10372 _ => None,
10373 }
10374 }
10375
10376 /// `a[i] = v` on a dense array with an integer index, as one store.
10377 ///
10378 /// The slow path for `put_array_el` is `propkey` → `write_field_key`, and `propkey`
10379 /// turns an integer key into a *string* (`number_to_string`, which is `grisu`'s
10380 /// shortest-round-trip search) only for `array_index` to parse it back to a `usize`.
10381 /// That round trip was 20% of `for (a[i] = i)` — the single biggest gap against the
10382 /// reference at the time it was measured (14.7x).
10383 ///
10384 /// Every condition here is one the slow path would also have to satisfy before
10385 /// storing into the element vector:
10386 ///
10387 /// * the key is an `Int` in `0..=u32::MAX-1`, which is exactly what `array_index`
10388 /// accepts as an index;
10389 /// * the target is an array whose elements are writable (`Object.freeze` clears it);
10390 /// * `array_store` itself decides the rest — an index beyond `ARRAY_ELEMENT_LIMIT`, or
10391 /// one inside a recorded descriptor, reports `false` and the caller stops.
10392 ///
10393 /// A prototype setter cannot intercept: an *own* element shadows it, and the slow path
10394 /// writes the own element too once `array_set` says it did.
10395 fn fast_array_set(&mut self) -> bool {
10396 // Every test runs *before* anything is popped: a refusal has to leave the stack
10397 // exactly as the slow path expects to find it. Popping first and reporting the
10398 // failure afterwards silently emptied the stack — `new Uint8Array(2); a[5] = 1`
10399 // then ran the slow path with nothing to write.
10400 let Value::Int(index) = self.peek(1) else {
10401 return false;
10402 };
10403 // `array_index` accepts `0..u32::MAX`, which for an `i32` is `0..=i32::MAX`.
10404 if index < 0 {
10405 return false;
10406 }
10407 // Only a real array: a typed array's elements live in its buffer, a string-like
10408 // object has no element vector, and `array_set` on either does nothing.
10409 let Value::Object(object) = self.peek(2) else {
10410 return false;
10411 };
10412 if !object.is_array() || !object.elements_writable() || object.has_element_descriptors() {
10413 return false;
10414 }
10415 // A non-extensible array reports `false` here, but the *slow* path has to decide
10416 // whether that is a silent no-op or a `TypeError` (strict mode), and it can only do
10417 // that with the key and the stack still intact.
10418 if !object.is_extensible() {
10419 return false;
10420 }
10421 // Inside the logical length, so the store cannot change `length`. Combined with
10422 // extensibility above, the only growth left for `array_set` is filling a hole in
10423 // the dense prefix — `new Array(n)` followed by `a[0], a[1], …`, which is the
10424 // shape this fast path exists for. A store past the length would grow the array,
10425 // and whether that is allowed is the slow path's question.
10426 if index as usize >= object.array_length().unwrap_or(0) {
10427 return false;
10428 }
10429 // Only an *own element* can take the inline store. A hole is not an own property,
10430 // so §10.1.9.2 step 1.d sends the store to the prototype chain — where a `set`
10431 // trap or a setter decides, and where `new Array(1)` with a proxy above it must
10432 // fire the trap (`Proxy/set/call-parameters-prototype-index`). Filling holes is
10433 // the one case this path used to swallow.
10434 //
10435 // The cost is small: `array:indexed` only reads after a 64-element fill, and
10436 // `array:push` appends past the length, which this path already refused.
10437 if !matches!(object.array_get(index as usize), Some(value) if !matches!(value, Value::Hole))
10438 {
10439 return false;
10440 }
10441 // The bound `array_set` refuses past. Checking it here keeps that arm from having
10442 // to report a failure after the operands are gone.
10443 if index as usize + 1 > crate::object::ARRAY_ELEMENT_LIMIT {
10444 return false;
10445 }
10446 let value = self.pop();
10447 self.pop();
10448 self.pop();
10449 object.array_store(self.heap, index as usize, value)
10450 }
10451
10452 /// Leave the fast loop in front of the record at `pc`, having executed nothing of it.
10453 fn stop(&mut self, pc: usize) -> Option<Value> {
10454 self.frame_mut().pc = pc;
10455 None
10456 }
10457
10458 fn push(&mut self, value: Value) {
10459 self.frame_mut().stack.push(value);
10460 }
10461
10462 fn pop(&mut self) -> Value {
10463 self.frame_mut().stack.pop().unwrap_or(Value::Undefined)
10464 }
10465
10466 fn pop_n(&mut self, count: usize) -> Vec<Value> {
10467 let frame = self.frame_mut();
10468 let start = frame.stack.len().saturating_sub(count);
10469 frame.stack.split_off(start)
10470 }
10471
10472 fn peek(&self, back: usize) -> Value {
10473 let frame = self.frame();
10474 frame
10475 .stack
10476 .get(frame.stack.len().wrapping_sub(1 + back))
10477 .cloned()
10478 .unwrap_or(Value::Undefined)
10479 }
10480
10481 #[allow(clippy::too_many_lines)]
10482 fn execute_instruction(&mut self, op: Opcode, a: u32, b: u32, next: usize) -> JsResult<Step> {
10483 use Opcode::*;
10484 match op {
10485 // -- constants and stack shuffling -----------------------------
10486 Nop => {}
10487 PushMinus1 => self.push(Value::Int(-1)),
10488 Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7 => {
10489 let value = match op {
10490 Push0 => 0,
10491 Push1 => 1,
10492 Push2 => 2,
10493 Push3 => 3,
10494 Push4 => 4,
10495 Push5 => 5,
10496 Push6 => 6,
10497 _ => 7,
10498 };
10499 self.push(Value::Int(value));
10500 }
10501 PushI8 | PushI16 | PushI32 => self.push(Value::Int(a as i32)),
10502 PushBigintI32 => {
10503 // The immediate form of a `BigInt` literal; the reference has the same
10504 // split between this and a constant-pool entry.
10505 let value = crate::bigint::BigInt::from_i64(a as i64);
10506 self.push(self.bigint(value));
10507 }
10508 PushTrue => self.push(Value::Bool(true)),
10509 PushFalse => self.push(Value::Bool(false)),
10510 PushEmptyString => self.push(self.string("")),
10511 Undefined => self.push(Value::Undefined),
10512 Null => self.push(Value::Null),
10513 Object => {
10514 let proto = self.realm.object_proto.clone();
10515 self.push(Value::Object(self.new_object(Some(proto))));
10516 }
10517 PushThis => {
10518 let this = self.frame().this.clone();
10519 self.push(this);
10520 }
10521 PushConst | PushConst8 => {
10522 let value = self.constant(a as usize)?;
10523 self.push(value);
10524 }
10525 PushAtomValue => {
10526 let text = self.atom_wtf8(a as usize);
10527 self.push(self.string_wtf8(text));
10528 }
10529 Dup => {
10530 let value = self.peek(0);
10531 self.push(value);
10532 }
10533 Dup2 => {
10534 // `a b -> a b a b`
10535 let b = self.peek(0);
10536 let a = self.peek(1);
10537 self.push(a);
10538 self.push(b);
10539 }
10540 Dup3 => {
10541 // `a b c -> a b c a b c`, which is how a super store keeps the receiver,
10542 // prototype and key while reading the current value through them.
10543 let c = self.peek(0);
10544 let b = self.peek(1);
10545 let a = self.peek(2);
10546 self.push(a);
10547 self.push(b);
10548 self.push(c);
10549 }
10550 Swap => {
10551 // `a b -> b a`
10552 let bottom = self.pop();
10553 let top = self.pop();
10554 self.push(bottom);
10555 self.push(top);
10556 }
10557 Perm3 => {
10558 // `a b c -> b a c`, the reference's reordering for a spread method
10559 // call: `obj func array` becomes the `func this array` that `apply`
10560 // takes.
10561 let c = self.pop();
10562 let b = self.pop();
10563 let a = self.pop();
10564 self.push(b);
10565 self.push(a);
10566 self.push(c);
10567 }
10568 Dup1 => {
10569 let value = self.peek(1);
10570 self.push(value);
10571 }
10572 Drop => {
10573 self.pop();
10574 }
10575 Nip => {
10576 // `a b -> b`
10577 let top = self.pop();
10578 self.pop();
10579 self.push(top);
10580 }
10581 Perm4 => {
10582 // `obj prop a b -> a obj prop b`, the reference's reordering for a
10583 // postfix update of a computed element: it puts the *old* value
10584 // underneath the receiver and key so `put_array_el` can consume them
10585 // and leave the old value as the expression's result.
10586 let d = self.pop();
10587 let c = self.pop();
10588 let b = self.pop();
10589 let a = self.pop();
10590 self.push(c);
10591 self.push(a);
10592 self.push(b);
10593 self.push(d);
10594 }
10595 Insert2 => {
10596 // `obj a -> a obj a`
10597 let value = self.pop();
10598 let object = self.pop();
10599 self.push(value.clone());
10600 self.push(object);
10601 self.push(value);
10602 }
10603 Insert3 => {
10604 // `obj prop a -> a obj prop a`
10605 let value = self.pop();
10606 let key = self.pop();
10607 let object = self.pop();
10608 self.push(value.clone());
10609 self.push(object);
10610 self.push(key);
10611 self.push(value);
10612 }
10613 Insert4 => {
10614 // `this obj prop a -> a this obj prop a`
10615 //
10616 // `put_super_value` consumes all four and yields nothing, so the copy
10617 // underneath is what leaves the assignment an expression value.
10618 let value = self.pop();
10619 let key = self.pop();
10620 let object = self.pop();
10621 let receiver = self.pop();
10622 self.push(value.clone());
10623 self.push(receiver);
10624 self.push(object);
10625 self.push(key);
10626 self.push(value);
10627 }
10628 Swap2 => {
10629 // `a b c d -> c d a b`
10630 let d = self.pop();
10631 let c = self.pop();
10632 let b = self.pop();
10633 let a = self.pop();
10634 self.push(c);
10635 self.push(d);
10636 self.push(a);
10637 self.push(b);
10638 }
10639 Rot3l => {
10640 // `x a b -> a b x`
10641 let b = self.pop();
10642 let a = self.pop();
10643 let x = self.pop();
10644 self.push(a);
10645 self.push(b);
10646 self.push(x);
10647 }
10648 Rot3r => {
10649 // `a b c -> c a b`
10650 let c = self.pop();
10651 let b = self.pop();
10652 let a_value = self.pop();
10653 self.push(c);
10654 self.push(a_value);
10655 self.push(b);
10656 }
10657
10658 Rest => {
10659 // `...rest` in a parameter list: the arguments from index `a` on, as a
10660 // real array. It takes nothing off the stack — the arguments are in the
10661 // frame, not on it.
10662 let frame = self.frame();
10663 let from = a as usize;
10664 let collected: Vec<Value> = frame.passed().iter().skip(from).cloned().collect();
10665 let array = self.new_array(collected);
10666 self.push(Value::Object(array));
10667 }
10668
10669 // -- slots ------------------------------------------------------
10670 GetLoc | GetLoc8 | GetLoc0 | GetLoc1 | GetLoc2 | GetLoc3 => {
10671 let slot = self.slot_operand(op, a);
10672 let value = self.get_loc(slot);
10673 self.push(value);
10674 }
10675 PutLoc | PutLoc8 | PutLoc0 | PutLoc1 | PutLoc2 | PutLoc3 => {
10676 let slot = self.slot_operand(op, a);
10677 let value = self.pop();
10678 self.put_loc(slot, value);
10679 }
10680 SetLoc | SetLoc8 | SetLoc0 | SetLoc1 | SetLoc2 | SetLoc3 => {
10681 let slot = self.slot_operand(op, a);
10682 let value = self.pop();
10683 self.put_loc(slot, value.clone());
10684 self.push(value);
10685 }
10686 // The `_check` forms are the temporal dead zone: they throw when the
10687 // slot still holds [`Value::Uninitialized`]. Only `get_loc_check`
10688 // *reads*, so only the two writes may pop — mishandling that quietly
10689 // consumes the value the caller pushed just before.
10690 GetLocCheck => {
10691 let slot = self.slot_operand(op, a);
10692 let value = self.get_loc(slot);
10693 if matches!(value, Value::Uninitialized) {
10694 return Err(self.dead_zone(slot, VarSlot::Loc));
10695 }
10696 self.push(value);
10697 }
10698 PutLocCheck | SetLocCheck => {
10699 let slot = self.slot_operand(op, a);
10700 let value = self.pop();
10701 if matches!(value, Value::Uninitialized) {
10702 return Err(self.dead_zone(slot, VarSlot::Loc));
10703 }
10704 // The initialiser goes through `put_loc`, not this, so any store that
10705 // reaches here is a later assignment — which a `const` refuses.
10706 if self.is_read_only(slot, VarSlot::Loc) {
10707 return Err(self.read_only(slot, VarSlot::Loc));
10708 }
10709 if op == SetLocCheck {
10710 self.put_loc(slot, value.clone());
10711 self.push(value);
10712 } else {
10713 self.put_loc(slot, value);
10714 }
10715 }
10716 PutLocCheckInit => {
10717 // The one store that *initialises* a lexical slot: `this` in a derived
10718 // constructor, which only exists after `super()` has run. A second
10719 // initialisation is the error the reference reports as
10720 // "'this' can be initialized only once".
10721 let slot = self.slot_operand(op, a);
10722 let value = self.pop();
10723 if !matches!(self.get_loc(slot), Value::Uninitialized) {
10724 return Err(Signal::Throw(self.make_error(
10725 "ReferenceError",
10726 "'this' can be initialized only once",
10727 )));
10728 }
10729 self.put_loc(slot, value);
10730 }
10731 CheckCtor => {
10732 // A class constructor may only run under `new`, which is what makes
10733 // `class A {}; A()` a TypeError.
10734 if matches!(self.frame().new_target, Value::Undefined) {
10735 return Err(Signal::Throw(self.make_error(
10736 "TypeError",
10737 "class constructors must be invoked with 'new'",
10738 )));
10739 }
10740 }
10741 InitCtor => {
10742 // The body a derived class gets when it declares no constructor:
10743 // forward every argument to the parent constructor, keeping `new.target`.
10744 if matches!(self.frame().new_target, Value::Undefined) {
10745 return Err(Signal::Throw(self.make_error(
10746 "TypeError",
10747 "class constructors must be invoked with 'new'",
10748 )));
10749 }
10750 let Some(callee) = self.current_callee() else {
10751 return Err(Signal::Throw(
10752 self.make_error("TypeError", "no constructor to inherit from"),
10753 ));
10754 };
10755 let parent = callee.proto().map_or(Value::Null, Value::Object);
10756 let new_target = self.frame().new_target.clone();
10757 let args = self.frame().passed().to_vec();
10758 let result = self.construct(parent, new_target, args)?;
10759 self.push(result);
10760 }
10761 SetLocUninitialized => {
10762 let slot = self.slot_operand(op, a);
10763 self.put_loc(slot, Value::Uninitialized);
10764 }
10765 CloseLoc => {
10766 // "Close" a binding: give it a *fresh* cell holding the current
10767 // value. Closures created before this point keep the old cell and the
10768 // ones created after see the new one, which is what makes every
10769 // iteration of `for (let i ...)` capture its own `i`, and what freezes
10770 // a block-scoped binding when the block ends.
10771 //
10772 // Clearing the slot instead (which this used to do) broke both: a
10773 // closure over a captured block variable read `undefined`, and a loop
10774 // terminated after one iteration.
10775 let slot = self.slot_operand(op, a);
10776 let index = self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1);
10777 if index >= 0 {
10778 let current = self.frame().cells[index as usize].get();
10779 let fresh = self.new_cell(current);
10780 if let Some(cell) = self.frame_mut().cells.get_mut(index as usize) {
10781 *cell = fresh;
10782 }
10783 }
10784 }
10785 GetArg | GetArg0 | GetArg1 | GetArg2 | GetArg3 => {
10786 let slot = self.slot_operand(op, a);
10787 let value = self.get_arg(slot);
10788 self.push(value);
10789 }
10790 PutArg | PutArg0 | PutArg1 | PutArg2 | PutArg3 => {
10791 let slot = self.slot_operand(op, a);
10792 let value = self.pop();
10793 self.put_arg(slot, value);
10794 }
10795 SetArg | SetArg0 | SetArg1 | SetArg2 | SetArg3 => {
10796 let slot = self.slot_operand(op, a);
10797 let value = self.pop();
10798 self.put_arg(slot, value.clone());
10799 self.push(value);
10800 }
10801
10802 // -- closure variables ------------------------------------------
10803 GetVarRef | GetVarRef0 | GetVarRef1 | GetVarRef2 | GetVarRef3 => {
10804 let slot = self.slot_operand(op, a);
10805 // A name a direct `eval` created shadows the binding the compiler chose.
10806 // `function t(){ var c = "outer"; function f(a = eval("var c = 1")) { } }`
10807 // leaves `t`'s `c` alone but makes every read inside `f` see the eval's,
10808 // and only a runtime lookup can know that.
10809 if let Some(cell) = self.eval_created_local(slot) {
10810 self.push(cell.get());
10811 return self.step();
10812 }
10813 let value = self.cell_value(slot)?;
10814 self.push(value);
10815 }
10816 GetVarRefCheck => {
10817 let slot = self.slot_operand(op, a);
10818 let value = self.cell_value(slot)?;
10819 if matches!(value, Value::Uninitialized) {
10820 return Err(self.dead_zone(slot, VarSlot::Closure));
10821 }
10822 self.push(value);
10823 }
10824 PutVarRef | PutVarRef0 | PutVarRef1 | PutVarRef2 | PutVarRef3 | PutVarRefCheck => {
10825 let slot = self.slot_operand(op, a);
10826 let value = self.pop();
10827 if let Some(cell) = self.eval_created_local(slot) {
10828 cell.set(value);
10829 return self.step();
10830 }
10831 // Same rule as `PutLocCheck`: a checked store to a captured binding
10832 // refuses a `const` once its initialiser has run.
10833 if op == PutVarRefCheck && self.is_read_only(slot, VarSlot::Closure) {
10834 return Err(self.read_only(slot, VarSlot::Closure));
10835 }
10836 self.set_cell(slot, value)?;
10837 }
10838 SetVarRef | SetVarRef0 | SetVarRef1 | SetVarRef2 | SetVarRef3 => {
10839 let slot = self.slot_operand(op, a);
10840 let value = self.pop();
10841 if let Some(cell) = self.eval_created_local(slot) {
10842 cell.set(value.clone());
10843 self.push(value);
10844 return self.step();
10845 }
10846 self.set_cell(slot, value.clone())?;
10847 self.push(value);
10848 }
10849
10850 // -- globals ----------------------------------------------------
10851 GetVar => {
10852 let value = self.get_global(a as usize)?;
10853 self.push(value);
10854 }
10855 GetVarUndef => {
10856 let value = self
10857 .get_global(a as usize)
10858 .or_else(|_| Ok(Value::Undefined))?;
10859 self.push(value);
10860 }
10861 DeleteVar => {
10862 // `delete name` for a name that is not a declared binding. A lexical
10863 // global lives in the reference table and cannot be deleted; anything
10864 // reachable only as a property of the global object is *implicit* —
10865 // `x = 1` with no declaration — and goes away if it is configurable,
10866 // which is what `delete` on an implicit global answers.
10867 let name = self.atom_text(a as usize);
10868 let global = self.realm.global.clone();
10869 let deleted = if self.realm.globals.contains_key(&name) {
10870 false
10871 } else if global.own_property(&name).is_some() {
10872 self.delete_property(&global, &name)?
10873 } else {
10874 true
10875 };
10876 self.push(Value::Bool(deleted));
10877 }
10878 PutVar => {
10879 let value = self.pop();
10880 self.put_global(a as usize, value)?;
10881 }
10882 PutVarInit => {
10883 let slot = a as usize;
10884 let value = self.pop();
10885 self.init_global(slot, value)?;
10886 }
10887
10888 // -- arithmetic -------------------------------------------------
10889 Add => self.binary_add()?,
10890 Sub | Mul | Div | Mod | Pow | And | Or | Xor | Shl | Sar | Shr => {
10891 let raw_right = self.pop();
10892 let raw_left = self.pop();
10893 // BigInt arithmetic is a separate path, and not only for the type of the
10894 // result: `ToNumber` of a bigint throws, so mixing the two must be an error
10895 // rather than a silent conversion.
10896 if matches!(raw_left, Value::BigInt(_)) || matches!(raw_right, Value::BigInt(_)) {
10897 let left = self.primitive_of(raw_left)?;
10898 let right = self.primitive_of(raw_right)?;
10899 let value = self.bigint_arithmetic(op, left, right)?;
10900 self.push(value);
10901 } else {
10902 let right = self.numeric(raw_right)?;
10903 let left = self.numeric(raw_left)?;
10904 self.push(arithmetic(op, left, right)?);
10905 }
10906 }
10907 Neg => {
10908 let raw = self.pop();
10909 match raw {
10910 // A bigint negates exactly, however wide it is.
10911 Value::BigInt(big) => {
10912 let negated = big.negate();
10913 self.push(self.bigint(negated));
10914 }
10915 other => {
10916 let value = self.numeric(other)?;
10917 self.push(negate(value));
10918 }
10919 }
10920 }
10921 Plus => {
10922 let value = self.pop();
10923 // `+x` is `ToNumber`, and `ToNumber` refuses a bigint: unlike `++`,
10924 // unary plus is defined to produce a *number*, which a bigint cannot
10925 // become without loss. It used to fall through to `NaN`.
10926 if matches!(value, Value::BigInt(_)) {
10927 return Err(self.type_error("cannot convert bigint to number"));
10928 }
10929 let numeric = self.numeric_of(value)?;
10930 self.push(numeric);
10931 }
10932 Inc => {
10933 let raw = self.pop();
10934 let (_, updated) = self.advance_numeric(raw, true)?;
10935 self.push(updated);
10936 }
10937 Dec => {
10938 let raw = self.pop();
10939 let (_, updated) = self.advance_numeric(raw, false)?;
10940 self.push(updated);
10941 }
10942 PostInc | PostDec => {
10943 // `x -> x x+1`: the *new* value ends up on top, so the store the
10944 // compiler emits right after (`put_var`) writes the incremented
10945 // one, while the old value stays underneath for the expression's
10946 // own result. Getting this backwards makes `i++` a no-op, which
10947 // turns `while (i < 3)` into an infinite loop.
10948 let raw = self.pop();
10949 let (old, updated) = self.advance_numeric(raw, op == PostInc)?;
10950 self.push(old);
10951 self.push(updated);
10952 }
10953 Not => {
10954 let raw = self.pop();
10955 match raw {
10956 // `~x` on a bigint is `-x - 1`, exact at any width.
10957 Value::BigInt(big) => {
10958 let inverted = big.bitnot();
10959 self.push(self.bigint(inverted));
10960 }
10961 other => {
10962 let value = self.numeric(other)?;
10963 self.push(Value::Int(!value.to_int32()));
10964 }
10965 }
10966 }
10967 Lnot => {
10968 let value = self.pop();
10969 self.push(Value::Bool(!value.to_boolean()));
10970 }
10971
10972 // -- comparison -------------------------------------------------
10973 Lt | Lte | Gt | Gte => {
10974 let right = self.pop();
10975 let left = self.pop();
10976 let answer = self.relational(op, left, right)?;
10977 self.push(answer);
10978 }
10979 Eq | Neq => {
10980 let right = self.pop();
10981 let left = self.pop();
10982 let equal = self.abstract_equals(left, right)?;
10983 self.push(Value::Bool(if op == Eq { equal } else { !equal }));
10984 }
10985 StrictEq => {
10986 let right = self.pop();
10987 let left = self.pop();
10988 self.push(Value::Bool(left.strict_equals(&right)));
10989 }
10990 StrictNeq => {
10991 let right = self.pop();
10992 let left = self.pop();
10993 self.push(Value::Bool(!left.strict_equals(&right)));
10994 }
10995 IsUndefined => {
10996 // `=== undefined`, which is what a destructuring default tests. It is
10997 // not `IsUndefinedOrNull`: `[a = 1] = [null]` keeps `null`.
10998 let value = self.pop();
10999 self.push(Value::Bool(matches!(value, Value::Undefined)));
11000 }
11001 IsUndefinedOrNull => {
11002 let value = self.pop();
11003 self.push(Value::Bool(value.is_nullish()));
11004 }
11005 Typeof => {
11006 let value = self.pop();
11007 self.push(self.string(value.type_of()));
11008 }
11009 ToObject => {
11010 // A destructuring *object* pattern starts here, which is why
11011 // `var {} = null` throws. Only `undefined` and `null` are refused; a
11012 // primitive is boxed.
11013 let value = self.pop();
11014 let object = self.object_from(&value)?;
11015 self.push(Value::Object(object));
11016 }
11017 Instanceof => {
11018 let constructor = self.pop();
11019 let object = self.pop();
11020 let answer = self.instance_of(&object, &constructor)?;
11021 self.push(Value::Bool(answer));
11022 }
11023 In => {
11024 let object = self.pop();
11025 let key = self.pop();
11026 let answer = self.has_property(&key, &object)?;
11027 self.push(Value::Bool(answer));
11028 }
11029
11030 // -- control flow -----------------------------------------------
11031 Goto | Goto8 | Goto16 => {
11032 self.frame_mut().pc = a as usize;
11033 }
11034 IfTrue | IfTrue8 => {
11035 let value = self.pop();
11036 if value.to_boolean() {
11037 self.frame_mut().pc = a as usize;
11038 }
11039 }
11040 IfFalse | IfFalse8 => {
11041 let value = self.pop();
11042 if !value.to_boolean() {
11043 self.frame_mut().pc = a as usize;
11044 }
11045 }
11046 Catch => {
11047 // Pushes the handler target onto the value stack; `unwind` finds it.
11048 self.push(Value::CatchOffset(a));
11049 }
11050 Gosub => {
11051 self.push(Value::ReturnAddress(next as u32));
11052 self.frame_mut().pc = a as usize;
11053 }
11054 Ret => {
11055 let value = self.pop();
11056 match value {
11057 Value::ReturnAddress(address) => self.frame_mut().pc = address as usize,
11058 _ => {
11059 return Err(Signal::Throw(
11060 self.make_error("InternalError", "invalid return address"),
11061 ));
11062 }
11063 }
11064 }
11065 NipCatch => {
11066 // `catch_offset ... ret_val -> ret_val`: drop everything down to and
11067 // including the marker, keeping the top value.
11068 let top = self.pop();
11069 loop {
11070 match self.pop() {
11071 Value::CatchOffset(_) | Value::Undefined => break,
11072 _ => {}
11073 }
11074 if self.frame().stack.is_empty() {
11075 break;
11076 }
11077 }
11078 self.push(top);
11079 }
11080 Throw => {
11081 let value = self.pop();
11082 return Err(Signal::Throw(value));
11083 }
11084 ThrowError => {
11085 let name = self.atom_text(a as usize);
11086 let (class, message) = match b {
11087 0 => ("TypeError", format!("'{name}' is read-only")),
11088 1 => ("SyntaxError", format!("redeclaration of '{name}'")),
11089 2 => ("ReferenceError", format!("'{name}' is not initialized")),
11090 // `delete super.x` is a syntax-level mistake the reference reports
11091 // with this wording, not a property-access failure.
11092 3 => (
11093 "ReferenceError",
11094 "unsupported reference to 'super'".to_string(),
11095 ),
11096 4 => (
11097 "TypeError",
11098 "iterator does not have a throw method".to_string(),
11099 ),
11100 5 => (
11101 "ReferenceError",
11102 "invalid assignment left-hand side".to_string(),
11103 ),
11104 _ => ("TypeError", format!("invalid operation on '{name}'")),
11105 };
11106 return Err(Signal::Throw(self.make_error(class, &message)));
11107 }
11108 InitialYield => return Ok(Step::Suspend(SuspendKind::Initial)),
11109 Yield => return Ok(Step::Suspend(SuspendKind::Yield)),
11110 YieldStar => return Ok(Step::Suspend(SuspendKind::YieldStar)),
11111 AsyncYieldStar => return Ok(Step::Suspend(SuspendKind::AsyncYieldStar)),
11112 Await => return Ok(Step::Suspend(SuspendKind::Await)),
11113 ReturnAsync => {
11114 // The reference's `return_async` returns `undefined` and lets the resume
11115 // machinery pick the real value off `sp[-1]`, which is how it tells a
11116 // completion from a suspension. Carrying the value explicitly says the
11117 // same thing without the implicit stack slot.
11118 let value = self.pop();
11119 return Ok(Step::Return(value));
11120 }
11121 Return => {
11122 let value = self.pop();
11123 return Ok(Step::Return(value));
11124 }
11125 ReturnUndef => return Ok(Step::Return(Value::Undefined)),
11126
11127 // -- calls ------------------------------------------------------
11128 Call | Call0 | Call1 | Call2 | Call3 => {
11129 let argc = self.argc_operand(op, a);
11130 let args = self.pop_n(argc);
11131 let callee = self.pop();
11132 // A plain call has no receiver; the callee decides what to do with
11133 // `undefined` (a sloppy function substitutes the global object).
11134 if let Some(result) = self.call_or_push(callee, Value::Undefined, args)? {
11135 self.push(result);
11136 }
11137 }
11138 CallConstructor => {
11139 // `constructor this_obj args… -> object`. The duplicated
11140 // constructor is `new.target`; this milestone does not expose it,
11141 // so the extra copy is simply consumed here.
11142 let argc = a as usize;
11143 let args = self.pop_n(argc);
11144 let new_target = self.pop();
11145 let callee = self.pop();
11146 let result = self.construct(callee, new_target, args)?;
11147 self.push(result);
11148 }
11149 CallMethod => {
11150 let argc = a as usize;
11151 let args = self.pop_n(argc);
11152 let callee = self.pop();
11153 let this = self.pop();
11154 if let Some(result) = self.call_or_push(callee, this, args)? {
11155 self.push(result);
11156 }
11157 }
11158 Apply => {
11159 // `func this array -> result`, the spread-call form: the compiler
11160 // builds one array of arguments, and all that is left here is to
11161 // unpack it. Magic 1 is `new` (`apply 1`), which constructs.
11162 let array = self.pop();
11163 let this = self.pop();
11164 let callee = self.pop();
11165 let args = self.array_like_to_args(&array)?;
11166 if a & 1 != 0 {
11167 let result = self.construct(callee, this, args)?;
11168 self.push(result);
11169 } else if let Some(result) = self.call_or_push(callee, this, args)? {
11170 self.push(result);
11171 }
11172 }
11173 TailCall | TailCallMethod => {
11174 // `tail_call` is `call` whose result is returned immediately — the
11175 // reference jumps straight to `done` instead of storing the value and
11176 // running on. The callee still gets its own frame, so deep tail
11177 // recursion hits the stack limit exactly like plain recursion does;
11178 // marking this frame lets the return path unwind without needing
11179 // instructions after the call.
11180 let argc = if op == TailCallMethod {
11181 a as usize
11182 } else {
11183 self.argc_operand(op, a)
11184 };
11185 let args = self.pop_n(argc);
11186 let callee = self.pop();
11187 let this = if op == TailCallMethod {
11188 self.pop()
11189 } else {
11190 Value::Undefined
11191 };
11192 if let Value::Object(function) = &callee
11193 && let Some((code, env)) = bytecode_of(function)
11194 {
11195 // A generator or async body is not run here at all: calling it only
11196 // *creates* the generator/coroutine, so it must not inherit this
11197 // frame. Doing so made `function f(){ return g() }` push `g`'s body
11198 // onto `f`'s frame, and the first `yield`/`await` then reported
11199 // "a generator body ran as an ordinary call".
11200 if code.code.kind.is_generator() || code.code.kind.is_async() {
11201 let value = self.call_value(callee, this, args)?;
11202 return Ok(Step::Return(value));
11203 }
11204 self.frame_mut().tail = true;
11205 self.push_frame(code, env, this, args, callee)?;
11206 return Ok(Step::Continue);
11207 }
11208 // A native callee has no frame to reuse, so its value is simply
11209 // returned.
11210 let value = self.call_value(callee, this, args)?;
11211 return Ok(Step::Return(value));
11212 }
11213
11214 // -- objects ----------------------------------------------------
11215 SpecialObject => {
11216 let value = self.special_object(a)?;
11217 self.push(value);
11218 }
11219 PrivateSymbol => {
11220 // `private_symbol "#x"`: the key a class's `#x` property lives under. A fresh
11221 // symbol each time it is evaluated, which is why the compiler evaluates it
11222 // once (at class definition) and stores it in a class-scope binding.
11223 let name = self.atom_text(a as usize);
11224 let symbol = Gc::new(self.heap, crate::value::JsSymbol::new_private(&name));
11225 self.push(Value::Symbol(symbol));
11226 }
11227 GetPrivateField => {
11228 // `obj symbol -> value`. A missing private field is a TypeError, which is what
11229 // makes `#x` inaccessible on any object not built by this class.
11230 let symbol = self.pop();
11231 let object = self.pop();
11232 let value = self.read_private_field(&object, &symbol)?;
11233 self.push(value);
11234 }
11235 PutPrivateField => {
11236 // `obj value symbol ->`, and the store is a plain assignment to a property the
11237 // class already created, so there is no setter to consult.
11238 let symbol = self.pop();
11239 let value = self.pop();
11240 let object = self.pop();
11241 self.write_private_field(&object, &symbol, value)?;
11242 }
11243 DefinePrivateField => {
11244 // `obj symbol value -> obj`: a field initialiser creates the property, and
11245 // redefining one is a TypeError ("already exists").
11246 let value = self.pop();
11247 let symbol = self.pop();
11248 let object = self.pop();
11249 self.define_private_field(&object, &symbol, value)?;
11250 self.push(object);
11251 }
11252 PrivateIn => {
11253 // `obj key -> bool`: `#x in o`. The second operand decides which question is
11254 // being asked, which is the reference's `js_operator_private_in`: a *symbol*
11255 // is a field, so this is an own-property test; a *function* is a method or
11256 // accessor, so this is a brand check.
11257 let key = self.pop();
11258 let object = self.pop();
11259 let Some(target) = object.as_object() else {
11260 return Err(Signal::Throw(
11261 self.make_error("TypeError", "invalid 'in' operand"),
11262 ));
11263 };
11264 let present = match &key {
11265 Value::Object(_) => self.check_brand(target, &key)?,
11266 _ => target.own_property_key(&self.private_key(&key)?).is_some(),
11267 };
11268 self.push(Value::Bool(present));
11269 }
11270 AddBrand => {
11271 // `obj home ->`: create the class brand on `home` if it has none, then give
11272 // `obj` that brand. `obj` may be `null`, which is the instance-brand case at
11273 // class definition: only the prototype's copy of the symbol is wanted.
11274 let home = self.pop();
11275 let object = self.pop();
11276 self.add_brand(&object, &home)?;
11277 }
11278 CheckBrand => {
11279 // `obj func -> obj func`: does `obj` carry the brand of `func`'s home object?
11280 // Both stay, because the caller needs them — `nip` halves a read into its
11281 // value and `call_method` uses the pair as receiver and callee.
11282 let function = self.peek(0);
11283 let object = self.peek(1);
11284 let Some(target) = object.as_object() else {
11285 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
11286 };
11287 if !self.check_brand(target, &function)? {
11288 return Err(Signal::Throw(
11289 self.make_error("TypeError", "invalid brand on object"),
11290 ));
11291 }
11292 }
11293 GetLength => {
11294 // `get_length` is the `.length` read; an array and a string answer
11295 // from their own length, anything else from the property.
11296 let target = self.pop();
11297 let value = match &target {
11298 Value::Object(object) => match object.array_length() {
11299 Some(length) => crate::object::length_value(length),
11300 None => self.read_field(&target, "length")?,
11301 },
11302 Value::String(text) => Value::Int(text.utf16_len() as i32),
11303 _ => self.read_field(&target, "length")?,
11304 };
11305 self.push(value);
11306 }
11307 GetField | GetField2 => {
11308 let object = self.pop();
11309 // Borrowed out of the code object, not cloned: `atom_key` returns an owned
11310 // `PropertyKey` (an `Rc` bump) and the lookup only reads it. The `Gc` clone
11311 // just below is what lets the borrow outlive the `&mut self` the lookup
11312 // needs — one refcount bump instead of a key clone plus its drop, on the
11313 // hottest property path there is: every `o.x` and every `o.m()` receiver.
11314 let code = self.frame().code.clone();
11315 let key = &code.atom_keys[a as usize];
11316 let value = self.read_field_cached(&object, key, next)?;
11317 if op == GetField2 {
11318 self.push(object);
11319 }
11320 self.push(value);
11321 }
11322 GetArrayEl | GetArrayEl2 | GetArrayEl3 => {
11323 let key = self.pop();
11324 let object = self.pop();
11325 let key = self.propkey(&key)?;
11326 let value = self.read_field_key(&object, &key)?;
11327 if matches!(op, GetArrayEl2 | GetArrayEl3) {
11328 self.push(object);
11329 }
11330 if op == GetArrayEl3 {
11331 // The key goes back in its *value* form, which the compiler stores
11332 // into the target of a destructuring assignment.
11333 self.push(match &key {
11334 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
11335 PropertyKey::String(text) => self.string_wtf8(text.clone()),
11336 });
11337 }
11338 self.push(value);
11339 }
11340 PutField => {
11341 let value = self.pop();
11342 let object = self.pop();
11343 // Borrowed, like the `get_field` arm: `atom_key` would return an owned
11344 // `PropertyKey`, which is an `Rc` bump plus its drop for a key the callee
11345 // only reads. `this.value = …` is the write half of the hottest loop in
11346 // `property:method-call`, and `own_property_key` was 4.8% of the case.
11347 let code = self.frame().code.clone();
11348 let key = &code.atom_keys[a as usize];
11349 self.write_field_key(&object, key, value)?;
11350 }
11351 PutArrayEl => {
11352 let value = self.pop();
11353 let key = self.pop();
11354 let object = self.pop();
11355 let key = self.propkey(&key)?;
11356 self.write_field_key(&object, &key, value)?;
11357 }
11358 DefineField => {
11359 let value = self.pop();
11360 let object = self.pop();
11361 // `atom_keys`, not `atom_text`: the key may hold an unpaired surrogate
11362 // (`{ "\uD800": 1 }`), and going through a `String` would turn that into
11363 // three U+FFFD — a property under a different name from the one
11364 // `o["\uD800"]` reads.
11365 let code = self.frame().code.clone();
11366 let key = code.atom_keys[a as usize].clone();
11367 // No naming here. `{m: function(){}}` is named by the *compiler*, which
11368 // emits `set_name` — and only where `NamedEvaluation` applies, so
11369 // `{m: (0, function(){})}` stays anonymous. Naming every function that
11370 // reaches a property definition got that case wrong, and the compiler is
11371 // the only place that can tell the two apart.
11372 if let Some(target) = object.as_object() {
11373 // Only an *array* stores into the element vector. A numeric key
11374 // on an ordinary object is an ordinary property, which is what
11375 // makes `{1: 'a'}` iterate as a key rather than disappear.
11376 let stored = target.is_array()
11377 && key.as_str().and_then(array_index).is_some_and(|index| {
11378 target.array_set(self.heap, index as usize, value.clone())
11379 });
11380 if !stored {
11381 target.define_data_key(&key, value);
11382 }
11383 }
11384 self.push(object);
11385 }
11386 DefineArrayEl => {
11387 // `obj key value -> obj key`. The *value* form of the key is what goes
11388 // back on the stack — the compiler stores it into the pattern's binding —
11389 // so the symbol is not stringified on the way through.
11390 let value = self.pop();
11391 let key_value = self.pop();
11392 let object = self.peek(0);
11393 let key = self.propkey(&key_value)?;
11394 self.write_field_key(&object, &key, value)?;
11395 self.push(key_value);
11396 }
11397 SetHomeObject => {
11398 // `obj func -> obj func`: records the object a method was defined on so
11399 // `super` inside it resolves against that object's prototype.
11400 let function = self.peek(0);
11401 let home = self.peek(1);
11402 if let (Value::Object(function), Value::Object(home)) = (&function, &home) {
11403 function.set_home_object(Some(home.clone()));
11404 }
11405 }
11406 Regexp => {
11407 // `pattern flags -> regexp`. A literal compiles here rather than through the
11408 // constructor, which is both what the reference's dedicated opcode is for
11409 // and what keeps `/a/g.source` from being affected by a patched `RegExp`.
11410 let flags = self.pop();
11411 let pattern = self.pop();
11412 let pattern = self.to_js_string(&pattern)?;
11413 let flags = self.to_js_string(&flags)?;
11414 let object = crate::builtins::regexp::new_regexp(self, &pattern, &flags)?;
11415 self.push(Value::Object(object));
11416 }
11417 UsingDisposeInit => {
11418 // The error state a disposal accumulates into. Uninitialised means "no
11419 // failure yet"; anything else is the exception being propagated.
11420 self.push(Value::Uninitialized);
11421 }
11422 UsingCheck => {
11423 // `value -> value, method`: validate and snapshot the disposer now, so a
11424 // later change to `Symbol.dispose` cannot change what gets called, and so a
11425 // value that is not disposable fails before the body runs.
11426 let value = self.pop();
11427 let method = self.using_method_for(&value, a as u8 == 1)?;
11428 self.push(value);
11429 self.push(method);
11430 }
11431 UsingDispose => {
11432 // `error_state -> error_state'`: dispose the variable at `slot` — its value
11433 // is `slot`, its snapshotted method `slot + 1` — folding any failure into
11434 // the pending error.
11435 let slot = self.slot_operand(op, a);
11436 let error_state = self.pop();
11437 let merged = self.using_dispose_once(slot, error_state)?;
11438 self.push(merged);
11439 }
11440 UsingDisposeMerge => {
11441 let new_error = self.pop();
11442 let error_state = self.pop();
11443 let merged = self.merge_dispose_error(new_error, error_state);
11444 self.push(merged);
11445 }
11446 UsingDisposeEnd => {
11447 // A disposal that failed replaces the block's normal completion, so the
11448 // error state becomes a real throw here rather than at the call site.
11449 let error_state = self.pop();
11450 if !matches!(error_state, Value::Uninitialized) {
11451 return Err(Signal::Throw(error_state));
11452 }
11453 }
11454 UsingDisposeAsync => {
11455 // `await using` needs a promise to await and this runtime has no
11456 // `Promise` builtin, so the disposer is called synchronously and its result
11457 // discarded. That is correct for a disposer that returns nothing and is
11458 // reported as a gap rather than silently skipped.
11459 let slot = self.slot_operand(op, a);
11460 let error_state = self.using_dispose_once(slot, Value::Uninitialized)?;
11461 self.push(error_state);
11462 }
11463 GetSuper => {
11464 // `obj -> obj's prototype`: the starting point of a `super` lookup.
11465 let object = self.pop();
11466 let proto = match &object {
11467 Value::Object(object) => object.proto().map_or(Value::Null, Value::Object),
11468 _ => Value::Null,
11469 };
11470 self.push(proto);
11471 }
11472 GetSuperValue => {
11473 // `receiver proto key -> value`, searching from `proto` but reporting to
11474 // `receiver`, which is what `super.g` must do for a getter to see `this`.
11475 //
11476 // Three values in, one out: the receiver is *consumed*, not left under the
11477 // result. Leaving it there was invisible for `super.x` in `return` or
11478 // statement position (the result is what gets popped) and corrupted the
11479 // frame everywhere else — `print(super.x)` left the class where the call
11480 // opcode looks for the receiver and called the class itself.
11481 let key = self.pop();
11482 let proto = self.pop();
11483 let receiver = self.pop();
11484 let value = self.super_read(&receiver, &proto, &key)?;
11485 self.push(value);
11486 }
11487 PutSuperValue => {
11488 // `receiver proto key value ->`: a store that starts at `proto` but
11489 // assigns to `receiver`.
11490 let value = self.pop();
11491 let key = self.pop();
11492 let proto = self.pop();
11493 let receiver = self.pop();
11494 self.super_write(&receiver, &proto, &key, value)?;
11495 }
11496 DefineClass => {
11497 // `parent ctor -> ctor proto`: the constructor becomes the class and a
11498 // fresh prototype object lands on top for the methods to go on.
11499 let name = self.atom_text(a as usize);
11500 let (ctor, proto) = self.define_class(&name, b)?;
11501 self.push(ctor);
11502 self.push(Value::Object(proto));
11503 }
11504 DefineClassComputed => {
11505 // `parent ctor key -> ctor proto key`: the computed name stays put so
11506 // `define_field`-style consumers can still read it.
11507 let key = self.pop();
11508 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11509 let (ctor, proto) = self.define_class(&name, b)?;
11510 self.push(ctor);
11511 self.push(Value::Object(proto));
11512 self.push(key);
11513 }
11514 DefineMethod => {
11515 let function = self.pop();
11516 let object = self.pop();
11517 // The exact key, like `define_field`: a quoted method key may hold an
11518 // unpaired surrogate, and `{ "\uD800"(){} }` has to define the property
11519 // that `o["\uD800"]` finds.
11520 let code = self.frame().code.clone();
11521 let key = code.atom_keys[a as usize].clone();
11522 // A method's `[[HomeObject]]` is the object it was defined on, which is
11523 // what `super` inside it resolves against.
11524 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11525 function.set_home_object(Some(object.clone()));
11526 }
11527 if let Some(text) = key.as_wtf8() {
11528 self.set_function_name_wtf8(&function, &accessor_prefixed(text, b));
11529 } else {
11530 self.set_function_name(
11531 &function,
11532 &key_with_accessor_prefix(&key.to_string(), b),
11533 );
11534 }
11535 if let Some(array) = object.as_object() {
11536 define_function_property(array, &key, function, b);
11537 }
11538 self.push(object);
11539 }
11540 DefineMethodComputed => {
11541 let function = self.pop();
11542 let key = self.pop();
11543 let object = self.pop();
11544 let key = self.propkey(&key)?;
11545 // Same `[[HomeObject]]` as `define_method`, and it has to be set *before*
11546 // the name: `super` inside a computed method resolves through it. Without
11547 // this, `class B extends A { [k]() { return super.m() } }` read the
11548 // home object as null and threw.
11549 if let (Value::Object(function), Value::Object(object)) = (&function, &object) {
11550 function.set_home_object(Some(object.clone()));
11551 }
11552 match key.as_wtf8() {
11553 Some(text) => {
11554 let name = accessor_prefixed(text, a);
11555 self.set_function_name_wtf8(&function, &name);
11556 }
11557 None => self.set_function_name(
11558 &function,
11559 &key_with_accessor_prefix(&key.to_string(), a),
11560 ),
11561 }
11562 if let Some(array) = object.as_object() {
11563 define_function_property(array, &key, function, a);
11564 }
11565 self.push(object);
11566 }
11567 SetProto => {
11568 let proto = self.pop();
11569 let object = self.pop();
11570 if let Some(target) = object.as_object() {
11571 target.set_proto(proto.as_object().cloned());
11572 }
11573 self.push(object);
11574 }
11575 CopyDataProperties => {
11576 let exclusion = self.pop();
11577 let source = self.pop();
11578 let target = self.peek(0);
11579 self.copy_properties(&target, &source, &exclusion)?;
11580 self.push(source);
11581 self.push(exclusion);
11582 }
11583 ToPropkey => {
11584 // A symbol survives unchanged: this is `ToPropertyKey`, not `ToString`,
11585 // and stringifying here would turn `{[Symbol("b")]: 2}` into an
11586 // ordinary `"Symbol(b)"` property.
11587 let value = self.pop();
11588 let key = match self.propkey(&value)? {
11589 PropertyKey::Symbol(symbol) => Value::Symbol(symbol),
11590 PropertyKey::String(text) => self.string_wtf8(text),
11591 };
11592 self.push(key);
11593 }
11594 SetName => {
11595 let function = self.peek(0);
11596 let name = self.atom_wtf8(a as usize);
11597 self.set_function_name_wtf8(&function, &name);
11598 }
11599 SetNameComputed => {
11600 let key = self.peek(1);
11601 let function = self.peek(0);
11602 let name = self.propkey_of(&key)?.to_string_lossy().into_owned();
11603 self.set_function_name(&function, &name);
11604 }
11605
11606 // -- arrays -----------------------------------------------------
11607 ArrayFrom => {
11608 let count = a as usize;
11609 let elements = self.pop_n(count);
11610 let array = self.new_array(elements);
11611 self.push(Value::Object(array));
11612 }
11613 Append => {
11614 // `array index iterable -> array new_index`
11615 let iterable = self.pop();
11616 self.pop();
11617 let array = self.peek(0);
11618 let added = self.append_enumerate(&array, &iterable)?;
11619 self.push(Value::Int(added));
11620 }
11621
11622 // -- iteration --------------------------------------------------
11623 ForInStart => {
11624 let value = self.pop();
11625 let record = self.for_in_record(&value)?;
11626 self.push(Value::Object(record));
11627 }
11628 ForInNext => {
11629 // `record -> record key done`. The flag is *done*, not "found":
11630 // the compiler tests it with `if_false` to jump back into the body,
11631 // so reporting `true` while keys remain would end the loop at once.
11632 let record = self.peek(0);
11633 match self.for_in_advance(&record)? {
11634 Some(key) => {
11635 let text = self.string(key);
11636 self.push(text);
11637 self.push(Value::Bool(false));
11638 }
11639 None => {
11640 self.push(Value::Undefined);
11641 self.push(Value::Bool(true));
11642 }
11643 }
11644 }
11645 ForOfStart => {
11646 let value = self.pop();
11647 let iterator = self.get_iterator(&value)?;
11648 self.push(iterator.object);
11649 self.push(iterator.next);
11650 self.push(Value::CatchOffset(0));
11651 }
11652 ForOfNext => {
11653 // `iter next catch_offset -> iter next catch_offset value done`.
11654 //
11655 // The operand is how many values sit *above* the iterator triple: a
11656 // destructuring rest element keeps its target array and running index
11657 // there while draining the iterator, so the triple is not at the top.
11658 let extra = a as usize;
11659 let iterator_slot = 2 + extra;
11660 // An exhausted iterator is replaced by `undefined` (see below), so a
11661 // second step must not call `next` again — `Array.from` and a
11662 // destructuring pattern both keep stepping past the end.
11663 let (value, done) = if matches!(self.peek(iterator_slot), Value::Undefined) {
11664 (Value::Undefined, true)
11665 } else {
11666 let iterator = Iterator {
11667 object: self.peek(iterator_slot),
11668 next: self.peek(1 + extra),
11669 };
11670 self.iterator_step(&iterator)?
11671 };
11672 if done {
11673 // The result's `value` is meaningless once the iterator is done:
11674 // `function* g(){ return 0 } var [x] = g()` leaves `x` undefined
11675 // rather than binding the generator's return value.
11676 let top = self.frame().stack.len() - 1 - iterator_slot;
11677 self.frame_mut().stack[top] = Value::Undefined;
11678 self.push(Value::Undefined);
11679 self.push(Value::Bool(true));
11680 } else {
11681 self.push(value);
11682 self.push(Value::Bool(false));
11683 }
11684 }
11685 IteratorNext => {
11686 // `iter next catch val -> iter next catch val'`: replace the argument with
11687 // the result of `next(val)`. The triple below stays put, which is why the
11688 // three instructions of the `yield*` loop all address the stack the same way.
11689 let value = self.pop();
11690 let object = self.peek(2);
11691 let next = self.peek(1);
11692 let result = self.call_value(next, object, vec![value])?;
11693 self.push(result);
11694 }
11695 IteratorCall => {
11696 // `iter next catch val -> iter next catch val' flag`.
11697 //
11698 // Bit 0 picks `.throw` over `.return`, bit 1 calls it with no argument.
11699 // The flag is `true` when the method was missing, which is how the
11700 // caller learns that the inner iterator cannot take part in the
11701 // unwinding.
11702 let value = self.pop();
11703 let object = self.peek(2);
11704 let key = if a & 1 != 0 { "throw" } else { "return" };
11705 let method = self.read_field(&object, key)?;
11706 if matches!(method, Value::Undefined | Value::Null) {
11707 self.push(value);
11708 self.push(Value::Bool(true));
11709 } else {
11710 let argument = if a & 2 != 0 { Vec::new() } else { vec![value] };
11711 let result = self.call_value(method, object, argument)?;
11712 self.push(result);
11713 self.push(Value::Bool(false));
11714 }
11715 }
11716 IteratorCheckObject => {
11717 if !matches!(self.peek(0), Value::Object(_)) {
11718 return Err(Signal::Throw(
11719 self.make_error("TypeError", "iterator must return an object"),
11720 ));
11721 }
11722 }
11723 IteratorClose => {
11724 // `iter_obj next catch_offset ->`: abandon a `for of` loop, which means
11725 // calling the iterator's `return` so it can release whatever it holds.
11726 //
11727 // The catch offset goes first, so an exception from `return` is not caught
11728 // by the loop being abandoned. This used to pop the three operands and call
11729 // nothing at all, which made `break` out of a `for of` invisible to an
11730 // iterator with a `return` method.
11731 self.pop();
11732 self.pop();
11733 let iterator = self.pop();
11734 if !matches!(iterator, Value::Undefined) {
11735 let method = self.read_field(&iterator, "return")?;
11736 if !matches!(method, Value::Undefined | Value::Null) {
11737 let result = self.call_value(method, iterator.clone(), Vec::new())?;
11738 // §7.4.6: a `return` that answers a non-object is a TypeError.
11739 if !matches!(result, Value::Object(_)) {
11740 return Err(Signal::Throw(
11741 self.make_error("TypeError", "iterator must return an object"),
11742 ));
11743 }
11744 }
11745 }
11746 }
11747 Import => {
11748 // `import(specifier)`: the options slot is on top and is not read yet.
11749 let _options = self.pop();
11750 let specifier = self.pop();
11751 let promise = self.dynamic_import(specifier)?;
11752 self.push(promise);
11753 }
11754 ForAwaitOfStart => {
11755 // Same triple as `for of`, but from `Symbol.asyncIterator` with a
11756 // `Symbol.iterator` fallback.
11757 let value = self.pop();
11758 let iterator = self.get_async_iterator(&value)?;
11759 self.push(iterator.object);
11760 self.push(iterator.next);
11761 self.push(Value::CatchOffset(0));
11762 }
11763 ForAwaitOfNext => {
11764 // `for await` steps the iterator and leaves the *result* wrapped in a
11765 // promise, so the `await` the compiler emits right after this can suspend
11766 // on it. Unwrapping happens in `iterator_get_value_done`.
11767 let extra = a as usize;
11768 let iterator_slot = 2 + extra;
11769 let result = if matches!(self.peek(iterator_slot), Value::Undefined) {
11770 Value::Undefined
11771 } else {
11772 let iterator = Iterator {
11773 object: self.peek(iterator_slot),
11774 next: self.peek(1 + extra),
11775 };
11776 let next = iterator.next.clone();
11777 self.call_value(next, iterator.object, Vec::new())?
11778 };
11779 let promise = self.promise_resolve_value(result)?;
11780 self.push(promise);
11781 }
11782 IteratorGetValueDone => {
11783 // `result -> value done`. A missing result object means the iterator was
11784 // already exhausted, which the loop treats as `done`.
11785 let result = self.pop();
11786 let done = match &result {
11787 Value::Object(object) => self
11788 .get_property(object, "done")?
11789 .is_some_and(|value| value.to_boolean()),
11790 _ => true,
11791 };
11792 if done {
11793 // Clear the iterator object so the `iterator_close` the loop emits on
11794 // its way out has nothing to close: `AsyncIteratorClose` must *not* run
11795 // on normal completion, and this is where a normal completion is
11796 // recognised — the same trick `for_of_next` uses, which also replaces
11797 // the slot with `undefined`.
11798 //
11799 // The layout is fixed because only `for await` emits this opcode:
11800 // `iter next catch [result]`, so the iterator is three below the top.
11801 let depth = self.frame().stack.len();
11802 if depth >= 3 {
11803 self.frame_mut().stack[depth - 3] = Value::Undefined;
11804 }
11805 self.push(Value::Undefined);
11806 self.push(Value::Bool(true));
11807 } else {
11808 let Value::Object(object) = &result else {
11809 self.push(Value::Undefined);
11810 self.push(Value::Bool(true));
11811 return Ok(Step::Continue);
11812 };
11813 let value = self
11814 .get_property(object, "value")?
11815 .unwrap_or(Value::Undefined);
11816 self.push(value);
11817 self.push(Value::Bool(false));
11818 }
11819 }
11820
11821 Delete => {
11822 // `delete obj[key]`, where the key was just pushed. Deleting an array
11823 // index leaves a *hole* rather than closing the gap, and a
11824 // non-configurable property answers `false` and stays.
11825 let key = self.pop();
11826 let target = self.pop();
11827 let key = self.propkey(&key)?;
11828 let text_label = key.as_str().unwrap_or("").to_string();
11829 let deleted = match &target {
11830 Value::Object(object) => {
11831 let object = object.clone();
11832 self.delete_property_key(&object, &key)?
11833 }
11834 // A string's `length` and its index properties are
11835 // non-configurable, so deleting one answers `false`.
11836 Value::String(text) => {
11837 !(text_label == "length"
11838 || array_index(&text_label)
11839 .is_some_and(|index| (index as usize) < text.utf16_len()))
11840 }
11841 // "delete null.a" is a TypeError, not a no-op: the operator needs an
11842 // object to delete from, and only a *boxable* primitive has one.
11843 Value::Undefined | Value::Null => {
11844 return Err(Signal::Throw(
11845 self.make_error("TypeError", "cannot convert to object"),
11846 ));
11847 }
11848 // Any other primitive has no own properties; deleting nothing
11849 // succeeds.
11850 _ => true,
11851 };
11852 // §13.5.1.2: in strict mode a `delete` that answers `false` is a
11853 // `TypeError` rather than a `false` result. Sloppy mode silently reports
11854 // the refusal, which is why the same statement throws here but not there.
11855 if !deleted && self.current_strict() {
11856 return Err(Signal::Throw(
11857 self.make_error("TypeError", "cannot delete property"),
11858 ));
11859 }
11860 self.push(Value::Bool(deleted));
11861 }
11862
11863 // -- exceptions and bookkeeping ---------------------------------
11864 Fclosure | Fclosure8 => {
11865 let value = self.closure(a as usize)?;
11866 self.push(value);
11867 }
11868
11869 other => {
11870 let name = other.info().name;
11871 return Err(Signal::Throw(self.make_error(
11872 "InternalError",
11873 &format!("{name} is not implemented yet"),
11874 )));
11875 }
11876 }
11877 Ok(Step::Continue)
11878 }
11879
11880 // -- operand helpers ----------------------------------------------------
11881
11882 /// The slot index an operand names, taking short forms into account.
11883 fn slot_operand(&self, op: Opcode, a: u32) -> usize {
11884 use Opcode::*;
11885 match op {
11886 GetLoc0 | PutLoc0 | SetLoc0 | GetArg0 | PutArg0 | SetArg0 | GetVarRef0 | PutVarRef0
11887 | SetVarRef0 => 0,
11888 GetLoc1 | PutLoc1 | SetLoc1 | GetArg1 | PutArg1 | SetArg1 | GetVarRef1 | PutVarRef1
11889 | SetVarRef1 => 1,
11890 GetLoc2 | PutLoc2 | SetLoc2 | GetArg2 | PutArg2 | SetArg2 | GetVarRef2 | PutVarRef2
11891 | SetVarRef2 => 2,
11892 GetLoc3 | PutLoc3 | SetLoc3 | GetArg3 | PutArg3 | SetArg3 | GetVarRef3 | PutVarRef3
11893 | SetVarRef3 => 3,
11894 _ => a as usize,
11895 }
11896 }
11897
11898 /// The argument count of a call, taking `call0`…`call3` into account.
11899 fn argc_operand(&self, op: Opcode, a: u32) -> usize {
11900 use Opcode::*;
11901 match op {
11902 Call0 => 0,
11903 Call1 => 1,
11904 Call2 => 2,
11905 Call3 => 3,
11906 _ => a as usize,
11907 }
11908 }
11909
11910 /// The atom's name as a property key.
11911 ///
11912 /// A `PropertyKey` rather than a `String` because that is what every caller needs, and
11913 /// because `Wtf8` is reference-counted: building the key is a refcount bump, while
11914 /// `String::clone` was a heap allocation and a copy — per property access.
11915 /// The atom at `index`, as a property key.
11916 ///
11917 /// Clones out of the prebuilt table, which is an `Rc` bump. Building the key here
11918 /// instead — as this used to — ran `Wtf8::from_rc_str`, and that *allocates*: it
11919 /// makes a fresh `Rc<[u8]>` and copies the bytes. A `malloc` per property read was
11920 /// 5.3% of `property:monomorphic`.
11921 /// The atom's text, exactly — including an unpaired surrogate.
11922 ///
11923 /// Used wherever the atom *is* a string value the script can observe: `push_atom_value`
11924 /// for a literal, `add_atom_loc` for string concatenation, and `set_name`. The lossy
11925 /// `atom_text` below is for the other kind of use, where the atom is a key in the
11926 /// engine's own tables.
11927 fn atom_wtf8(&self, index: usize) -> crate::value::Wtf8 {
11928 self.frame()
11929 .code
11930 .code
11931 .atoms
11932 .get(index)
11933 .map(|atom| match atom {
11934 Atom::Str(text) => text.clone(),
11935 Atom::Index(value) => crate::value::Wtf8::new(value.to_string()),
11936 // `JS_ATOM_NULL`: no name, and the opcodes that take one never read it.
11937 Atom::Null => crate::value::Wtf8::new(String::new()),
11938 })
11939 .unwrap_or_default()
11940 }
11941
11942 fn atom_text(&self, index: usize) -> String {
11943 self.frame()
11944 .code
11945 .code
11946 .atoms
11947 .get(index)
11948 .map(|atom| match atom {
11949 // Lossy on purpose: these callers put the atom in a `HashMap<String, _>` or
11950 // compare it to an identifier, and a surrogate-bearing name is reachable
11951 // through `atom_wtf8` where it matters.
11952 Atom::Str(text) => text.to_string_lossy().into_owned(),
11953 Atom::Index(value) => value.to_string(),
11954 // `JS_ATOM_NULL`: no name. The opcodes that take one (the generic
11955 // `throw_error`, `delete super.x`) never read it.
11956 Atom::Null => String::new(),
11957 })
11958 .unwrap_or_default()
11959 }
11960
11961 fn constant(&mut self, index: usize) -> JsResult<Value> {
11962 let constant = self.frame().code.code.cpool.get(index).cloned();
11963 Ok(match &constant {
11964 Some(Constant::Number(number)) => Value::Float(*number),
11965 Some(Constant::String(text)) => self.string_wtf8(text.clone()),
11966 Some(Constant::BigInt { digits, radix }) => {
11967 match crate::bigint::BigInt::from_radix(digits, *radix) {
11968 Some(big) => self.bigint(big),
11969 // A literal the parser accepted is always parseable; a failure here
11970 // would be a compiler bug, so it reads as an `InternalError`.
11971 None => {
11972 return Err(Signal::Throw(
11973 self.make_error("InternalError", "unparseable bigint literal"),
11974 ));
11975 }
11976 }
11977 }
11978 Some(Constant::Function(_)) => {
11979 return Err(Signal::Throw(
11980 self.make_error("InternalError", "a bare function constant"),
11981 ));
11982 }
11983 // A tagged template's call site: a frozen array of the cooked chunks with a
11984 // frozen `raw` array beside it, which is what `String.raw` reads back.
11985 Some(Constant::Template { cooked, raw }) => {
11986 let cooked_values: Vec<Value> = cooked
11987 .iter()
11988 .map(|chunk| match chunk {
11989 Some(text) => self.string_wtf8(text.clone()),
11990 None => Value::Undefined,
11991 })
11992 .collect();
11993 let raw_values: Vec<Value> =
11994 raw.iter().map(|text| self.string(text.clone())).collect();
11995 let raw_array = self.new_array(raw_values);
11996 raw_array.set_extensible(false);
11997 let template = self.new_array(cooked_values);
11998 template.define(
11999 "raw",
12000 Property::with_attributes(Value::Object(raw_array), false, false),
12001 );
12002 template.set_extensible(false);
12003 Value::Object(template)
12004 }
12005 _ => Value::Undefined,
12006 })
12007 }
12008
12009 /// The reference cell a closure-variable slot names.
12010 ///
12011 /// Two kinds of binding share this addressing: a genuine closure variable
12012 /// (captured from an enclosing function) lives in this frame's environment,
12013 /// while a *declared global* lives in the realm so that a script, a function
12014 /// declaration and their uses all see one binding. A plain `Global` — an
12015 /// undeclared name that may be satisfied by the global object — has no cell at
12016 /// all, which is how `typeof x` still works for a name that does not exist.
12017 /// The reference cell a closure-variable slot names.
12018 ///
12019 /// The environment is resolved once, when the closure is built, and this is
12020 /// just the lookup afterwards. A *declared global* is in there too, pointing at
12021 /// the realm's cell, so a script, a hoisted function declaration and their uses
12022 /// all share one binding. A plain `Global` — a name the script never declared —
12023 /// is read and written through `get_var`/`put_var` by name instead, which is
12024 /// what lets the global object satisfy it.
12025 fn var_ref_cell(&self, slot: usize) -> Option<Gc<Cell>> {
12026 self.frame().env.cells.get(slot).cloned()
12027 }
12028
12029 /// Whether `slot` refers to a global binding through the reference table.
12030 ///
12031 /// A global's cell in the closure environment only exists so the slot has
12032 /// something to point at; the binding itself lives on the global object (a `var`)
12033 /// or in the realm's lexical table (a `let`). Reads and writes therefore have to
12034 /// be routed, not performed on the placeholder.
12035 fn is_global_slot(&self, slot: usize) -> bool {
12036 self.frame()
12037 .code
12038 .code
12039 .closure_vars
12040 .get(slot)
12041 .is_some_and(|c| {
12042 // A module's declarations and imports are *not* globals: their cells are
12043 // the module environment's, filled by the host, so the placeholder routing
12044 // must not apply to them.
12045 matches!(
12046 c.closure_type,
12047 ClosureType::GlobalDecl | ClosureType::Global | ClosureType::GlobalRef
12048 )
12049 })
12050 }
12051
12052 fn cell_value(&mut self, slot: usize) -> JsResult<Value> {
12053 if self.is_global_slot(slot) {
12054 return self.get_global(slot);
12055 }
12056 Ok(self
12057 .var_ref_cell(slot)
12058 .map(|cell| cell.get())
12059 .unwrap_or(Value::Undefined))
12060 }
12061
12062 fn set_cell(&mut self, slot: usize, value: Value) -> JsResult<()> {
12063 // A function declaration is hoisted by storing into a global reference before
12064 // the body runs, so this path is also what puts it on the global object.
12065 if self.is_global_slot(slot) {
12066 return self.put_global(slot, value);
12067 }
12068 if let Some(cell) = self.var_ref_cell(slot) {
12069 cell.set(value);
12070 }
12071 Ok(())
12072 }
12073
12074 // -- closures -----------------------------------------------------------
12075
12076 /// Build the closure for the function constant `index`.
12077 ///
12078 /// Every entry in the child's closure table names where its binding lives in
12079 /// *this* frame: a local or argument slot that was marked captured, or a cell
12080 /// this frame is itself holding. That is how a variable three functions deep
12081 /// stays one binding.
12082 fn closure(&mut self, index: usize) -> JsResult<Value> {
12083 let Some(Constant::Function(function)) = self.frame().code.code.cpool.get(index).cloned()
12084 else {
12085 return Err(Signal::Throw(
12086 self.make_error("InternalError", "fclosure of a non-function"),
12087 ));
12088 };
12089 let mut cells = Vec::with_capacity(function.closure_vars.len());
12090 for closure_var in &function.closure_vars {
12091 let cell = match closure_var.closure_type {
12092 ClosureType::Arg => {
12093 let slot = closure_var.var_idx as usize;
12094 self.frame().code.arg_cell.get(slot).copied().unwrap_or(-1)
12095 }
12096 ClosureType::Local => {
12097 let slot = closure_var.var_idx as usize;
12098 self.frame().code.loc_cell.get(slot).copied().unwrap_or(-1)
12099 }
12100 ClosureType::Ref | ClosureType::GlobalRef => {
12101 // A `Ref` names a cell in this frame's own closure table; a
12102 // `GlobalRef` also starts there, then resolves by name below.
12103 let slot = closure_var.var_idx as usize;
12104 if let Some(cell) = self.frame().env.cells.get(slot) {
12105 cells.push(cell.clone());
12106 continue;
12107 }
12108 -1
12109 }
12110 _ => -1,
12111 };
12112 if cell >= 0 {
12113 let cell = self.frame().cells[cell as usize].clone();
12114 cells.push(cell);
12115 continue;
12116 }
12117 // A global: the cell is created on demand and shared through the realm,
12118 // so every function sees one binding.
12119 let name = closure_var.name.clone();
12120 let cell = match self.realm.globals.get(&name) {
12121 Some(cell) => cell.clone(),
12122 None => {
12123 let cell = self.new_cell(Value::Undefined);
12124 self.realm.globals.insert(name.clone(), cell.clone());
12125 cell
12126 }
12127 };
12128 cells.push(cell);
12129 }
12130 let name = function.name.clone();
12131 // `.length` is the arity before any default or rest parameter, not the number
12132 // of slots a pattern parameter needs.
12133 let length = function.defined_args;
12134 // `[[Construct]]` per §10.2.1: an ordinary function has it, a generator, an async
12135 // function and an arrow function do not. A *method* also does not, but that is not
12136 // known here — the method is marked when the `[[HomeObject]]` is attached (see
12137 // `set_home_object`), which is the moment it becomes a method.
12138 let function_kind = function.kind;
12139 let constructible =
12140 !function.is_arrow && function_kind == js_compile::bytecode::FunctionKind::Normal;
12141 let code = Gc::new(self.heap, CompiledCode::new(*function));
12142 // A closure built inside an `eval` inherits the eval's view of the enclosing
12143 // bindings, so it can still read them once the eval has returned.
12144 let eval_scope = self
12145 .active_eval_scope
12146 .clone()
12147 .or_else(|| self.frame().env.eval_scope.clone());
12148 // A closure sees the variables a direct `eval` declared in the frame it was
12149 // created in — the ones declared before *and after* it, so the same object is
12150 // shared; only the phase bounds which of them are visible.
12151 let local_vars = self.visible_local_vars().map(|(vars, _)| vars);
12152 let local_phase = if self.in_parameter_list() { 0 } else { 1 };
12153 let env = Gc::new(
12154 self.heap,
12155 ClosureEnv {
12156 cells,
12157 eval_scope,
12158 local_vars,
12159 local_phase,
12160 },
12161 );
12162 // A generator or async function inherits from `%GeneratorFunction.prototype%` or
12163 // `%AsyncFunction.prototype%`, not straight from `Function.prototype`. That link is
12164 // the only thing that carries `Symbol.toStringTag`, so without it
12165 // `delete g.constructor.prototype[Symbol.toStringTag]` has nothing to delete and
12166 // `Object.prototype.toString` keeps reporting `GeneratorFunction`.
12167 let proto = match function_kind {
12168 js_compile::bytecode::FunctionKind::AsyncGenerator => self
12169 .realm
12170 .async_generator_function_proto
12171 .clone()
12172 .or_else(|| self.realm.function_proto.clone().into()),
12173 js_compile::bytecode::FunctionKind::Generator => self
12174 .realm
12175 .generator_function_proto
12176 .clone()
12177 .or_else(|| self.realm.function_proto.clone().into()),
12178 js_compile::bytecode::FunctionKind::Async => self
12179 .realm
12180 .async_function_proto
12181 .clone()
12182 .or_else(|| self.realm.function_proto.clone().into()),
12183 js_compile::bytecode::FunctionKind::Normal => self.realm.function_proto.clone().into(),
12184 };
12185 let object = JsObject::function(self.heap, proto, Callable::Bytecode { code, env });
12186 object.set_constructible(constructible);
12187 object.define(
12188 "length",
12189 Property::name_or_length(Value::Int(length as i32)),
12190 );
12191 // Defined even when empty: `(function(){}).name` is `""`, not absent, and a test
12192 // that checks the own-property descriptor fails if the property is missing.
12193 object.define("name", Property::name_or_length(self.string(name)));
12194 // Only a function that can be constructed has a `prototype`: §10.2.5 makes it
12195 // when `[[Construct]]` is created, so an async function and an arrow function have
12196 // none of their own. Installing it unconditionally gave `Array.fromAsync` (an async
12197 // function) an own `prototype` property, which `builtin.js` checks for absence.
12198 //
12199 // A **generator** function is the exception that is not constructible: it still
12200 // gets a `prototype` field, because that object is what a generator *instance*
12201 // inherits from (§27.3.3.1 via `OrdinaryCreateFromConstructor`). Leaving it off
12202 // made `function* g(){}; g.prototype` `undefined` and every generator share
12203 // `%GeneratorPrototype%` as its direct prototype.
12204 if constructible {
12205 self.install_function_prototype(&object);
12206 } else if matches!(
12207 function_kind,
12208 js_compile::bytecode::FunctionKind::Generator
12209 | js_compile::bytecode::FunctionKind::AsyncGenerator
12210 ) {
12211 let parent = if function_kind == js_compile::bytecode::FunctionKind::Generator {
12212 self.realm.generator_proto.clone()
12213 } else {
12214 self.realm
12215 .async_generator_proto
12216 .clone()
12217 .unwrap_or_else(|| self.realm.generator_proto.clone())
12218 };
12219 self.install_generator_prototype(&object, parent);
12220 }
12221 Ok(Value::Object(object))
12222 }
12223
12224 // -- conversions used by the operators ----------------------------------
12225
12226 fn numeric_of(&mut self, value: Value) -> JsResult<Value> {
12227 // `+x` is `ToNumber`, which for a string parses it and for an object runs
12228 // `ToPrimitive` first. Returning a string unchanged would let `+"1"` stay a
12229 // string, which then behaves differently in every later comparison.
12230 match value {
12231 Value::Int(_) | Value::Float(_) => Ok(value),
12232 other => Ok(Value::Float(self.to_js_number(&other)?)),
12233 }
12234 }
12235
12236 /// `++`/`--`, which step a bigint by `1n` and everything else by `1`.
12237 ///
12238 /// Returns the *converted* old value and the new one, because the two callers need
12239 /// different halves: `++x` yields the new value, while `x++` yields the old one and
12240 /// still stores the new. The old value is `ToNumeric(x)`, not `x` — `a.x++` where
12241 /// `a.x` is `true` evaluates to `1`, so returning the raw operand handed back a
12242 /// boolean.
12243 ///
12244 /// A bigint stays a bigint here: `ToNumeric` keeps the type, so routing `i++` through
12245 /// the number path turned it into `NaN`, and every `for (i = 0n; i < n; i++)` loop in
12246 /// a bigint algorithm then ran exactly once.
12247 fn advance_numeric(&mut self, value: Value, up: bool) -> JsResult<(Value, Value)> {
12248 if let Value::BigInt(big) = &value {
12249 let one = crate::bigint::BigInt::from_i64(1);
12250 let next = if up { big.add(&one) } else { big.sub(&one) };
12251 return Ok((value, self.bigint(next)));
12252 }
12253 let old = self.numeric(value)?;
12254 let new = if up {
12255 increment(old.clone())
12256 } else {
12257 decrement(old.clone())
12258 };
12259 Ok((old, new))
12260 }
12261
12262 fn numeric(&mut self, value: Value) -> JsResult<Value> {
12263 // `ToNumber` on an object runs `ToPrimitive` first, which is how
12264 // `2 * {valueOf(){return 3}}` sees the 3 — and how a `valueOf` that throws is
12265 // heard at all. Reading the object's own tag instead (`other.to_number()`)
12266 // turned the whole operand into `NaN` and swallowed the exception.
12267 match value {
12268 Value::Int(_) | Value::Float(_) => Ok(value),
12269 other => Ok(Value::Float(self.to_js_number(&other)?)),
12270 }
12271 }
12272
12273 /// The operand of a `BigInt` operation, or the `TypeError` that mixing raises.
12274 fn bigint_operand(&self, value: &Value) -> JsResult<crate::bigint::BigInt> {
12275 match value {
12276 Value::BigInt(big) => Ok((**big).clone()),
12277 // The reference words this the same way for every operator, so a failing
12278 // script reads identically; the operator itself adds nothing a caller can use.
12279 _ => Err(Signal::Throw(
12280 self.make_error("TypeError", "cannot convert bigint to number"),
12281 )),
12282 }
12283 }
12284
12285 /// Arithmetic where at least one operand is a `BigInt`.
12286 ///
12287 /// The two numeric types never mix, so a bigint paired with anything else is an error
12288 /// rather than a conversion: `1n + 1` throws, and so does `1n < 1` only in the sense
12289 /// that the relational operators handle it separately.
12290 fn bigint_arithmetic(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12291 use Opcode::*;
12292 let a = self.bigint_operand(&left)?;
12293 let b = self.bigint_operand(&right)?;
12294 let result = match op {
12295 Add => a.add(&b),
12296 Sub => a.sub(&b),
12297 Mul => a.mul(&b),
12298 Div | Mod => {
12299 let Some((quotient, remainder)) = a.div_rem(&b) else {
12300 return Err(Signal::Throw(
12301 self.make_error("RangeError", "division by zero"),
12302 ));
12303 };
12304 if op == Div { quotient } else { remainder }
12305 }
12306 Pow => {
12307 let Some(value) = a.pow(&b) else {
12308 return Err(Signal::Throw(self.make_error(
12309 "RangeError",
12310 "BigInt exponent must be non-negative and not absurdly large",
12311 )));
12312 };
12313 value
12314 }
12315 And => a.bitand(&b),
12316 Or => a.bitor(&b),
12317 Xor => a.bitxor(&b),
12318 Shl | Sar => {
12319 // A shift count is a `BigInt` here, and both directions are exact; a
12320 // negative count would be the other direction, which the spec forbids.
12321 let Some(count) = b.to_i64() else {
12322 return Err(Signal::Throw(
12323 self.make_error("RangeError", "BigInt shift count is too large"),
12324 ));
12325 };
12326 if count < 0 {
12327 return Err(Signal::Throw(self.make_error(
12328 "RangeError",
12329 "BigInt shift count must be non-negative",
12330 )));
12331 }
12332 if op == Shl {
12333 a.shl(count as u64)
12334 } else {
12335 a.shr(count as u64)
12336 }
12337 }
12338 // `>>>` is defined only for 32-bit integers, so a bigint has no unsigned shift.
12339 _ => {
12340 return Err(Signal::Throw(self.make_error(
12341 "TypeError",
12342 "BigInts have no unsigned right shift, use >> instead",
12343 )));
12344 }
12345 };
12346 Ok(self.bigint(result))
12347 }
12348
12349 /// `<`, `<=`, `>`, `>=`, which accept a `BigInt` and a Number alongside each other.
12350 ///
12351 /// Unlike arithmetic, relation is defined across the two numeric types: the comparison
12352 /// is on the mathematical values, and nothing is rounded first.
12353 /// `<`, `<=`, `>`, `>=`.
12354 ///
12355 /// Both operands go through `ToPrimitive` **before** the comparison, which is what
12356 /// makes `0 < {valueOf: () => 2}` true and what makes `{valueOf(){throw}} < 1` throw.
12357 /// It is a `?`-returning function for exactly that reason: an object operand can run
12358 /// script, and script can throw. The old version compared `to_number` of the raw
12359 /// values, which answered `false` for every object instead of calling `valueOf` —
12360 /// a wrong answer, and one that `for (i = 0; i < obj; i++)` turned into a loop that
12361 /// never ran.
12362 fn relational(&mut self, op: Opcode, left: Value, right: Value) -> JsResult<Value> {
12363 // The hot arm first: `i < n` with both sides already integers. No conversion, no
12364 // call, nothing that can throw.
12365 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12366 let ordering = Some(left.cmp(right));
12367 return Ok(ordering_answer(op, ordering));
12368 }
12369 // Anything that can run script has to be converted first, in this order.
12370 let (left, right) = if matches!(left, Value::Object(_)) || matches!(right, Value::Object(_))
12371 {
12372 (
12373 self.to_primitive(left, Hint::Number)?,
12374 self.to_primitive(right, Hint::Number)?,
12375 )
12376 } else {
12377 (left, right)
12378 };
12379 let ordering = match (&left, &right) {
12380 // The loop condition `i < n` is integer against integer, and it runs once
12381 // per iteration of every loop in every program. Without this arm it took the
12382 // `to_number` path twice, which is a `match` plus a conversion each.
12383 (Value::Int(a), Value::Int(b)) => Some(a.cmp(b)),
12384 (Value::String(a), Value::String(b)) => {
12385 Some(a.to_string_lossy().cmp(&b.to_string_lossy()))
12386 }
12387 (Value::BigInt(a), Value::BigInt(b)) => Some(a.cmp(b)),
12388 // A bigint against a number compares the *mathematical* values, so `2n < 2.5`
12389 // is true even though `2.5` has no bigint form.
12390 (Value::BigInt(a), other) if !matches!(other, Value::BigInt(_)) => {
12391 let b = other.to_number();
12392 if b.is_nan() {
12393 None
12394 } else {
12395 compare_bigint_and_f64(a, b)
12396 }
12397 }
12398 (other, Value::BigInt(b)) if !matches!(other, Value::BigInt(_)) => {
12399 let a = other.to_number();
12400 if a.is_nan() {
12401 None
12402 } else {
12403 compare_bigint_and_f64(b, a).map(std::cmp::Ordering::reverse)
12404 }
12405 }
12406 // `ToNumeric` on the pair, which refuses a Symbol rather than answering `NaN`:
12407 // `Object(Symbol()) <= ""` is a `TypeError`, and the total `to_number` made it
12408 // `false` (`Symbol/prototype/Symbol.toPrimitive/…-ordinary-toprimitive`).
12409 _ => self
12410 .to_js_number(&left)?
12411 .partial_cmp(&self.to_js_number(&right)?),
12412 };
12413 Ok(ordering_answer(op, ordering))
12414 }
12415
12416 fn binary_add(&mut self) -> JsResult<()> {
12417 let right = self.pop();
12418 let left = self.pop();
12419 // Two integers add without any of the machinery below: no `ToPrimitive` (an
12420 // `Int` is already primitive), no string check, no bigint check, no allocation.
12421 // `x += 1` in a loop is the single most common instruction sequence in real
12422 // script, and it used to walk every one of those checks before reaching the
12423 // same `checked_add`.
12424 if let (Value::Int(left), Value::Int(right)) = (&left, &right) {
12425 self.push(add_numbers(Value::Int(*left), Value::Int(*right)));
12426 return Ok(());
12427 }
12428 let left = self.primitive_of(left)?;
12429 let right = self.primitive_of(right)?;
12430 // `+` concatenates when either operand is a string *after* `ToPrimitive`, and
12431 // that check comes before the bigint one: `"" + 1n` is a string, not a
12432 // mixed-type error.
12433 if matches!(left, Value::String(_)) || matches!(right, Value::String(_)) {
12434 // `ToString` on both sides, which rejects a symbol: `"" + Symbol()` is a
12435 // `TypeError`, the one place a symbol and a string do not mix.
12436 // Keep the operands as strings rather than as bytes: `JsString::concat` decides
12437 // between a copy and a rope from their lengths, and a rope is what turns
12438 // `text += "abc"` in a loop from quadratic into linear.
12439 if let (Value::String(left), Value::String(right)) = (&left, &right) {
12440 // `None` is the length ceiling (`JS_STRING_LEN_MAX`), which the reference
12441 // reports as `InternalError: string too long`.
12442 let Some(joined) = crate::value::JsString::concat(self.heap, left, right) else {
12443 return Err(Signal::Throw(
12444 self.make_error("InternalError", "string too long"),
12445 ));
12446 };
12447 self.push(Value::String(Gc::new(self.heap, joined)));
12448 return Ok(());
12449 }
12450 // At least one operand was not a string, so `ToString` it. This rejects a
12451 // symbol, which is the one place a symbol and a string do not mix.
12452 let left = self.checked_to_wtf8(&left)?;
12453 let right = self.checked_to_wtf8(&right)?;
12454 // Not `format!`: `Wtf8::concat` is what keeps a surrogate pair split across the
12455 // join canonical, so `"\uD800" + "\uDC00"` equals `"\u{10000}"`.
12456 let text = left.concat(&right);
12457 self.push(self.string_wtf8(text));
12458 return Ok(());
12459 }
12460 // The two numeric types never mix, and `+` is no exception: `1n + 1` is an error,
12461 // not a conversion.
12462 if matches!(left, Value::BigInt(_)) || matches!(right, Value::BigInt(_)) {
12463 let value = self.bigint_arithmetic(Opcode::Add, left, right)?;
12464 self.push(value);
12465 return Ok(());
12466 }
12467 let left = self.numeric(left)?;
12468 let right = self.numeric(right)?;
12469 self.push(add_numbers(left, right));
12470 Ok(())
12471 }
12472
12473 fn primitive_of(&mut self, value: Value) -> JsResult<Value> {
12474 self.to_primitive(value, Hint::Default)
12475 }
12476
12477 /// `ToPrimitive`, which is what makes `"" + obj` produce `obj.toString()`.
12478 ///
12479 /// The order depends on the hint: the "number" order tries `valueOf` first and
12480 /// `toString` second, the "string" order the other way round, and the default
12481 /// hint uses the number order. A result that is still an object is a `TypeError`,
12482 /// because no built-in `valueOf`/`toString` returns one.
12483 pub fn to_primitive(&mut self, value: Value, hint: Hint) -> JsResult<Value> {
12484 let Value::Object(object) = &value else {
12485 return Ok(value);
12486 };
12487 // A Date overrides the default hint to mean "string", which is what
12488 // `Date.prototype[Symbol.toPrimitive]` does with hint `"default"`. Without
12489 // this, `"" + new Date()` would print the milliseconds, not the date.
12490 let hint = if hint == Hint::Default && is_date_object(self, object) {
12491 Hint::String
12492 } else {
12493 hint
12494 };
12495 // `Symbol.toPrimitive` wins over `valueOf`/`toString` when it exists, and it is
12496 // handed the hint as a string. This is the hook a Date uses for its default hint
12497 // and a script uses to take over conversion entirely.
12498 let key = self.realm.well_known_key(WellKnown::ToPrimitive);
12499 // `GetMethod`, not "is it a callable object": the property has to be read and then
12500 // checked, in that order. Matching `Some(Value::Object(function))` instead skipped
12501 // every non-object `@@toPrimitive` outright, so `{ [Symbol.toPrimitive]: 1 }`
12502 // converted as if it had no hook at all — `"" + o` gave `"[object Object]"` where
12503 // the spec (and the reference) raise a `TypeError`. `undefined` and `null` mean
12504 // "no hook" and fall through to `OrdinaryToPrimitive`; anything else must be
12505 // callable.
12506 match self.get_property_key(object, &key)? {
12507 None | Some(Value::Undefined) | Some(Value::Null) => {}
12508 Some(Value::Object(function)) if function.is_callable() => {
12509 let hint = match hint {
12510 Hint::String => "string",
12511 Hint::Number => "number",
12512 Hint::Default => "default",
12513 };
12514 let hint = self.string(hint);
12515 let result = self.call_value(
12516 Value::Object(function),
12517 Value::Object(object.clone()),
12518 vec![hint],
12519 )?;
12520 if !matches!(result, Value::Object(_)) {
12521 return Ok(result);
12522 }
12523 return Err(self.type_error("Symbol.toPrimitive must return a primitive"));
12524 }
12525 Some(_) => return Err(self.type_error("Symbol.toPrimitive is not a function")),
12526 }
12527 let order: [&str; 2] = match hint {
12528 Hint::String => ["toString", "valueOf"],
12529 Hint::Number | Hint::Default => ["valueOf", "toString"],
12530 };
12531 let receiver = object.clone();
12532 for method in order {
12533 if let Some(function) = self.get_property(&receiver, method)?
12534 && matches!(&function, Value::Object(object) if object.is_callable())
12535 {
12536 let result =
12537 self.call_value(function, Value::Object(receiver.clone()), Vec::new())?;
12538 if !matches!(result, Value::Object(_)) {
12539 return Ok(result);
12540 }
12541 }
12542 }
12543 Err(self.type_error("cannot convert object to primitive value"))
12544 }
12545
12546 /// `ToString` with the object case going through `ToPrimitive`.
12547 pub fn to_js_string(&mut self, value: &Value) -> JsResult<String> {
12548 if matches!(value, Value::Object(_)) {
12549 let primitive = self.to_primitive(value.clone(), Hint::String)?;
12550 return Ok(primitive.to_js_string());
12551 }
12552 // `Value::to_js_string` renders a symbol as `"Symbol(desc)"`, which is what
12553 // `String(sym)` and `sym.toString()` need. The spec's `ToString` raises instead, so
12554 // callers that want that strictness call [`Interp::to_string_strict`] — putting the
12555 // check here broke `String(Symbol())` and 45 cases that print a symbol.
12556 Ok(value.to_js_string())
12557 }
12558
12559 /// `ToString(value)`, with §7.1.19's symbol refusal.
12560 ///
12561 /// Every `ToString` in a function signature means this one: `"a".includes(Symbol())` is
12562 /// a `TypeError` even though `String(Symbol())` is not. The two are genuinely different
12563 /// operations and conflating them cost 45 cases in one direction and 6 in the other.
12564 pub fn to_string_strict(&mut self, value: &Value) -> JsResult<String> {
12565 if matches!(value, Value::Symbol(_)) {
12566 return Err(self.type_error("cannot convert a Symbol to a string"));
12567 }
12568 if matches!(value, Value::Object(_)) {
12569 let primitive = self.to_primitive(value.clone(), Hint::String)?;
12570 if matches!(primitive, Value::Symbol(_)) {
12571 return Err(self.type_error("cannot convert a Symbol to a string"));
12572 }
12573 return Ok(primitive.to_js_string());
12574 }
12575 Ok(value.to_js_string())
12576 }
12577
12578 /// `ToString` that keeps the string's code units instead of flattening them.
12579 ///
12580 /// This is what `+` needs: `String.fromCharCode(0xD800) + "a"` must keep the unpaired
12581 /// surrogate, and a lossy `String` in between would turn it into U+FFFD.
12582 pub fn checked_to_wtf8(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12583 if matches!(value, Value::Symbol(_)) {
12584 return Err(Signal::Throw(
12585 self.make_error("TypeError", "cannot convert symbol to string"),
12586 ));
12587 }
12588 // An object runs `ToPrimitive` first, which may itself produce a symbol.
12589 let value = self.to_primitive(value.clone(), Hint::String)?;
12590 match value {
12591 Value::Symbol(_) => Err(Signal::Throw(
12592 self.make_error("TypeError", "cannot convert symbol to string"),
12593 )),
12594 Value::String(text) => Ok(text.wtf8().clone()),
12595 other => Ok(crate::value::Wtf8::new(other.to_js_string())),
12596 }
12597 }
12598
12599 /// `ToNumber` with the object case going through `ToPrimitive`.
12600 pub fn to_js_number(&mut self, value: &Value) -> JsResult<f64> {
12601 let value = if matches!(value, Value::Object(_)) {
12602 self.to_primitive(value.clone(), Hint::Number)?
12603 } else {
12604 value.clone()
12605 };
12606 // `ToNumber` refuses a BigInt: there is no lossless number for a 2^70 integer, so
12607 // the spec makes this a `TypeError` rather than `NaN`. `Value::to_number` answers
12608 // `NaN` to stay total, and the operators check for the bigint themselves — but
12609 // `Math.max(1n)`, `new Int32Array(1n)` and every other `ToNumber` caller needs to
12610 // refuse, and answering `NaN` made them silently wrong instead.
12611 // Both are checked *after* `ToPrimitive`, so a boxed Symbol or BigInt is refused
12612 // too: `ToNumber(Object(Symbol()))` unwraps to the symbol and then fails.
12613 match value {
12614 Value::BigInt(_) => Err(self.type_error("cannot convert bigint to number")),
12615 Value::Symbol(_) => Err(self.type_error("cannot convert symbol to number")),
12616 other => Ok(other.to_number()),
12617 }
12618 }
12619
12620 /// `ToNumber` or `ToBigInt`, whichever `element` stores, as a primitive ready for
12621 /// [`ElementType::write`].
12622 ///
12623 /// This is separated from the write because both conversions are observable script —
12624 /// `ToPrimitive` calls `valueOf` — and a conversion that runs script must not happen
12625 /// with a buffer's `RefCell` borrowed. Every element-write path calls this first:
12626 /// the constructor's initialiser list, `fill`/`set`/`sort`'s write-back, `DataView`'s
12627 /// setters, and a plain `a[i] = v`.
12628 pub(crate) fn element_value(
12629 &mut self,
12630 element: crate::builtins::typedarray::ElementType,
12631 value: Value,
12632 ) -> JsResult<Value> {
12633 // `ToPrimitive` with the number hint, which is what turns `{valueOf(){return 5}}`
12634 // into `5` and `{valueOf(){return 1n}}` into a BigInt. A primitive passes through.
12635 let primitive = match &value {
12636 Value::Object(_) => self.to_primitive(value, Hint::Number)?,
12637 _ => value,
12638 };
12639 if element.is_bigint() {
12640 let big = crate::builtins::bigint::to_bigint(self, &primitive)?;
12641 Ok(Value::BigInt(Gc::new(self.heap, big)))
12642 } else {
12643 // `ToNumber` refuses a BigInt and a Symbol rather than answering `NaN`.
12644 Ok(Value::Float(self.to_js_number(&primitive)?))
12645 }
12646 }
12647
12648 /// `ToPropertyKey`: what a computed member access uses as its key.
12649 ///
12650 /// A symbol is returned as itself, never stringified — that is what keeps
12651 /// `o[sym]` and `o["Symbol(a)"]` apart. Everything else becomes its string form.
12652 pub fn propkey(&mut self, value: &Value) -> JsResult<PropertyKey> {
12653 match value {
12654 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol.clone())),
12655 // An object key runs `ToPropertyKey`, which is `ToPrimitive` *then* a symbol
12656 // check: a wrapper whose `toString` answers a symbol makes a symbol key, not
12657 // the string `"Symbol()"`. Going through `propkey_of` here would stringify it.
12658 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12659 Value::Symbol(symbol) => Ok(PropertyKey::Symbol(symbol)),
12660 Value::String(text) => Ok(PropertyKey::String(text.wtf8().clone())),
12661 other => Ok(PropertyKey::String(crate::value::Wtf8::new(
12662 other.to_js_string(),
12663 ))),
12664 },
12665 _ => Ok(PropertyKey::String(self.propkey_of(value)?)),
12666 }
12667 }
12668
12669 /// `ToPropertyKey` for the callers that can only use a string key.
12670 ///
12671 /// Fallible on purpose: an object key runs `ToPrimitive`, and that can throw —
12672 /// `{ toString(){ throw new Error('ts') } }` used as a template substitution is a
12673 /// throw, not `[object Object]`. Swallowing it made `` `${o}` `` report the string
12674 /// `[object Object]` and carry on, which is the worst kind of wrong answer: the
12675 /// program continues with a value nobody asked for.
12676 fn propkey_of(&mut self, value: &Value) -> JsResult<crate::value::Wtf8> {
12677 use crate::value::Wtf8;
12678 Ok(match value {
12679 // A string key keeps its code units. Going through a lossy `String` would make
12680 // `o["\uD800"]` and `o["\uFFFD"]` the same property.
12681 Value::String(text) => text.wtf8().clone(),
12682 Value::Int(_) | Value::Float(_) => Wtf8::new(number_to_string(value.to_number())),
12683 // An object key runs `ToPropertyKey`, which needs `ToPrimitive` first;
12684 // falling back to its `ToString` would print `[object Object]`.
12685 Value::Object(_) => match self.to_primitive(value.clone(), Hint::String)? {
12686 Value::String(text) => text.wtf8().clone(),
12687 other => Wtf8::new(other.to_js_string()),
12688 },
12689 other => Wtf8::new(other.to_js_string()),
12690 })
12691 }
12692
12693 // -- object operations used by instructions -----------------------------
12694
12695 /// Read `object[key]`, returning `undefined` when the property is missing.
12696 ///
12697 /// Unlike [`Interp::get_property`] this takes a runtime `Value`, so it works on a
12698 /// primitive (looking through its prototype) as well as an object — which is what
12699 /// `get_field`/`get_array_el` need and what a builtin reading a property off an
12700 /// argument needs too.
12701 pub fn read_field(&mut self, object: &Value, key: &str) -> JsResult<Value> {
12702 self.read_field_key(object, &PropertyKey::from(key))
12703 }
12704
12705 /// [`Interp::read_field`] with a key that may be a symbol.
12706 ///
12707 /// A symbol key never reaches the string shortcuts: a string's `length` and its
12708 /// indices are string properties, and a symbol named `length` is a different
12709 /// property that a string primitive cannot have.
12710 /// [`Interp::read_field_key`], with an inline cache in front of it.
12711 ///
12712 /// Caches own *data* properties and — since the sixth step of M12b — prototype hits,
12713 /// which is the case every method call takes: `a.push` lives on `Array.prototype`, so
12714 /// without this the engine walked the chain and compared ~40 property names on each
12715 /// iteration of `for (i…) a.push(i)` (measured at 100 ns per call over an empty loop).
12716 ///
12717 /// Still never cached: a getter, a proxy, a string primitive, an array index, and a
12718 /// missing property. Those answers depend on running code or on state the guard below
12719 /// does not cover, and a wrong answer here is far more expensive than a lookup.
12720 ///
12721 /// A hit is re-validated against the *whole* walked chain, not just the level that
12722 /// answered: the receiver and every prototype down to that level must still be the same
12723 /// object (weakly, so a collected and reallocated object is a miss) with unchanged
12724 /// property-table *lengths* — which is what catches a property appearing on an
12725 /// intermediate prototype and shadowing the cached one.
12726 pub fn read_field_cached(
12727 &mut self,
12728 object: &Value,
12729 key: &PropertyKey,
12730 slot: usize,
12731 ) -> JsResult<Value> {
12732 let index = Self::field_cache_slot(object, key, slot);
12733 let Value::Object(target) = object else {
12734 return self.read_field_key(object, key);
12735 };
12736 if target.proxy_state().is_some() {
12737 return self.read_field_key(object, key);
12738 }
12739 if let Some(cached) = &self.field_cache[index]
12740 && cached.key == *key
12741 && let Some(value) = Self::cached_hit(target, cached)
12742 {
12743 return Ok(value);
12744 }
12745 let value = self.read_field_key(object, key)?;
12746 self.field_cache[index] = Self::record_field_lookup(target, key, value.clone());
12747 Ok(value)
12748 }
12749
12750 /// Whether a cache entry still describes this lookup, and if so the value.
12751 ///
12752 /// The guard is the whole point of the entry: identity plus property-table length for
12753 /// every level walked. Re-checked per level rather than once at the receiving end,
12754 /// because a shadowing property can appear anywhere along the chain.
12755 fn cached_hit(target: &Gc<JsObject>, cached: &FieldCache) -> Option<Value> {
12756 // Level 0 — the receiver itself answered — without the `Gc` clone this loop
12757 // starts with: a clone is a reference-count bump and a drop, and for
12758 // `property:monomorphic` every single hit takes only this arm.
12759 let (weak, len) = cached.chain[0].as_ref()?;
12760 if !target.upgrades_to(weak) {
12761 return None;
12762 }
12763 if cached.level == 0 {
12764 // Length and key and accessor-ness in one borrow: see `cached_property_at`.
12765 return target.cached_property_at(cached.index, &cached.key, *len);
12766 }
12767 if target.props_len() != *len {
12768 return None;
12769 }
12770 let mut level = 1;
12771 let mut current = target.proto()?;
12772 loop {
12773 let (weak, len) = cached.chain[level].as_ref()?;
12774 if !current.upgrades_to(weak) || current.props_len() != *len {
12775 return None;
12776 }
12777 if level == cached.level as usize {
12778 // The level that answered: the value is only reusable while the key is
12779 // still there and still a plain data property.
12780 return current.cached_data_property(cached.index, &cached.key);
12781 }
12782 current = current.proto()?;
12783 level += 1;
12784 }
12785 }
12786
12787 /// Build a cache entry for a lookup that just went through the slow path.
12788 ///
12789 /// Records the chain only when the answer came from a plain data property at a level
12790 /// the fixed-size array can hold; everything else simply leaves the slot empty, which
12791 /// costs the next lookup the walk it would have cost anyway.
12792 fn record_field_lookup(
12793 target: &Gc<JsObject>,
12794 key: &PropertyKey,
12795 _value: Value,
12796 ) -> Option<FieldCache> {
12797 let mut chain: [Option<(js_gc::WeakGc<JsObject>, usize)>; MAX_CACHED_CHAIN] =
12798 [None, None, None];
12799 let mut current = target.clone();
12800 for level in 0..MAX_CACHED_CHAIN {
12801 chain[level] = Some((current.downgrade(), current.props_len()));
12802 if let Some((found, _)) = current.own_property_index(key) {
12803 // `own_property_index` declines an accessor and a hole, which is exactly
12804 // the set that must not be cached.
12805 return Some(FieldCache {
12806 key: key.clone(),
12807 index: found,
12808 level: level as u8,
12809 chain,
12810 });
12811 }
12812 current = current.proto()?;
12813 }
12814 None
12815 }
12816
12817 /// Which cache slot a lookup uses.
12818 ///
12819 /// Mixes the object's address, the name and the site, so that two properties of one
12820 /// object, and one property of two objects, land in different slots — which is what lets
12821 /// a *polymorphic* site hold both of its shapes at once instead of evicting itself every
12822 /// other iteration.
12823 fn field_cache_slot(object: &Value, key: &PropertyKey, site: usize) -> usize {
12824 let mut hash = match object {
12825 Value::Object(object) => object.address(),
12826 _ => 0,
12827 };
12828 hash = hash
12829 .wrapping_mul(0x9e37_79b9_7f4a_7c15)
12830 .rotate_left(17)
12831 .wrapping_add(key.hash_code());
12832 hash = hash.wrapping_add(site.wrapping_mul(31));
12833 // The table is a power of two, so the low bits are the slot.
12834 hash & (FIELD_CACHE_SLOTS - 1)
12835 }
12836
12837 /// Read `key` from `object`, without the inline cache.
12838 ///
12839 /// Use [`Interp::read_field_cached`] from an opcode handler: this one always walks the
12840 /// prototype chain, while the cached form answers an own data property from memory.
12841 pub fn read_field_key(&mut self, object: &Value, key: &PropertyKey) -> JsResult<Value> {
12842 let text = key.as_str().unwrap_or("");
12843 let Value::Object(object) = object else {
12844 // Reading a property of `undefined`/`null` is the classic TypeError.
12845 if object.is_nullish() {
12846 return Err(Signal::Throw(self.make_error(
12847 "TypeError",
12848 &format!("cannot read property '{key}' of {}", object.to_js_string()),
12849 )));
12850 }
12851 // A string has `length` and index access without being boxed.
12852 if let Value::String(value) = object {
12853 if text == "length" {
12854 return Ok(Value::Int(value.utf16_len() as i32));
12855 }
12856 if let Some(index) = array_index(text) {
12857 return Ok(match value.wtf8().unit_at(index as usize) {
12858 Some(unit) => self.string_wtf8(unit),
12859 None => Value::Undefined,
12860 });
12861 }
12862 }
12863 // A property of a primitive is looked up on its prototype: this is what
12864 // makes `"a".toUpperCase()` reach `String.prototype` without boxing.
12865 let prototype = match object {
12866 Value::String(_) => self.realm.string_proto.clone(),
12867 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
12868 Value::Bool(_) => self.realm.boolean_proto.clone(),
12869 // A symbol's methods live on `Symbol.prototype`, reached the same way —
12870 // `sym.description` reads through the prototype, not off the symbol.
12871 Value::Symbol(_) => self.realm.symbol_proto.clone(),
12872 // …and a bigint's on `BigInt.prototype`, which is how
12873 // `(255n).toString(16)` reaches its method.
12874 Value::BigInt(_) => self.realm.bigint_proto.clone(),
12875 _ => None,
12876 };
12877 if let Some(prototype) = prototype
12878 && let Some(value) = self.get_property_key_for(&prototype, Some(object), key)?
12879 {
12880 return Ok(value);
12881 }
12882 return Ok(Value::Undefined);
12883 };
12884 Ok(self
12885 .get_property_key(object, key)?
12886 .unwrap_or(Value::Undefined))
12887 }
12888
12889 /// The `#name` a private symbol stands for, for error messages.
12890 ///
12891 /// The reference reports `#x` (with the `#`), and formats it through the atom the symbol
12892 /// was made from.
12893 fn private_name(symbol: &Value) -> Option<String> {
12894 match symbol {
12895 Value::Symbol(symbol) if symbol.is_private() => Some(
12896 symbol
12897 .description()
12898 .map(|text| text.to_string())
12899 .unwrap_or_default(),
12900 ),
12901 _ => None,
12902 }
12903 }
12904
12905 /// Resolve the private-key operand to a [`PropertyKey`], or reject it.
12906 ///
12907 /// Every private-field opcode takes the symbol the class stored in its own scope; a
12908 /// non-symbol here would be a compiler bug, and the reference guards it with
12909 /// `JS_ThrowTypeErrorNotASymbol`.
12910 fn private_key(&mut self, symbol: &Value) -> JsResult<PropertyKey> {
12911 match symbol {
12912 Value::Symbol(symbol) if symbol.is_private() => Ok(PropertyKey::Symbol(symbol.clone())),
12913 _ => Err(Signal::Throw(self.make_error("TypeError", "not a symbol"))),
12914 }
12915 }
12916
12917 /// `JS_DefinePrivateField`: `obj.#name = value` from a field initialiser.
12918 ///
12919 /// Three early errors, all from the reference: a non-object receiver, a non-extensible
12920 /// one, and a field that already exists — the last is what `class C { #x = 1; #x = 2 }`
12921 /// would hit if the parser did not reject it first.
12922 fn define_private_field(
12923 &mut self,
12924 object: &Value,
12925 symbol: &Value,
12926 value: Value,
12927 ) -> JsResult<()> {
12928 let key = self.private_key(symbol)?;
12929 let Some(target) = object.as_object() else {
12930 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12931 };
12932 if !target.is_extensible() {
12933 return Err(Signal::Throw(
12934 self.make_error("TypeError", "object is not extensible"),
12935 ));
12936 }
12937 if target.own_property_key(&key).is_some() {
12938 let name = Self::private_name(symbol).unwrap_or_default();
12939 return Err(Signal::Throw(self.make_error(
12940 "TypeError",
12941 &format!("private class field '{name}' already exists"),
12942 )));
12943 }
12944 target.define_data_key(&key, value);
12945 Ok(())
12946 }
12947
12948 /// `JS_GetPrivateField`: only an own property, never the prototype chain.
12949 fn read_private_field(&mut self, object: &Value, symbol: &Value) -> JsResult<Value> {
12950 let key = self.private_key(symbol)?;
12951 let Some(target) = object.as_object() else {
12952 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12953 };
12954 match target.own_property_key(&key) {
12955 Some(property) => Ok(property.value.unwrap_or(Value::Undefined)),
12956 None => {
12957 let name = Self::private_name(symbol).unwrap_or_default();
12958 Err(Signal::Throw(self.make_error(
12959 "TypeError",
12960 &format!("private class field '{name}' does not exist"),
12961 )))
12962 }
12963 }
12964 }
12965
12966 /// `JS_SetPrivateField`: the store half of the same rule.
12967 fn write_private_field(
12968 &mut self,
12969 object: &Value,
12970 symbol: &Value,
12971 value: Value,
12972 ) -> JsResult<()> {
12973 let key = self.private_key(symbol)?;
12974 let Some(target) = object.as_object() else {
12975 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12976 };
12977 if target.write_value_key(&key, value) {
12978 return Ok(());
12979 }
12980 let name = Self::private_name(symbol).unwrap_or_default();
12981 Err(Signal::Throw(self.make_error(
12982 "TypeError",
12983 &format!("private class field '{name}' does not exist"),
12984 )))
12985 }
12986
12987 /// The `in` half: does `object` have this private field?
12988 /// `JS_AddBrand`: make `home` the owner of a brand symbol, and give that symbol to `obj`.
12989 ///
12990 /// The symbol is created once per class — the first `add_brand` on a given home object
12991 /// makes it, every later one reuses it, which is what ties the prototype, the constructor
12992 /// and each instance to one identity. `obj` being `null` is not an error: the class-level
12993 /// emit for the *instance* brand passes null because all it wants is the symbol.
12994 fn add_brand(&mut self, object: &Value, home: &Value) -> JsResult<()> {
12995 let Some(home_object) = home.as_object() else {
12996 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
12997 };
12998 let symbol = match home_object.private_brand() {
12999 Some(symbol) => symbol,
13000 None => {
13001 let symbol = Gc::new(
13002 self.heap,
13003 crate::value::JsSymbol::new_private(BRAND_DESCRIPTION),
13004 );
13005 home_object.set_private_brand(symbol.clone());
13006 symbol
13007 }
13008 };
13009 let Some(target) = object.as_object() else {
13010 // Not an object: nothing to brand. The reference does the same, and `undefined`
13011 // here would otherwise turn a field initialiser into a TypeError.
13012 return Ok(());
13013 };
13014 if !target.is_extensible() {
13015 return Err(Signal::Throw(
13016 self.make_error("TypeError", "object is not extensible"),
13017 ));
13018 }
13019 if target.carries_brand(&symbol) {
13020 return Err(Signal::Throw(
13021 self.make_error("TypeError", "private method is already present"),
13022 ));
13023 }
13024 target.add_brand(symbol);
13025 Ok(())
13026 }
13027
13028 /// `JS_CheckBrand`: does `object` carry the brand of `function`'s home object?
13029 ///
13030 /// A `false` answer is not an exception — `#m in o` reports it as a value — so the caller
13031 /// decides whether to throw.
13032 fn check_brand(&mut self, object: &Gc<JsObject>, function: &Value) -> JsResult<bool> {
13033 let Some(function) = function.as_object() else {
13034 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13035 };
13036 let Some(home) = function.home_object() else {
13037 return Err(Signal::Throw(self.make_error("TypeError", "not an object")));
13038 };
13039 let Some(brand) = home.private_brand() else {
13040 return Err(Signal::Throw(
13041 self.make_error("TypeError", "expecting <brand> private field"),
13042 ));
13043 };
13044 Ok(object.carries_brand(&brand))
13045 }
13046
13047 fn write_field_key(&mut self, object: &Value, key: &PropertyKey, value: Value) -> JsResult<()> {
13048 let Value::Object(object) = object else {
13049 // `PutValue` on a property of a primitive is a silent no-op in sloppy mode and a
13050 // `TypeError` in strict mode: `sym.a = 1` on a Symbol must leave `sym.a`
13051 // `undefined` rather than throwing (`Symbol/auto-boxing-non-strict`). `null` and
13052 // `undefined` still throw, with their own message.
13053 if !self.current_strict() && !matches!(object, Value::Null | Value::Undefined) {
13054 return Ok(());
13055 }
13056 return Err(Signal::Throw(self.make_error(
13057 "TypeError",
13058 &format!("cannot set property '{key}' of {}", object.to_js_string()),
13059 )));
13060 };
13061 // The write half of the property inline cache, in effect: an own, writable,
13062 // non-accessor data property already holds this key, so `[[Set]]` has nothing to
13063 // decide — no prototype walk (an own property shadows the chain before a setter
13064 // there could matter), no extensibility check (the object already has the key),
13065 // and no `[[DefineOwnProperty]]`.
13066 //
13067 // `this.value = …` inside a method is the whole write side of
13068 // `property:method-call`, and it was reaching `set_property_with_key` with its
13069 // proxy test, its typed-array test, its array-index test and finally a linear
13070 // scan — 5.3% `own_property_key` plus the `memcmp` inside it.
13071 //
13072 // Every disqualifier is checked here: a proxy traps the set, an array index and
13073 // `length` live outside the property table, and a typed array's element is stored
13074 // through its view's element type.
13075 if object.proxy_state().is_none()
13076 && !object.is_array()
13077 && object.typed_array_element_type().is_none()
13078 && object.write_value_key(key, value.clone())
13079 {
13080 return Ok(());
13081 }
13082 // `put_field`/`put_array_el` are plain assignments, so the mode decides.
13083 let on_failure = if self.frame().code.code.strict {
13084 DeleteFailure::Throw
13085 } else {
13086 DeleteFailure::Ignore
13087 };
13088 self.set_property_with_key(object, key, value, on_failure)
13089 }
13090
13091 /// `ToString`, as the spec defines it: a symbol is a `TypeError`.
13092 ///
13093 /// [`Value::to_js_string`] cannot fail, so it answers the descriptive form for a
13094 /// symbol. That is right for `String(sym)` and for error messages, and wrong for
13095 /// everything the spec routes through `ToString` — `"" + sym`, `${sym}`,
13096 /// `Number.parseInt(sym)` — so those callers use this instead.
13097 pub fn checked_to_string(&mut self, value: &Value) -> JsResult<String> {
13098 if matches!(value, Value::Symbol(_)) {
13099 return Err(Signal::Throw(
13100 self.make_error("TypeError", "cannot convert symbol to string"),
13101 ));
13102 }
13103 // An object runs `ToPrimitive` first, which may itself produce a symbol —
13104 // `({[Symbol.toPrimitive]: () => sym}) + ""` has to throw too.
13105 let value = self.to_primitive(value.clone(), Hint::String)?;
13106 if matches!(value, Value::Symbol(_)) {
13107 return Err(Signal::Throw(
13108 self.make_error("TypeError", "cannot convert symbol to string"),
13109 ));
13110 }
13111 Ok(value.to_js_string())
13112 }
13113
13114 /// `ToPropertyKey` for a builtin that takes a key argument.
13115 ///
13116 /// Fallible: a key whose `toString` throws has to propagate that error, both for
13117 /// `Reflect.get({}, {toString(){ throw 1 }})` (`return-abrupt-from-property-key`) and
13118 /// for a template substitution. This used to answer `"[object Object]"` on a throw,
13119 /// which made `` `${o}` `` and the like carry on with a value nobody asked for.
13120 pub fn property_key(&mut self, value: &Value) -> JsResult<PropertyKey> {
13121 self.propkey(value)
13122 }
13123
13124 /// `ToUint32` with `ArraySetLength`'s refusal, for an array's `length`.
13125 ///
13126 /// `ToUint32` is `ToNumber` *then* the modulo, but an object that yields a fraction or
13127 /// `NaN` falls through to `ToString` and is parsed as decimal digits. That is why
13128 /// `{toString: () => "2"}` is a legal length while `{valueOf: () => 2.5}` is a
13129 /// `RangeError` — and why this cannot be a plain `ToNumber`.
13130 /// `ToNumber(value)` for `ArraySetLength`, which the spec performs **twice**.
13131 ///
13132 /// §10.4.2.4 steps 3–5 are `ToUint32(Desc.[[Value]])`, then `ToNumber(Desc.[[Value]])`,
13133 /// then a `RangeError` when they disagree. Two conversions rather than one is
13134 /// observable: a `valueOf` that runs the first time can make `length` non-writable
13135 /// before the second, which turns the store into a refused write
13136 /// (`length/define-own-prop-length-coercion-order`, `…-set`).
13137 pub fn coerce_array_length_twice(&mut self, value: &Value) -> JsResult<u32> {
13138 let first = self.array_length_of(value)?;
13139 let second = self.array_length_of(value)?;
13140 debug_assert_eq!(first, second);
13141 Ok(first)
13142 }
13143
13144 /// `ArraySetLength`'s `ToNumber(value)`, then the `ToUint32` round-trip check.
13145 ///
13146 /// Separate from [`Interp::coerce_array_length_twice`] so the callers that need one
13147 /// conversion can say so; a caller that needs the spec's two uses that instead.
13148 pub fn array_length_of(&mut self, value: &Value) -> JsResult<u32> {
13149 let number = match value {
13150 Value::Int(number) => *number as f64,
13151 Value::Float(number) => *number,
13152 // `null`/`undefined`/`false` convert through `ToPrimitive` and then arithmetically:
13153 // `null` is 0, `false` is 0, `true` is 1. Refusing them made
13154 // `Object.defineProperty(a, "length", {value: null})` a `RangeError` where the
13155 // reference answers 0.
13156 Value::Null | Value::Bool(_) | Value::Undefined => value.to_number(),
13157 // A string goes through the full numeric-literal grammar: `"0x00B"` is 11 and
13158 // `" 5 "` is 5, which is exactly what `string_to_number` implements.
13159 Value::String(text) => crate::value::string_to_number(&text.to_string_lossy()),
13160 _ => {
13161 // The primitive comes back through this same conversion, so a wrapper of a
13162 // boolean (`new Boolean(false)`) is `0` rather than the `NaN` that
13163 // `ToNumber("false")` would give — `S15.4.5.1_A1.3_T1` walks every wrapper.
13164 let primitive = self.to_primitive(value.clone(), Hint::Number)?;
13165 return self.array_length_of(&primitive);
13166 }
13167 };
13168 // `ToUint32` of anything outside `0 ..= 2^32-1` that is still an integer is a
13169 // modulo in the spec, but `ArraySetLength` refuses it outright: `a.length = 2**32`
13170 // is a `RangeError`, not `0`.
13171 if !number.is_finite()
13172 || number.fract() != 0.0
13173 || !(0.0..=u32::MAX as f64).contains(&number)
13174 {
13175 return Err(self.range_error("invalid array length"));
13176 }
13177 Ok(number as u32)
13178 }
13179
13180 /// A [`PropertyKey`] as the `Value` a script sees — what `Reflect.ownKeys` and
13181 /// `Object.getOwnPropertySymbols` put in their result array.
13182 pub fn key_value(&self, key: &PropertyKey) -> Value {
13183 match key {
13184 PropertyKey::String(text) => self.string_wtf8(text.clone()),
13185 PropertyKey::Symbol(symbol) => Value::Symbol(symbol.clone()),
13186 }
13187 }
13188
13189 /// Fill in a String exotic object: `_value`, `length` and the index properties.
13190 ///
13191 /// `new String("ab")` used to get only `_value`, so `new String("ab").length` was
13192 /// `undefined`, `new String("ab")[0]` was `undefined`, and every `Array.prototype`
13193 /// method called on a box saw an array-like of length 0 — 36 test262 files exercise
13194 /// exactly that. `ToObject` on a *primitive* string built the indices correctly, so
13195 /// the two paths had drifted; this is the one both now use.
13196 ///
13197 /// The indices are *code units*, so an astral character occupies two of them — the
13198 /// same rule `s.length` and `s[i]` follow.
13199 /// Give an already-created object the internal slot that makes it a wrapper of
13200 /// `value`, so the primitive's prototype methods work on it.
13201 ///
13202 /// Used for `%Boolean.prototype%`, `%Number.prototype%` and `%String.prototype%`,
13203 /// which are wrappers of their own type holding the empty value.
13204 pub(crate) fn init_primitive_wrapper(&mut self, object: &Gc<JsObject>, value: Value) {
13205 self.internal_set(object, "_value", value);
13206 }
13207
13208 pub(crate) fn init_string_wrapper(
13209 &mut self,
13210 object: &Gc<JsObject>,
13211 text: &Gc<crate::value::JsString>,
13212 ) {
13213 object.define(
13214 "length",
13215 Property::with_attributes(Value::Int(text.utf16_len() as i32), false, false),
13216 );
13217 for index in 0..text.utf16_len() {
13218 if let Some(unit) = text.wtf8().unit_at(index) {
13219 object.define(
13220 &index.to_string(),
13221 // Own, non-writable, enumerable, non-configurable — §10.4.3.4.
13222 Property::with_attributes(self.string_wtf8(unit), false, true),
13223 );
13224 }
13225 }
13226 object.define_key(
13227 &self.internal_slot("_value"),
13228 Property::with_attributes(Value::String(text.clone()), false, false),
13229 );
13230 }
13231
13232 /// `ToObject`: box a primitive, refuse `undefined` and `null`.
13233 ///
13234 /// A destructuring *object* pattern starts with this, which is why `var {} = null`
13235 /// throws. The wrapper carries its primitive in `_value` — the same slot
13236 /// `new Number(x)` and friends fill in — so `valueOf` and the prototype methods work
13237 /// on a boxed value no constructor ever built.
13238 pub fn object_from(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13239 let (prototype, primitive) = match value {
13240 Value::Object(object) => return Ok(object.clone()),
13241 Value::String(text) => {
13242 let object = self.new_object(self.realm.string_proto.clone());
13243 self.init_string_wrapper(&object, text);
13244 return Ok(object);
13245 }
13246 Value::Int(_) | Value::Float(_) => (self.realm.number_proto.clone(), value.clone()),
13247 Value::Bool(_) => (self.realm.boolean_proto.clone(), value.clone()),
13248 // A symbol and a bigint box into wrappers whose methods live on
13249 // `Symbol.prototype` and `BigInt.prototype` — `Object(sym).description` and
13250 // `Object(1n).toString(2)` both go through the wrapper. Falling into the
13251 // branch below instead produced an object with *no* prototype, so those
13252 // methods were unreachable on a box.
13253 Value::Symbol(_) => (self.realm.symbol_proto.clone(), value.clone()),
13254 Value::BigInt(_) => (self.realm.bigint_proto.clone(), value.clone()),
13255 Value::Undefined | Value::Null => {
13256 return Err(Signal::Throw(self.make_error(
13257 "TypeError",
13258 &format!("cannot convert {} to object", value.to_js_string()),
13259 )));
13260 }
13261 _ => (None, value.clone()),
13262 };
13263 let object = self.new_object(prototype);
13264 self.internal_set(&object, "_value", primitive);
13265 Ok(object)
13266 }
13267
13268 /// Make `object` a wrapper of `value`, the way [`Interp::object_from`] would build one.
13269 ///
13270 /// Split out for a reader that has to create the object *before* it knows what it wraps:
13271 /// `JS_ReadObject` registers every object in the order it was written, and a wrapper is
13272 /// written before its primitive, so the placeholder has to exist first and be filled in
13273 /// afterwards. Doing it here keeps one implementation of "what makes a wrapper" rather
13274 /// than a second in the deserialiser.
13275 pub fn fill_wrapper(&mut self, object: &Gc<JsObject>, value: &Value) -> JsResult<()> {
13276 let prototype = match value {
13277 Value::String(_) => self.realm.string_proto.clone(),
13278 Value::Int(_) | Value::Float(_) => self.realm.number_proto.clone(),
13279 Value::Bool(_) => self.realm.boolean_proto.clone(),
13280 Value::Symbol(_) => self.realm.symbol_proto.clone(),
13281 Value::BigInt(_) => self.realm.bigint_proto.clone(),
13282 _ => {
13283 return Err(Signal::Throw(self.make_error(
13284 "TypeError",
13285 &format!("cannot box {}", value.to_js_string()),
13286 )));
13287 }
13288 };
13289 object.set_proto(prototype);
13290 if let Value::String(text) = value {
13291 self.init_string_wrapper(object, text);
13292 return Ok(());
13293 }
13294 self.internal_set(object, "_value", value.clone());
13295 Ok(())
13296 }
13297
13298 /// `Symbol.for(key)`: the registered symbol for `key`, created on first use.
13299 ///
13300 /// The C API's `JS_NewSymbol(ctx, description, is_global)` needs this without going
13301 /// through the `Symbol` function object, so the registry is reachable as a method rather
13302 /// than only from `builtins::symbol`.
13303 pub fn symbol_for(&mut self, key: &str) -> Value {
13304 if let Some(existing) = self.realm.symbol_registry.get(key) {
13305 return existing.clone();
13306 }
13307 let symbol = crate::builtins::symbol::symbol_value(
13308 self,
13309 crate::value::JsSymbol::registered(key.to_string()),
13310 );
13311 self.realm
13312 .symbol_registry
13313 .insert(key.to_string(), symbol.clone());
13314 symbol
13315 }
13316
13317 /// `a == b`, the coercing comparison.
13318 ///
13319 /// An object operand is converted with `ToPrimitive` *through the interpreter*,
13320 /// which is what makes `[] == ""` true: `[]` becomes `""` via
13321 /// `Array.prototype.toString`. [`Value::loose_equals`] cannot do that on its own
13322 /// because the conversion is allowed to call script code, so the two primitive
13323 /// operands are handed back to it.
13324 fn abstract_equals(&mut self, left: Value, right: Value) -> JsResult<bool> {
13325 if !matches!(left, Value::Object(_)) && !matches!(right, Value::Object(_)) {
13326 return Ok(left.loose_equals(&right));
13327 }
13328 // `null == undefined` holds even though neither is an object.
13329 if matches!(left, Value::Undefined | Value::Null)
13330 && matches!(right, Value::Undefined | Value::Null)
13331 {
13332 return Ok(true);
13333 }
13334 if matches!(left, Value::Undefined | Value::Null)
13335 || matches!(right, Value::Undefined | Value::Null)
13336 {
13337 return Ok(false);
13338 }
13339 // Two objects compare by identity. Only an object *against a primitive* is
13340 // converted, which is why `{} == {}` is false while `[] == ""` is true.
13341 if let (Value::Object(a), Value::Object(b)) = (&left, &right) {
13342 return Ok(a.ptr_eq(b));
13343 }
13344 let left = self.to_primitive(left, Hint::Default)?;
13345 let right = self.to_primitive(right, Hint::Default)?;
13346 Ok(left.loose_equals(&right))
13347 }
13348
13349 fn has_property(&mut self, key: &Value, object: &Value) -> JsResult<bool> {
13350 let Value::Object(object) = object else {
13351 return Err(Signal::Throw(
13352 self.make_error("TypeError", "cannot use 'in' on a non-object"),
13353 ));
13354 };
13355 let key = self.propkey(key)?;
13356 // `in` is `[[HasProperty]]`, over the whole chain and through a proxy's `has`
13357 // trap. One implementation, so an array's derived `length` and its inherited holes
13358 // cannot be right in one caller and wrong in another.
13359 self.has_own_or_inherited(object, &key)
13360 }
13361
13362 /// `InstanceofOperator`: `Symbol.hasInstance` first, then the ordinary walk.
13363 ///
13364 /// The C API's `JS_IsInstanceOf` must honour a `Symbol.hasInstance` override, which is the
13365 /// whole reason the operator is a hook rather than a prototype walk.
13366 pub fn instance_of_operator(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13367 if let Value::Object(function) = constructor {
13368 let key = self.realm.well_known_key(WellKnown::HasInstance);
13369 let method = self.get_property_key(function, &key)?;
13370 if let Some(method) = method
13371 && !matches!(method, Value::Undefined)
13372 {
13373 let answer = self.call_value(method, constructor.clone(), vec![object.clone()])?;
13374 return Ok(answer.to_boolean());
13375 }
13376 }
13377 self.instance_of(object, constructor)
13378 }
13379
13380 /// `OrdinaryHasInstance`: the prototype walk on its own.
13381 pub fn ordinary_instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13382 self.instance_of(object, constructor)
13383 }
13384
13385 /// `IsArray`: an array, or a proxy whose target is one.
13386 ///
13387 /// A proxy answers through `get_proxy_target` rather than through its kind, which is what
13388 /// makes `Array.isArray(new Proxy([], {}))` true.
13389 pub fn is_array_value(&self, value: &Value) -> bool {
13390 match value {
13391 Value::Object(object) => {
13392 if let Some(state) = object.proxy_state() {
13393 return state.borrow().target.as_ref().is_some_and(|t| t.is_array());
13394 }
13395 object.is_array()
13396 }
13397 _ => false,
13398 }
13399 }
13400
13401 /// Queue one microtask (`Promise` reaction ordering, `JS_EnqueueJob`).
13402 ///
13403 /// The queue holds [`Job`]s rather than closures because a job that captured its arguments
13404 /// in a Rust closure would hide GC values from the collector. A host-supplied job is
13405 /// therefore wrapped in a native function and queued with `Job::Reaction`-like semantics:
13406 /// see [`Interp::enqueue_job_function`].
13407 pub fn enqueue_job_function(&mut self, function: Value) -> JsResult<()> {
13408 // A settled, already-rejected-on-nothing promise is the carrier so that a throw out of
13409 // the handler is reported rather than lost — the same reason a `then` reaction needs a
13410 // promise to settle.
13411 let promise = self.new_promise();
13412 self.fulfill_promise(&promise, Value::Undefined);
13413 self.jobs.push_back(Job::Reaction {
13414 handler: Some(function),
13415 argument: Value::Undefined,
13416 rejected: false,
13417 promise,
13418 });
13419 Ok(())
13420 }
13421
13422 /// §10.3.1 `OrdinaryHasInstance(C, O)`, step for step.
13423 ///
13424 /// Four of its steps were missing or wrong, and each one is a test262 case in
13425 /// `Function/prototype/Symbol.hasInstance/`:
13426 ///
13427 /// * step 2 — a non-callable `C` answers `false`, not a `TypeError`;
13428 /// * step 3 — a **bound function** recurses into `[[BoundTargetFunction]]` (with
13429 /// `[[BoundThis]]` standing in for the object when that is an object), which is why
13430 /// `f.bind()[Symbol.hasInstance](x)` works at all: a bound function has no
13431 /// `prototype` of its own, so without this step the walk below gives `false`;
13432 /// * step 4 — `Get(C, "prototype")` **propagates** a throwing getter;
13433 /// * step 6 — a non-object `prototype` is a `TypeError`, not `false`.
13434 fn instance_of(&mut self, object: &Value, constructor: &Value) -> JsResult<bool> {
13435 let Value::Object(function) = constructor else {
13436 return Ok(false);
13437 };
13438 if !function.is_callable() {
13439 return Ok(false);
13440 }
13441 // Step 3: `[[BoundTargetFunction]]`. When `[[BoundThis]]` is an object it is what
13442 // the walk starts from, so `bound[Symbol.hasInstance](x)` answers for the original
13443 // `this` and not for `x` — which is the case `this-val-bound-target.js` covers.
13444 if let Some((target, this)) = function.bound_target_and_this() {
13445 let object = if this.as_object().is_some() {
13446 this
13447 } else {
13448 object.clone()
13449 };
13450 return self.instance_of(&object, &target);
13451 }
13452 let Value::Object(target) = object else {
13453 return Ok(false);
13454 };
13455 let prototype = self.get_property(function, "prototype")?;
13456 let Some(Value::Object(prototype)) = prototype else {
13457 return Err(Signal::Throw(self.make_error(
13458 "TypeError",
13459 "function has non-object prototype in instanceof check",
13460 )));
13461 };
13462 // `instanceof` walks `[[GetPrototypeOf]]`, so a proxy answers through its trap —
13463 // which is also what makes `proxyOfInstance instanceof C` work.
13464 let mut current = Some(target.clone());
13465 while let Some(object) = current {
13466 if object.ptr_eq(&prototype) {
13467 return Ok(true);
13468 }
13469 current = self.object_prototype_of(&object)?;
13470 }
13471 Ok(false)
13472 }
13473
13474 /// `[[GetPrototypeOf]]`, with the proxy trap when there is one.
13475 pub fn object_prototype_of(&mut self, object: &Gc<JsObject>) -> JsResult<Option<Gc<JsObject>>> {
13476 if let Some(proto) = self.proxy_get_prototype_of(object)? {
13477 return Ok(proto);
13478 }
13479 if let Some(exotic) = object.exotic()
13480 && let Some(proto) = exotic.get_prototype(self, object)?
13481 {
13482 return Ok(proto);
13483 }
13484 Ok(object.proto())
13485 }
13486
13487 /// `[[SetPrototypeOf]]`, with the proxy trap when there is one.
13488 pub fn object_set_prototype_of(
13489 &mut self,
13490 object: &Gc<JsObject>,
13491 proto: Option<Gc<JsObject>>,
13492 ) -> JsResult<bool> {
13493 if let Some(answer) = self.proxy_set_prototype_of(object, proto.clone())? {
13494 return Ok(answer);
13495 }
13496 if let Some(exotic) = object.exotic()
13497 && let Some(answer) = exotic.set_prototype(self, object, proto.clone())?
13498 {
13499 return Ok(answer);
13500 }
13501 // `SetImmutablePrototype`: `%Object.prototype%`'s own prototype is fixed. The
13502 // refusal is `false` rather than a throw — `Object.setPrototypeOf` turns that into
13503 // the `TypeError`, `Reflect.setPrototypeOf` returns it, and the `__proto__` setter
13504 // throws it (`Object/prototype/setPrototypeOf-with-non-circular-values`).
13505 if self
13506 .internal_get(object, "_immutable_proto")
13507 .is_some_and(|flag| flag.to_boolean())
13508 && !same_proto(object.proto().as_ref(), proto.as_ref())
13509 {
13510 return Ok(false);
13511 }
13512 // `OrdinarySetPrototypeOf` step 6: a prototype chain that loops is a `TypeError`.
13513 // Without this `Object.setPrototypeOf(o, o)` returned `true` and left the object
13514 // inheriting from itself, which every later prototype walk then had to defend
13515 // against — and `Reflect.setPrototypeOf` reported success for an operation the
13516 // language says is impossible.
13517 if let Some(proto) = &proto {
13518 let mut current = Some(proto.clone());
13519 let mut guard = 0;
13520 while let Some(node) = current {
13521 if node.ptr_eq(object) {
13522 // §10.1.2.1 step 5.a: a cycle is `return false`, not a throw —
13523 // `Object.setPrototypeOf` turns that `false` into the `TypeError`,
13524 // while `Reflect.setPrototypeOf` reports it
13525 // (`setPrototypeOf/return-false-if-target-is-prototype-of-proto`).
13526 return Ok(false);
13527 }
13528 guard += 1;
13529 if guard > 1000 {
13530 break;
13531 }
13532 current = node.proto();
13533 }
13534 }
13535 // `OrdinarySetPrototypeOf` step 2: a non-extensible object's prototype is fixed, and
13536 // re-setting it to the *same* one is a no-op `true`. Missing this made
13537 // `Reflect.setPrototypeOf(Object.preventExtensions({}), null)` answer `true` and
13538 // actually reparent the object — and it is what
13539 // `Proxy/setPrototypeOf/trap-is-undefined-target-is-proxy` trips over, because the
13540 // forwarding path has nothing else left to refuse it.
13541 if !object.is_extensible() && !same_proto(object.proto().as_ref(), proto.as_ref()) {
13542 return Ok(false);
13543 }
13544 object.set_proto(proto);
13545 Ok(true)
13546 }
13547
13548 /// `[[HasProperty]]` by key: whether `object` or its prototype chain has `key`.
13549 ///
13550 /// The C API's `JS_HasProperty` needs this without going through a `Value` key, which is
13551 /// what `has_property` takes — and going through that would `ToPropertyKey` a key that is
13552 /// already one.
13553 /// `HasProperty(O, P)`.
13554 ///
13555 /// One implementation, shared with the `in` operator. It used to be a second copy that
13556 /// walked the chain with `[[GetOwnProperty]]` — which answers a **proxy** through its
13557 /// `getOwnPropertyDescriptor` trap instead of its `has` trap, so `HasProperty` on a
13558 /// proxy ran the wrong hook and could even disagree with `in`. The
13559 /// `length-exceeding-integer-limit-with-proxy` cases read the trap log back and saw
13560 /// `GetOwnPropertyDescriptor:0` where the spec asks for `Has:0`.
13561 pub fn has_property_key(&mut self, object: &Gc<JsObject>, key: &PropertyKey) -> JsResult<bool> {
13562 self.has_own_or_inherited(object, key)
13563 }
13564
13565 /// `[[Set]]` with an explicit receiver, which is what a C caller's `this_obj` is.
13566 ///
13567 /// Answers whether the store was accepted. The plain [`Interp::set_property_with_key`]
13568 /// reports a refusal as an error or a no-op depending on `on_failure`; the C API needs the
13569 /// boolean as well, and it needs the receiver to be the one the caller named.
13570 pub fn set_property_with_key_receiver(
13571 &mut self,
13572 object: &Gc<JsObject>,
13573 key: &PropertyKey,
13574 value: Value,
13575 receiver: Option<&Value>,
13576 on_failure: DeleteFailure,
13577 ) -> JsResult<bool> {
13578 let receiver = receiver
13579 .cloned()
13580 .unwrap_or_else(|| Value::Object(object.clone()));
13581 if object.proxy_state().is_some() {
13582 return match self.proxy_set(object, key, value, &receiver)? {
13583 Some(accepted) => Ok(accepted),
13584 None => Ok(true),
13585 };
13586 }
13587 // §10.4.5.5 step 1.b: a canonical numeric index on an integer-indexed exotic object
13588 // never reaches `OrdinarySet`, so a setter anywhere on the chain — including
13589 // `Object.defineProperty(%TypedArray%.prototype, "0", {set})` — must not run.
13590 // `Set/indexed-value` asserts exactly that by installing a throwing setter there.
13591 //
13592 // The three sub-cases are the whole of `key-is-valid-index-*` and friends:
13593 //
13594 // * `SameValue(O, Receiver)` stores into the buffer, converting first;
13595 // * an *invalid* index with a different receiver answers `true` and does nothing,
13596 // not even converting `V` (`valueOfCalls` stays 0);
13597 // * a valid index with a different receiver falls through to
13598 // `OrdinarySetWithOwnDescriptor` with the element's own descriptor — so the
13599 // value lands on the **receiver**, unconverted, and can be refused by a
13600 // non-extensible receiver, an accessor, or a read-only index there.
13601 //
13602 // The last one used to write into the view itself, which left `target[0]` changed
13603 // and `receiver[0]` untouched — backwards.
13604 if object.typed_array_element_type().is_some()
13605 && let Some(numeric) = canonical_numeric_index(key)
13606 {
13607 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13608 if same {
13609 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13610 return Ok(true);
13611 }
13612 if !typed_array_index_is_valid(object, numeric) {
13613 return Ok(true);
13614 }
13615 let Some(receiver) = receiver.as_object().cloned() else {
13616 return Ok(false);
13617 };
13618 if let Some(existing) = self.object_get_own_property(&receiver, key)? {
13619 if existing.is_accessor() || !existing.writable {
13620 return Ok(false);
13621 }
13622 let property = Property {
13623 value: Some(value),
13624 ..existing
13625 };
13626 return self.object_define_own_property(&receiver, key, property);
13627 }
13628 return self.object_define_own_property(&receiver, key, Property::data(value));
13629 }
13630 // `OrdinarySet` answers `false` where a plain assignment is a silent no-op or a
13631 // `TypeError`, and `Reflect.set` is the one caller that needs that answer:
13632 // `Set/key-is-not-numeric-index` redefines `sample.foo` as read-only and expects
13633 // `Reflect.set` to *report* the refusal instead of raising.
13634 //
13635 // A receiver that is not the object turns the whole operation into
13636 // `OrdinarySet(O, P, V, Receiver)`, whose step 2 is a *dispatch* to the prototype's
13637 // `[[Set]]` rather than a lookup — that is what makes
13638 // `Reflect.set(Object.create(view), 100, v, view)` reach the view again and convert
13639 // `V` there (`key-is-out-of-bounds-receiver-is-proto`). The plain path below always
13640 // writes to `object`, so it cannot express that and is only used when the two are
13641 // the same.
13642 let same = matches!(&receiver, Value::Object(other) if other.ptr_eq(object));
13643 if !same {
13644 return self.ordinary_set_with_receiver(object, &receiver, key, value, on_failure);
13645 }
13646 // Same receiver: the plain path below writes into `object`, which is right, but it
13647 // reports a refusal only by throwing or ignoring. `Reflect.set` asked for the
13648 // boolean, so the two step-1 refusals have to be read off the own descriptor here.
13649 if let Some(existing) = self.object_get_own_property(object, key)? {
13650 if existing.is_accessor() {
13651 return match existing.setter.filter(|v| !matches!(v, Value::Undefined)) {
13652 Some(setter) => {
13653 self.call_value(setter, receiver, vec![value])?;
13654 Ok(true)
13655 }
13656 None => Ok(false),
13657 };
13658 }
13659 if !existing.writable {
13660 return Ok(false);
13661 }
13662 }
13663 // Otherwise it is an ordinary create-or-write into `object` itself.
13664 self.set_property_with_key_receiver_aware(object, key, value, on_failure)?;
13665 Ok(true)
13666 }
13667
13668 /// `[[IsExtensible]]`, with the proxy trap when there is one.
13669 pub fn object_is_extensible(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13670 if let Some(answer) = self.proxy_is_extensible(object)? {
13671 return Ok(answer);
13672 }
13673 if let Some(exotic) = object.exotic()
13674 && let Some(answer) = exotic.is_extensible(self, object)?
13675 {
13676 return Ok(answer);
13677 }
13678 Ok(object.is_extensible())
13679 }
13680
13681 /// `[[PreventExtensions]]`, with the proxy trap when there is one.
13682 pub fn object_prevent_extensions(&mut self, object: &Gc<JsObject>) -> JsResult<bool> {
13683 if let Some(answer) = self.proxy_prevent_extensions(object)? {
13684 return Ok(answer);
13685 }
13686 // §10.4.5.3 `Integer-Indexed Exotic Objects.[[PreventExtensions]]`:
13687 //
13688 // 1. If `IsTypedArrayFixedLength(O)` is **false**, throw a `TypeError`.
13689 //
13690 // A view over a *resizable* `ArrayBuffer` is never fixed-length — even when it was
13691 // created with an explicit length, because the buffer can still move it. That is
13692 // what makes `Object.freeze` refuse every such view, including a zero-length one
13693 // (`freeze/typedarray-backed-by-resizable-buffer`), while a zero-length view over a
13694 // plain buffer is allowed.
13695 if let Some((buffer, _, _, _, _)) = object.typed_array_geometry()
13696 && buffer
13697 .array_buffer_storage()
13698 .is_some_and(|storage| storage.borrow().is_resizable())
13699 {
13700 return Err(
13701 self.type_error("cannot prevent extensions on a view over a resizable ArrayBuffer")
13702 );
13703 }
13704 if let Some(exotic) = object.exotic()
13705 && let Some(answer) = exotic.prevent_extensions(self, object)?
13706 {
13707 return Ok(answer);
13708 }
13709 object.set_extensible(false);
13710 Ok(true)
13711 }
13712
13713 fn copy_properties(
13714 &mut self,
13715 target: &Value,
13716 source: &Value,
13717 exclusion: &Value,
13718 ) -> JsResult<()> {
13719 // `CopyDataProperties` starts with `ToObject(source)`, so a *string* primitive
13720 // does contribute: its index properties are own, enumerable and writable, which
13721 // is why `{..."ab"}` is `{"0":"a","1":"b"}`. Numbers and booleans box to objects
13722 // with no own properties, so they copy nothing, and spreading `undefined`/`null`
13723 // is a no-op.
13724 let Some(target) = target.as_object() else {
13725 return Ok(());
13726 };
13727 let source_object = match source {
13728 Value::Object(object) => object.clone(),
13729 Value::String(text) => {
13730 // Untaken keys are the string's indices, which are code units.
13731 for index in 0..text.utf16_len() {
13732 if let Some(unit) = text.wtf8().unit_at(index) {
13733 target.define_data(&index.to_string(), self.string_wtf8(unit));
13734 }
13735 }
13736 return Ok(());
13737 }
13738 _ => return Ok(()),
13739 };
13740 // An object *rest* element passes the keys already taken by the literal part as
13741 // an array of strings; a spread passes `null`, which excludes nothing. Only the
13742 // string keys of the exclusion array are meaningful, so an array is read by its
13743 // elements rather than by its own property names.
13744 let mut excluded: Vec<crate::value::Wtf8> = Vec::new();
13745 if let Value::Object(list) = exclusion
13746 && let Some(length) = list.array_length()
13747 {
13748 for index in 0..length {
13749 if let Some(value) = list.array_get(index) {
13750 excluded.push(self.propkey_of(&value)?);
13751 }
13752 }
13753 }
13754 let source = &source_object;
13755 // Through `[[OwnPropertyKeys]]` and `[[Get]]`, so `{...proxy}` asks the handler.
13756 // Reading the property table directly made every spread of a proxy empty.
13757 let keys = self.object_own_property_keys(source)?;
13758 for as_key in keys {
13759 if as_key.is_symbol() {
13760 // A spread copies string-keyed properties only.
13761 continue;
13762 }
13763 if excluded.contains(&crate::value::Wtf8::new(
13764 as_key.as_str().unwrap_or_default(),
13765 )) {
13766 continue;
13767 }
13768 let enumerable = self
13769 .object_get_own_property(source, &as_key)?
13770 .is_some_and(|property| property.enumerable);
13771 if !enumerable {
13772 continue;
13773 }
13774 let value = self
13775 .get_property_key(source, &as_key)?
13776 .unwrap_or(Value::Undefined);
13777 target.define_data_key(&as_key, value);
13778 }
13779 Ok(())
13780 }
13781
13782 // -- iteration ---------------------------------------------------------
13783
13784 /// One object's own keys in enumeration order: array indices ascending, then the
13785 /// rest in insertion order.
13786 ///
13787 /// An index is ASCII, so a key with no `&str` form is never one. The flag says
13788 /// whether the key is enumerable, which the caller resolves per key because an
13789 /// array's elements are not in the same store as its named properties.
13790 fn order_own_keys(own: Vec<(crate::value::Wtf8, bool)>) -> Vec<(crate::value::Wtf8, bool)> {
13791 // An index can arrive twice, once from the array's element store and once from
13792 // its property map, so the numeric keys go through a map that keeps the
13793 // enumerable answer if either source gave one.
13794 let mut numeric: std::collections::BTreeMap<u32, bool> = std::collections::BTreeMap::new();
13795 for (key, enumerable) in &own {
13796 if let Some(index) = key.as_str().and_then(array_index) {
13797 let entry = numeric.entry(index).or_insert(false);
13798 *entry = *entry || *enumerable;
13799 }
13800 }
13801 let mut ordered: Vec<(crate::value::Wtf8, bool)> = numeric
13802 .into_iter()
13803 .map(|(index, enumerable)| (crate::value::Wtf8::new(index.to_string()), enumerable))
13804 .collect();
13805 ordered.extend(
13806 own.into_iter()
13807 .filter(|(key, _)| key.as_str().and_then(array_index).is_none()),
13808 );
13809 ordered
13810 }
13811
13812 /// Build the key list a `for-in` loop walks.
13813 ///
13814 /// The order is the specification's: own properties before inherited ones, and
13815 /// within one object the integer-like keys in ascending numeric order ahead of the
13816 /// string keys in insertion order. A shadowed key only appears once, and a key that
13817 /// is a non-enumerable own property anywhere nearer is skipped entirely.
13818 fn for_in_record(&mut self, value: &Value) -> JsResult<Gc<JsObject>> {
13819 let record = self.new_object(None);
13820 let mut keys: Vec<crate::value::Wtf8> = Vec::new();
13821 // A proxy supplies its own key list, and — the reason this is not just another
13822 // branch of the ordinary walk — *re-decides* whether each key is enumerable as
13823 // the loop goes. `record.__proxy` marks that, and `for_in_advance` re-reads the
13824 // descriptor there.
13825 if let Value::Object(object) = value
13826 && object.proxy_state().is_some()
13827 {
13828 let own = self
13829 .proxy_own_keys(object)?
13830 .unwrap_or_else(|| object.own_property_keys());
13831 let mut ordered: Vec<PropertyKey> = Vec::with_capacity(own.len());
13832 let mut numeric: Vec<u32> = Vec::new();
13833 let mut rest: Vec<PropertyKey> = Vec::new();
13834 for key in own {
13835 match key.as_str().and_then(array_index) {
13836 Some(index) => numeric.push(index),
13837 None => rest.push(key),
13838 }
13839 }
13840 numeric.sort_unstable();
13841 ordered.extend(
13842 numeric
13843 .into_iter()
13844 .map(|index| PropertyKey::from(index.to_string())),
13845 );
13846 ordered.extend(rest);
13847 for (index, key) in ordered.into_iter().enumerate() {
13848 record.define_data(&index.to_string(), self.key_value(&key));
13849 }
13850 record.define_data("__index", Value::Int(0));
13851 // The mark that makes `for_in_advance` re-ask the proxy per key.
13852 record.define_data("__proxy", Value::Object(object.clone()));
13853 return Ok(record);
13854 }
13855 if let Value::Object(object) = value {
13856 let mut chain = vec![object.clone()];
13857 chain.extend(object.chain());
13858 // Every own string key the walk has seen, enumerable or not. A
13859 // non-enumerable own property still hides a same-named enumerable one
13860 // further up the chain, so `Object.defineProperty(a, "x", {value: 1})`
13861 // keeps `x` out of the loop even when the prototype has one.
13862 let mut visited: Vec<crate::value::Wtf8> = Vec::new();
13863 for object in chain {
13864 let mut own: Vec<(crate::value::Wtf8, bool)> = object
13865 .own_property_keys()
13866 .iter()
13867 .filter_map(|key| key.as_wtf8().cloned())
13868 .map(|key| {
13869 let enumerable = object
13870 .own_property(&key.to_string_lossy())
13871 .map(|property| property.enumerable)
13872 .unwrap_or(false);
13873 (key, enumerable)
13874 })
13875 .collect();
13876 if let Some(length) = object.array_length() {
13877 own.retain(|(key, _)| key.as_str() != Some("length"));
13878 for index in 0..length {
13879 // A dense element is enumerable; a **hole** is not there at all —
13880 // and a hole is also what an index with a recorded descriptor
13881 // leaves behind, in which case the table entry above already
13882 // carries the real attributes (`defineProperties/15.2.3.7-6-a-198`
13883 // defines index 0 non-enumerable and `for…in` must skip it).
13884 if let Some(value) = object.array_get(index)
13885 && !matches!(value, Value::Hole)
13886 {
13887 own.push((crate::value::Wtf8::new(index.to_string()), true));
13888 }
13889 }
13890 }
13891 // Integer-like keys come first in ascending order, then the rest in
13892 // insertion order — and the ordering is *per object*, not for the chain
13893 // as a whole: one pass over every collected key lifted a prototype's
13894 // `"4"` above the target's own `x`/`y`, which is not the order
13895 // `for…in` reports.
13896 for (key, enumerable) in Self::order_own_keys(own) {
13897 if visited.contains(&key) {
13898 continue;
13899 }
13900 visited.push(key.clone());
13901 if enumerable {
13902 keys.push(key);
13903 }
13904 }
13905 }
13906 }
13907 for (index, key) in keys.into_iter().enumerate() {
13908 record.define_data(&index.to_string(), self.string_wtf8(key));
13909 }
13910 record.define_data("__index", Value::Int(0));
13911 Ok(record)
13912 }
13913
13914 /// The next key of a `for…in` record, `None` when the loop is done.
13915 ///
13916 /// For a proxy the descriptor is re-read on *every* step rather than filtered once up
13917 /// front: the spec's `EnumerateObjectProperties` asks `[[GetOwnProperty]]` per key as
13918 /// the loop reaches it, so a handler that stops reporting a key partway through drops
13919 /// it from the rest of the iteration. Snapshotting the list instead kept yielding a
13920 /// key the handler had already withdrawn.
13921 fn for_in_advance(&mut self, record: &Value) -> JsResult<Option<String>> {
13922 let Value::Object(record) = record else {
13923 return Ok(None);
13924 };
13925 let proxy = record
13926 .own_property("__proxy")
13927 .and_then(|property| property.value);
13928 loop {
13929 let index = record
13930 .own_property("__index")
13931 .and_then(|property| property.value)
13932 .map(|value| value.to_int32())
13933 .unwrap_or(0);
13934 let Some(candidate) = record
13935 .own_property(&index.to_string())
13936 .and_then(|property| property.value)
13937 else {
13938 return Ok(None);
13939 };
13940 record.define_data("__index", Value::Int(index + 1));
13941 let text = candidate.to_js_string();
13942 let Some(Value::Object(proxy)) = &proxy else {
13943 return Ok(Some(text));
13944 };
13945 // The candidate is already a key string here, so the lookup does not need a
13946 // second `ToPropertyKey` conversion.
13947 let key = PropertyKey::from(text.as_str());
13948 let live = match self.proxy_get_own_property(proxy, &key)? {
13949 Some(descriptor) => descriptor,
13950 // Not a proxy after all, or it lost its state: fall back to the target.
13951 None => proxy.own_property_key(&key),
13952 };
13953 if live.is_some_and(|property| property.enumerable) {
13954 return Ok(Some(text));
13955 }
13956 // Withdrawn or non-enumerable: this key is skipped, and the loop looks at the
13957 // next one.
13958 }
13959 }
13960
13961 /// The iterator for `for-of`: the object and its `next` method.
13962 ///
13963 /// An object that already carries a `next` method is used as it is — that is what
13964 /// `arr.values()` returns — and only arrays and strings get the built-in
13965 /// sequence iterator.
13966 /// Whether `value` has a callable `Symbol.iterator`, i.e. `GetMethod` succeeds.
13967 ///
13968 /// Callers that must choose between the iterable and the array-like protocol — the
13969 /// typed-array constructor is the main one — need to ask *before* committing to one.
13970 pub fn has_iterator(&mut self, value: &Value) -> JsResult<bool> {
13971 let key = self.realm.well_known_key(WellKnown::Iterator);
13972 let method = self.read_field_key(value, &key)?;
13973 if matches!(method, Value::Undefined | Value::Null) {
13974 return Ok(false);
13975 }
13976 if !matches!(&method, Value::Object(object) if object.is_callable()) {
13977 return Err(Signal::Throw(
13978 self.make_error("TypeError", "Symbol.iterator is not callable"),
13979 ));
13980 }
13981 Ok(true)
13982 }
13983
13984 /// Collect everything an iterable yields.
13985 ///
13986 /// The cap is a guard against a generator that never ends: an unbounded collect would
13987 /// be an out-of-memory abort rather than a catchable error. The spec has no such bound,
13988 /// so exceeding it is a `RangeError` — a deliberate resource limit, the same shape as
13989 /// `MAX_ARRAY_LIKE` in the `Array` builtins.
13990 pub fn collect_iterable(&mut self, value: &Value) -> JsResult<Vec<Value>> {
13991 const MAX_ITEMS: usize = 1 << 24;
13992 let iterator = self.get_iterator(value)?;
13993 let mut out = Vec::new();
13994 loop {
13995 let (element, done) = self.iterator_step(&iterator)?;
13996 if done {
13997 return Ok(out);
13998 }
13999 out.push(element);
14000 if out.len() > MAX_ITEMS {
14001 // Close before refusing: the walk is being abandoned, so the iterator's
14002 // `return` has to run (§7.4.6). Leaving it open left a `finally` block
14003 // unrun and a locked resource unreleased.
14004 self.close_iterator_after_throw(&iterator)?;
14005 return Err(self.range_error("iterable is too long to collect"));
14006 }
14007 }
14008 }
14009
14010 /// `OrdinaryCreateFromConstructor(new.target, default_proto)`.
14011 ///
14012 /// A native constructor calls this once it has validated its arguments, which is the
14013 /// order the spec uses for `Promise`, the typed arrays and `DataView`: a bad argument is
14014 /// a `TypeError` *before* `new.target.prototype` is read, so a throwing getter there is
14015 /// never reached. The prototype comes from `new.target` when it is an object, and from
14016 /// `default_proto` otherwise.
14017 pub fn new_ctor_instance(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14018 let proto = self.ctor_prototype(default_proto)?;
14019 Ok(self.new_object(Some(proto)))
14020 }
14021
14022 /// An **array** whose prototype comes from `new.target`.
14023 ///
14024 /// `class A extends Array {}` has to make `new A(3)` an `A` — the reference builds the
14025 /// instance from `new.target.prototype`, and building a plain array instead made every
14026 /// subclass lose its identity, which in turn made `ArraySpeciesCreate` useless.
14027 pub fn new_ctor_array(&mut self) -> JsResult<Gc<JsObject>> {
14028 let proto = self.ctor_prototype(self.realm.array_proto.clone())?;
14029 Ok(JsObject::array(self.heap, Some(proto), 0))
14030 }
14031
14032 /// `new.target.prototype` when this is a construction, or `None` for a plain call.
14033 ///
14034 /// The `Option` form is for the constructors that build their instance in a helper which
14035 /// also serves internal callers: `new_promise` is reached both from `new Sub(…)` and
14036 /// from `await`'s internal promise, and only the first has a `new.target`.
14037 fn ctor_prototype_opt(
14038 &mut self,
14039 default_proto: Option<Gc<JsObject>>,
14040 ) -> JsResult<Option<Gc<JsObject>>> {
14041 // `active_new_target`: by the time a native constructor runs, `call_value` has
14042 // already consumed the parked value.
14043 let Some(target) = self
14044 .active_new_target
14045 .as_object()
14046 .cloned()
14047 .map(Value::Object)
14048 else {
14049 return Ok(default_proto);
14050 };
14051 let Some(target) = target.as_object().cloned() else {
14052 return Ok(default_proto);
14053 };
14054 match self.get_property(&target, "prototype")? {
14055 Some(Value::Object(proto)) => Ok(Some(proto)),
14056 _ => Ok(default_proto),
14057 }
14058 }
14059
14060 /// `new.target.prototype`, or `default_proto` when this is a plain call.
14061 fn ctor_prototype(&mut self, default_proto: Gc<JsObject>) -> JsResult<Gc<JsObject>> {
14062 let Some(target) = self.active_new_target.as_object().cloned() else {
14063 return Ok(default_proto);
14064 };
14065 match self.get_property(&target, "prototype")? {
14066 Some(Value::Object(proto)) => Ok(proto),
14067 _ => Ok(default_proto),
14068 }
14069 }
14070
14071 /// `CreateDataPropertyOrThrow(O, key, value)`.
14072 ///
14073 /// A *definition*, not an assignment. The difference is visible the moment the target
14074 /// has a non-writable index — `Array.of.call(A, 2)` where `A`'s constructor froze
14075 /// `"0"` — because `Set` would silently skip the write while `CreateDataProperty`
14076 /// replaces the descriptor. It is a `TypeError` only when the definition itself is
14077 /// refused (`configurable: false`).
14078 ///
14079 /// The fast path exists because this is called once per element by `map`, `filter`,
14080 /// `slice` and friends: a plain array with no custom element descriptors and a writable
14081 /// `length` can store straight into its element vector.
14082 pub fn create_data_property_or_throw(
14083 &mut self,
14084 object: &Gc<JsObject>,
14085 index: usize,
14086 value: Value,
14087 ) -> JsResult<()> {
14088 // A proxy is excluded on both counts below. `is_array` answers `true` for a proxy of
14089 // an array (that is what `Array.isArray` must say), so the element fast path would
14090 // write into the *proxy's* empty vector and skip its `defineProperty` trap; and the
14091 // `[[GetOwnProperty]]` guard below would run a `getOwnPropertyDescriptor` trap that
14092 // `CreateDataProperty` never asks for. `splice/property-traps-order-with-species`
14093 // records the exact trap sequence.
14094 if object.proxy_state().is_none()
14095 && object.is_array()
14096 && object.elements_writable()
14097 && !object.has_element_descriptors()
14098 && object.is_extensible()
14099 && object.array_set(self.heap, index, value.clone())
14100 {
14101 return Ok(());
14102 }
14103 let key = PropertyKey::from(index.to_string());
14104 let property = Property {
14105 value: Some(value),
14106 writable: true,
14107 enumerable: true,
14108 configurable: true,
14109 ..Property::default()
14110 };
14111 // `CreateDataProperty` always asks for the default attributes, so it can only ever
14112 // replace a property that is already configurable — §10.1.6.3 step 4.a.ii refuses
14113 // the rest. Checking here rather than inside `object_define_own_property` is
14114 // deliberate: that function receives a fully-populated `Property` and cannot tell
14115 // an omitted attribute from an explicit `false`, so the generic check it would need
14116 // rejects legal partial redefinitions like `{value: 1002}` on a non-configurable
14117 // writable property (that cost eight `Object/defineProperty` tests).
14118 if object.proxy_state().is_none()
14119 && let Some(existing) = self.object_get_own_property(object, &key)?
14120 && !existing.configurable
14121 {
14122 return Err(self.type_error("cannot create the property"));
14123 }
14124 if self.object_define_own_property(object, &key, property)? {
14125 return Ok(());
14126 }
14127 Err(self.type_error("cannot create the property"))
14128 }
14129
14130 /// `CreateDataPropertyOrThrow(O, P, V)` for a **string** key.
14131 ///
14132 /// [`Interp::create_data_property_or_throw`] takes an array index because that is what
14133 /// its callers have; this is the same operation for the named properties a built-in
14134 /// defines on a result (`"index"`, `"input"`, `"groups"`). The distinction matters:
14135 /// `CreateDataProperty` bypasses the prototype chain, so an accessor installed on
14136 /// `Array.prototype` cannot see it — while `Set` would run that accessor.
14137 pub fn create_named_data_property_or_throw(
14138 &mut self,
14139 object: &Gc<JsObject>,
14140 key: &str,
14141 value: Value,
14142 ) -> JsResult<()> {
14143 let key = PropertyKey::from(key);
14144 let property = Property {
14145 value: Some(value),
14146 writable: true,
14147 enumerable: true,
14148 configurable: true,
14149 ..Property::default()
14150 };
14151 if object.proxy_state().is_none()
14152 && let Some(existing) = self.object_get_own_property(object, &key)?
14153 && !existing.configurable
14154 {
14155 return Err(self.type_error("cannot create the property"));
14156 }
14157 if self.object_define_own_property(object, &key, property)? {
14158 return Ok(());
14159 }
14160 Err(self.type_error("cannot create the property"))
14161 }
14162
14163 /// §7.3.20 `SpeciesConstructor(O, defaultConstructor)`.
14164 ///
14165 /// `O.constructor[Symbol.species]` decides what a derived array/collection is built
14166 /// from: `undefined`/`null` falls back to the intrinsic, anything that is not a
14167 /// constructor is a `TypeError`. A non-object `constructor` is a `TypeError` too, and
14168 /// note it is `Get` *twice* — once for `constructor`, once for the symbol — so both can
14169 /// run user code and both can throw.
14170 pub fn species_constructor(
14171 &mut self,
14172 object: &Gc<JsObject>,
14173 default: Value,
14174 ) -> JsResult<Value> {
14175 let Some(constructor) = self.get_property(object, "constructor")? else {
14176 return Ok(default);
14177 };
14178 let constructor = match constructor {
14179 Value::Undefined => return Ok(default),
14180 Value::Object(constructor) => constructor,
14181 _ => return Err(self.type_error("constructor is not an object")),
14182 };
14183 let key = self.realm.well_known_key(WellKnown::Species);
14184 let species = self.get_property_key(&constructor, &key)?;
14185 match species {
14186 None | Some(Value::Undefined) | Some(Value::Null) => Ok(default),
14187 Some(Value::Object(object)) if object.is_constructor() => Ok(Value::Object(object)),
14188 Some(_) => Err(self.type_error("species is not a constructor")),
14189 }
14190 }
14191
14192 /// §7.3.21 `ArraySpeciesCreate(originalArray, length)`.
14193 ///
14194 /// The result is an array of `length` holes whose prototype comes from
14195 /// `originalArray.constructor[Symbol.species]`. Only an *array* receiver takes the
14196 /// species route: `Array.prototype.map.call({length: 2}, f)` makes a plain array, which
14197 /// is why the `IsArray` check is the first step and not an optimisation.
14198 pub fn array_species_create(
14199 &mut self,
14200 original: &Value,
14201 length: usize,
14202 ) -> JsResult<Gc<JsObject>> {
14203 // §23.1.3.1.1 step 3 is `ArrayCreate(length)`, and §10.4.2.2 refuses a length past
14204 // `2**32 - 1` with a `RangeError` — whatever `original` turns out to be. Checking it
14205 // on the *default* paths only is not enough: `Array.prototype.slice.call({length:
14206 // 2**32}, 0)` takes the `!object.is_array()` shortcut straight to
14207 // `new_array_of_length` (`slice/create-non-array-invalid-len`).
14208 // `ArrayCreate(length)` is only reached when the result is a **plain array of this
14209 // realm** — the species may be a user function that ignores the length entirely, and
14210 // then `2**53 - 1` is not its problem
14211 // (`splice/create-species-length-exceeding-integer-limit` has a species that answers
14212 // a short proxy and expects the copy loop to run).
14213 let default = |interp: &Interp<'_>| -> JsResult<Gc<JsObject>> {
14214 if length > ARRAY_CREATE_LIMIT {
14215 return Err(interp.range_error("invalid array length"));
14216 }
14217 Ok(interp.new_array_of_length(length))
14218 };
14219 let Some(object) = original.as_object().cloned() else {
14220 return default(self);
14221 };
14222 if !object.is_array() {
14223 return default(self);
14224 }
14225 // A `constructor` that *is* this realm's `Array` means "the default", and skipping
14226 // it here is what keeps `Array.prototype.map` from calling `Array` at all.
14227 let Some(constructor) = self.get_property(&object, "constructor")? else {
14228 return default(self);
14229 };
14230 let species = match constructor {
14231 Value::Undefined => return Ok(self.new_array_of_length(length)),
14232 Value::Object(constructor) if self.is_intrinsic_array(&constructor) => {
14233 return default(self);
14234 }
14235 Value::Object(constructor) => {
14236 let key = self.realm.well_known_key(WellKnown::Species);
14237 match self.get_property_key(&constructor, &key)? {
14238 None | Some(Value::Undefined) | Some(Value::Null) => {
14239 return default(self);
14240 }
14241 Some(species) => species,
14242 }
14243 }
14244 // §23.1.3.1.1 step 5: a `constructor` that is neither `undefined` nor an object
14245 // is a `TypeError`, not "the default". Treating it as the default made
14246 // `[].constructor = null; [].flat()` answer `[]` where the spec raises —
14247 // `flat/non-object-ctor-throws`, `flatMap/this-value-ctor-non-object` and
14248 // `concat/create-ctor-non-object` are the same rule three times.
14249 _ => return Err(self.type_error("constructor is not an object")),
14250 };
14251 // `IsConstructor(species)` decides whether step 7 may construct at all; a species
14252 // that is merely callable is the `create-species-non-ctor` case.
14253 if !matches!(&species, Value::Object(object) if object.is_constructor()) {
14254 return Err(self.type_error("species is not a constructor"));
14255 }
14256 // The length goes in as a **Number**: `Value::Int(length as i32)` wrapped at
14257 // `2**32` and turned `2**53 - 1` into `-1`, which a species reading its argument
14258 // sees (`splice/create-species-length-exceeding-integer-limit` checks it).
14259 let created = self.construct(
14260 species.clone(),
14261 species,
14262 vec![crate::object::length_value(length)],
14263 )?;
14264 let Some(created) = created.as_object().cloned() else {
14265 return Err(self.type_error("species constructor did not answer an object"));
14266 };
14267 // `ArraySpeciesCreate` does **not** require an array here — that check belongs to
14268 // `TypedArraySpeciesCreate`. `Array.prototype.concat`'s species may answer a plain
14269 // object, and `create-species-with-non-writable-property` asserts exactly that.
14270 // The length is set for the array case; the generic case is the caller's
14271 // `Set(A, "length", …)`.
14272 if created.is_array() {
14273 created.array_set_length(self.heap, length);
14274 }
14275 Ok(created)
14276 }
14277
14278 /// Whether `object` is this realm's `%Array%`.
14279 fn is_intrinsic_array(&self, object: &Gc<JsObject>) -> bool {
14280 self.realm
14281 .array_constructor
14282 .as_ref()
14283 .is_some_and(|array| array.ptr_eq(object))
14284 }
14285
14286 /// A fresh `length`-hole array with the intrinsic prototype.
14287 pub fn new_array_of_length(&self, length: usize) -> Gc<JsObject> {
14288 let array = JsObject::array(self.heap, Some(self.realm.array_proto.clone()), 0);
14289 array.array_set_length(self.heap, length);
14290 array
14291 }
14292
14293 /// Whether this call is a construction, i.e. `new.target` is defined.
14294 ///
14295 /// A native constructor receives `this = undefined` (it builds its own instance), so it
14296 /// cannot use "`this` is not an object" to tell `Ctor()` from `new Ctor()` — this can.
14297 /// The native function currently executing, if any.
14298 pub fn current_native(&self) -> Option<Gc<JsObject>> {
14299 self.current_native.clone()
14300 }
14301
14302 /// Whether this call is a construction, i.e. `new.target` is defined.
14303 pub fn is_constructing(&self) -> bool {
14304 // `active_new_target`, not `pending_new_target`: the parked value is consumed by
14305 // `call_value` before a native runs, so by the time a constructor body asks, the
14306 // answer is only in the active slot.
14307 matches!(self.active_new_target, Value::Object(_))
14308 }
14309
14310 /// The `TypeError` a constructor too primitive to have a wrapper raises.
14311 ///
14312 /// `BigInt` and `Symbol` are *constructors* as far as `[[Construct]]` is concerned —
14313 /// the reference creates both with `JS_CFUNC_constructor_or_func` — and the refusal
14314 /// happens inside the native function, which is why the trace carries an
14315 /// `at BigInt (native)` frame. The message names `new.target`, not the callee: a
14316 /// `class B extends BigInt {}` constructed as `new B(1)` reports `B is not a
14317 /// constructor`, and an unnamed one reports the leading space of `" is not a
14318 /// constructor"` because the reference formats the empty name as it is.
14319 ///
14320 /// It is also the answer for a `new.target` that cannot be named at all — not a
14321 /// function, or a throwing `name` getter — where the reference falls back to the bare
14322 /// `not a constructor`.
14323 pub fn not_a_constructor_error(&mut self) -> Signal {
14324 let target = self.active_new_target.clone();
14325 self.not_a_constructor_error_for(target)
14326 }
14327
14328 /// The same `TypeError` for an explicit target, for the callers that check
14329 /// `IsConstructor` themselves — `Reflect.construct` does, on its third argument.
14330 pub fn not_a_constructor_error_for(&mut self, target: Value) -> Signal {
14331 let target = match target {
14332 Value::Object(target) if target.is_callable() => target,
14333 _ => return self.type_error("not a constructor"),
14334 };
14335 let name = match self.get_property(&target, "name") {
14336 Ok(Some(value)) => value.to_js_string(),
14337 _ => return self.type_error("not a constructor"),
14338 };
14339 self.type_error(format!("{name} is not a constructor"))
14340 }
14341
14342 /// Whether the pending `new.target` needs its own `prototype` honoured by the constructor.
14343 ///
14344 /// True whenever `new.target` is not the callee itself, or when it has no usable
14345 /// `prototype` — the cases where reading the property is observable at all.
14346 pub fn new_target_is_custom(&mut self, callee: &Gc<JsObject>) -> bool {
14347 match &self.active_new_target {
14348 Value::Object(target) => !target.ptr_eq(callee),
14349 Value::Undefined => false,
14350 _ => true,
14351 }
14352 }
14353
14354 /// The symbol key for one of the engine's own hidden slots.
14355 ///
14356 /// Cached on the realm, so every object of a kind shares one key and a slot can be
14357 /// read back by name.
14358 /// Whether any object on `object`'s **prototype chain** owns an array index.
14359 ///
14360 /// The one question the array methods' dense fast paths have to ask before touching the
14361 /// element vector: `[[Set]]` and `HasProperty` both consult the chain first, so an
14362 /// `Array.prototype[0]` accessor, or a prototype that supplies an element, makes the
14363 /// vector an unreliable answer. Walking the chain once per call is cheap because a
14364 /// prototype almost never holds an index.
14365 pub fn prototype_chain_has_indexed_property(&self, object: &Gc<JsObject>) -> bool {
14366 let mut current = object.proto();
14367 // Bounded, like every other prototype walk here: a proxy can answer a cycle.
14368 for _ in 0..10_000 {
14369 let Some(proto) = current else {
14370 return false;
14371 };
14372 if proto.has_indexed_own_property() {
14373 return true;
14374 }
14375 current = proto.proto();
14376 }
14377 false
14378 }
14379
14380 /// The hidden symbol a named internal slot is keyed by, created on first use.
14381 ///
14382 /// One symbol per name per realm, so `internal_set` and `internal_get` agree without
14383 /// either keeping a table of its own.
14384 pub fn internal_slot(&self, name: &'static str) -> PropertyKey {
14385 if let Some(Value::Symbol(symbol)) = self.realm.internal_slots.borrow().get(name) {
14386 return PropertyKey::Symbol(symbol.clone());
14387 }
14388 let symbol = Gc::new(self.heap, crate::value::JsSymbol::hidden(name));
14389 self.realm
14390 .internal_slots
14391 .borrow_mut()
14392 .insert(name, Value::Symbol(symbol.clone()));
14393 PropertyKey::Symbol(symbol)
14394 }
14395
14396 /// Read a hidden slot, or `None` when the object has none of that name.
14397 pub fn internal_get(&self, object: &Gc<JsObject>, name: &'static str) -> Option<Value> {
14398 let slots = self.realm.internal_slots.borrow();
14399 let Value::Symbol(symbol) = slots.get(name)? else {
14400 return None;
14401 };
14402 object
14403 .own_property_key(&PropertyKey::Symbol(symbol.clone()))
14404 .and_then(|property| property.value)
14405 }
14406
14407 /// Define a hidden slot.
14408 pub fn internal_set(&self, object: &Gc<JsObject>, name: &'static str, value: Value) {
14409 let key = self.internal_slot(name);
14410 object.define_key(&key, Property::with_attributes(value, false, false));
14411 }
14412
14413 /// `GetIterator(value)`: the real `Symbol.iterator` protocol.
14414 ///
14415 /// The method is looked up on the value (through its prototype), called with no
14416 /// arguments, and its result becomes the iterator. A generator gets here through
14417 /// `%GeneratorPrototype%[Symbol.iterator]`, which answers `this`; an array through
14418 /// `Array.prototype[Symbol.iterator]`, which builds a one-shot index iterator.
14419 ///
14420 /// This used to be a shortcut — "has a callable `next`, or is an array" — because
14421 /// there were no symbols to key the protocol on. Now that there are, the shortcut is
14422 /// gone: a `for…of` over `null`, over a plain object, or over an object whose
14423 /// `Symbol.iterator` is not callable all report the same `TypeError` the reference
14424 /// does, and a user-defined iterable works without a special case.
14425 /// `GetIterator(value, async)`: `Symbol.asyncIterator`, falling back to
14426 /// `Symbol.iterator`.
14427 ///
14428 /// The fallback is what makes `for await (x of [1,2])` work: a plain synchronous
14429 /// iterable is legal there, and each value it produces is simply already settled by
14430 /// the time the `await` around it runs.
14431 fn get_async_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14432 let async_key = self.realm.well_known_key(WellKnown::AsyncIterator);
14433 let method = self.read_field_key(value, &async_key)?;
14434 // §7.4.2 GetIterator with `async` reads `@@asyncIterator` first, and only falls back
14435 // to the synchronous `@@iterator` when that is `undefined` or `null`. A method that
14436 // is *present but not callable* is a TypeError — it does not mean "try the other
14437 // one". Treating it as absent read `Symbol.iterator` too and ran whatever it found,
14438 // which is the opposite of what the test's `get [Symbol.iterator]() { throw }`
14439 // guard is there to catch.
14440 let absent = matches!(method, Value::Undefined | Value::Null);
14441 if !absent {
14442 let Value::Object(object) = &method else {
14443 return Err(Signal::Throw(
14444 self.make_error("TypeError", "value is not iterable"),
14445 ));
14446 };
14447 if !object.is_callable() {
14448 return Err(Signal::Throw(
14449 self.make_error("TypeError", "value is not iterable"),
14450 ));
14451 }
14452 }
14453 if absent {
14454 // §7.4.2 step 5: the synchronous iterator is **wrapped**. `for await` and an async
14455 // generator's `yield*` both reach here, and the wrapper is what puts
14456 // `PromiseResolve(%Promise%, value)` between the sync iterator's `value` and the
14457 // caller — a poisoned `constructor` on that value rejects instead of being
14458 // yielded, and a rejection closes the synchronous iterator first.
14459 let sync = self.get_iterator(value)?;
14460 return self.async_from_sync_iterator(sync);
14461 }
14462 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14463 if !matches!(iterator, Value::Object(_)) {
14464 return Err(Signal::Throw(
14465 self.make_error("TypeError", "iterator is not an object"),
14466 ));
14467 }
14468 // §7.4.2 `GetIteratorFromMethod` step 3.b: `GetIteratorDirect` reads `next` and
14469 // §7.4.1 requires it to be **callable** straight away — a throwing `return` must
14470 // not be reached, because the `TypeError` comes before any stepping
14471 // (`fromEntries/iterator-not-closed-for-uncallable-next`).
14472 let next = self.read_field(&iterator, "next")?;
14473 if !matches!(&next, Value::Object(function) if function.is_callable()) {
14474 return Err(Signal::Throw(
14475 self.make_error("TypeError", "iterator's next method is not callable"),
14476 ));
14477 }
14478 Ok(Iterator {
14479 object: iterator,
14480 next,
14481 })
14482 }
14483
14484 /// `CreateAsyncFromSyncIterator(syncIteratorRecord)` (§27.1.4.1).
14485 ///
14486 /// The wrapper itself is script (see [`crate::builtins::async_from_sync`]); this only
14487 /// hands it the record and reads back its `next`. Both are properties of the wrapper, so
14488 /// the returned [`Iterator`] steps through `%AsyncFromSyncIteratorPrototype%.next`.
14489 fn async_from_sync_iterator(&mut self, sync: Iterator) -> JsResult<Iterator> {
14490 let Some(factory) = self.realm.async_from_sync.clone() else {
14491 // No wrapper installed (a realm whose heap refused to hold it): fall back to the
14492 // raw synchronous iterator rather than refusing to iterate at all.
14493 return Ok(sync);
14494 };
14495 let wrapper = self.call_value(factory, Value::Undefined, vec![sync.object, sync.next])?;
14496 let next = self.read_field(&wrapper, "next")?;
14497 Ok(Iterator {
14498 object: wrapper,
14499 next,
14500 })
14501 }
14502
14503 /// §7.4.2 `GetIteratorFromMethod`: `value` is already the iterator, so only `next` is
14504 /// read — `@@iterator` is **not** consulted.
14505 ///
14506 /// The distinction is observable and test262 exercises it: a set-like object's `keys`
14507 /// may return a bare `{ next() {...} }` with no `Symbol.iterator` at all, and
14508 /// `Set/prototype/*/set-like-class-order` hands back exactly that (an object whose
14509 /// `next` is a getter recording the read). Routing through [`Interp::get_iterator`]
14510 /// refused it with "[object Object] is not iterable".
14511 pub(crate) fn iterator_from_method(&mut self, value: Value) -> JsResult<Iterator> {
14512 if !matches!(value, Value::Object(_)) {
14513 return Err(self.type_error("iterator is not an object"));
14514 }
14515 let next = self.read_field(&value, "next")?;
14516 Ok(Iterator {
14517 object: value,
14518 next,
14519 })
14520 }
14521
14522 pub(crate) fn get_iterator(&mut self, value: &Value) -> JsResult<Iterator> {
14523 let key = self.realm.well_known_key(WellKnown::Iterator);
14524 let method = self.read_field_key(value, &key)?;
14525 let Value::Object(function) = &method else {
14526 return Err(Signal::Throw(self.make_error(
14527 "TypeError",
14528 &format!("{} is not iterable", value.to_js_string()),
14529 )));
14530 };
14531 if !function.is_callable() {
14532 return Err(Signal::Throw(self.make_error(
14533 "TypeError",
14534 &format!("{} is not iterable", value.to_js_string()),
14535 )));
14536 }
14537 let iterator = self.call_value(method, value.clone(), Vec::new())?;
14538 // The spec requires an object here; a primitive iterator has no `next` to call
14539 // and would fail one step later with a confusing message.
14540 if !matches!(iterator, Value::Object(_)) {
14541 return Err(Signal::Throw(
14542 self.make_error("TypeError", "iterator is not an object"),
14543 ));
14544 }
14545 // `GetIteratorDirect` requires `next` to be **callable** right away, before any
14546 // stepping and therefore before any `return` can be reached
14547 // (`fromEntries/iterator-not-closed-for-uncallable-next`).
14548 let next = self.read_field(&iterator, "next")?;
14549 if !matches!(&next, Value::Object(function) if function.is_callable()) {
14550 return Err(Signal::Throw(
14551 self.make_error("TypeError", "iterator's next method is not callable"),
14552 ));
14553 }
14554 Ok(Iterator {
14555 object: iterator,
14556 next,
14557 })
14558 }
14559
14560 /// §7.4.6 `IteratorClose` after a **normal** completion: the iterator is being left
14561 /// early by design (a `break` out of a `for-of`, a search that found its answer), so an
14562 /// exception from `return` propagates normally instead of being swallowed. That is the
14563 /// opposite of [`Interp::close_iterator_after_throw`], and the two are separate methods
14564 /// because confusing them is exactly the bug both exist to avoid.
14565 pub(crate) fn close_iterator(&mut self, iterator: &Iterator) -> JsResult<()> {
14566 let method = self.read_field(&iterator.object, "return")?;
14567 if matches!(method, Value::Undefined | Value::Null) {
14568 return Ok(());
14569 }
14570 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14571 return Err(self.type_error("iterator return is not a function"));
14572 }
14573 self.call_value(method, iterator.object.clone(), Vec::new())?;
14574 Ok(())
14575 }
14576
14577 /// §7.4.6 `IteratorClose` where an error is already propagating, so the `return` result
14578 /// cannot replace it.
14579 fn close_iterator_after_throw(&mut self, iterator: &Iterator) -> JsResult<()> {
14580 let method = self.read_field(&iterator.object, "return")?;
14581 if matches!(method, Value::Undefined | Value::Null) {
14582 return Ok(());
14583 }
14584 if !matches!(&method, Value::Object(object) if object.is_callable()) {
14585 return Err(self.type_error("iterator return is not a function"));
14586 }
14587 self.call_value(method, iterator.object.clone(), Vec::new())?;
14588 Ok(())
14589 }
14590
14591 /// One step of an internal iterator: the value and whether it is exhausted.
14592 pub(crate) fn iterator_step(&mut self, iterator: &Iterator) -> JsResult<(Value, bool)> {
14593 // A real iterator (`next` is a function) answers with a result object.
14594 if matches!(&iterator.next, Value::Object(object) if object.is_callable()) {
14595 let result =
14596 self.call_value(iterator.next.clone(), iterator.object.clone(), Vec::new())?;
14597 let Some(result) = result.as_object().cloned() else {
14598 return Err(self.type_error("iterator result is not an object"));
14599 };
14600 let done = self
14601 .get_property(&result, "done")?
14602 .is_some_and(|value| value.to_boolean());
14603 // §7.4.3 `IteratorComplete`/`IteratorValue`: `value` is read **only** when
14604 // `done` is false. Reading it unconditionally ran a throwing `value` getter on
14605 // the terminal step — `AggregateError/errors-iterabletolist` counts the reads
14606 // and expects `[1, 2]` from a three-step iterator, not `[1, 2, 3]`. It also
14607 // made an unrelated `value` getter observable after the loop was over.
14608 if done {
14609 return Ok((Value::Undefined, true));
14610 }
14611 let value = self
14612 .get_property(&result, "value")?
14613 .unwrap_or(Value::Undefined);
14614 return Ok((value, false));
14615 }
14616 // An iterator whose `next` is not callable is treated as exhausted, which is
14617 // what `for (x of {})` relies on: `for_of_start` has already refused the ones
14618 // that are not iterable at all.
14619 Ok((Value::Undefined, true))
14620 }
14621
14622 /// `[...iterable]`: append everything the iterator yields, and answer the next
14623 /// index.
14624 ///
14625 /// This goes through the same iterator machinery `for-of` uses rather than copying
14626 /// an array's elements, because a spread source is any iterable: a string spreads
14627 /// into its characters and an array iterator spreads into its results. Handling
14628 /// only arrays made `[..."ab"]` come out empty with no error at all.
14629 fn append_enumerate(&mut self, array: &Value, iterable: &Value) -> JsResult<i32> {
14630 let Some(target) = array.as_object().cloned() else {
14631 return Ok(0);
14632 };
14633 let start = target.array_length().unwrap_or(0);
14634 let mut added = 0;
14635 let iterator = self.get_iterator(iterable)?;
14636 loop {
14637 let (value, done) = self.iterator_step(&iterator)?;
14638 if done {
14639 break;
14640 }
14641 target.array_set(self.heap, start + added, value);
14642 added += 1;
14643 }
14644 Ok((start + added) as i32)
14645 }
14646
14647 /// How an uncaught exception is reported.
14648 ///
14649 /// The reference reports a pending exception with `JS_PrintValue`, the *printer*, not
14650 /// with `ToString` — `js_std_dump_error` is three lines that end in
14651 /// `JS_PrintValue(stderr, …)`. The difference is visible for every value that is not
14652 /// already a string: `throw "s"` prints with its quotes, `throw {a:1}` prints
14653 /// `{ a: 1 }`, `throw [1,2]` prints `[ 1, 2 ]`, and an error prints its stack.
14654 ///
14655 /// `ToString` was the wrong primitive here — it is what `error.message` is for, not
14656 /// what a reporter is for. An earlier note claimed `JS_PrintValue` "ends up calling
14657 /// `toString`"; it does call it, but only for objects of a class it does not know how
14658 /// to walk, and never for errors, arrays or plain objects.
14659 ///
14660 /// A printer that fails must not take the reporter down with it, so that case falls
14661 /// back to the `ToString` rendering.
14662 pub fn describe_exception(&mut self, value: &Value) -> String {
14663 match crate::print::sprint(self, value) {
14664 Ok(text) => text,
14665 Err(_) => self.to_js_string(value).unwrap_or_else(|_| display(value)),
14666 }
14667 }
14668
14669 /// The file name of whatever is running, innermost frame first.
14670 ///
14671 /// The reference's `JS_GetScriptOrModuleName(ctx, 0)`: it walks the stack and returns the
14672 /// innermost frame's file name, without distinguishing a module body from a plain
14673 /// script. `import()` uses it as the base for a relative specifier, which is why
14674 /// `import('./x.js')` inside a script resolves next to the script and not next to the
14675 /// process's working directory.
14676 pub fn script_or_module_name(&self) -> Option<String> {
14677 self.script_or_module_name_at(0)
14678 }
14679
14680 /// [`Interp::script_or_module_name`] `level` frames further out.
14681 ///
14682 /// The C API's `JS_GetScriptOrModuleName(ctx, n)`: level 0 is the innermost frame, and a
14683 /// level past the end answers `None` — which is what the reference's `NULL` becomes. A
14684 /// frame without a file name is skipped rather than counted, because a native call
14685 /// pushes no frame of its own and so cannot be a level.
14686 pub fn script_or_module_name_at(&self, level: usize) -> Option<String> {
14687 self.frames
14688 .iter()
14689 .rev()
14690 .filter_map(|frame| frame.code.code.filename.clone())
14691 .nth(level)
14692 }
14693
14694 /// The current call stack, formatted the way `qjs` prints `error.stack`.
14695 ///
14696 /// One ` at name (file:line:col)` line per active frame, innermost first. The
14697 /// position is the one recorded for the instruction each frame is stopped on, which
14698 /// is why the compiler builds a pc-to-position table per function: without it a
14699 /// trace could only name the function, not the line inside it.
14700 ///
14701 /// A frame whose code has no positions prints just `(file)`, matching the
14702 /// reference's output for stripped bytecode.
14703 pub fn stack_trace(&self) -> String {
14704 self.stack_trace_skipping(0)
14705 }
14706
14707 /// [`Interp::stack_trace`] with the `skip` innermost frames left out.
14708 fn stack_trace_skipping(&self, skip: usize) -> String {
14709 // One ordered list, innermost first, so `skip` counts the same thing whether the
14710 // frames it leaves out are native or bytecode. Indices rather than references: a
14711 // `Frame` borrows from `self`, and a mixed list of borrows cannot name that lifetime.
14712 let depth = self.frames.len();
14713 let mut order: Vec<(bool, usize)> = Vec::with_capacity(depth + self.native_frames.len());
14714 // A native entered while `at` bytecode frames were live was called *from* the
14715 // innermost of those, so it belongs between frame `at` and frame `at - 1`. Natives
14716 // entered at the current depth are therefore innermost of all.
14717 let push_natives = |order: &mut Vec<(bool, usize)>, wanted: usize| {
14718 for (index, (_, at)) in self.native_frames.iter().enumerate().rev() {
14719 if *at == wanted {
14720 order.push((true, index));
14721 }
14722 }
14723 };
14724 push_natives(&mut order, depth);
14725 for index in (0..depth).rev() {
14726 order.push((false, index));
14727 push_natives(&mut order, index);
14728 }
14729 // A `backtrace_barrier` eval hides its caller: keep only what is at or inside the
14730 // barrier. Natives entered at exactly the barrier depth are the eval entry point
14731 // itself (`evalScript (native)`), and the reference leaves those out too.
14732 if let Some(barrier) = self.trace_barriers.last().copied() {
14733 order.retain(|(is_native, index)| match is_native {
14734 true => *index == usize::MAX || self.native_frames[*index].1 > barrier,
14735 false => *index >= barrier,
14736 });
14737 }
14738
14739 let mut out = String::new();
14740 for (is_native, index) in order.into_iter().skip(skip) {
14741 match is_native {
14742 true => {
14743 out.push_str(" at ");
14744 let (native, _) = &self.native_frames[index];
14745 let name = native
14746 .own_property("name")
14747 .and_then(|property| property.value)
14748 .map(|value| value.to_js_string())
14749 .unwrap_or_default();
14750 out.push_str(&name);
14751 out.push_str(" (native)\n");
14752 }
14753 false => {
14754 let frame = &self.frames[index];
14755 let code = &frame.code.code;
14756 let file = code.filename.as_deref().unwrap_or("<input>");
14757 // The name comes from the function *object*, not from the compiled code:
14758 // an anonymous function expression is named by the property it is stored
14759 // in (`{valueOf: function(){}}`), which only the object knows.
14760 let bound_name = match &frame.callee {
14761 Value::Object(object) => {
14762 object
14763 .own_property("name")
14764 .and_then(|property| match property.value {
14765 Some(Value::String(text)) if !text.wtf8().is_empty() => {
14766 Some(text.to_string_lossy().into_owned())
14767 }
14768 _ => None,
14769 })
14770 }
14771 _ => None,
14772 };
14773 // No callee object means the body was entered by the host, so the
14774 // name has to come from the compiled code. Two cases differ:
14775 //
14776 // * an *unnamed* function of any kind — the reference reads the
14777 // `name` property, finds it empty, and prints `<anonymous>`;
14778 // * a *module* body, which has no `name` property at all: the
14779 // reference builds that function object with `js_closure2` and
14780 // never runs `js_function_set_properties` (`js_create_module_bytecode_function`),
14781 // so a trace reaching it also prints `<anonymous>` — while a
14782 // *script* body prints `<eval>`, its `name`.
14783 let unnamed = code.name.is_empty() || code.module.is_some();
14784 out.push_str(" at ");
14785 match bound_name.as_deref() {
14786 Some(name) => out.push_str(name),
14787 None if unnamed => out.push_str("<anonymous>"),
14788 None => out.push_str(&code.name),
14789 }
14790 match code.position_at(frame.at as u32) {
14791 Some((line, column)) => {
14792 out.push_str(&format!(" ({file}:{line}:{column})\n"));
14793 }
14794 None => out.push_str(&format!(" ({file})\n")),
14795 }
14796 }
14797 }
14798 }
14799 out
14800 }
14801
14802 /// Give an anonymous function the name of the property it is stored in.
14803 ///
14804 /// `{m: function(){}}.m.name` is `"m"`. The name property is not writable, not
14805 /// enumerable and not configurable, and a function that already has a real name
14806 /// keeps it.
14807 ///
14808 /// "Already named" means a *non-empty* name: every function object is created with
14809 /// a `name` of `""` so the property exists on all of them, and treating that empty
14810 /// string as a name left every anonymous function nameless — which is how a stack
14811 /// trace came out as `at (file:1:2)` instead of `at valueOf (file:1:2)`.
14812 /// `SetFunctionName`, for a name that came from source text.
14813 fn set_function_name(&mut self, function: &Value, name: &str) {
14814 self.set_function_name_wtf8(function, &crate::value::Wtf8::new(name));
14815 }
14816
14817 /// `SetFunctionName` with the exact name, which may hold an unpaired surrogate:
14818 /// `{ "\uD800": function () {} }.name` is that surrogate, not U+FFFD.
14819 fn set_function_name_wtf8(&mut self, function: &Value, name: &crate::value::Wtf8) {
14820 let Value::Object(object) = function else {
14821 return;
14822 };
14823 // `SetFunctionName` applies to *functions* and classes only, and only when they are
14824 // anonymous. Without the callability guard, `{value: someObject}` renamed
14825 // `someObject` to `"value"` — silently mutating an unrelated object that merely sat
14826 // on the right-hand side of a property. That is how a `zipKeyed` result object
14827 // acquired a `name` property, and it applied to `Object.defineProperty` too, which
14828 // has no `NamedEvaluation` at all.
14829 if !object.is_callable() {
14830 return;
14831 }
14832 if let Some(Value::String(existing)) = object.own_property("name").and_then(|p| p.value)
14833 && !existing.wtf8().is_empty()
14834 {
14835 return;
14836 }
14837 let text = self.string_wtf8(name.clone());
14838 object.define("name", Property::name_or_length(text));
14839 }
14840
14841 // -- global declarations -----------------------------------------------
14842
14843 /// Declare a global binding, creating its reference cell.
14844 /// Declare a `var` or function global, whose home is the global object.
14845 ///
14846 /// Writable and enumerable but not configurable: `globalThis.v` reads it,
14847 /// `for-in` lists it, `delete` refuses. A name that is already there — a built-in
14848 /// such as `print`, or a redeclaration — is left alone.
14849 pub fn declare_var_global(&mut self, name: &str) {
14850 // A strict `eval`'s `var` belongs to the eval's own scope: declaring it on the
14851 // global object is exactly the leak `typeof my_var === "undefined"` after
14852 // `eval("var my_var=2")` rules out.
14853 if let Some(scope) = self.eval_scope.as_mut() {
14854 scope.entry(name.to_string()).or_insert(Value::Undefined);
14855 return;
14856 }
14857 // A sloppy direct eval declares into its *caller's* variable environment. Doing
14858 // this on the global object instead made `eval("var c = 1")` inside a parameter
14859 // list overwrite a global `c`, and made two calls to the same function share one
14860 // binding.
14861 if let Some(cell) = self.declare_eval_local(name) {
14862 cell.set(Value::Undefined);
14863 return;
14864 }
14865 let global = self.realm.global.clone();
14866 if global.own_property(name).is_some() {
14867 return;
14868 }
14869 // A `var` in a *direct* declaration is non-configurable, but one introduced by an
14870 // eval — `(1, eval)("var g")` — is created with `configurable: true`, which is the
14871 // whole point of that trick and what lets `Object.defineProperty` reshape it
14872 // afterwards. `eval_scope` is `Some` while an eval is running.
14873 let from_eval = self.eval_depth > 0 || self.eval_scope.is_some();
14874 global.define(
14875 name,
14876 Property {
14877 value: Some(Value::Undefined),
14878 writable: true,
14879 enumerable: true,
14880 configurable: from_eval,
14881 ..Property::default()
14882 },
14883 );
14884 }
14885
14886 /// Declare a *lexical* global binding, which starts in its dead zone.
14887 ///
14888 /// Only `let`/`const`/`class` need this: a `var` global is a property of the
14889 /// global object and is created when its initialiser runs.
14890 pub fn declare_global(&mut self, name: &str, is_const: bool) {
14891 if is_const {
14892 self.realm.lexical_consts.insert(name.to_string());
14893 }
14894 if !self.realm.globals.contains_key(name) {
14895 // `Uninitialized` rather than `Undefined`: the binding exists but is not
14896 // readable until its initialiser runs, and that is what `let x` before
14897 // `x = 1` has to observe.
14898 let cell = self.new_cell(Value::Uninitialized);
14899 self.realm.globals.insert(name.to_string(), cell);
14900 self.realm.declared.push(name.to_string());
14901 }
14902 }
14903}
14904
14905/// The bytecode and environment of a function object, if it is a bytecode function.
14906///
14907/// Extracted before a call so no borrow of the object is held across it.
14908fn bytecode_of(function: &Gc<JsObject>) -> Option<(Gc<CompiledCode>, Gc<ClosureEnv>)> {
14909 function.with(|data| match &data.kind {
14910 ObjectKind::Function(Callable::Bytecode { code, env }) => Some((code.clone(), env.clone())),
14911 _ => None,
14912 })
14913}
14914
14915/// A native call target, extracted before the call so no borrow is held.
14916enum NativeCall {
14917 Native(NativeFn),
14918 /// A host closure. The `Rc` was cloned out of the function object, so calling it does
14919 /// not hold that object's `RefCell` borrow.
14920 Host(std::rc::Rc<std::cell::RefCell<crate::object::HostFn>>),
14921 Bytecode(Gc<CompiledCode>, Gc<ClosureEnv>),
14922 Bound {
14923 target: Value,
14924 this: Value,
14925 leading: Vec<Value>,
14926 },
14927 /// `Proxy.revocable`'s `revoke`: clear the proxy's slots and answer `undefined`.
14928 Revoker(crate::object::ProxyRef),
14929 /// A promise's `resolve`.
14930 PromiseResolve(Gc<JsObject>),
14931 /// A promise's `reject`.
14932 PromiseReject(Gc<JsObject>),
14933 /// The executor `NewPromiseCapability(C)` hands a user constructor.
14934 CapabilityExecutor {
14935 state: Gc<JsObject>,
14936 },
14937 /// One leg of a `then` that settles through a user capability.
14938 ThenShim {
14939 handler: Option<Value>,
14940 resolve: Value,
14941 reject: Value,
14942 fulfilled: bool,
14943 },
14944 /// One continuation of an `await`.
14945 AwaitResume {
14946 coroutine: Gc<JsObject>,
14947 promise: Gc<JsObject>,
14948 kind: ResumeKind,
14949 },
14950 /// One element of a `Promise` combinator settling.
14951 CombinatorSettle {
14952 state: Gc<JsObject>,
14953 index: usize,
14954 fulfilled: bool,
14955 },
14956 /// One of `Promise.prototype.finally`'s two shims.
14957 FinallyShim {
14958 callback: Option<Value>,
14959 fulfilled: bool,
14960 constructor: Value,
14961 },
14962 /// A thunk that answers a fixed value, for `finally`'s `valueThunk`.
14963 ReturnValue(Value),
14964 /// A thunk that throws a fixed value, for `finally`'s `thrower`.
14965 ThrowValue(Value),
14966 /// Settle a promise with a fixed outcome.
14967 SettlePromise {
14968 promise: Gc<JsObject>,
14969 value: Value,
14970 rejected: bool,
14971 },
14972 /// Continue an async generator after its `await` settled.
14973 GeneratorResume {
14974 generator: Gc<JsObject>,
14975 promise: Gc<JsObject>,
14976 kind: ResumeKind,
14977 },
14978 /// Read a module namespace's binding out of its cell.
14979 ModuleBinding(Gc<Cell>),
14980 /// Finish a completed async generator's `return(v)` once `v` has settled.
14981 CompletedReturn {
14982 generator: Gc<JsObject>,
14983 promise: Gc<JsObject>,
14984 rejected: bool,
14985 },
14986 /// Answer a pending async-generator method with `{value, done}`.
14987 YieldResult {
14988 generator: Gc<JsObject>,
14989 promise: Gc<JsObject>,
14990 done: bool,
14991 },
14992 /// One step of `AsyncDisposableStack.disposeAsync`.
14993 DisposeStep {
14994 remaining: Gc<JsObject>,
14995 promise: Gc<JsObject>,
14996 error: Value,
14997 rejected: bool,
14998 awaited: bool,
14999 needs_await: bool,
15000 },
15001}
15002
15003/// What a store does when the object refuses the write.
15004#[derive(Clone, Copy, PartialEq, Eq)]
15005pub enum DeleteFailure {
15006 /// Raise a `TypeError`, which is what strict mode and every built-in does.
15007 Throw,
15008 /// Ignore the write, which is what a sloppy-mode assignment does.
15009 Ignore,
15010}
15011
15012/// Whether `object` is a `Date` instance, by the class tag it carries.
15013///
15014/// Lives here rather than in `builtins::date` so `ToPrimitive` can ask without the
15015/// builtins module depending on the interpreter's conversion order.
15016fn is_date_object(interp: &Interp<'_>, object: &Gc<JsObject>) -> bool {
15017 interp
15018 .internal_get(object, "_class")
15019 .is_some_and(|value| value.to_js_string() == "Date")
15020}
15021
15022/// Which type `ToPrimitive` prefers when it converts an object.
15023#[derive(Clone, Copy, PartialEq, Eq)]
15024pub enum Hint {
15025 /// The default hint, which behaves like [`Hint::Number`].
15026 Default,
15027 /// `Number(obj)` and the arithmetic operators.
15028 Number,
15029 /// `String(obj)` and `ToPropertyKey`.
15030 String,
15031}
15032
15033/// Which table a binding slot indexes, for the messages that name it.
15034#[derive(Clone, Copy)]
15035enum VarSlot {
15036 Loc,
15037 Closure,
15038}
15039
15040/// `%IteratorPrototype%[Symbol.iterator]`, which answers the iterator itself.
15041fn self_iterator(_interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
15042 Ok(this)
15043}
15044
15045/// An internal iterator: the sequence plus a cursor.
15046pub(crate) struct Iterator {
15047 pub(crate) object: Value,
15048 pub(crate) next: Value,
15049}
15050
15051/// The name an accessor function gets: `get a` for a getter, `set a` for a setter,
15052/// and plain `a` for a method.
15053///
15054/// The reference prefixes accessors (`js_method_set_properties`), and the prefix is
15055/// visible: `{get a(){}}.a.name` is `"get a"`, and a stack trace from inside a getter
15056/// reads `at get a (file:1:2)`.
15057/// The same prefixing, for a name that may hold an unpaired surrogate.
15058fn accessor_prefixed(key: &crate::value::Wtf8, flags: u32) -> crate::value::Wtf8 {
15059 let prefix = match flags & 3 {
15060 1 => "get ",
15061 2 => "set ",
15062 _ => return key.clone(),
15063 };
15064 let mut units: Vec<u16> = prefix.encode_utf16().collect();
15065 units.extend_from_slice(&key.to_units());
15066 crate::value::Wtf8::from_units(&units)
15067}
15068
15069fn key_with_accessor_prefix(key: &str, flags: u32) -> String {
15070 match flags & 3 {
15071 1 => format!("get {key}"),
15072 2 => format!("set {key}"),
15073 _ => key.to_string(),
15074 }
15075}
15076
15077/// Define a method or accessor property, per the `define_method` flag byte.
15078///
15079/// The low two bits pick value/getter/setter and bit 2 marks the property
15080/// enumerable.
15081///
15082/// A getter and a setter arrive as two separate `define_method` instructions, and the
15083/// second one must only fill in its own half: `{get z(){…}, set z(v){…}}` defines
15084/// `z` twice, and replacing the property wholesale dropped the getter, so `a.z` read
15085/// `undefined`. The reference passes `JS_PROP_HAS_GET`/`JS_PROP_HAS_SET` to
15086/// `JS_DefineProperty`, which leaves the other half alone.
15087fn define_function_property(object: &Gc<JsObject>, key: &PropertyKey, function: Value, flags: u32) {
15088 let enumerable = flags & 4 != 0;
15089 let kind = flags & 3;
15090 let existing = object.own_property_key(key);
15091 let property = match kind {
15092 1 => Property {
15093 getter: Some(function),
15094 // The setter half, if this literal already defined one.
15095 setter: existing
15096 .filter(Property::is_accessor)
15097 .and_then(|p| p.setter),
15098 enumerable,
15099 configurable: true,
15100 ..Property::default()
15101 },
15102 2 => Property {
15103 getter: existing
15104 .filter(Property::is_accessor)
15105 .and_then(|p| p.getter),
15106 setter: Some(function),
15107 enumerable,
15108 configurable: true,
15109 ..Property::default()
15110 },
15111 _ => Property {
15112 value: Some(function),
15113 writable: true,
15114 enumerable,
15115 configurable: true,
15116 ..Property::default()
15117 },
15118 };
15119 object.define_key(key, property);
15120}
15121
15122// ---------------------------------------------------------------------------
15123// Operand decoding
15124// ---------------------------------------------------------------------------
15125
15126/// How `print` renders a value: the reference's `JS_PrintValue`.
15127///
15128/// This is *not* `ToString`. `print({a:1})` shows `{ a: 1 }` and `print([1])` shows
15129/// `[ 1 ]`, because the host printer dumps the structure rather than converting it.
15130/// The format is reproduced closely because the test suite compares output text:
15131///
15132/// * an empty container has two spaces inside its brackets — `[ ]`, `{ }`;
15133/// * nesting stops at depth 2 and prints `[Array]` / `[Object]`;
15134/// * a cycle prints `[circular N]` with `N` the stack index of the object;
15135/// * an array with an interior hole prints as `idx: value` pairs, while holes at the
15136/// end print as `<N empty item(s)>`;
15137/// * a string is quoted inside a container but raw at the top level, which is why
15138/// `print("x")` and `print(["x"])` differ.
15139pub fn debug_display(interp: &Interp<'_>, value: &Value) -> String {
15140 // A string argument is printed raw: `js_print` converts it with `ToString`
15141 // instead of dumping it, and the quoting only appears inside a container.
15142 if let Value::String(text) = value {
15143 return text.to_string_lossy().into_owned();
15144 }
15145 let mut printer = Printer {
15146 interp,
15147 out: String::new(),
15148 stack: Vec::new(),
15149 };
15150 printer.value(value, 0);
15151 printer.out
15152}
15153
15154/// The internal class name an object carries, when it has one.
15155fn class_of(interp: &Interp<'_>, object: &Gc<JsObject>) -> Option<String> {
15156 interp
15157 .internal_get(object, "_class")
15158 .map(|value| value.to_js_string())
15159}
15160
15161/// A string property, looked up the way `GetProperty` does: own first, then the
15162/// prototype chain. Needed because the print formatter holds the interpreter
15163/// immutably and so cannot run getters.
15164fn inherited(object: &Gc<JsObject>, name: &str) -> Option<String> {
15165 let mut current = Some(object.clone());
15166 // Bounded, because a prototype cycle would otherwise loop forever.
15167 for _ in 0..100 {
15168 let node = current?;
15169 if let Some(property) = node.own_property(name)
15170 && let Some(value) = property.value
15171 {
15172 return Some(value.to_js_string());
15173 }
15174 current = node.with(|data| data.proto.clone());
15175 }
15176 None
15177}
15178
15179/// The `JS_PrintValue` state: output, and the objects currently being printed.
15180struct Printer<'a, 'rt> {
15181 /// Kept for the class-name lookups that typed arrays and `Date` will need.
15182 #[allow(dead_code)]
15183 interp: &'a Interp<'rt>,
15184 out: String,
15185 stack: Vec<Gc<JsObject>>,
15186}
15187
15188impl Printer<'_, '_> {
15189 /// Depth past which a container is summarised by its class name.
15190 const MAX_DEPTH: usize = 2;
15191
15192 fn value(&mut self, value: &Value, level: usize) {
15193 match value {
15194 Value::Undefined
15195 | Value::Uninitialized
15196 | Value::Hole
15197 | Value::CatchOffset(_)
15198 | Value::ReturnAddress(_) => self.out.push_str("undefined"),
15199 Value::Symbol(symbol) => self.out.push_str(&symbol.to_display_string()),
15200 // The printer writes a bigint the way the language spells one, so a dump is
15201 // unambiguous about which kind of number it is showing.
15202 Value::BigInt(big) => {
15203 self.out.push_str(&big.to_decimal_string());
15204 self.out.push('n');
15205 }
15206 Value::Null => self.out.push_str("null"),
15207 Value::Bool(true) => self.out.push_str("true"),
15208 Value::Bool(false) => self.out.push_str("false"),
15209 Value::Int(number) => self.out.push_str(&number.to_string()),
15210 Value::Float(number) => {
15211 self.out
15212 .push_str(&crate::value::number_to_string_for_print(*number));
15213 }
15214 Value::String(text) => self.print_string(&text.to_string_lossy()),
15215 Value::Object(object) => self.object(object, level),
15216 }
15217 }
15218
15219 fn object(&mut self, object: &Gc<JsObject>, level: usize) {
15220 // A cycle is reported rather than followed; the index is where the object
15221 // already sits in the print stack, which is what the reference shows.
15222 if let Some(index) = self.stack.iter().position(|seen| seen.ptr_eq(object)) {
15223 self.out.push_str(&format!("[circular {index}]"));
15224 return;
15225 }
15226 if object.is_callable() {
15227 let name = object
15228 .own_property("name")
15229 .and_then(|property| property.value)
15230 .map(|value| value.to_js_string())
15231 .unwrap_or_default();
15232 if name.is_empty() {
15233 self.out.push_str("[Function (anonymous)]");
15234 } else {
15235 self.out.push_str(&format!("[Function {name}]"));
15236 }
15237 return;
15238 }
15239 if level >= Self::MAX_DEPTH {
15240 let class = if object.is_array() { "Array" } else { "Object" };
15241 self.out.push_str(&format!("[{class}]"));
15242 return;
15243 }
15244 // `Date` and `Error` print as themselves rather than as bags of properties:
15245 // the ISO string, and `Name: message` followed by the trace.
15246 if let Some(class) = class_of(self.interp, object) {
15247 if class == "Date" {
15248 self.date(object);
15249 return;
15250 }
15251 if class == "Error" {
15252 self.error(object);
15253 return;
15254 }
15255 }
15256 self.stack.push(object.clone());
15257 if object.is_array() {
15258 self.array(object, level);
15259 } else {
15260 self.plain_object(object, level);
15261 }
15262 self.stack.pop();
15263 }
15264
15265 /// A Date prints as its ISO string; an invalid one falls through to the plain
15266 /// object form, the way the reference falls back when `toISOString` throws.
15267 fn date(&mut self, object: &Gc<JsObject>) {
15268 let value = self
15269 .interp
15270 .internal_get(object, "_date_value")
15271 .map(|value| value.to_number());
15272 match value.and_then(crate::builtins::date::iso_string) {
15273 Some(text) => self.out.push_str(&text),
15274 None => self.plain_object(object, 0),
15275 }
15276 }
15277
15278 /// `Name: message`, then the trace with its trailing newline removed.
15279 fn error(&mut self, object: &Gc<JsObject>) {
15280 let name = inherited(object, "name").unwrap_or_else(|| "Error".to_string());
15281 self.out.push_str(&name);
15282 if let Some(message) = inherited(object, "message")
15283 && !message.is_empty()
15284 {
15285 self.out.push_str(": ");
15286 self.out.push_str(&message);
15287 }
15288 if let Some(stack) = inherited(object, "stack") {
15289 self.out.push('\n');
15290 self.out.push_str(stack.trim_end_matches('\n'));
15291 }
15292 }
15293
15294 fn array(&mut self, object: &Gc<JsObject>, level: usize) {
15295 let elements = object.array_elements().unwrap_or_default();
15296 self.out.push_str("[ ");
15297 // An interior hole means the array is "sparse": the reference prints those
15298 // as `index: value` pairs and says nothing about the holes themselves, while
15299 // a hole run at the end becomes a single `<N empty items>` note.
15300 let last_present = elements
15301 .iter()
15302 .rposition(|value| !matches!(value, Value::Hole));
15303 let has_interior_hole = match last_present {
15304 Some(last) => elements[..last]
15305 .iter()
15306 .any(|value| matches!(value, Value::Hole)),
15307 None => false,
15308 };
15309 let mut first = true;
15310 if has_interior_hole {
15311 let mut index = 0;
15312 while index < elements.len() {
15313 let value = &elements[index];
15314 if matches!(value, Value::Hole) {
15315 index += 1;
15316 continue;
15317 }
15318 if !first {
15319 self.out.push_str(", ");
15320 }
15321 first = false;
15322 self.out.push_str(&format!("{index}: "));
15323 self.value(value, level + 1);
15324 index += 1;
15325 }
15326 } else {
15327 for (index, value) in elements.iter().enumerate() {
15328 if matches!(value, Value::Hole) {
15329 continue;
15330 }
15331 if !first {
15332 self.out.push_str(", ");
15333 }
15334 first = false;
15335 let _ = index;
15336 self.value(value, level + 1);
15337 }
15338 if let Some(last) = last_present {
15339 let trailing = elements.len() - last - 1;
15340 if trailing > 0 {
15341 if !first {
15342 self.out.push_str(", ");
15343 }
15344 self.out.push_str(&format!(
15345 "<{trailing} empty item{}>",
15346 if trailing > 1 { "s" } else { "" }
15347 ));
15348 }
15349 } else if !elements.is_empty() {
15350 let count = elements.len();
15351 self.out.push_str(&format!(
15352 "<{count} empty item{}>",
15353 if count > 1 { "s" } else { "" }
15354 ));
15355 }
15356 }
15357 self.out.push_str(" ]");
15358 }
15359
15360 fn plain_object(&mut self, object: &Gc<JsObject>, level: usize) {
15361 self.out.push_str("{ ");
15362 let mut first = true;
15363 for key in object.own_keys() {
15364 let Some(property) = object.own_property_key(&PropertyKey::from(key.clone())) else {
15365 continue;
15366 };
15367 if !property.enumerable {
15368 continue;
15369 }
15370 if !first {
15371 self.out.push_str(", ");
15372 }
15373 first = false;
15374 self.out
15375 .push_str(&js_compile::disasm::print_atom(&Atom::from_text(
15376 &key.to_string_lossy(),
15377 )));
15378 self.out.push_str(": ");
15379 // An accessor has no value to dump; the reference names the half that
15380 // exists instead of calling it.
15381 if property.is_accessor() {
15382 let text = match (property.getter.is_some(), property.setter.is_some()) {
15383 (true, true) => "[Getter/Setter]",
15384 (false, true) => "[Setter]",
15385 _ => "[Getter]",
15386 };
15387 self.out.push_str(text);
15388 } else {
15389 self.value(&property.value.unwrap_or(Value::Undefined), level + 1);
15390 }
15391 }
15392 self.out.push_str(" }");
15393 }
15394
15395 /// A string inside a container, quoted with the escapes `js_print_string1` uses.
15396 fn print_string(&mut self, text: &str) {
15397 self.out.push('"');
15398 for character in text.chars() {
15399 match character {
15400 '"' => self.out.push_str("\\\""),
15401 '\\' => self.out.push_str("\\\\"),
15402 '\n' => self.out.push_str("\\n"),
15403 '\r' => self.out.push_str("\\r"),
15404 '\t' => self.out.push_str("\\t"),
15405 c if (c as u32) < 0x20 => {
15406 self.out.push_str(&format!("\\u{:04x}", c as u32));
15407 }
15408 c => self.out.push(c),
15409 }
15410 }
15411 self.out.push('"');
15412 }
15413}
15414
15415/// How `print` renders a value.
15416///
15417/// `ToString`, except that negative zero keeps its sign — the reference's host
15418/// printer does that while `String(-0)` is `"0"`.
15419pub fn display(value: &Value) -> String {
15420 match value {
15421 Value::Float(number) => crate::value::number_to_string_for_print(*number),
15422 Value::Uninitialized | Value::CatchOffset(_) | Value::ReturnAddress(_) => {
15423 "undefined".to_string()
15424 }
15425 other => other.to_js_string(),
15426 }
15427}
15428
15429// ---------------------------------------------------------------------------
15430// Numeric operators
15431// ---------------------------------------------------------------------------
15432
15433/// `a + b` keeping the `Int` representation when it fits.
15434fn add_numbers(left: Value, right: Value) -> Value {
15435 match (&left, &right) {
15436 (Value::Int(a), Value::Int(b)) => match a.checked_add(*b) {
15437 Some(sum) => Value::Int(sum),
15438 None => Value::Float(*a as f64 + *b as f64),
15439 },
15440 _ => Value::Float(left.to_number() + right.to_number()),
15441 }
15442}
15443
15444/// The arithmetic operators other than `+`, which needs string concatenation.
15445fn arithmetic(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15446 use Opcode::*;
15447 // Two integers and a bitwise operator is the whole of `x ^ y`, `flags | mask`,
15448 // `n & 1` — no float conversion, no `to_int32` of a float. `to_number` used to run
15449 // *before* the match, so even the arms that never needed `a` or `b` paid for it.
15450 if let (Value::Int(x), Value::Int(y)) = (&left, &right) {
15451 return Ok(match op {
15452 And => Value::Int(x & y),
15453 Or => Value::Int(x | y),
15454 Xor => Value::Int(x ^ y),
15455 Shl => Value::Int(x.wrapping_shl((*y as u32) & 31)),
15456 Sar => Value::Int(x.wrapping_shr((*y as u32) & 31)),
15457 Shr => match (*x as u32) >> ((*y as u32) & 31) {
15458 shifted if shifted <= i32::MAX as u32 => Value::Int(shifted as i32),
15459 shifted => Value::Float(shifted as f64),
15460 },
15461 Sub => match x.checked_sub(*y) {
15462 Some(value) => Value::Int(value),
15463 None => Value::Float(*x as f64 - *y as f64),
15464 },
15465 _ => return arithmetic_slow(op, left, right),
15466 });
15467 }
15468 arithmetic_slow(op, left, right)
15469}
15470
15471/// [`arithmetic`] for everything the integer fast path above does not take.
15472fn arithmetic_slow(op: Opcode, left: Value, right: Value) -> JsResult<Value> {
15473 use Opcode::*;
15474 let (a, b) = (left.to_number(), right.to_number());
15475 Ok(match op {
15476 Sub => match (&left, &right) {
15477 (Value::Int(x), Value::Int(y)) => match x.checked_sub(*y) {
15478 Some(value) => Value::Int(value),
15479 None => Value::Float(a - b),
15480 },
15481 _ => Value::Float(a - b),
15482 },
15483 Mul => Value::Float(a * b),
15484 Div => Value::Float(a / b),
15485 Mod => Value::Float(js_mod(a, b)),
15486 Pow => Value::Float(a.powf(b)),
15487 And => Value::Int(left.to_int32() & right.to_int32()),
15488 Or => Value::Int(left.to_int32() | right.to_int32()),
15489 Xor => Value::Int(left.to_int32() ^ right.to_int32()),
15490 Shl => Value::Int(left.to_int32().wrapping_shl(right.to_uint32() & 31)),
15491 Sar => Value::Int(left.to_int32().wrapping_shr(right.to_uint32() & 31)),
15492 // `>>>` is the *unsigned* shift, so its result is a uint32 and can exceed
15493 // `i32::MAX`: `(1<<31) >>> 0` is `2147483648`, not `-2147483648`. A value that
15494 // fits the small-integer representation stays an `Int`; the rest become a
15495 // float, which is how the reference keeps `n >>> 0` non-negative.
15496 Shr => {
15497 let shifted = left.to_uint32() >> (right.to_uint32() & 31);
15498 match i32::try_from(shifted) {
15499 Ok(value) => Value::Int(value),
15500 Err(_) => Value::Float(shifted as f64),
15501 }
15502 }
15503 _ => Value::Float(a),
15504 })
15505}
15506
15507/// Whether a value is a number, which is the precondition for the arithmetic fast paths.
15508///
15509/// `Int` and `Float` are both numbers; nothing else is. A `BigInt` deliberately is not:
15510/// `1n + 1` is a `TypeError` and `1n < 1` is a different comparison, so those take the
15511/// slow path where the rules live.
15512fn is_number(value: &Value) -> bool {
15513 matches!(value, Value::Int(_) | Value::Float(_))
15514}
15515
15516/// The `Value::Bool` a comparison operator answers for `ordering`.
15517///
15518/// `None` is the unordered case — a `NaN` on either side — and every operator answers
15519/// false for it, including `<=` and `>=`.
15520fn ordering_answer(op: Opcode, ordering: Option<std::cmp::Ordering>) -> Value {
15521 use Opcode::*;
15522 let answer = match (op, ordering) {
15523 (_, None) => false,
15524 (Lt, Some(ordering)) => ordering.is_lt(),
15525 (Lte, Some(ordering)) => ordering.is_le(),
15526 (Gt, Some(ordering)) => ordering.is_gt(),
15527 (Gte, Some(ordering)) => ordering.is_ge(),
15528 _ => false,
15529 };
15530 Value::Bool(answer)
15531}
15532
15533/// `%`, which follows the sign of the dividend rather than Rust's.
15534fn js_mod(left: f64, right: f64) -> f64 {
15535 if right == 0.0 || left.is_nan() || right.is_nan() || left.is_infinite() {
15536 return f64::NAN;
15537 }
15538 if right.is_infinite() {
15539 return left;
15540 }
15541 let remainder = left % right;
15542 // `-1 % 3` is `-1` in both languages, so only the exact-zero case needs care:
15543 // the spec makes the sign match the dividend.
15544 if remainder == 0.0 {
15545 0.0f64.copysign(left)
15546 } else {
15547 remainder
15548 }
15549}
15550
15551fn negate(value: Value) -> Value {
15552 match value {
15553 Value::Int(0) => Value::Float(-0.0),
15554 Value::Int(i) => Value::Int(-i),
15555 other => Value::Float(-other.to_number()),
15556 }
15557}
15558
15559fn increment(value: Value) -> Value {
15560 match value {
15561 Value::Int(i) => match i.checked_add(1) {
15562 Some(next) => Value::Int(next),
15563 None => Value::Float(i as f64 + 1.0),
15564 },
15565 other => Value::Float(other.to_number() + 1.0),
15566 }
15567}
15568
15569fn decrement(value: Value) -> Value {
15570 match value {
15571 Value::Int(i) => match i.checked_sub(1) {
15572 Some(next) => Value::Int(next),
15573 None => Value::Float(i as f64 - 1.0),
15574 },
15575 other => Value::Float(other.to_number() - 1.0),
15576 }
15577}
15578
15579/// Compare a `BigInt` with an `f64` on their mathematical values.
15580///
15581/// Neither side is rounded to the other's precision: the number is split into its integer
15582/// part (compared as an exact bigint) and its fraction, which is what decides the answer
15583/// when the integer parts are equal. An infinite value is larger than every bigint.
15584fn compare_bigint_and_f64(big: &crate::bigint::BigInt, number: f64) -> Option<std::cmp::Ordering> {
15585 use std::cmp::Ordering;
15586 if number.is_nan() {
15587 return None;
15588 }
15589 if number.is_infinite() {
15590 return Some(if number > 0.0 {
15591 Ordering::Less
15592 } else {
15593 Ordering::Greater
15594 });
15595 }
15596 let truncated = number.trunc();
15597 // A number wider than `i128` still has an exact integer part, but no bigint form we can
15598 // build cheaply; the sign of the difference is all that is needed, so compare against
15599 // the bigint's own magnitude instead.
15600 if truncated.abs() >= 1.7e38 {
15601 let big_as_f64 = big.to_f64();
15602 return big_as_f64.partial_cmp(&number);
15603 }
15604 let integer = crate::bigint::BigInt::from_f64_truncated(truncated);
15605 match big.cmp(&integer) {
15606 Ordering::Equal => {
15607 // Same integer part: the fraction decides, and a negative number's fraction is
15608 // below the integer (`-1.5` truncates to `-1`).
15609 if number > truncated {
15610 Some(Ordering::Less)
15611 } else if number < truncated {
15612 Some(Ordering::Greater)
15613 } else {
15614 Some(Ordering::Equal)
15615 }
15616 }
15617 other => Some(other),
15618 }
15619}
15620
15621/// `CanonicalNumericIndexString(argument)` (§7.1.21).
15622///
15623/// Returns `Some(numeric)` when the string is the canonical spelling of a number — the
15624/// property key `"10"` for the number `10`, but not `"010"` (whose `ToString(ToNumber(...))`
15625/// is `"10"`) and not `"1e2"` either. `"-0"` is the one special case: it canonicalises to
15626/// `-0`, which is *not* a valid typed-array index, so callers have to reject it explicitly
15627/// rather than treating it as `0`.
15628fn canonical_numeric_index(key: &PropertyKey) -> Option<f64> {
15629 let PropertyKey::String(text) = key else {
15630 // A symbol is never an index.
15631 return None;
15632 };
15633 let text = text.to_string_lossy();
15634 if text == "-0" {
15635 return Some(-0.0);
15636 }
15637 let number: f64 = text.parse().ok()?;
15638 // The round-trip test *is* the definition: only the canonical spelling qualifies.
15639 // `to_js_string` matches what `ToString` would print, so `"0.1"` round-trips and
15640 // `"0.10"` does not.
15641 let rendered = Value::Float(number).to_js_string();
15642 (rendered == text).then_some(number)
15643}
15644
15645/// §10.4.5 `IsValidIntegerIndex(O, index)` for a typed-array view.
15646///
15647/// One predicate, four call sites: `[[Get]]`, `[[HasProperty]]`, `[[DefineOwnProperty]]`
15648/// and `[[Delete]]` all turn on exactly this question, and the spec asks it of the
15649/// *canonical numeric index* — `"-0"`, `"1.5"` and `"-1"` are not "not numeric", they are
15650/// numeric and invalid, which is why they stop the prototype chain instead of falling
15651/// through it.
15652///
15653/// `-0` needs its sign test because `-0.0 == 0.0` and `fract() == 0.0`: without it the
15654/// key `"-0"` would read and write element zero, and test262 checks the read, the write,
15655/// `in`, `delete` and `defineProperty` separately to make sure it does not.
15656fn typed_array_index_is_valid(object: &Gc<JsObject>, numeric: f64) -> bool {
15657 numeric.is_finite()
15658 && numeric.fract() == 0.0
15659 && !(numeric == 0.0 && numeric.is_sign_negative())
15660 && numeric >= 0.0
15661 && object
15662 .typed_array_length()
15663 .is_some_and(|length| (numeric as usize) < length)
15664}
15665
15666/// `ArrayCreate`'s length bound, `2**32 - 1`.
15667///
15668/// `[`crate::builtins::array`] spells the same number for its own checks; this copy exists
15669/// so [`Interp::array_species_create`] — the one place every `ArraySpeciesCreate` goes
15670/// through — can enforce it without depending on a builtin module.
15671const ARRAY_CREATE_LIMIT: usize = (1 << 32) - 1;